From c06f61e35a7b8406b5687ac478815990f8f33ecc Mon Sep 17 00:00:00 2001 From: kenta-elys Date: Tue, 19 Sep 2023 08:01:31 +0000 Subject: [PATCH 1/4] chore: manage eden boost burning from elys unstake and eden uncommitted --- proto/elys/incentive/elys_staked.proto | 17 + proto/elys/incentive/query.proto | 1 - x/amm/types/query.pb.gw.go | 19 +- x/commitment/keeper/hooks.go | 15 + .../keeper/msg_server_uncommit_tokens.go | 6 + x/commitment/types/interfaces.go | 3 + x/incentive/keeper/abci.go | 57 +++ x/incentive/keeper/elys_staked.go | 63 +++ x/incentive/keeper/hooks_commitment.go | 10 + x/incentive/keeper/hooks_staking.go | 6 +- x/incentive/keeper/keeper_burn_edenB.go | 78 ++++ x/incentive/module.go | 4 +- x/incentive/types/elys_staked.pb.go | 396 ++++++++++++++++++ x/incentive/types/expected_keepers.go | 2 + x/incentive/types/keys.go | 15 + 15 files changed, 686 insertions(+), 6 deletions(-) create mode 100644 proto/elys/incentive/elys_staked.proto create mode 100644 x/incentive/keeper/abci.go create mode 100644 x/incentive/keeper/elys_staked.go create mode 100644 x/incentive/keeper/keeper_burn_edenB.go create mode 100644 x/incentive/types/elys_staked.pb.go diff --git a/proto/elys/incentive/elys_staked.proto b/proto/elys/incentive/elys_staked.proto new file mode 100644 index 000000000..d48647966 --- /dev/null +++ b/proto/elys/incentive/elys_staked.proto @@ -0,0 +1,17 @@ +syntax = "proto3"; +package elys.incentive; + +option go_package = "github.com/elys-network/elys/x/incentive/types"; +option (gogoproto.equal_all) = true; + +import "gogoproto/gogo.proto"; + +// Elys staked +message ElysStaked { + string address = 1; + string amount = 2 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", + (gogoproto.nullable) = false + ]; + } + \ No newline at end of file diff --git a/proto/elys/incentive/query.proto b/proto/elys/incentive/query.proto index 33217a4bf..191b8fc20 100644 --- a/proto/elys/incentive/query.proto +++ b/proto/elys/incentive/query.proto @@ -25,7 +25,6 @@ service Query { option (google.api.http).get = "/elys-network/elys/incentive/community_pool"; } - } // QueryParamsRequest is request type for the Query/Params RPC method. message QueryParamsRequest {} diff --git a/x/amm/types/query.pb.gw.go b/x/amm/types/query.pb.gw.go index 2babba22a..3b891ece9 100644 --- a/x/amm/types/query.pb.gw.go +++ b/x/amm/types/query.pb.gw.go @@ -20,6 +20,7 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) @@ -30,6 +31,7 @@ var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage +var _ = metadata.Join func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq QueryParamsRequest @@ -232,12 +234,14 @@ func local_request_Query_DenomLiquidityAll_0(ctx context.Context, marshaler runt // RegisterQueryHandlerServer registers the http handlers for service Query to "mux". // UnaryRPC :call QueryServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features (such as grpc.SendHeader, etc) to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. +// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { @@ -245,6 +249,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) @@ -258,6 +263,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_Pool_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { @@ -265,6 +272,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_Pool_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) @@ -278,6 +286,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_PoolAll_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { @@ -285,6 +295,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_PoolAll_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) @@ -298,6 +309,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_DenomLiquidity_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { @@ -305,6 +318,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_DenomLiquidity_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) @@ -318,6 +332,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_DenomLiquidityAll_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { @@ -325,6 +341,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_DenomLiquidityAll_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) diff --git a/x/commitment/keeper/hooks.go b/x/commitment/keeper/hooks.go index 86b8ae763..55b216868 100644 --- a/x/commitment/keeper/hooks.go +++ b/x/commitment/keeper/hooks.go @@ -21,6 +21,13 @@ func (mh MultiCommitmentHooks) CommitmentChanged(ctx sdk.Context, creator string } } +// Committed is called when staker committed his token +func (mh MultiCommitmentHooks) EdenUncommitted(ctx sdk.Context, creator string, amount sdk.Coin) { + for i := range mh { + mh[i].EdenUncommitted(ctx, creator, amount) + } +} + // Committed executes the indicated for committed hook func (k Keeper) AfterCommitmentChange(ctx sdk.Context, creator string, amount sdk.Coin) { if k.hooks == nil { @@ -28,3 +35,11 @@ func (k Keeper) AfterCommitmentChange(ctx sdk.Context, creator string, amount sd } k.hooks.CommitmentChanged(ctx, creator, amount) } + +// Committed executes the indicated for committed hook +func (k Keeper) EdenUncommitted(ctx sdk.Context, creator string, amount sdk.Coin) { + if k.hooks == nil { + return + } + k.hooks.EdenUncommitted(ctx, creator, amount) +} diff --git a/x/commitment/keeper/msg_server_uncommit_tokens.go b/x/commitment/keeper/msg_server_uncommit_tokens.go index 5c4e00e74..53023c630 100644 --- a/x/commitment/keeper/msg_server_uncommit_tokens.go +++ b/x/commitment/keeper/msg_server_uncommit_tokens.go @@ -7,6 +7,7 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" aptypes "github.com/elys-network/elys/x/assetprofile/types" "github.com/elys-network/elys/x/commitment/types" + ptypes "github.com/elys-network/elys/x/parameter/types" ) func (k msgServer) UncommitTokens(goCtx context.Context, msg *types.MsgUncommitTokens) (*types.MsgUncommitTokensResponse, error) { @@ -58,6 +59,11 @@ func (k msgServer) UncommitTokens(goCtx context.Context, msg *types.MsgUncommitT // Emit Hook commitment changed k.AfterCommitmentChange(ctx, msg.Creator, sdk.NewCoin(msg.Denom, msg.Amount)) + // Emit Hook if Eden is uncommitted + if msg.Denom == ptypes.Eden { + k.EdenUncommitted(ctx, msg.Creator, sdk.NewCoin(msg.Denom, msg.Amount)) + } + // Emit blockchain event ctx.EventManager().EmitEvent( sdk.NewEvent( diff --git a/x/commitment/types/interfaces.go b/x/commitment/types/interfaces.go index f0ef60a5d..9247e744c 100644 --- a/x/commitment/types/interfaces.go +++ b/x/commitment/types/interfaces.go @@ -6,4 +6,7 @@ import sdk "github.com/cosmos/cosmos-sdk/types" type CommitmentHooks interface { // Token commitment changed CommitmentChanged(ctx sdk.Context, creator string, amount sdk.Coin) + + // Eden uncommitted + EdenUncommitted(ctx sdk.Context, creator string, amount sdk.Coin) } diff --git a/x/incentive/keeper/abci.go b/x/incentive/keeper/abci.go new file mode 100644 index 000000000..8aa538757 --- /dev/null +++ b/x/incentive/keeper/abci.go @@ -0,0 +1,57 @@ +// Copyright 2022 Evmos Foundation +// This file is part of the Evmos Network packages. +// +// Evmos is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The Evmos packages are distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the Evmos packages. If not, see https://github.com/evmos/evmos/blob/main/LICENSE + +package keeper + +import ( + "time" + + "github.com/cosmos/cosmos-sdk/telemetry" + sdk "github.com/cosmos/cosmos-sdk/types" + + ctypes "github.com/elys-network/elys/x/commitment/types" + "github.com/elys-network/elys/x/incentive/types" +) + +// EndBlocker of incentive module +func (k Keeper) EndBlocker(ctx sdk.Context) { + defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyEndBlocker) + // Track the amount of Elys staked + k.cmk.IterateCommitments( + ctx, func(commitments ctypes.Commitments) bool { + // Commitment owner + creator := commitments.Creator + _, err := sdk.AccAddressFromBech32(creator) + if err != nil { + // This could be validator address + return false + } + + // Calculate delegated amount per delegator + delegatedAmt := k.CalculateDelegatedAmount(ctx, creator) + + elysStaked := types.ElysStaked{ + Address: creator, + Amount: delegatedAmt, + } + + // Set Elys staked amount + k.SetElysStaked(ctx, elysStaked) + + return false + }, + ) +} diff --git a/x/incentive/keeper/elys_staked.go b/x/incentive/keeper/elys_staked.go new file mode 100644 index 000000000..575322c31 --- /dev/null +++ b/x/incentive/keeper/elys_staked.go @@ -0,0 +1,63 @@ +package keeper + +import ( + "github.com/cosmos/cosmos-sdk/store/prefix" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/elys-network/elys/x/incentive/types" +) + +// SetSuperAdmin set a specific superAdmin in the store from its index +func (k Keeper) SetElysStaked(ctx sdk.Context, elysStaked types.ElysStaked) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ElysStakedKeyPrefix)) + b := k.cdc.MustMarshal(&elysStaked) + store.Set(types.ElysStakedKey( + elysStaked.Address, + ), b) +} + +// GetSuperAdmin returns a superAdmin from its index +func (k Keeper) GetElysStaked( + ctx sdk.Context, + address string, + +) (val types.ElysStaked, found bool) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ElysStakedKeyPrefix)) + + b := store.Get(types.ElysStakedKey( + address, + )) + if b == nil { + return val, false + } + + k.cdc.MustUnmarshal(b, &val) + return val, true +} + +// RemoveSuperAdmin removes a superAdmin from the store +func (k Keeper) RemoveElysStaked( + ctx sdk.Context, + address string, + +) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ElysStakedKeyPrefix)) + store.Delete(types.ElysStakedKey( + address, + )) +} + +// GetAllSuperAdmin returns all superAdmin +func (k Keeper) GetAllElysStaked(ctx sdk.Context) (list []types.ElysStaked) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ElysStakedKeyPrefix)) + iterator := sdk.KVStorePrefixIterator(store, []byte{}) + + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + var val types.ElysStaked + k.cdc.MustUnmarshal(iterator.Value(), &val) + list = append(list, val) + } + + return +} diff --git a/x/incentive/keeper/hooks_commitment.go b/x/incentive/keeper/hooks_commitment.go index 278b34afd..638b18500 100644 --- a/x/incentive/keeper/hooks_commitment.go +++ b/x/incentive/keeper/hooks_commitment.go @@ -9,6 +9,11 @@ import ( func (k Keeper) CommitmentChanged(ctx sdk.Context, creator string, amount sdk.Coin) { } +// Process eden uncommitted hook +func (k Keeper) EdenUncommitted(ctx sdk.Context, creator string, amount sdk.Coin) { + k.BurnEdenBFromEdenUncommitted(ctx, creator, amount.Amount) +} + // ___________________________________________________________________________________________________ // Hooks wrapper struct for incentive keeper @@ -27,3 +32,8 @@ func (k Keeper) CommitmentHooks() CommitmentHooks { func (h CommitmentHooks) CommitmentChanged(ctx sdk.Context, creator string, amount sdk.Coin) { h.k.CommitmentChanged(ctx, creator, amount) } + +// EdenUncommitted implements EdenUncommitted +func (h CommitmentHooks) EdenUncommitted(ctx sdk.Context, creator string, amount sdk.Coin) { + h.k.EdenUncommitted(ctx, creator, amount) +} diff --git a/x/incentive/keeper/hooks_staking.go b/x/incentive/keeper/hooks_staking.go index 3099077ce..abd2c0b79 100644 --- a/x/incentive/keeper/hooks_staking.go +++ b/x/incentive/keeper/hooks_staking.go @@ -22,15 +22,15 @@ func (k Keeper) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, // Updating commitments on delegation changes func (k Keeper) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { - return nil + return k.BurnEdenBFromElysUnstaking(ctx, delAddr) } func (k Keeper) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { - return nil + return k.BurnEdenBFromElysUnstaking(ctx, delAddr) } func (k Keeper) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { - return nil + return k.BurnEdenBFromElysUnstaking(ctx, delAddr) } // ________________________________________________________________________________________ diff --git a/x/incentive/keeper/keeper_burn_edenB.go b/x/incentive/keeper/keeper_burn_edenB.go new file mode 100644 index 000000000..b313d3d29 --- /dev/null +++ b/x/incentive/keeper/keeper_burn_edenB.go @@ -0,0 +1,78 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + ptypes "github.com/elys-network/elys/x/parameter/types" +) + +// Burn EdenBoost from Elys unstaked +func (k Keeper) BurnEdenBFromElysUnstaking(ctx sdk.Context, delegator sdk.AccAddress) error { + delAddr := delegator.String() + // Get commitments + commitments, found := k.cmk.GetCommitments(ctx, delAddr) + if !found { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid address %s", delegator.String()) + } + + // Get previous amount + prevElysStaked, found := k.GetElysStaked(ctx, delAddr) + if !found { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid address %s", delegator.String()) + } + + // Calculate current delegated amount of delegator + delegatedAmt := k.CalculateDelegatedAmount(ctx, delAddr) + + // If not unstaked, + if delegatedAmt.GTE(prevElysStaked.Amount) { + return nil + } + + edenCommitted := commitments.GetCommittedAmountForDenom(ptypes.Eden) + + //Total EdenB amount + edenBCommitted := commitments.GetCommittedAmountForDenom(ptypes.EdenB) + edenBUncommitted := commitments.GetUncommittedAmountForDenom(ptypes.EdenB) + + // Total EdenB amount + totalEdenB := edenBCommitted.Add(edenBUncommitted) + + // Unstaked + unstakedElys := prevElysStaked.Amount.Sub(delegatedAmt) + + edenBToBurn := unstakedElys.Quo(edenCommitted.Add(prevElysStaked.Amount)).Mul(totalEdenB) + + // Burn EdenB ( Deduction EdenB in commitment module) + _, err := k.cmk.DeductCommitments(ctx, delAddr, ptypes.EdenB, edenBToBurn) + return err +} + +// Burn EdenBoost from Eden uncommitted +func (k Keeper) BurnEdenBFromEdenUncommitted(ctx sdk.Context, delegator string, uncommittedAmt sdk.Int) error { + // Get elys staked amount + elysStaked, found := k.GetElysStaked(ctx, delegator) + if !found { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid address %s", delegator) + } + + commitments, found := k.cmk.GetCommitments(ctx, delegator) + if !found { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid address %s", delegator) + } + + edenCommitted := commitments.GetCommittedAmountForDenom(ptypes.Eden) + + //Total EdenB amount + edenBCommitted := commitments.GetCommittedAmountForDenom(ptypes.EdenB) + edenBUncommitted := commitments.GetUncommittedAmountForDenom(ptypes.EdenB) + + // Total EdenB amount + totalEdenB := edenBCommitted.Add(edenBUncommitted) + + edenBToBurn := uncommittedAmt.Quo(edenCommitted.Add(elysStaked.Amount)).Mul(totalEdenB) + + // Burn EdenB ( Deduction EdenB in commitment module) + _, err := k.cmk.DeductCommitments(ctx, delegator, ptypes.EdenB, edenBToBurn) + return err +} diff --git a/x/incentive/module.go b/x/incentive/module.go index a38da13e8..d8103b813 100644 --- a/x/incentive/module.go +++ b/x/incentive/module.go @@ -143,6 +143,8 @@ func (AppModule) ConsensusVersion() uint64 { return 3 } func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} // EndBlock contains the logic that is automatically triggered at the end of each block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { +func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { + am.keeper.EndBlocker(ctx) + return []abci.ValidatorUpdate{} } diff --git a/x/incentive/types/elys_staked.pb.go b/x/incentive/types/elys_staked.pb.go new file mode 100644 index 000000000..cbaa038dd --- /dev/null +++ b/x/incentive/types/elys_staked.pb.go @@ -0,0 +1,396 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: elys/incentive/elys_staked.proto + +package types + +import ( + fmt "fmt" + github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// Elys staked +type ElysStaked struct { + Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` + Amount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=amount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"amount"` +} + +func (m *ElysStaked) Reset() { *m = ElysStaked{} } +func (m *ElysStaked) String() string { return proto.CompactTextString(m) } +func (*ElysStaked) ProtoMessage() {} +func (*ElysStaked) Descriptor() ([]byte, []int) { + return fileDescriptor_ebe5e1add8f72d5c, []int{0} +} +func (m *ElysStaked) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ElysStaked) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ElysStaked.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 *ElysStaked) XXX_Merge(src proto.Message) { + xxx_messageInfo_ElysStaked.Merge(m, src) +} +func (m *ElysStaked) XXX_Size() int { + return m.Size() +} +func (m *ElysStaked) XXX_DiscardUnknown() { + xxx_messageInfo_ElysStaked.DiscardUnknown(m) +} + +var xxx_messageInfo_ElysStaked proto.InternalMessageInfo + +func (m *ElysStaked) GetAddress() string { + if m != nil { + return m.Address + } + return "" +} + +func init() { + proto.RegisterType((*ElysStaked)(nil), "elys.incentive.ElysStaked") +} + +func init() { proto.RegisterFile("elys/incentive/elys_staked.proto", fileDescriptor_ebe5e1add8f72d5c) } + +var fileDescriptor_ebe5e1add8f72d5c = []byte{ + // 226 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x48, 0xcd, 0xa9, 0x2c, + 0xd6, 0xcf, 0xcc, 0x4b, 0x4e, 0xcd, 0x2b, 0xc9, 0x2c, 0x4b, 0xd5, 0x07, 0x71, 0xe3, 0x8b, 0x4b, + 0x12, 0xb3, 0x53, 0x53, 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0xf8, 0x40, 0x42, 0x7a, 0x70, + 0x15, 0x52, 0x22, 0xe9, 0xf9, 0xe9, 0xf9, 0x60, 0x29, 0x7d, 0x10, 0x0b, 0xa2, 0x4a, 0x29, 0x8f, + 0x8b, 0xcb, 0x35, 0xa7, 0xb2, 0x38, 0x18, 0xac, 0x53, 0x48, 0x82, 0x8b, 0x3d, 0x31, 0x25, 0xa5, + 0x28, 0xb5, 0xb8, 0x58, 0x82, 0x51, 0x81, 0x51, 0x83, 0x33, 0x08, 0xc6, 0x15, 0x72, 0xe3, 0x62, + 0x4b, 0xcc, 0xcd, 0x2f, 0xcd, 0x2b, 0x91, 0x60, 0x02, 0x49, 0x38, 0xe9, 0x9d, 0xb8, 0x27, 0xcf, + 0x70, 0xeb, 0x9e, 0xbc, 0x5a, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, + 0x72, 0x7e, 0x71, 0x6e, 0x7e, 0x31, 0x94, 0xd2, 0x2d, 0x4e, 0xc9, 0xd6, 0x2f, 0xa9, 0x2c, 0x48, + 0x2d, 0xd6, 0xf3, 0xcc, 0x2b, 0x09, 0x82, 0xea, 0x76, 0xf2, 0x59, 0xf1, 0x48, 0x8e, 0xf1, 0xc4, + 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, + 0xc2, 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, 0x18, 0xa2, 0xf4, 0x90, 0x4c, 0x03, 0x39, 0x5f, 0x37, + 0x2f, 0xb5, 0xa4, 0x3c, 0xbf, 0x28, 0x1b, 0xcc, 0xd1, 0xaf, 0x40, 0xf2, 0x2f, 0xd8, 0xe4, 0x24, + 0x36, 0xb0, 0x27, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xb5, 0xe0, 0x1a, 0xce, 0x0e, 0x01, + 0x00, 0x00, +} + +func (this *ElysStaked) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*ElysStaked) + if !ok { + that2, ok := that.(ElysStaked) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Address != that1.Address { + return false + } + if !this.Amount.Equal(that1.Amount) { + return false + } + return true +} +func (m *ElysStaked) 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 *ElysStaked) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ElysStaked) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size := m.Amount.Size() + i -= size + if _, err := m.Amount.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintElysStaked(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.Address) > 0 { + i -= len(m.Address) + copy(dAtA[i:], m.Address) + i = encodeVarintElysStaked(dAtA, i, uint64(len(m.Address))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintElysStaked(dAtA []byte, offset int, v uint64) int { + offset -= sovElysStaked(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *ElysStaked) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovElysStaked(uint64(l)) + } + l = m.Amount.Size() + n += 1 + l + sovElysStaked(uint64(l)) + return n +} + +func sovElysStaked(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozElysStaked(x uint64) (n int) { + return sovElysStaked(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *ElysStaked) 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 ErrIntOverflowElysStaked + } + 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: ElysStaked: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ElysStaked: 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 ErrIntOverflowElysStaked + } + 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 ErrInvalidLengthElysStaked + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthElysStaked + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowElysStaked + } + 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 ErrInvalidLengthElysStaked + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthElysStaked + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipElysStaked(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthElysStaked + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipElysStaked(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowElysStaked + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowElysStaked + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowElysStaked + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthElysStaked + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupElysStaked + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthElysStaked + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthElysStaked = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowElysStaked = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupElysStaked = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/incentive/types/expected_keepers.go b/x/incentive/types/expected_keepers.go index cf4ebe9c4..7aa398c80 100644 --- a/x/incentive/types/expected_keepers.go +++ b/x/incentive/types/expected_keepers.go @@ -25,6 +25,8 @@ type CommitmentKeeper interface { ProcessWithdrawValidatorCommission(sdk.Context, string, string, string, sdk.Int) error // Withdraw tokens - only USDC ProcessWithdrawUSDC(ctx sdk.Context, creator string, denom string, amount sdk.Int) error + // Deduct commitments + DeductCommitments(ctx sdk.Context, creator string, denom string, amount sdk.Int) (ctypes.Commitments, error) } // Staking keeper diff --git a/x/incentive/types/keys.go b/x/incentive/types/keys.go index e33d4f316..73b72db6a 100644 --- a/x/incentive/types/keys.go +++ b/x/incentive/types/keys.go @@ -12,6 +12,8 @@ const ( // MemStoreKey defines the in-memory store key MemStoreKey = "mem_incentive" + + ElysStakedKeyPrefix = "ElysStaked/value/" ) func KeyPrefix(p string) []byte { @@ -21,3 +23,16 @@ func KeyPrefix(p string) []byte { var ( FeePoolKey = []byte{0x00} // key for global distribution state ) + +// ElysStakedKey returns the store key to retrieve a ElysStaked from the address fields +func ElysStakedKey( + address string, +) []byte { + var key []byte + + addressBytes := []byte(address) + key = append(key, addressBytes...) + key = append(key, []byte("/")...) + + return key +} From b5ee6db154352d493a7c6d953ecb28a2b855ef2a Mon Sep 17 00:00:00 2001 From: kenta-elys Date: Tue, 19 Sep 2023 09:00:10 +0000 Subject: [PATCH 2/4] chore: add abci test --- x/incentive/keeper/abci_test.go | 50 +++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 x/incentive/keeper/abci_test.go diff --git a/x/incentive/keeper/abci_test.go b/x/incentive/keeper/abci_test.go new file mode 100644 index 000000000..d808bf78a --- /dev/null +++ b/x/incentive/keeper/abci_test.go @@ -0,0 +1,50 @@ +package keeper_test + +import ( + "testing" + + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + sdk "github.com/cosmos/cosmos-sdk/types" + simapp "github.com/elys-network/elys/app" + ctypes "github.com/elys-network/elys/x/commitment/types" + ptypes "github.com/elys-network/elys/x/parameter/types" + "github.com/stretchr/testify/require" +) + +func TestABCI_EndBlocker(t *testing.T) { + app, genAccount, _ := simapp.InitElysTestAppWithGenAccount() + ctx := app.BaseApp.NewContext(initChain, tmproto.Header{}) + + ik := app.IncentiveKeeper + + var committed []sdk.Coins + var uncommitted []sdk.Coins + + // Prepare uncommitted tokens + uedenToken := sdk.NewCoins(sdk.NewCoin(ptypes.Eden, sdk.NewInt(2000))) + uedenBToken := sdk.NewCoins(sdk.NewCoin(ptypes.EdenB, sdk.NewInt(2000))) + uncommitted = append(uncommitted, uedenToken) + uncommitted = append(uncommitted, uedenBToken) + + // Eden + err := app.BankKeeper.MintCoins(ctx, ctypes.ModuleName, uedenToken) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, ctypes.ModuleName, genAccount, uedenToken) + require.NoError(t, err) + + // EdenB + err = app.BankKeeper.MintCoins(ctx, ctypes.ModuleName, uedenBToken) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, ctypes.ModuleName, genAccount, uedenBToken) + require.NoError(t, err) + + // Add testing commitment + simapp.AddTestCommitment(app, ctx, genAccount, committed, uncommitted) + // Update Elys staked amount + ik.EndBlocker(ctx) + + // Get elys staked + elysStaked, found := ik.GetElysStaked(ctx, genAccount.String()) + require.Equal(t, found, true) + require.Equal(t, elysStaked.Amount, sdk.DefaultPowerReduction) +} From 4cc81777ab08a88eeb9f8b96d42b11c6f6fd7cf4 Mon Sep 17 00:00:00 2001 From: Cosmic Vagabond <121588426+cosmic-vagabond@users.noreply.github.com> Date: Mon, 18 Sep 2023 16:03:34 +0200 Subject: [PATCH 3/4] refactor: margin functions (#194) * refactor: margin functions * fix: test cases * fix: mocks * test: fix test cases --- x/margin/keeper/check_long_assets.go | 2 +- x/margin/keeper/check_long_assets_test.go | 8 +-- x/margin/keeper/check_short_assets.go | 27 +++++++++ x/margin/keeper/check_short_assets_test.go | 59 ++++++++++++++++++++ x/margin/keeper/open.go | 14 ++++- x/margin/keeper/open_long_process.go | 17 +++++- x/margin/keeper/open_short_process.go | 9 ++- x/margin/keeper/open_test.go | 31 ++++------- x/margin/types/expected_keepers.go | 5 +- x/margin/types/mocks/open_checker.go | 64 ++++++++++++++++++---- x/margin/types/mocks/open_long_checker.go | 20 +++---- 11 files changed, 204 insertions(+), 52 deletions(-) create mode 100644 x/margin/keeper/check_short_assets.go create mode 100644 x/margin/keeper/check_short_assets_test.go diff --git a/x/margin/keeper/check_long_assets.go b/x/margin/keeper/check_long_assets.go index 563047b77..372c5884e 100644 --- a/x/margin/keeper/check_long_assets.go +++ b/x/margin/keeper/check_long_assets.go @@ -7,7 +7,7 @@ import ( ptypes "github.com/elys-network/elys/x/parameter/types" ) -func (k Keeper) CheckLongingAssets(ctx sdk.Context, collateralAsset string, borrowAsset string) error { +func (k Keeper) CheckLongAssets(ctx sdk.Context, collateralAsset string, borrowAsset string) error { if borrowAsset == ptypes.BaseCurrency { return sdkerrors.Wrap(types.ErrInvalidBorrowingAsset, "invalid borrowing asset") } diff --git a/x/margin/keeper/check_long_assets_test.go b/x/margin/keeper/check_long_assets_test.go index 802437e31..e357795cc 100644 --- a/x/margin/keeper/check_long_assets_test.go +++ b/x/margin/keeper/check_long_assets_test.go @@ -25,10 +25,10 @@ func TestCheckLongAssets_InvalidAssets(t *testing.T) { ctx := sdk.Context{} // mock or setup a context - err := k.CheckLongingAssets(ctx, ptypes.BaseCurrency, ptypes.BaseCurrency) + err := k.CheckLongAssets(ctx, ptypes.BaseCurrency, ptypes.BaseCurrency) assert.True(t, errors.Is(err, sdkerrors.Wrap(types.ErrInvalidBorrowingAsset, "invalid borrowing asset"))) - err = k.CheckLongingAssets(ctx, ptypes.ATOM, ptypes.BaseCurrency) + err = k.CheckLongAssets(ctx, ptypes.ATOM, ptypes.BaseCurrency) assert.True(t, errors.Is(err, sdkerrors.Wrap(types.ErrInvalidBorrowingAsset, "invalid borrowing asset"))) // Expect no error @@ -46,10 +46,10 @@ func TestCheckLongAssets_ValidAssets(t *testing.T) { ctx := sdk.Context{} // mock or setup a context - err := k.CheckLongingAssets(ctx, ptypes.BaseCurrency, ptypes.ATOM) + err := k.CheckLongAssets(ctx, ptypes.BaseCurrency, ptypes.ATOM) assert.Nil(t, err) - err = k.CheckLongingAssets(ctx, ptypes.ATOM, ptypes.ATOM) + err = k.CheckLongAssets(ctx, ptypes.ATOM, ptypes.ATOM) assert.Nil(t, err) // Expect an error about max open positions diff --git a/x/margin/keeper/check_short_assets.go b/x/margin/keeper/check_short_assets.go new file mode 100644 index 000000000..cefd273fe --- /dev/null +++ b/x/margin/keeper/check_short_assets.go @@ -0,0 +1,27 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/elys-network/elys/x/margin/types" + ptypes "github.com/elys-network/elys/x/parameter/types" +) + +func (k Keeper) CheckShortAssets(ctx sdk.Context, collateralAsset string, borrowAsset string) error { + // You shouldn't be shorting the base currency (like USDC). + if borrowAsset == ptypes.BaseCurrency { + return sdkerrors.Wrap(types.ErrInvalidBorrowingAsset, "cannot short the base currency") + } + + // If both the collateralAsset and borrowAsset are the same, it doesn't make sense. + if collateralAsset == borrowAsset { + return sdkerrors.Wrap(types.ErrInvalidCollateralAsset, "collateral asset cannot be the same as the borrowed asset in a short position") + } + + // The collateral for a short must be the base currency. + if collateralAsset != ptypes.BaseCurrency { + return sdkerrors.Wrap(types.ErrInvalidCollateralAsset, "collateral asset for a short position must be the base currency") + } + + return nil +} diff --git a/x/margin/keeper/check_short_assets_test.go b/x/margin/keeper/check_short_assets_test.go new file mode 100644 index 000000000..1249a33e6 --- /dev/null +++ b/x/margin/keeper/check_short_assets_test.go @@ -0,0 +1,59 @@ +package keeper_test + +import ( + "errors" + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/elys-network/elys/x/margin/keeper" + "github.com/elys-network/elys/x/margin/types" + "github.com/elys-network/elys/x/margin/types/mocks" + "github.com/stretchr/testify/assert" + + ptypes "github.com/elys-network/elys/x/parameter/types" +) + +func TestCheckShortAssets_InvalidAssets(t *testing.T) { + // Setup the mock checker + mockChecker := new(mocks.OpenShortChecker) + + // Create an instance of Keeper with the mock checker + k := keeper.Keeper{ + OpenShortChecker: mockChecker, + } + + ctx := sdk.Context{} // mock or setup a context + + // Test invalid cases for short positions + err := k.CheckShortAssets(ctx, ptypes.ATOM, ptypes.BaseCurrency) + assert.True(t, errors.Is(err, sdkerrors.Wrap(types.ErrInvalidBorrowingAsset, "cannot short the base currency"))) + + err = k.CheckShortAssets(ctx, ptypes.ATOM, ptypes.ATOM) + assert.True(t, errors.Is(err, sdkerrors.Wrap(types.ErrInvalidCollateralAsset, "collateral asset cannot be the same as the borrowed asset in a short position"))) + + err = k.CheckShortAssets(ctx, ptypes.ATOM, "btc") + assert.True(t, errors.Is(err, sdkerrors.Wrap(types.ErrInvalidCollateralAsset, "collateral asset for a short position must be the base currency"))) + + // Expect no error + mockChecker.AssertExpectations(t) +} + +func TestCheckShortAssets_ValidAssets(t *testing.T) { + // Setup the mock checker + mockChecker := new(mocks.OpenShortChecker) + + // Create an instance of Keeper with the mock checker + k := keeper.Keeper{ + OpenShortChecker: mockChecker, + } + + ctx := sdk.Context{} // mock or setup a context + + // Test valid case for short position + err := k.CheckShortAssets(ctx, ptypes.BaseCurrency, ptypes.ATOM) + assert.Nil(t, err) + + // Expect no error + mockChecker.AssertExpectations(t) +} diff --git a/x/margin/keeper/open.go b/x/margin/keeper/open.go index 7d29d3878..eb202afa7 100644 --- a/x/margin/keeper/open.go +++ b/x/margin/keeper/open.go @@ -7,8 +7,18 @@ import ( ) func (k Keeper) Open(ctx sdk.Context, msg *types.MsgOpen) (*types.MsgOpenResponse, error) { - if err := k.OpenChecker.CheckLongingAssets(ctx, msg.CollateralAsset, msg.BorrowAsset); err != nil { - return nil, err + // Determine the type of position (long or short) and validate assets accordingly. + switch msg.Position { + case types.Position_LONG: + if err := k.OpenChecker.CheckLongAssets(ctx, msg.CollateralAsset, msg.BorrowAsset); err != nil { + return nil, err + } + case types.Position_SHORT: + if err := k.OpenChecker.CheckShortAssets(ctx, msg.CollateralAsset, msg.BorrowAsset); err != nil { + return nil, err + } + default: + return nil, sdkerrors.Wrap(types.ErrInvalidPosition, msg.Position.String()) } if err := k.OpenChecker.CheckUserAuthorization(ctx, msg); err != nil { diff --git a/x/margin/keeper/open_long_process.go b/x/margin/keeper/open_long_process.go index 6b91a61f0..d3fd4f433 100644 --- a/x/margin/keeper/open_long_process.go +++ b/x/margin/keeper/open_long_process.go @@ -8,24 +8,29 @@ import ( ) func (k Keeper) ProcessOpenLong(ctx sdk.Context, mtp *types.MTP, leverage sdk.Dec, eta sdk.Dec, collateralAmountDec sdk.Dec, poolId uint64, msg *types.MsgOpen) (*types.MTP, error) { - // Get token asset other than base currency + // Determine the trading asset. tradingAsset := k.OpenLongChecker.GetTradingAsset(msg.CollateralAsset, msg.BorrowAsset) + // Fetch the pool associated with the given pool ID. pool, found := k.OpenLongChecker.GetPool(ctx, poolId) if !found { return nil, sdkerrors.Wrap(types.ErrPoolDoesNotExist, tradingAsset) } + // Check if the pool is enabled. if !k.OpenLongChecker.IsPoolEnabled(ctx, poolId) { return nil, sdkerrors.Wrap(types.ErrMTPDisabled, tradingAsset) } + // Fetch the corresponding AMM (Automated Market Maker) pool. ammPool, err := k.OpenLongChecker.GetAmmPool(ctx, poolId, tradingAsset) if err != nil { return nil, err } + // Calculate the leveraged amount based on the collateral provided and the leverage. leveragedAmount := sdk.NewInt(collateralAmountDec.Mul(leverage).TruncateInt().Int64()) + // If collateral is not base currency, calculate the borrowing amount in base currency and check the balance if msg.CollateralAsset != ptypes.BaseCurrency { custodyAmtToken := sdk.NewCoin(msg.CollateralAsset, leveragedAmount) @@ -42,12 +47,14 @@ func (k Keeper) ProcessOpenLong(ctx sdk.Context, mtp *types.MTP, leverage sdk.De } } + // Check minimum liabilities. collateralTokenAmt := sdk.NewCoin(msg.CollateralAsset, msg.CollateralAmount) err = k.OpenLongChecker.CheckMinLiabilities(ctx, collateralTokenAmt, eta, pool, ammPool, msg.BorrowAsset) if err != nil { return nil, err } + // Calculate custody amount. leveragedAmtTokenIn := sdk.NewCoin(msg.CollateralAsset, leveragedAmount) custodyAmount, err := k.OpenLongChecker.EstimateSwap(ctx, leveragedAmtTokenIn, msg.BorrowAsset, ammPool) if err != nil { @@ -59,26 +66,34 @@ func (k Keeper) ProcessOpenLong(ctx sdk.Context, mtp *types.MTP, leverage sdk.De custodyAmount = leveragedAmount } + // Ensure the AMM pool has enough balance. if !k.OpenLongChecker.HasSufficientPoolBalance(ctx, ammPool, msg.BorrowAsset, custodyAmount) { return nil, sdkerrors.Wrap(types.ErrCustodyTooHigh, custodyAmount.String()) } + // Borrow the asset the user wants to long. err = k.OpenLongChecker.Borrow(ctx, msg.CollateralAsset, msg.BorrowAsset, msg.CollateralAmount, custodyAmount, mtp, &ammPool, &pool, eta) if err != nil { return nil, err } + + // Update the pool health. if err = k.OpenLongChecker.UpdatePoolHealth(ctx, &pool); err != nil { return nil, err } + + // Take custody from the pool balance. if err = k.OpenLongChecker.TakeInCustody(ctx, *mtp, &pool); err != nil { return nil, err } + // Update the MTP health. lr, err := k.OpenLongChecker.UpdateMTPHealth(ctx, *mtp, ammPool) if err != nil { return nil, err } + // Check if the MTP is unhealthy safetyFactor := k.OpenLongChecker.GetSafetyFactor(ctx) if lr.LTE(safetyFactor) { return nil, types.ErrMTPUnhealthy diff --git a/x/margin/keeper/open_short_process.go b/x/margin/keeper/open_short_process.go index 7ed5c0642..d497882e1 100644 --- a/x/margin/keeper/open_short_process.go +++ b/x/margin/keeper/open_short_process.go @@ -6,7 +6,7 @@ import ( ) func (k Keeper) ProcessOpenShort(ctx sdk.Context, mtp *types.MTP, leverage sdk.Dec, eta sdk.Dec, collateralAmountDec sdk.Dec, poolId uint64, msg *types.MsgOpen) (*types.MTP, error) { - // // Determine the trading asset. + // Determine the trading asset. // tradingAsset := k.OpenShortChecker.GetTradingAsset(msg.CollateralAsset, msg.BorrowAsset) // // Fetch the pool associated with the given pool ID. @@ -30,9 +30,12 @@ func (k Keeper) ProcessOpenShort(ctx sdk.Context, mtp *types.MTP, leverage sdk.D // leveragedAmount := sdk.NewInt(collateralAmountDec.Mul(leverage).TruncateInt().Int64()) // // Borrow the asset the user wants to short. - // // ... (Logic to borrow the asset; error handling) ... + // // err = k.OpenLongChecker.Borrow(ctx, msg.CollateralAsset, msg.BorrowAsset, msg.CollateralAmount, custodyAmount, mtp, &ammPool, &pool, eta) + // // if err != nil { + // // return nil, err + // // } - // // Swap the borrowed asset for base currency. + // // Calculate the custody amount. // swappedAmount, err := k.OpenShortChecker.EstimateSwap(ctx, leveragedAmount, ptypes.BaseCurrency, ammPool) // if err != nil { // return nil, err diff --git a/x/margin/keeper/open_test.go b/x/margin/keeper/open_test.go index 5f60d32ff..9e174492a 100644 --- a/x/margin/keeper/open_test.go +++ b/x/margin/keeper/open_test.go @@ -13,7 +13,7 @@ import ( "github.com/stretchr/testify/assert" ) -func TestOpen_ErrorCheckLongingAssets(t *testing.T) { +func TestOpen_ErrorCheckLongAssets(t *testing.T) { // Setup the mock checker mockChecker := new(mocks.OpenChecker) @@ -27,11 +27,12 @@ func TestOpen_ErrorCheckLongingAssets(t *testing.T) { msg = &types.MsgOpen{ CollateralAsset: "aaa", BorrowAsset: "bbb", + Position: types.Position_LONG, } ) // Mock behavior - mockChecker.On("CheckLongingAssets", ctx, msg.CollateralAsset, msg.BorrowAsset).Return(sdkerrors.Wrap(types.ErrInvalidBorrowingAsset, "invalid borrowing asset")) + mockChecker.On("CheckLongAssets", ctx, msg.CollateralAsset, msg.BorrowAsset).Return(sdkerrors.Wrap(types.ErrInvalidBorrowingAsset, "invalid borrowing asset")) _, err := k.Open(ctx, msg) @@ -53,11 +54,12 @@ func TestOpen_ErrorCheckUserAuthorization(t *testing.T) { msg = &types.MsgOpen{ CollateralAsset: "aaa", BorrowAsset: "bbb", + Position: types.Position_LONG, } ) // Mock behavior - mockChecker.On("CheckLongingAssets", ctx, msg.CollateralAsset, msg.BorrowAsset).Return(nil) + mockChecker.On("CheckLongAssets", ctx, msg.CollateralAsset, msg.BorrowAsset).Return(nil) mockChecker.On("CheckUserAuthorization", ctx, msg).Return(sdkerrors.Wrap(types.ErrUnauthorised, "unauthorised")) _, err := k.Open(ctx, msg) @@ -87,7 +89,7 @@ func TestOpen_ErrorCheckMaxOpenPositions(t *testing.T) { ) // Mock behavior - mockChecker.On("CheckLongingAssets", ctx, msg.CollateralAsset, msg.BorrowAsset).Return(nil) + mockChecker.On("CheckLongAssets", ctx, msg.CollateralAsset, msg.BorrowAsset).Return(nil) mockChecker.On("CheckUserAuthorization", ctx, msg).Return(nil) mockChecker.On("CheckSamePosition", ctx, msg).Return(nil) mockChecker.On("CheckMaxOpenPositions", ctx).Return(sdkerrors.Wrap(types.ErrMaxOpenPositions, "cannot open new positions")) @@ -119,7 +121,7 @@ func TestOpen_ErrorPreparePools(t *testing.T) { ) // Mock behavior - mockChecker.On("CheckLongingAssets", ctx, msg.CollateralAsset, msg.BorrowAsset).Return(nil) + mockChecker.On("CheckLongAssets", ctx, msg.CollateralAsset, msg.BorrowAsset).Return(nil) mockChecker.On("CheckUserAuthorization", ctx, msg).Return(nil) mockChecker.On("CheckSamePosition", ctx, msg).Return(nil) mockChecker.On("CheckMaxOpenPositions", ctx).Return(nil) @@ -146,12 +148,13 @@ func TestOpen_ErrorCheckPoolHealth(t *testing.T) { msg = &types.MsgOpen{ CollateralAsset: "aaa", BorrowAsset: "bbb", + Position: types.Position_LONG, } poolId = uint64(1) ) // Mock behavior - mockChecker.On("CheckLongingAssets", ctx, msg.CollateralAsset, msg.BorrowAsset).Return(nil) + mockChecker.On("CheckLongAssets", ctx, msg.CollateralAsset, msg.BorrowAsset).Return(nil) mockChecker.On("CheckUserAuthorization", ctx, msg).Return(nil) mockChecker.On("CheckSamePosition", ctx, msg).Return(nil) mockChecker.On("CheckMaxOpenPositions", ctx).Return(nil) @@ -180,18 +183,8 @@ func TestOpen_ErrorInvalidPosition(t *testing.T) { CollateralAsset: "aaa", BorrowAsset: "bbb", } - poolId = uint64(1) ) - // Mock behavior - mockChecker.On("CheckLongingAssets", ctx, msg.CollateralAsset, msg.BorrowAsset).Return(nil) - mockChecker.On("CheckUserAuthorization", ctx, msg).Return(nil) - mockChecker.On("CheckSamePosition", ctx, msg).Return(nil) - mockChecker.On("CheckMaxOpenPositions", ctx).Return(nil) - mockChecker.On("GetTradingAsset", msg.CollateralAsset, msg.BorrowAsset).Return(msg.BorrowAsset) - mockChecker.On("PreparePools", ctx, msg.BorrowAsset).Return(poolId, ammtypes.Pool{}, types.Pool{}, nil) - mockChecker.On("CheckPoolHealth", ctx, poolId).Return(nil) - _, err := k.Open(ctx, msg) assert.True(t, errors.Is(err, types.ErrInvalidPosition)) @@ -218,7 +211,7 @@ func TestOpen_ErrorOpenLong(t *testing.T) { ) // Mock behavior - mockChecker.On("CheckLongingAssets", ctx, msg.CollateralAsset, msg.BorrowAsset).Return(nil) + mockChecker.On("CheckLongAssets", ctx, msg.CollateralAsset, msg.BorrowAsset).Return(nil) mockChecker.On("CheckUserAuthorization", ctx, msg).Return(nil) mockChecker.On("CheckSamePosition", ctx, msg).Return(nil) mockChecker.On("CheckMaxOpenPositions", ctx).Return(nil) @@ -253,7 +246,7 @@ func TestOpen_ErrorOpenShort(t *testing.T) { ) // Mock behavior - mockChecker.On("CheckLongingAssets", ctx, msg.CollateralAsset, msg.BorrowAsset).Return(nil) + mockChecker.On("CheckShortAssets", ctx, msg.CollateralAsset, msg.BorrowAsset).Return(nil) mockChecker.On("CheckUserAuthorization", ctx, msg).Return(nil) mockChecker.On("CheckSamePosition", ctx, msg).Return(nil) mockChecker.On("CheckMaxOpenPositions", ctx).Return(nil) @@ -289,7 +282,7 @@ func TestOpen_Successful(t *testing.T) { ) // Mock behavior - mockChecker.On("CheckLongingAssets", ctx, msg.CollateralAsset, msg.BorrowAsset).Return(nil) + mockChecker.On("CheckShortAssets", ctx, msg.CollateralAsset, msg.BorrowAsset).Return(nil) mockChecker.On("CheckUserAuthorization", ctx, msg).Return(nil) mockChecker.On("CheckSamePosition", ctx, msg).Return(nil) mockChecker.On("CheckMaxOpenPositions", ctx).Return(nil) diff --git a/x/margin/types/expected_keepers.go b/x/margin/types/expected_keepers.go index 899be375b..54b7c9647 100644 --- a/x/margin/types/expected_keepers.go +++ b/x/margin/types/expected_keepers.go @@ -29,7 +29,8 @@ type PoolChecker interface { //go:generate mockery --srcpkg . --name OpenChecker --structname OpenChecker --filename open_checker.go --with-expecter type OpenChecker interface { - CheckLongingAssets(ctx sdk.Context, collateralAsset string, borrowAsset string) error + CheckLongAssets(ctx sdk.Context, collateralAsset string, borrowAsset string) error + CheckShortAssets(ctx sdk.Context, collateralAsset string, borrowAsset string) error CheckUserAuthorization(ctx sdk.Context, msg *MsgOpen) error CheckMaxOpenPositions(ctx sdk.Context) error GetTradingAsset(collateralAsset string, borrowAsset string) string @@ -62,7 +63,7 @@ type OpenLongChecker interface { GetSafetyFactor(ctx sdk.Context) sdk.Dec SetPool(ctx sdk.Context, pool Pool) GetAmmPoolBalance(ctx sdk.Context, ammPool ammtypes.Pool, assetDenom string) (sdk.Int, error) - CheckLongingAssets(ctx sdk.Context, collateralAsset string, borrowAsset string) error + CheckLongAssets(ctx sdk.Context, collateralAsset string, borrowAsset string) error CheckSamePosition(ctx sdk.Context, msg *MsgOpen) *MTP SetMTP(ctx sdk.Context, mtp *MTP) error CalcMTPConsolidateCollateral(ctx sdk.Context, mtp *MTP) error diff --git a/x/margin/types/mocks/open_checker.go b/x/margin/types/mocks/open_checker.go index 9d8510243..668b328c9 100644 --- a/x/margin/types/mocks/open_checker.go +++ b/x/margin/types/mocks/open_checker.go @@ -24,8 +24,8 @@ func (_m *OpenChecker) EXPECT() *OpenChecker_Expecter { return &OpenChecker_Expecter{mock: &_m.Mock} } -// CheckLongingAssets provides a mock function with given fields: ctx, collateralAsset, borrowAsset -func (_m *OpenChecker) CheckLongingAssets(ctx types.Context, collateralAsset string, borrowAsset string) error { +// CheckLongAssets provides a mock function with given fields: ctx, collateralAsset, borrowAsset +func (_m *OpenChecker) CheckLongAssets(ctx types.Context, collateralAsset string, borrowAsset string) error { ret := _m.Called(ctx, collateralAsset, borrowAsset) var r0 error @@ -38,32 +38,32 @@ func (_m *OpenChecker) CheckLongingAssets(ctx types.Context, collateralAsset str return r0 } -// OpenChecker_CheckLongingAssets_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CheckLongingAssets' -type OpenChecker_CheckLongingAssets_Call struct { +// OpenChecker_CheckLongAssets_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CheckLongAssets' +type OpenChecker_CheckLongAssets_Call struct { *mock.Call } -// CheckLongingAssets is a helper method to define mock.On call +// CheckLongAssets is a helper method to define mock.On call // - ctx types.Context // - collateralAsset string // - borrowAsset string -func (_e *OpenChecker_Expecter) CheckLongingAssets(ctx interface{}, collateralAsset interface{}, borrowAsset interface{}) *OpenChecker_CheckLongingAssets_Call { - return &OpenChecker_CheckLongingAssets_Call{Call: _e.mock.On("CheckLongingAssets", ctx, collateralAsset, borrowAsset)} +func (_e *OpenChecker_Expecter) CheckLongAssets(ctx interface{}, collateralAsset interface{}, borrowAsset interface{}) *OpenChecker_CheckLongAssets_Call { + return &OpenChecker_CheckLongAssets_Call{Call: _e.mock.On("CheckLongAssets", ctx, collateralAsset, borrowAsset)} } -func (_c *OpenChecker_CheckLongingAssets_Call) Run(run func(ctx types.Context, collateralAsset string, borrowAsset string)) *OpenChecker_CheckLongingAssets_Call { +func (_c *OpenChecker_CheckLongAssets_Call) Run(run func(ctx types.Context, collateralAsset string, borrowAsset string)) *OpenChecker_CheckLongAssets_Call { _c.Call.Run(func(args mock.Arguments) { run(args[0].(types.Context), args[1].(string), args[2].(string)) }) return _c } -func (_c *OpenChecker_CheckLongingAssets_Call) Return(_a0 error) *OpenChecker_CheckLongingAssets_Call { +func (_c *OpenChecker_CheckLongAssets_Call) Return(_a0 error) *OpenChecker_CheckLongAssets_Call { _c.Call.Return(_a0) return _c } -func (_c *OpenChecker_CheckLongingAssets_Call) RunAndReturn(run func(types.Context, string, string) error) *OpenChecker_CheckLongingAssets_Call { +func (_c *OpenChecker_CheckLongAssets_Call) RunAndReturn(run func(types.Context, string, string) error) *OpenChecker_CheckLongAssets_Call { _c.Call.Return(run) return _c } @@ -198,6 +198,50 @@ func (_c *OpenChecker_CheckSamePosition_Call) RunAndReturn(run func(types.Contex return _c } +// CheckShortAssets provides a mock function with given fields: ctx, collateralAsset, borrowAsset +func (_m *OpenChecker) CheckShortAssets(ctx types.Context, collateralAsset string, borrowAsset string) error { + ret := _m.Called(ctx, collateralAsset, borrowAsset) + + var r0 error + if rf, ok := ret.Get(0).(func(types.Context, string, string) error); ok { + r0 = rf(ctx, collateralAsset, borrowAsset) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// OpenChecker_CheckShortAssets_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CheckShortAssets' +type OpenChecker_CheckShortAssets_Call struct { + *mock.Call +} + +// CheckShortAssets is a helper method to define mock.On call +// - ctx types.Context +// - collateralAsset string +// - borrowAsset string +func (_e *OpenChecker_Expecter) CheckShortAssets(ctx interface{}, collateralAsset interface{}, borrowAsset interface{}) *OpenChecker_CheckShortAssets_Call { + return &OpenChecker_CheckShortAssets_Call{Call: _e.mock.On("CheckShortAssets", ctx, collateralAsset, borrowAsset)} +} + +func (_c *OpenChecker_CheckShortAssets_Call) Run(run func(ctx types.Context, collateralAsset string, borrowAsset string)) *OpenChecker_CheckShortAssets_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(string), args[2].(string)) + }) + return _c +} + +func (_c *OpenChecker_CheckShortAssets_Call) Return(_a0 error) *OpenChecker_CheckShortAssets_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *OpenChecker_CheckShortAssets_Call) RunAndReturn(run func(types.Context, string, string) error) *OpenChecker_CheckShortAssets_Call { + _c.Call.Return(run) + return _c +} + // CheckUserAuthorization provides a mock function with given fields: ctx, msg func (_m *OpenChecker) CheckUserAuthorization(ctx types.Context, msg *margintypes.MsgOpen) error { ret := _m.Called(ctx, msg) diff --git a/x/margin/types/mocks/open_long_checker.go b/x/margin/types/mocks/open_long_checker.go index 696a37310..0c2ee21a0 100644 --- a/x/margin/types/mocks/open_long_checker.go +++ b/x/margin/types/mocks/open_long_checker.go @@ -153,8 +153,8 @@ func (_c *OpenLongChecker_CalcMTPConsolidateLiability_Call) RunAndReturn(run fun return _c } -// CheckLongingAssets provides a mock function with given fields: ctx, collateralAsset, borrowAsset -func (_m *OpenLongChecker) CheckLongingAssets(ctx types.Context, collateralAsset string, borrowAsset string) error { +// CheckLongAssets provides a mock function with given fields: ctx, collateralAsset, borrowAsset +func (_m *OpenLongChecker) CheckLongAssets(ctx types.Context, collateralAsset string, borrowAsset string) error { ret := _m.Called(ctx, collateralAsset, borrowAsset) var r0 error @@ -167,32 +167,32 @@ func (_m *OpenLongChecker) CheckLongingAssets(ctx types.Context, collateralAsset return r0 } -// OpenLongChecker_CheckLongingAssets_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CheckLongingAssets' -type OpenLongChecker_CheckLongingAssets_Call struct { +// OpenLongChecker_CheckLongAssets_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CheckLongAssets' +type OpenLongChecker_CheckLongAssets_Call struct { *mock.Call } -// CheckLongingAssets is a helper method to define mock.On call +// CheckLongAssets is a helper method to define mock.On call // - ctx types.Context // - collateralAsset string // - borrowAsset string -func (_e *OpenLongChecker_Expecter) CheckLongingAssets(ctx interface{}, collateralAsset interface{}, borrowAsset interface{}) *OpenLongChecker_CheckLongingAssets_Call { - return &OpenLongChecker_CheckLongingAssets_Call{Call: _e.mock.On("CheckLongingAssets", ctx, collateralAsset, borrowAsset)} +func (_e *OpenLongChecker_Expecter) CheckLongAssets(ctx interface{}, collateralAsset interface{}, borrowAsset interface{}) *OpenLongChecker_CheckLongAssets_Call { + return &OpenLongChecker_CheckLongAssets_Call{Call: _e.mock.On("CheckLongAssets", ctx, collateralAsset, borrowAsset)} } -func (_c *OpenLongChecker_CheckLongingAssets_Call) Run(run func(ctx types.Context, collateralAsset string, borrowAsset string)) *OpenLongChecker_CheckLongingAssets_Call { +func (_c *OpenLongChecker_CheckLongAssets_Call) Run(run func(ctx types.Context, collateralAsset string, borrowAsset string)) *OpenLongChecker_CheckLongAssets_Call { _c.Call.Run(func(args mock.Arguments) { run(args[0].(types.Context), args[1].(string), args[2].(string)) }) return _c } -func (_c *OpenLongChecker_CheckLongingAssets_Call) Return(_a0 error) *OpenLongChecker_CheckLongingAssets_Call { +func (_c *OpenLongChecker_CheckLongAssets_Call) Return(_a0 error) *OpenLongChecker_CheckLongAssets_Call { _c.Call.Return(_a0) return _c } -func (_c *OpenLongChecker_CheckLongingAssets_Call) RunAndReturn(run func(types.Context, string, string) error) *OpenLongChecker_CheckLongingAssets_Call { +func (_c *OpenLongChecker_CheckLongAssets_Call) RunAndReturn(run func(types.Context, string, string) error) *OpenLongChecker_CheckLongAssets_Call { _c.Call.Return(run) return _c } From 6d828d7ef3c95351d472b7d15e079f0caf280169 Mon Sep 17 00:00:00 2001 From: kenta-elys Date: Wed, 20 Sep 2023 09:29:15 +0000 Subject: [PATCH 4/4] fix: issue with staking hook handling and burning amount calculation --- config.yml | 1 + docs/static/openapi.yml | 9 ++ proto/elys/incentive/params.proto | 2 + x/incentive/keeper/abci.go | 6 + x/incentive/keeper/hooks_staking.go | 4 +- x/incentive/keeper/keeper_burn_edenB.go | 32 ++-- x/incentive/keeper/keeper_burn_edenB_test.go | 158 +++++++++++++++++++ x/incentive/types/genesis.go | 2 +- x/incentive/types/params.go | 44 ++++-- x/incentive/types/params.pb.go | 92 +++++++---- 10 files changed, 299 insertions(+), 51 deletions(-) create mode 100644 x/incentive/keeper/keeper_burn_edenB_test.go diff --git a/config.yml b/config.yml index 770e65a91..a8c80126b 100644 --- a/config.yml +++ b/config.yml @@ -238,6 +238,7 @@ genesis: withdraw_addr_enabled: true reward_portion_for_lps: "0.65" pool_infos: [] + elys_stake_tracking_rate: "10" fee_pool: community_pool: - amount: "0" diff --git a/docs/static/openapi.yml b/docs/static/openapi.yml index 1717056b1..ae44dc8e2 100644 --- a/docs/static/openapi.yml +++ b/docs/static/openapi.yml @@ -38979,6 +38979,9 @@ paths: title: |- Pool information poolId, reward wallet, mulitplier + elys_stake_tracking_rate: + type: string + format: int64 description: >- QueryParamsResponse is response type for the Query/Params RPC method. @@ -78818,6 +78821,9 @@ definitions: title: |- Pool information poolId, reward wallet, mulitplier + elys_stake_tracking_rate: + type: string + format: int64 description: Params defines the parameters for the module. elys.incentive.PoolInfo: type: object @@ -78938,6 +78944,9 @@ definitions: title: |- Pool information poolId, reward wallet, mulitplier + elys_stake_tracking_rate: + type: string + format: int64 description: QueryParamsResponse is response type for the Query/Params RPC method. elys.liquidityprovider.Params: type: object diff --git a/proto/elys/incentive/params.proto b/proto/elys/incentive/params.proto index 6e8f0ff80..05f445d09 100644 --- a/proto/elys/incentive/params.proto +++ b/proto/elys/incentive/params.proto @@ -28,4 +28,6 @@ message Params { // Pool information // poolId, reward wallet, mulitplier repeated PoolInfo pool_infos = 6 [(gogoproto.nullable) = false]; + + int64 elys_stake_tracking_rate = 7; } diff --git a/x/incentive/keeper/abci.go b/x/incentive/keeper/abci.go index 8aa538757..150059152 100644 --- a/x/incentive/keeper/abci.go +++ b/x/incentive/keeper/abci.go @@ -29,6 +29,12 @@ import ( // EndBlocker of incentive module func (k Keeper) EndBlocker(ctx sdk.Context) { defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyEndBlocker) + params := k.GetParams(ctx) + // Update Elys staked amount every n blocks + if params.ElysStakeTrackingRate == 0 || ctx.BlockHeight()%params.ElysStakeTrackingRate != 0 { + return + } + // Track the amount of Elys staked k.cmk.IterateCommitments( ctx, func(commitments ctypes.Commitments) bool { diff --git a/x/incentive/keeper/hooks_staking.go b/x/incentive/keeper/hooks_staking.go index abd2c0b79..ef76f14ba 100644 --- a/x/incentive/keeper/hooks_staking.go +++ b/x/incentive/keeper/hooks_staking.go @@ -26,11 +26,11 @@ func (k Keeper) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, } func (k Keeper) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { - return k.BurnEdenBFromElysUnstaking(ctx, delAddr) + return nil } func (k Keeper) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { - return k.BurnEdenBFromElysUnstaking(ctx, delAddr) + return nil } // ________________________________________________________________________________________ diff --git a/x/incentive/keeper/keeper_burn_edenB.go b/x/incentive/keeper/keeper_burn_edenB.go index b313d3d29..b3d06fb29 100644 --- a/x/incentive/keeper/keeper_burn_edenB.go +++ b/x/incentive/keeper/keeper_burn_edenB.go @@ -2,7 +2,6 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ptypes "github.com/elys-network/elys/x/parameter/types" ) @@ -11,20 +10,23 @@ func (k Keeper) BurnEdenBFromElysUnstaking(ctx sdk.Context, delegator sdk.AccAdd delAddr := delegator.String() // Get commitments commitments, found := k.cmk.GetCommitments(ctx, delAddr) + // should return nil otherwise it will break staking module if !found { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid address %s", delegator.String()) + return nil } // Get previous amount prevElysStaked, found := k.GetElysStaked(ctx, delAddr) + // should return nil otherwise it will break staking module if !found { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid address %s", delegator.String()) + return nil } // Calculate current delegated amount of delegator delegatedAmt := k.CalculateDelegatedAmount(ctx, delAddr) // If not unstaked, + // should return nil otherwise it will break staking module if delegatedAmt.GTE(prevElysStaked.Amount) { return nil } @@ -41,10 +43,15 @@ func (k Keeper) BurnEdenBFromElysUnstaking(ctx sdk.Context, delegator sdk.AccAdd // Unstaked unstakedElys := prevElysStaked.Amount.Sub(delegatedAmt) - edenBToBurn := unstakedElys.Quo(edenCommitted.Add(prevElysStaked.Amount)).Mul(totalEdenB) + unstakedElysDec := sdk.NewDecFromInt(unstakedElys) + edenCommittedAndElysStakedDec := sdk.NewDecFromInt(edenCommitted.Add(prevElysStaked.Amount)) + totalEdenBDec := sdk.NewDecFromInt(totalEdenB) + edenBToBurn := unstakedElysDec.Quo(edenCommittedAndElysStakedDec).Mul(totalEdenBDec) // Burn EdenB ( Deduction EdenB in commitment module) - _, err := k.cmk.DeductCommitments(ctx, delAddr, ptypes.EdenB, edenBToBurn) + commitment, err := k.cmk.DeductCommitments(ctx, delAddr, ptypes.EdenB, edenBToBurn.TruncateInt()) + k.cmk.SetCommitments(ctx, commitment) + return err } @@ -53,12 +60,13 @@ func (k Keeper) BurnEdenBFromEdenUncommitted(ctx sdk.Context, delegator string, // Get elys staked amount elysStaked, found := k.GetElysStaked(ctx, delegator) if !found { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid address %s", delegator) + return nil } commitments, found := k.cmk.GetCommitments(ctx, delegator) + // should return nil otherwise it will break commitment module if !found { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid address %s", delegator) + return nil } edenCommitted := commitments.GetCommittedAmountForDenom(ptypes.Eden) @@ -70,9 +78,15 @@ func (k Keeper) BurnEdenBFromEdenUncommitted(ctx sdk.Context, delegator string, // Total EdenB amount totalEdenB := edenBCommitted.Add(edenBUncommitted) - edenBToBurn := uncommittedAmt.Quo(edenCommitted.Add(elysStaked.Amount)).Mul(totalEdenB) + uncommittedAmtDec := sdk.NewDecFromInt(uncommittedAmt) + edenCommittedAndElysStakedDec := sdk.NewDecFromInt(edenCommitted.Add(elysStaked.Amount)) + totalEdenBDec := sdk.NewDecFromInt(totalEdenB) + + edenBToBurn := uncommittedAmtDec.Quo(edenCommittedAndElysStakedDec).Mul(totalEdenBDec) // Burn EdenB ( Deduction EdenB in commitment module) - _, err := k.cmk.DeductCommitments(ctx, delegator, ptypes.EdenB, edenBToBurn) + commitment, err := k.cmk.DeductCommitments(ctx, delegator, ptypes.EdenB, edenBToBurn.TruncateInt()) + k.cmk.SetCommitments(ctx, commitment) + return err } diff --git a/x/incentive/keeper/keeper_burn_edenB_test.go b/x/incentive/keeper/keeper_burn_edenB_test.go new file mode 100644 index 000000000..7b37fb811 --- /dev/null +++ b/x/incentive/keeper/keeper_burn_edenB_test.go @@ -0,0 +1,158 @@ +package keeper_test + +import ( + "testing" + + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + sdk "github.com/cosmos/cosmos-sdk/types" + simapp "github.com/elys-network/elys/app" + aptypes "github.com/elys-network/elys/x/assetprofile/types" + commkeeper "github.com/elys-network/elys/x/commitment/keeper" + ctypes "github.com/elys-network/elys/x/commitment/types" + ptypes "github.com/elys-network/elys/x/parameter/types" + "github.com/stretchr/testify/require" +) + +func TestBurnEdenBFromElysUnstaked(t *testing.T) { + app, genAccount, valAddr := simapp.InitElysTestAppWithGenAccount() + ctx := app.BaseApp.NewContext(initChain, tmproto.Header{}) + + ik, sk := app.IncentiveKeeper, app.StakingKeeper + + var committed []sdk.Coins + var uncommitted []sdk.Coins + + // Prepare uncommitted tokens + uedenToken := sdk.NewCoins(sdk.NewCoin(ptypes.Eden, sdk.NewInt(2000))) + uedenBToken := sdk.NewCoins(sdk.NewCoin(ptypes.EdenB, sdk.NewInt(20000))) + uncommitted = append(uncommitted, uedenToken) + uncommitted = append(uncommitted, uedenBToken) + + // Eden + err := app.BankKeeper.MintCoins(ctx, ctypes.ModuleName, uedenToken) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, ctypes.ModuleName, genAccount, uedenToken) + require.NoError(t, err) + + // EdenB + err = app.BankKeeper.MintCoins(ctx, ctypes.ModuleName, uedenBToken) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, ctypes.ModuleName, genAccount, uedenBToken) + require.NoError(t, err) + + // Prepare committed tokens + uedenToken = sdk.NewCoins(sdk.NewCoin(ptypes.Eden, sdk.NewInt(10000))) + uedenBToken = sdk.NewCoins(sdk.NewCoin(ptypes.EdenB, sdk.NewInt(5000))) + committed = append(committed, uedenToken) + committed = append(committed, uedenBToken) + + // Eden + err = app.BankKeeper.MintCoins(ctx, ctypes.ModuleName, uedenToken) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, ctypes.ModuleName, genAccount, uedenToken) + require.NoError(t, err) + + // EdenB + err = app.BankKeeper.MintCoins(ctx, ctypes.ModuleName, uedenBToken) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, ctypes.ModuleName, genAccount, uedenBToken) + require.NoError(t, err) + + // Add testing commitment + simapp.AddTestCommitment(app, ctx, genAccount, committed, uncommitted) + + commitment, found := app.CommitmentKeeper.GetCommitments(ctx, genAccount.String()) + require.True(t, found) + require.Equal(t, commitment.UncommittedTokens[1].Denom, ptypes.EdenB) + require.Equal(t, commitment.UncommittedTokens[1].Amount, sdk.NewInt(20000)) + + // Track Elys staked amount + ik.EndBlocker(ctx) + + // burn amount = 100000 (unbonded amt) / (1000000 (elys staked) + 10000 (Eden committed)) * (20000 EdenB + 5000 EdenB committed) + unbondAmt, err := sk.Unbond(ctx, genAccount, valAddr, sdk.NewDecWithPrec(10, 2)) + require.Equal(t, unbondAmt, sdk.NewInt(100000)) + + commitment, found = app.CommitmentKeeper.GetCommitments(ctx, genAccount.String()) + require.True(t, found) + + require.Equal(t, commitment.UncommittedTokens[1].Denom, ptypes.EdenB) + require.Equal(t, commitment.UncommittedTokens[1].Amount, sdk.NewInt(17525)) +} + +func TestBurnEdenBFromEdenUncommitted(t *testing.T) { + app, genAccount, _ := simapp.InitElysTestAppWithGenAccount() + ctx := app.BaseApp.NewContext(initChain, tmproto.Header{}) + + ik, cmk := app.IncentiveKeeper, app.CommitmentKeeper + + var committed []sdk.Coins + var uncommitted []sdk.Coins + + // Prepare uncommitted tokens + uedenToken := sdk.NewCoins(sdk.NewCoin(ptypes.Eden, sdk.NewInt(2000))) + uedenBToken := sdk.NewCoins(sdk.NewCoin(ptypes.EdenB, sdk.NewInt(20000))) + uncommitted = append(uncommitted, uedenToken) + uncommitted = append(uncommitted, uedenBToken) + + // Eden + err := app.BankKeeper.MintCoins(ctx, ctypes.ModuleName, uedenToken) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, ctypes.ModuleName, genAccount, uedenToken) + require.NoError(t, err) + + // EdenB + err = app.BankKeeper.MintCoins(ctx, ctypes.ModuleName, uedenBToken) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, ctypes.ModuleName, genAccount, uedenBToken) + require.NoError(t, err) + + // Prepare committed tokens + uedenToken = sdk.NewCoins(sdk.NewCoin(ptypes.Eden, sdk.NewInt(10000))) + uedenBToken = sdk.NewCoins(sdk.NewCoin(ptypes.EdenB, sdk.NewInt(5000))) + committed = append(committed, uedenToken) + committed = append(committed, uedenBToken) + + // Eden + err = app.BankKeeper.MintCoins(ctx, ctypes.ModuleName, uedenToken) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, ctypes.ModuleName, genAccount, uedenToken) + require.NoError(t, err) + + // EdenB + err = app.BankKeeper.MintCoins(ctx, ctypes.ModuleName, uedenBToken) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, ctypes.ModuleName, genAccount, uedenBToken) + require.NoError(t, err) + + // Add testing commitment + simapp.AddTestCommitment(app, ctx, genAccount, committed, uncommitted) + + commitment, found := app.CommitmentKeeper.GetCommitments(ctx, genAccount.String()) + require.True(t, found) + require.Equal(t, commitment.UncommittedTokens[1].Denom, ptypes.EdenB) + require.Equal(t, commitment.UncommittedTokens[1].Amount, sdk.NewInt(20000)) + + // Track Elys staked amount + ik.EndBlocker(ctx) + + // Set assetprofile entry for denom + app.AssetprofileKeeper.SetEntry(ctx, aptypes.Entry{BaseDenom: ptypes.Eden, CommitEnabled: true}) + + msg := &ctypes.MsgUncommitTokens{ + Creator: genAccount.String(), + Amount: sdk.NewInt(1000), + Denom: ptypes.Eden, + } + + msgServer := commkeeper.NewMsgServerImpl(cmk) + _, err = msgServer.UncommitTokens(sdk.WrapSDKContext(ctx), msg) + require.NoError(t, err) + + // burn amount = 1000 (uncommitted amt) / (1000000 (elys staked) + 10000 (Eden committed)) * (20000 EdenB + 5000 EdenB committed) + commitment, found = app.CommitmentKeeper.GetCommitments(ctx, genAccount.String()) + require.True(t, found) + + require.Equal(t, commitment.UncommittedTokens[1].Denom, ptypes.EdenB) + require.Equal(t, commitment.UncommittedTokens[1].Amount, sdk.NewInt(19976)) +} diff --git a/x/incentive/types/genesis.go b/x/incentive/types/genesis.go index 1e2878c81..62f1d161e 100644 --- a/x/incentive/types/genesis.go +++ b/x/incentive/types/genesis.go @@ -26,7 +26,7 @@ func DefaultGenesis() *GenesisState { // failure. func (gs GenesisState) Validate() error { // this line is used by starport scaffolding # genesis/types/validate - if err := gs.Params.ValidateBasic(); err != nil { + if err := gs.Params.Validate(); err != nil { return err } diff --git a/x/incentive/types/params.go b/x/incentive/types/params.go index bcf33541b..e190299d2 100644 --- a/x/incentive/types/params.go +++ b/x/incentive/types/params.go @@ -13,12 +13,13 @@ var _ paramtypes.ParamSet = (*Params)(nil) // Parameter keys var ( - ParamStoreKeyCommunityTax = []byte("communitytax") - ParamStoreKeyWithdrawAddrEnabled = []byte("withdrawaddrenabled") - ParamStoreKeyRewardPortionForLps = []byte("rewardportionforlps") - ParamStoreKeyLPIncentives = []byte("lpincentives") - ParamStoreKeyStkIncentives = []byte("stkincentives") - ParamStoreKeyPoolInfos = []byte("poolinfos") + ParamStoreKeyCommunityTax = []byte("communitytax") + ParamStoreKeyWithdrawAddrEnabled = []byte("withdrawaddrenabled") + ParamStoreKeyRewardPortionForLps = []byte("rewardportionforlps") + ParamStoreKeyLPIncentives = []byte("lpincentives") + ParamStoreKeyStkIncentives = []byte("stkincentives") + ParamStoreKeyPoolInfos = []byte("poolinfos") + ParamStoreKeyElysStakeTrackingRate = []byte("elysstaketrackingrate") ) // ParamKeyTable the param key table for launch module @@ -29,12 +30,13 @@ func ParamKeyTable() paramtypes.KeyTable { // NewParams creates a new Params instance func NewParams() Params { return Params{ - LpIncentives: []IncentiveInfo(nil), - StakeIncentives: []IncentiveInfo(nil), - CommunityTax: sdk.NewDecWithPrec(2, 2), // 2% - WithdrawAddrEnabled: true, - RewardPortionForLps: sdk.NewDecWithPrec(65, 2), - PoolInfos: []PoolInfo(nil), + LpIncentives: []IncentiveInfo(nil), + StakeIncentives: []IncentiveInfo(nil), + CommunityTax: sdk.NewDecWithPrec(2, 2), // 2% + WithdrawAddrEnabled: true, + RewardPortionForLps: sdk.NewDecWithPrec(65, 2), + PoolInfos: []PoolInfo(nil), + ElysStakeTrackingRate: 10, } } @@ -52,11 +54,16 @@ func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { paramtypes.NewParamSetPair(ParamStoreKeyLPIncentives, &p.LpIncentives, validateLPIncentives), paramtypes.NewParamSetPair(ParamStoreKeyStkIncentives, &p.StakeIncentives, validateStakeIncentives), paramtypes.NewParamSetPair(ParamStoreKeyPoolInfos, &p.PoolInfos, validatePoolInfos), + paramtypes.NewParamSetPair(ParamStoreKeyElysStakeTrackingRate, &p.ElysStakeTrackingRate, validateElysStakeTrakcingRate), } } // Validate validates the set of params func (p Params) Validate() error { + if err := p.ValidateBasic(); err != nil { + return err + } + if err := validateCommunityTax(p.CommunityTax); err != nil { return err } @@ -81,6 +88,10 @@ func (p Params) Validate() error { return err } + if err := validateElysStakeTrakcingRate(p.ElysStakeTrackingRate); err != nil { + return err + } + return nil } @@ -228,3 +239,12 @@ func validatePoolInfos(i interface{}) error { return nil } + +func validateElysStakeTrakcingRate(i interface{}) error { + _, ok := i.(int64) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + return nil +} diff --git a/x/incentive/types/params.pb.go b/x/incentive/types/params.pb.go index ade36d298..874d06fae 100644 --- a/x/incentive/types/params.pb.go +++ b/x/incentive/types/params.pb.go @@ -34,7 +34,8 @@ type Params struct { RewardPortionForLps github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=reward_portion_for_lps,json=rewardPortionForLps,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"reward_portion_for_lps"` // Pool information // poolId, reward wallet, mulitplier - PoolInfos []PoolInfo `protobuf:"bytes,6,rep,name=pool_infos,json=poolInfos,proto3" json:"pool_infos"` + PoolInfos []PoolInfo `protobuf:"bytes,6,rep,name=pool_infos,json=poolInfos,proto3" json:"pool_infos"` + ElysStakeTrackingRate int64 `protobuf:"varint,7,opt,name=elys_stake_tracking_rate,json=elysStakeTrackingRate,proto3" json:"elys_stake_tracking_rate,omitempty"` } func (m *Params) Reset() { *m = Params{} } @@ -97,6 +98,13 @@ func (m *Params) GetPoolInfos() []PoolInfo { return nil } +func (m *Params) GetElysStakeTrackingRate() int64 { + if m != nil { + return m.ElysStakeTrackingRate + } + return 0 +} + func init() { proto.RegisterType((*Params)(nil), "elys.incentive.Params") } @@ -104,32 +112,35 @@ func init() { func init() { proto.RegisterFile("elys/incentive/params.proto", fileDescriptor_3bca0267cb466fec) } var fileDescriptor_3bca0267cb466fec = []byte{ - // 398 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x92, 0xc1, 0xef, 0xd2, 0x30, - 0x14, 0xc7, 0x37, 0x41, 0x22, 0x15, 0xd4, 0x0c, 0x35, 0x13, 0xe3, 0x20, 0x1e, 0x0c, 0x17, 0xba, - 0x04, 0x6f, 0x26, 0x1e, 0x24, 0x6a, 0x20, 0x31, 0x86, 0xa0, 0x27, 0x2f, 0x4d, 0x59, 0x0b, 0x2c, - 0x6c, 0x7d, 0x4d, 0x5b, 0x1c, 0xfc, 0x17, 0x1e, 0x3d, 0xfa, 0xe7, 0x70, 0xe4, 0x62, 0x62, 0x3c, - 0x10, 0x03, 0xff, 0x88, 0xd9, 0x06, 0xcb, 0xe4, 0x64, 0x7e, 0xa7, 0xbe, 0xd7, 0xef, 0xeb, 0xe7, - 0x7d, 0xf3, 0xfa, 0xd0, 0x53, 0x1e, 0x6d, 0xb5, 0x1f, 0x8a, 0x80, 0x0b, 0x13, 0x7e, 0xe5, 0xbe, - 0xa4, 0x8a, 0xc6, 0x1a, 0x4b, 0x05, 0x06, 0x9c, 0x7b, 0xa9, 0x88, 0x0b, 0xb1, 0xfd, 0x70, 0x01, - 0x0b, 0xc8, 0x24, 0x3f, 0x8d, 0xf2, 0xaa, 0xb6, 0x77, 0x85, 0x28, 0xa2, 0xb3, 0xfe, 0xe4, 0xba, - 0x05, 0x40, 0x94, 0x4b, 0xcf, 0x7f, 0x56, 0x50, 0x6d, 0x92, 0x75, 0x74, 0x46, 0xa8, 0x19, 0x49, - 0x52, 0x54, 0x69, 0xd7, 0xee, 0x56, 0x7a, 0x77, 0x07, 0xcf, 0xf0, 0xbf, 0x1e, 0xf0, 0xf8, 0x12, - 0x8d, 0xc5, 0x1c, 0x86, 0xd5, 0xdd, 0xa1, 0x63, 0x4d, 0x1b, 0x91, 0x2c, 0xae, 0xb5, 0xf3, 0x11, - 0x3d, 0xd0, 0x86, 0xae, 0x78, 0x19, 0x76, 0xeb, 0xff, 0x61, 0xf7, 0xb3, 0xc7, 0x25, 0xde, 0x27, - 0xd4, 0x0c, 0x20, 0x8e, 0xd7, 0x22, 0x34, 0x5b, 0x62, 0xe8, 0xc6, 0xad, 0x74, 0xed, 0x5e, 0x7d, - 0x88, 0xd3, 0xea, 0xdf, 0x87, 0xce, 0x8b, 0x45, 0x68, 0x96, 0xeb, 0x19, 0x0e, 0x20, 0xf6, 0x03, - 0xd0, 0x31, 0xe8, 0xf3, 0xd1, 0xd7, 0x6c, 0xe5, 0x9b, 0xad, 0xe4, 0x1a, 0xbf, 0xe5, 0xc1, 0xb4, - 0x51, 0x40, 0x3e, 0xd3, 0x8d, 0x33, 0x40, 0x8f, 0x92, 0xd0, 0x2c, 0x99, 0xa2, 0x09, 0xa1, 0x8c, - 0x29, 0xc2, 0x05, 0x9d, 0x45, 0x9c, 0xb9, 0xd5, 0xae, 0xdd, 0xbb, 0x33, 0x6d, 0x5d, 0xc4, 0x37, - 0x8c, 0xa9, 0x77, 0xb9, 0xe4, 0x04, 0xe8, 0xb1, 0xe2, 0x09, 0x55, 0x8c, 0x48, 0x50, 0x26, 0x04, - 0x41, 0xe6, 0xa0, 0x48, 0x24, 0xb5, 0x7b, 0xfb, 0x46, 0x8e, 0x5a, 0x39, 0x6d, 0x92, 0xc3, 0xde, - 0x83, 0xfa, 0x20, 0xb5, 0xf3, 0x1a, 0xa1, 0xf4, 0x83, 0x48, 0x28, 0xe6, 0xa0, 0xdd, 0x5a, 0x36, - 0x37, 0xf7, 0x7a, 0x6e, 0x13, 0x80, 0xa8, 0x34, 0xb2, 0xba, 0x3c, 0xe7, 0xfa, 0x55, 0xf5, 0xfb, - 0x8f, 0x8e, 0x35, 0x1c, 0xed, 0x8e, 0x9e, 0xbd, 0x3f, 0x7a, 0xf6, 0x9f, 0xa3, 0x67, 0x7f, 0x3b, - 0x79, 0xd6, 0xfe, 0xe4, 0x59, 0xbf, 0x4e, 0x9e, 0xf5, 0x05, 0x97, 0xbc, 0xa5, 0xd0, 0xbe, 0xe0, - 0x26, 0x01, 0xb5, 0xca, 0x12, 0x7f, 0x53, 0x5a, 0x93, 0xcc, 0xe7, 0xac, 0x96, 0x2d, 0xca, 0xcb, - 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x0b, 0x38, 0x21, 0x0a, 0xa8, 0x02, 0x00, 0x00, + // 435 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x92, 0xc1, 0x6e, 0xd3, 0x30, + 0x18, 0xc7, 0x13, 0x5a, 0x0a, 0x33, 0x1b, 0xa0, 0x8c, 0x21, 0x33, 0x44, 0x5a, 0x71, 0x40, 0xbd, + 0xcc, 0x91, 0xc6, 0x01, 0x09, 0x89, 0x03, 0x15, 0xa0, 0x4d, 0x42, 0xa8, 0xca, 0x76, 0xe2, 0x62, + 0xb9, 0xb1, 0xdb, 0x59, 0x4d, 0xfc, 0x59, 0xb6, 0x47, 0xdb, 0x97, 0x40, 0x1c, 0x39, 0xf2, 0x38, + 0x3b, 0xee, 0x88, 0x38, 0x4c, 0xa8, 0x7d, 0x11, 0xe4, 0xa4, 0x8d, 0x42, 0x4f, 0x88, 0x53, 0x3e, + 0xe7, 0xf7, 0xf7, 0xcf, 0xf6, 0x67, 0xa3, 0xa7, 0x22, 0x5f, 0xd8, 0x44, 0xaa, 0x4c, 0x28, 0x27, + 0xbf, 0x88, 0x44, 0x33, 0xc3, 0x0a, 0x4b, 0xb4, 0x01, 0x07, 0xd1, 0x7d, 0x0f, 0x49, 0x0d, 0x0f, + 0x1f, 0x4d, 0x60, 0x02, 0x25, 0x4a, 0x7c, 0x55, 0xa5, 0x0e, 0xe3, 0x2d, 0x45, 0x5d, 0xad, 0xf9, + 0x93, 0xed, 0x25, 0x00, 0xf2, 0x0a, 0x3d, 0xff, 0xda, 0x46, 0x9d, 0x61, 0xb9, 0x62, 0x74, 0x82, + 0xf6, 0x72, 0x4d, 0xeb, 0x94, 0xc5, 0x61, 0xaf, 0xd5, 0xbf, 0x77, 0xfc, 0x8c, 0xfc, 0xbd, 0x07, + 0x72, 0xba, 0xa9, 0x4e, 0xd5, 0x18, 0x06, 0xed, 0xab, 0x9b, 0x6e, 0x90, 0xee, 0xe6, 0xba, 0xfe, + 0x6d, 0xa3, 0x4f, 0xe8, 0xa1, 0x75, 0x6c, 0x2a, 0x9a, 0xb2, 0x5b, 0xff, 0x2e, 0x7b, 0x50, 0x4e, + 0x6e, 0xf8, 0xce, 0xd0, 0x5e, 0x06, 0x45, 0x71, 0xa9, 0xa4, 0x5b, 0x50, 0xc7, 0xe6, 0xb8, 0xd5, + 0x0b, 0xfb, 0x3b, 0x03, 0xe2, 0xd3, 0xbf, 0x6e, 0xba, 0x2f, 0x26, 0xd2, 0x5d, 0x5c, 0x8e, 0x48, + 0x06, 0x45, 0x92, 0x81, 0x2d, 0xc0, 0xae, 0x3f, 0x47, 0x96, 0x4f, 0x13, 0xb7, 0xd0, 0xc2, 0x92, + 0x77, 0x22, 0x4b, 0x77, 0x6b, 0xc9, 0x39, 0x9b, 0x47, 0xc7, 0xe8, 0x60, 0x26, 0xdd, 0x05, 0x37, + 0x6c, 0x46, 0x19, 0xe7, 0x86, 0x0a, 0xc5, 0x46, 0xb9, 0xe0, 0xb8, 0xdd, 0x0b, 0xfb, 0x77, 0xd3, + 0xfd, 0x0d, 0x7c, 0xcb, 0xb9, 0x79, 0x5f, 0xa1, 0x28, 0x43, 0x8f, 0x8d, 0x98, 0x31, 0xc3, 0xa9, + 0x06, 0xe3, 0x24, 0x28, 0x3a, 0x06, 0x43, 0x73, 0x6d, 0xf1, 0xed, 0xff, 0xda, 0xd1, 0x7e, 0x65, + 0x1b, 0x56, 0xb2, 0x0f, 0x60, 0x3e, 0x6a, 0x1b, 0xbd, 0x41, 0xc8, 0x5f, 0x10, 0x95, 0x6a, 0x0c, + 0x16, 0x77, 0xca, 0xbe, 0xe1, 0xed, 0xbe, 0x0d, 0x01, 0xf2, 0x46, 0xcb, 0x76, 0xf4, 0x7a, 0x6c, + 0xa3, 0x57, 0x08, 0xfb, 0x2c, 0xad, 0x6e, 0xc0, 0x19, 0x96, 0x4d, 0xa5, 0x9a, 0x50, 0xc3, 0x9c, + 0xc0, 0x77, 0x7a, 0x61, 0xbf, 0x95, 0x1e, 0x78, 0x7e, 0xe6, 0xf1, 0xf9, 0x9a, 0xa6, 0xcc, 0x89, + 0xd7, 0xed, 0xef, 0x3f, 0xba, 0xc1, 0xe0, 0xe4, 0x6a, 0x19, 0x87, 0xd7, 0xcb, 0x38, 0xfc, 0xbd, + 0x8c, 0xc3, 0x6f, 0xab, 0x38, 0xb8, 0x5e, 0xc5, 0xc1, 0xcf, 0x55, 0x1c, 0x7c, 0x26, 0x8d, 0x43, + 0x79, 0xc3, 0x91, 0x12, 0x6e, 0x06, 0x66, 0x5a, 0x0e, 0x92, 0x79, 0xe3, 0x7d, 0x95, 0x07, 0x1c, + 0x75, 0xca, 0x17, 0xf6, 0xf2, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xcb, 0xb6, 0x05, 0x1f, 0xe1, + 0x02, 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { @@ -152,6 +163,11 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.ElysStakeTrackingRate != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.ElysStakeTrackingRate)) + i-- + dAtA[i] = 0x38 + } if len(m.PoolInfos) > 0 { for iNdEx := len(m.PoolInfos) - 1; iNdEx >= 0; iNdEx-- { { @@ -269,6 +285,9 @@ func (m *Params) Size() (n int) { n += 1 + l + sovParams(uint64(l)) } } + if m.ElysStakeTrackingRate != 0 { + n += 1 + sovParams(uint64(m.ElysStakeTrackingRate)) + } return n } @@ -497,6 +516,25 @@ func (m *Params) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 7: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ElysStakeTrackingRate", wireType) + } + m.ElysStakeTrackingRate = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ElysStakeTrackingRate |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } default: iNdEx = preIndex skippy, err := skipParams(dAtA[iNdEx:])