diff --git a/app/app.go b/app/app.go index 137c51458..371f0f4b4 100644 --- a/app/app.go +++ b/app/app.go @@ -158,6 +158,10 @@ import ( marginmodulekeeper "github.com/elys-network/elys/x/margin/keeper" marginmoduletypes "github.com/elys-network/elys/x/margin/types" + accountedpoolmodule "github.com/elys-network/elys/x/accountedpool" + accountedpoolmodulekeeper "github.com/elys-network/elys/x/accountedpool/keeper" + accountedpoolmoduletypes "github.com/elys-network/elys/x/accountedpool/types" + // this line is used by starport scaffolding # stargate/app/moduleImport "github.com/elys-network/elys/docs" @@ -257,6 +261,7 @@ var ( ammmodule.AppModuleBasic{}, parametermodule.AppModuleBasic{}, marginmodule.AppModuleBasic{}, + accountedpoolmodule.AppModuleBasic{}, // this line is used by starport scaffolding # stargate/app/moduleBasic ) @@ -351,6 +356,8 @@ type ElysApp struct { AmmKeeper ammmodulekeeper.Keeper ParameterKeeper parametermodulekeeper.Keeper MarginKeeper marginmodulekeeper.Keeper + + AccountedPoolKeeper accountedpoolmodulekeeper.Keeper // this line is used by starport scaffolding # stargate/app/keeperDeclaration // mm is the module manager @@ -415,6 +422,7 @@ func NewElysApp( tokenomicsmoduletypes.StoreKey, incentivemoduletypes.StoreKey, burnermoduletypes.StoreKey, + accountedpoolmoduletypes.StoreKey, ammmoduletypes.StoreKey, parametermoduletypes.StoreKey, marginmoduletypes.StoreKey, @@ -667,6 +675,15 @@ func NewElysApp( app.AssetprofileKeeper, ) + app.AccountedPoolKeeper = *accountedpoolmodulekeeper.NewKeeper( + appCodec, + keys[accountedpoolmoduletypes.StoreKey], + keys[accountedpoolmoduletypes.MemStoreKey], + app.GetSubspace(accountedpoolmoduletypes.ModuleName), + app.BankKeeper, + ) + accountedPoolModule := accountedpoolmodule.NewAppModule(appCodec, app.AccountedPoolKeeper, app.AccountKeeper, app.BankKeeper) + app.AmmKeeper = *ammmodulekeeper.NewKeeper( appCodec, keys[ammmoduletypes.StoreKey], @@ -677,6 +694,7 @@ func NewElysApp( app.OracleKeeper, &app.CommitmentKeeper, app.AssetprofileKeeper, + app.AccountedPoolKeeper, ) ammModule := ammmodule.NewAppModule(appCodec, app.AmmKeeper, app.AccountKeeper, app.BankKeeper) @@ -859,6 +877,7 @@ func NewElysApp( ammmoduletypes.NewMultiAmmHooks( // insert amm hooks receivers here app.IncentiveKeeper.AmmHooks(), + app.MarginKeeper.AmmHooks(), ), ) @@ -869,10 +888,18 @@ func NewElysApp( app.CommitmentKeeper.Hooks(), app.IncentiveKeeper.Hooks(), app.BurnerKeeper.Hooks(), + app.MarginKeeper.Hooks(), ), ) epochsModule := epochsmodule.NewAppModule(appCodec, app.EpochsKeeper) + app.MarginKeeper.SetHooks( + marginmoduletypes.NewMultiMarginHooks( + // insert margin hooks receivers here + app.AccountedPoolKeeper.MarginHooks(), + ), + ) + /**** Module Options ****/ // NOTE: we may consider parsing `appOpts` inside module constructors. For the moment @@ -918,6 +945,7 @@ func NewElysApp( ammModule, parameterModule, marginModule, + accountedPoolModule, // this line is used by starport scaffolding # stargate/app/appModule ) @@ -960,6 +988,7 @@ func NewElysApp( parametermoduletypes.ModuleName, marginmoduletypes.ModuleName, wasm.ModuleName, + accountedpoolmoduletypes.ModuleName, // this line is used by starport scaffolding # stargate/app/beginBlockers ) @@ -997,6 +1026,7 @@ func NewElysApp( parametermoduletypes.ModuleName, marginmoduletypes.ModuleName, wasm.ModuleName, + accountedpoolmoduletypes.ModuleName, // this line is used by starport scaffolding # stargate/app/endBlockers ) @@ -1038,6 +1068,7 @@ func NewElysApp( parametermoduletypes.ModuleName, marginmoduletypes.ModuleName, wasm.ModuleName, + accountedpoolmoduletypes.ModuleName, // this line is used by starport scaffolding # stargate/app/initGenesis } app.mm.SetOrderInitGenesis(genesisModuleOrder...) @@ -1333,6 +1364,7 @@ func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino paramsKeeper.Subspace(ammmoduletypes.ModuleName) paramsKeeper.Subspace(parametermoduletypes.ModuleName) paramsKeeper.Subspace(marginmoduletypes.ModuleName) + paramsKeeper.Subspace(accountedpoolmoduletypes.ModuleName) // this line is used by starport scaffolding # stargate/app/paramSubspace return paramsKeeper diff --git a/app/setup_handlers.go b/app/setup_handlers.go index c45314fb2..1b32775e7 100644 --- a/app/setup_handlers.go +++ b/app/setup_handlers.go @@ -16,6 +16,7 @@ import ( slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + accountedpooltypes "github.com/elys-network/elys/x/accountedpool/types" ammtypes "github.com/elys-network/elys/x/amm/types" assetprofiletypes "github.com/elys-network/elys/x/assetprofile/types" burnertypes "github.com/elys-network/elys/x/burner/types" @@ -77,6 +78,8 @@ func setUpgradeHandler(app *ElysApp) { keyTable = parametertypes.ParamKeyTable() //nolint:staticcheck case tokenomicstypes.ModuleName: keyTable = tokenomicstypes.ParamKeyTable() //nolint:staticcheck + case accountedpooltypes.ModuleName: + keyTable = accountedpooltypes.ParamKeyTable() //nolint:staticcheck } if !subspace.HasKeyTable() { diff --git a/config.yml b/config.yml index a7e4a4de6..50bebb8af 100644 --- a/config.yml +++ b/config.yml @@ -357,5 +357,6 @@ genesis: sq_modifier: "1.0" safety_factor: "1.0" incremental_interest_payment_enabled: true - whitelisting_enabled: true + whitelisting_enabled: false + invariant_check_epoch: day chain_id: elystestnet-1 diff --git a/docs/static/openapi.yml b/docs/static/openapi.yml index 0bfad83c7..1906e6417 100644 --- a/docs/static/openapi.yml +++ b/docs/static/openapi.yml @@ -37237,6 +37237,286 @@ paths: type: boolean tags: - Query + /elys-network/elys/accountedpool/accounted_pool: + get: + operationId: ElysAccountedpoolAccountedPoolAll + responses: + '200': + description: A successful response. + schema: + type: object + properties: + accountedPool: + type: array + items: + type: object + properties: + poolId: + type: string + format: uint64 + totalShares: + 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. + poolAssets: + type: array + items: + type: object + properties: + token: + 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. + weight: + type: string + totalWeight: + type: string + pagination: + type: object + properties: + next_key: + type: string + format: byte + description: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently. It will be empty if + there are no more results. + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: >- + PageResponse is to be embedded in gRPC response messages where + the + + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + 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: pagination.key + description: |- + key is a value returned in PageResponse.next_key to begin + querying the next page most efficiently. Only one of offset or key + should be set. + in: query + required: false + type: string + format: byte + - name: pagination.offset + description: >- + offset is a numeric offset that can be used when key is unavailable. + + It is less efficient than using key. Only one of offset or key + should + + be set. + in: query + required: false + type: string + format: uint64 + - name: pagination.limit + description: >- + limit is the total number of results to be returned in the result + page. + + If left empty it will default to a value to be set by each app. + in: query + required: false + type: string + format: uint64 + - name: pagination.count_total + description: >- + count_total is set to true to indicate that the result set should + include + + a count of the total number of items available for pagination in + UIs. + + count_total is only respected when offset is used. It is ignored + when key + + is set. + in: query + required: false + type: boolean + - name: pagination.reverse + description: >- + reverse is set to true if results are to be returned in the + descending order. + + + Since: cosmos-sdk 0.43 + in: query + required: false + type: boolean + tags: + - Query + /elys-network/elys/accountedpool/accounted_pool/{poolId}: + get: + summary: Queries a list of AccountedPool items. + operationId: ElysAccountedpoolAccountedPool + responses: + '200': + description: A successful response. + schema: + type: object + properties: + accountedPool: + type: object + properties: + poolId: + type: string + format: uint64 + totalShares: + 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. + poolAssets: + type: array + items: + type: object + properties: + token: + 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. + weight: + type: string + totalWeight: + type: string + 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: poolId + in: path + required: true + type: string + format: uint64 + tags: + - Query + /elys-network/elys/accountedpool/params: + get: + summary: Parameters queries the parameters of the module. + operationId: ElysAccountedpoolParams + responses: + '200': + description: A successful response. + schema: + type: object + properties: + params: + description: params holds all the parameters of this module. + type: object + description: >- + QueryParamsResponse is response type for the Query/Params RPC + method. + 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: {} + tags: + - Query /elys-network/elys/amm/denom_liquidity: get: operationId: ElysAmmDenomLiquidityAll @@ -39246,6 +39526,8 @@ paths: type: boolean whitelisting_enabled: type: boolean + invariant_check_epoch: + type: string description: ParamsResponse is response type for the Query/Params RPC method. default: description: An unexpected error response. @@ -77123,6 +77405,199 @@ definitions: title: |- QuerySmartContractStateResponse is the response type for the Query/SmartContractState RPC method + elys.accountedpool.AccountedPool: + type: object + properties: + poolId: + type: string + format: uint64 + totalShares: + 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. + poolAssets: + type: array + items: + type: object + properties: + token: + 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. + weight: + type: string + totalWeight: + type: string + elys.accountedpool.Params: + type: object + description: Params defines the parameters for the module. + elys.accountedpool.QueryAllAccountedPoolResponse: + type: object + properties: + accountedPool: + type: array + items: + type: object + properties: + poolId: + type: string + format: uint64 + totalShares: + 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. + poolAssets: + type: array + items: + type: object + properties: + token: + 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. + weight: + type: string + totalWeight: + type: string + pagination: + type: object + properties: + next_key: + type: string + format: byte + description: |- + next_key is the key to be passed to PageRequest.key to + query the next page most efficiently. It will be empty if + there are no more results. + total: + type: string + format: uint64 + title: >- + total is total number of results available if + PageRequest.count_total + + was set, its value is undefined otherwise + description: |- + PageResponse is to be embedded in gRPC response messages where the + corresponding request message has used PageRequest. + + message SomeResponse { + repeated Bar results = 1; + PageResponse page = 2; + } + elys.accountedpool.QueryGetAccountedPoolResponse: + type: object + properties: + accountedPool: + type: object + properties: + poolId: + type: string + format: uint64 + totalShares: + 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. + poolAssets: + type: array + items: + type: object + properties: + token: + 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. + weight: + type: string + totalWeight: + type: string + elys.accountedpool.QueryParamsResponse: + type: object + properties: + params: + description: params holds all the parameters of this module. + type: object + description: QueryParamsResponse is response type for the Query/Params RPC method. + elys.amm.PoolAsset: + type: object + properties: + token: + 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. + weight: + type: string elys.amm.DenomLiquidity: type: object properties: @@ -77259,23 +77734,6 @@ definitions: type: string rebalanceTreasury: type: string - elys.amm.PoolAsset: - type: object - properties: - token: - 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. - weight: - type: string elys.amm.PoolParams: type: object properties: @@ -78519,6 +78977,8 @@ definitions: type: boolean whitelisting_enabled: type: boolean + invariant_check_epoch: + type: string description: Params defines the parameters for the module. elys.margin.ParamsResponse: type: object @@ -78565,6 +79025,8 @@ definitions: type: boolean whitelisting_enabled: type: boolean + invariant_check_epoch: + type: string description: ParamsResponse is response type for the Query/Params RPC method. elys.margin.Pool: type: object diff --git a/proto/elys/accountedpool/accounted_pool.proto b/proto/elys/accountedpool/accounted_pool.proto new file mode 100644 index 000000000..5837dd639 --- /dev/null +++ b/proto/elys/accountedpool/accounted_pool.proto @@ -0,0 +1,19 @@ +syntax = "proto3"; +package elys.accountedpool; + +option go_package = "github.com/elys-network/elys/x/accountedpool/types"; +import "elys/amm/pool_asset.proto"; +import "gogoproto/gogo.proto"; +import "cosmos/base/v1beta1/coin.proto"; +import "cosmos_proto/cosmos.proto"; + +message AccountedPool { + uint64 poolId = 1; + cosmos.base.v1beta1.Coin totalShares = 2 [(gogoproto.nullable) = false]; + repeated elys.amm.PoolAsset poolAssets = 3 [(gogoproto.nullable) = false]; + string totalWeight = 4 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", + (gogoproto.nullable) = false + ]; +} + diff --git a/proto/elys/accountedpool/genesis.proto b/proto/elys/accountedpool/genesis.proto new file mode 100644 index 000000000..e2aea03fd --- /dev/null +++ b/proto/elys/accountedpool/genesis.proto @@ -0,0 +1,16 @@ +syntax = "proto3"; + +package elys.accountedpool; + +import "gogoproto/gogo.proto"; +import "elys/accountedpool/params.proto"; +import "elys/accountedpool/accounted_pool.proto"; + +option go_package = "github.com/elys-network/elys/x/accountedpool/types"; + +// GenesisState defines the tvl module's genesis state. +message GenesisState { + Params params = 1 [(gogoproto.nullable) = false]; + repeated AccountedPool accountedPoolList = 2 [(gogoproto.nullable) = false]; +} + diff --git a/proto/elys/accountedpool/params.proto b/proto/elys/accountedpool/params.proto new file mode 100644 index 000000000..280821fe6 --- /dev/null +++ b/proto/elys/accountedpool/params.proto @@ -0,0 +1,11 @@ +syntax = "proto3"; +package elys.accountedpool; + +import "gogoproto/gogo.proto"; + +option go_package = "github.com/elys-network/elys/x/accountedpool/types"; + +// Params defines the parameters for the module. +message Params { + option (gogoproto.goproto_stringer) = false; +} diff --git a/proto/elys/accountedpool/query.proto b/proto/elys/accountedpool/query.proto new file mode 100644 index 000000000..25b2b87e1 --- /dev/null +++ b/proto/elys/accountedpool/query.proto @@ -0,0 +1,58 @@ +syntax = "proto3"; + +package elys.accountedpool; + +import "gogoproto/gogo.proto"; +import "google/api/annotations.proto"; +import "cosmos/base/query/v1beta1/pagination.proto"; +import "elys/accountedpool/params.proto"; +import "elys/accountedpool/accounted_pool.proto"; + +option go_package = "github.com/elys-network/elys/x/accountedpool/types"; + +// Query defines the gRPC querier service. +service Query { + + // Parameters queries the parameters of the module. + rpc Params (QueryParamsRequest) returns (QueryParamsResponse) { + option (google.api.http).get = "/elys-network/elys/accountedpool/params"; + + } + + // Queries a list of AccountedPool items. + rpc AccountedPool (QueryGetAccountedPoolRequest) returns (QueryGetAccountedPoolResponse) { + option (google.api.http).get = "/elys-network/elys/accountedpool/accounted_pool/{poolId}"; + + } + rpc AccountedPoolAll (QueryAllAccountedPoolRequest) returns (QueryAllAccountedPoolResponse) { + option (google.api.http).get = "/elys-network/elys/accountedpool/accounted_pool"; + + } +} +// QueryParamsRequest is request type for the Query/Params RPC method. +message QueryParamsRequest {} + +// QueryParamsResponse is response type for the Query/Params RPC method. +message QueryParamsResponse { + + // params holds all the parameters of this module. + Params params = 1 [(gogoproto.nullable) = false]; +} + +message QueryGetAccountedPoolRequest { + uint64 poolId = 1; +} + +message QueryGetAccountedPoolResponse { + AccountedPool accountedPool = 1 [(gogoproto.nullable) = false]; +} + +message QueryAllAccountedPoolRequest { + cosmos.base.query.v1beta1.PageRequest pagination = 1; +} + +message QueryAllAccountedPoolResponse { + repeated AccountedPool accountedPool = 1 [(gogoproto.nullable) = false]; + cosmos.base.query.v1beta1.PageResponse pagination = 2; +} + diff --git a/proto/elys/accountedpool/tx.proto b/proto/elys/accountedpool/tx.proto new file mode 100644 index 000000000..c887e9185 --- /dev/null +++ b/proto/elys/accountedpool/tx.proto @@ -0,0 +1,7 @@ +syntax = "proto3"; +package elys.accountedpool; + +option go_package = "github.com/elys-network/elys/x/accountedpool/types"; + +// Msg defines the Msg service. +service Msg {} \ No newline at end of file diff --git a/proto/elys/margin/params.proto b/proto/elys/margin/params.proto index 263b98d89..35a6a7703 100644 --- a/proto/elys/margin/params.proto +++ b/proto/elys/margin/params.proto @@ -62,4 +62,5 @@ message Params { ]; bool incremental_interest_payment_enabled = 17; bool whitelisting_enabled = 18; + string invariant_check_epoch = 19; } diff --git a/testutil/keeper/accountedpool.go b/testutil/keeper/accountedpool.go new file mode 100644 index 000000000..a6a65dd4f --- /dev/null +++ b/testutil/keeper/accountedpool.go @@ -0,0 +1,54 @@ +package keeper + +import ( + "testing" + + tmdb "github.com/cometbft/cometbft-db" + "github.com/cometbft/cometbft/libs/log" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/store" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + typesparams "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/elys-network/elys/x/accountedpool/keeper" + "github.com/elys-network/elys/x/accountedpool/types" + "github.com/stretchr/testify/require" +) + +func AccountedPoolKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) { + storeKey := sdk.NewKVStoreKey(types.StoreKey) + memStoreKey := storetypes.NewMemoryStoreKey(types.MemStoreKey) + + db := tmdb.NewMemDB() + stateStore := store.NewCommitMultiStore(db) + stateStore.MountStoreWithDB(storeKey, storetypes.StoreTypeIAVL, db) + stateStore.MountStoreWithDB(memStoreKey, storetypes.StoreTypeMemory, nil) + require.NoError(t, stateStore.LoadLatestVersion()) + + registry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(registry) + + paramsSubspace := typesparams.NewSubspace(cdc, + types.Amino, + storeKey, + memStoreKey, + "AccountedPoolParams", + ) + k := keeper.NewKeeper( + cdc, + storeKey, + memStoreKey, + paramsSubspace, + nil, + ) + + ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, log.NewNopLogger()) + + params := types.DefaultParams() + // Initialize params + k.SetParams(ctx, ¶ms) + + return k, ctx +} diff --git a/testutil/keeper/amm.go b/testutil/keeper/amm.go index 45362a494..3c076f7b3 100644 --- a/testutil/keeper/amm.go +++ b/testutil/keeper/amm.go @@ -46,6 +46,7 @@ func AmmKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) { nil, nil, nil, + nil, ) ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, log.NewNopLogger()) diff --git a/x/accountedpool/client/cli/query.go b/x/accountedpool/client/cli/query.go new file mode 100644 index 000000000..4b4c2cd09 --- /dev/null +++ b/x/accountedpool/client/cli/query.go @@ -0,0 +1,33 @@ +package cli + +import ( + "fmt" + // "strings" + + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" + // "github.com/cosmos/cosmos-sdk/client/flags" + // sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/elys-network/elys/x/accountedpool/types" +) + +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd(queryRoute string) *cobra.Command { + // Group tvl queries under a subcommand + cmd := &cobra.Command{ + Use: types.ModuleName, + Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName), + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + cmd.AddCommand(CmdQueryParams()) + cmd.AddCommand(CmdListAccountedPool()) + cmd.AddCommand(CmdShowAccountedPool()) + // this line is used by starport scaffolding # 1 + + return cmd +} diff --git a/x/accountedpool/client/cli/query_accounted_pool.go b/x/accountedpool/client/cli/query_accounted_pool.go new file mode 100644 index 000000000..0f020443a --- /dev/null +++ b/x/accountedpool/client/cli/query_accounted_pool.go @@ -0,0 +1,84 @@ +package cli + +import ( + "strconv" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/spf13/cobra" + + "github.com/elys-network/elys/x/accountedpool/types" +) + +func CmdListAccountedPool() *cobra.Command { + cmd := &cobra.Command{ + Use: "list-accounted-pool", + Short: "list all accounted-pool", + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + + pageReq, err := client.ReadPageRequest(cmd.Flags()) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + params := &types.QueryAllAccountedPoolRequest{ + Pagination: pageReq, + } + + res, err := queryClient.AccountedPoolAll(cmd.Context(), params) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddPaginationFlagsToCmd(cmd, cmd.Use) + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +func CmdShowAccountedPool() *cobra.Command { + cmd := &cobra.Command{ + Use: "show-accounted-pool [index]", + Short: "shows a accounted-pool", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) (err error) { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + argIndex := args[0] + poolId, err := strconv.ParseUint(argIndex, 10, 64) + if err != nil { + return err + } + + params := &types.QueryGetAccountedPoolRequest{ + PoolId: poolId, + } + + res, err := queryClient.AccountedPool(cmd.Context(), params) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/x/accountedpool/client/cli/query_accounted_pool_test.go b/x/accountedpool/client/cli/query_accounted_pool_test.go new file mode 100644 index 000000000..263872bcf --- /dev/null +++ b/x/accountedpool/client/cli/query_accounted_pool_test.go @@ -0,0 +1,181 @@ +package cli_test + +import ( + "fmt" + "strconv" + "testing" + + tmcli "github.com/cometbft/cometbft/libs/cli" + "github.com/cosmos/cosmos-sdk/client/flags" + clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/elys-network/elys/testutil/network" + "github.com/elys-network/elys/testutil/nullify" + "github.com/elys-network/elys/x/accountedpool/client/cli" + "github.com/elys-network/elys/x/accountedpool/types" +) + +// Prevent strconv unused error +var _ = strconv.IntSize + +func networkWithAccountedPoolObjects(t *testing.T, n int) (*network.Network, []types.AccountedPool) { + t.Helper() + cfg := network.DefaultConfig() + state := types.GenesisState{} + for i := 0; i < n; i++ { + accountedPool := types.AccountedPool{ + PoolId: (uint64)(i), + } + nullify.Fill(&accountedPool) + state.AccountedPoolList = append(state.AccountedPoolList, accountedPool) + } + buf, err := cfg.Codec.MarshalJSON(&state) + require.NoError(t, err) + cfg.GenesisState[types.ModuleName] = buf + return network.New(t, cfg), state.AccountedPoolList +} + +func TestShowAccountedPool(t *testing.T) { + net, objs := networkWithAccountedPoolObjects(t, 2) + + ctx := net.Validators[0].ClientCtx + common := []string{ + fmt.Sprintf("--%s=json", tmcli.OutputFlag), + } + tests := []struct { + desc string + idIndex uint64 + + args []string + err error + obj types.AccountedPool + }{ + { + desc: "found", + idIndex: objs[0].PoolId, + + args: common, + obj: objs[0], + }, + { + desc: "not found", + idIndex: (uint64)(100000), + + args: common, + err: status.Error(codes.NotFound, "not found"), + }, + } + for _, tc := range tests { + t.Run(tc.desc, func(t *testing.T) { + args := []string{ + fmt.Sprintf("%d", tc.idIndex), + } + args = append(args, tc.args...) + out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdShowAccountedPool(), args) + if tc.err != nil { + stat, ok := status.FromError(tc.err) + require.True(t, ok) + require.ErrorIs(t, stat.Err(), tc.err) + } else { + require.NoError(t, err) + var resp types.QueryGetAccountedPoolResponse + require.NoError(t, net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp)) + require.NotNil(t, resp.AccountedPool) + // total weight is not set in genesis state + tc.obj.TotalWeight = resp.AccountedPool.TotalWeight + require.Equal(t, + nullify.Fill(&tc.obj), + nullify.Fill(&resp.AccountedPool), + ) + } + }) + } +} + +func TestListAccountedPool(t *testing.T) { + net, objs := networkWithAccountedPoolObjects(t, 5) + ctx := net.Validators[0].ClientCtx + const stepSize = 2 + + type RequestArgs struct { + Next []byte + Offset uint64 + Limit uint64 + Total bool + } + + request := func(args RequestArgs) []string { + var requestArgs []string + requestArgs = append(requestArgs, fmt.Sprintf("--%s=json", tmcli.OutputFlag)) + + if args.Next == nil { + requestArgs = append(requestArgs, fmt.Sprintf("--%s=%d", flags.FlagOffset, args.Offset)) + } else { + requestArgs = append(requestArgs, fmt.Sprintf("--%s=%s", flags.FlagPageKey, args.Next)) + } + + requestArgs = append(requestArgs, fmt.Sprintf("--%s=%d", flags.FlagLimit, args.Limit)) + + if args.Total { + requestArgs = append(requestArgs, fmt.Sprintf("--%s", flags.FlagCountTotal)) + } + return requestArgs + } + + executeCmdAndCheck := func(t *testing.T, args RequestArgs) (types.QueryAllAccountedPoolResponse, error) { + cmdArgs := request(args) + out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListAccountedPool(), cmdArgs) + if err != nil { + return types.QueryAllAccountedPoolResponse{}, err + } + + var resp types.QueryAllAccountedPoolResponse + err = net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp) + return resp, err + } + + t.Run("ByOffset", func(t *testing.T) { + for i := 0; i < len(objs); i += stepSize { + resp, err := executeCmdAndCheck(t, RequestArgs{Next: nil, Offset: uint64(i), Limit: uint64(stepSize), Total: false}) + require.NoError(t, err) + require.LessOrEqual(t, len(resp.AccountedPool), stepSize) + + for j, accountedPool := range resp.AccountedPool { + objs[i+j].TotalWeight = accountedPool.TotalWeight + } + + require.Subset(t, nullify.Fill(objs), nullify.Fill(resp.AccountedPool)) + } + }) + + t.Run("ByKey", func(t *testing.T) { + var next []byte + for i := 0; i < len(objs); i += stepSize { + resp, err := executeCmdAndCheck(t, RequestArgs{Next: next, Offset: 0, Limit: uint64(stepSize), Total: false}) + require.NoError(t, err) + require.LessOrEqual(t, len(resp.AccountedPool), stepSize) + + for j, accountedPool := range resp.AccountedPool { + objs[i+j].TotalWeight = accountedPool.TotalWeight + } + + require.Subset(t, nullify.Fill(objs), nullify.Fill(resp.AccountedPool)) + next = resp.Pagination.NextKey + } + }) + + t.Run("Total", func(t *testing.T) { + resp, err := executeCmdAndCheck(t, RequestArgs{Next: nil, Offset: 0, Limit: uint64(len(objs)), Total: true}) + require.NoError(t, err) + require.Equal(t, len(objs), int(resp.Pagination.Total)) + + for i, accountedPool := range resp.AccountedPool { + objs[i].TotalWeight = accountedPool.TotalWeight + } + + require.ElementsMatch(t, nullify.Fill(objs), nullify.Fill(resp.AccountedPool)) + }) +} diff --git a/x/accountedpool/client/cli/query_params.go b/x/accountedpool/client/cli/query_params.go new file mode 100644 index 000000000..5741fc1aa --- /dev/null +++ b/x/accountedpool/client/cli/query_params.go @@ -0,0 +1,36 @@ +package cli + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/spf13/cobra" + + "github.com/elys-network/elys/x/accountedpool/types" +) + +func CmdQueryParams() *cobra.Command { + cmd := &cobra.Command{ + Use: "params", + Short: "shows the parameters of the module", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + res, err := queryClient.Params(cmd.Context(), &types.QueryParamsRequest{}) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/x/accountedpool/client/cli/tx.go b/x/accountedpool/client/cli/tx.go new file mode 100644 index 000000000..781dcd4a4 --- /dev/null +++ b/x/accountedpool/client/cli/tx.go @@ -0,0 +1,36 @@ +package cli + +import ( + "fmt" + "time" + + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" + // "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/elys-network/elys/x/accountedpool/types" +) + +var ( + DefaultRelativePacketTimeoutTimestamp = uint64((time.Duration(10) * time.Minute).Nanoseconds()) +) + +const ( + flagPacketTimeoutTimestamp = "packet-timeout-timestamp" + listSeparator = "," +) + +// GetTxCmd returns the transaction commands for this module +func GetTxCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: types.ModuleName, + Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName), + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + // this line is used by starport scaffolding # 1 + + return cmd +} diff --git a/x/accountedpool/genesis.go b/x/accountedpool/genesis.go new file mode 100644 index 000000000..867ca74e8 --- /dev/null +++ b/x/accountedpool/genesis.go @@ -0,0 +1,28 @@ +package tvl + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/elys-network/elys/x/accountedpool/keeper" + "github.com/elys-network/elys/x/accountedpool/types" +) + +// InitGenesis initializes the module's state from a provided genesis state. +func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) { + // Set all the accountedPool + for _, elem := range genState.AccountedPoolList { + k.SetAccountedPool(ctx, elem) + } + // this line is used by starport scaffolding # genesis/module/init + k.SetParams(ctx, &genState.Params) +} + +// ExportGenesis returns the module's exported genesis +func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { + genesis := types.DefaultGenesis() + genesis.Params = k.GetParams(ctx) + + genesis.AccountedPoolList = k.GetAllAccountedPool(ctx) + // this line is used by starport scaffolding # genesis/module/export + + return genesis +} diff --git a/x/accountedpool/genesis_test.go b/x/accountedpool/genesis_test.go new file mode 100644 index 000000000..b90383221 --- /dev/null +++ b/x/accountedpool/genesis_test.go @@ -0,0 +1,38 @@ +package tvl_test + +import ( + "testing" + + keepertest "github.com/elys-network/elys/testutil/keeper" + "github.com/elys-network/elys/testutil/nullify" + tvl "github.com/elys-network/elys/x/accountedpool" + "github.com/elys-network/elys/x/accountedpool/types" + "github.com/stretchr/testify/require" +) + +func TestGenesis(t *testing.T) { + genesisState := types.GenesisState{ + Params: types.DefaultParams(), + + AccountedPoolList: []types.AccountedPool{ + { + PoolId: (uint64)(0), + }, + { + PoolId: (uint64)(1), + }, + }, + // this line is used by starport scaffolding # genesis/test/state + } + + k, ctx := keepertest.AccountedPoolKeeper(t) + tvl.InitGenesis(ctx, *k, genesisState) + got := tvl.ExportGenesis(ctx, *k) + require.NotNil(t, got) + + nullify.Fill(&genesisState) + nullify.Fill(got) + + require.ElementsMatch(t, genesisState.AccountedPoolList, got.AccountedPoolList) + // this line is used by starport scaffolding # genesis/test/assert +} diff --git a/x/accountedpool/keeper/accounted_pool.go b/x/accountedpool/keeper/accounted_pool.go new file mode 100644 index 000000000..5c336654f --- /dev/null +++ b/x/accountedpool/keeper/accounted_pool.go @@ -0,0 +1,71 @@ +package keeper + +import ( + "github.com/cosmos/cosmos-sdk/store/prefix" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/elys-network/elys/x/accountedpool/types" +) + +// SetAccountedPool set a specific accountedPool in the store from its index +func (k Keeper) SetAccountedPool(ctx sdk.Context, accountedPool types.AccountedPool) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.AccountedPoolKeyPrefix)) + b := k.cdc.MustMarshal(&accountedPool) + store.Set(types.AccountedPoolKey( + accountedPool.PoolId, + ), b) +} + +// GetAccountedPool returns a accountedPool from its index +func (k Keeper) GetAccountedPool( + ctx sdk.Context, + PoolId uint64, + +) (val types.AccountedPool, found bool) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.AccountedPoolKeyPrefix)) + + b := store.Get(types.AccountedPoolKey( + PoolId, + )) + + if b == nil { + return val, false + } + + k.cdc.MustUnmarshal(b, &val) + return val, true +} + +// RemoveAccountedPool removes a accountedPool from the store +func (k Keeper) RemoveAccountedPool( + ctx sdk.Context, + poolId uint64, + +) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.AccountedPoolKeyPrefix)) + store.Delete(types.AccountedPoolKey( + poolId, + )) +} + +// GetAllAccountedPool returns all accountedPool +func (k Keeper) GetAllAccountedPool(ctx sdk.Context) (list []types.AccountedPool) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.AccountedPoolKeyPrefix)) + iterator := sdk.KVStorePrefixIterator(store, []byte{}) + + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + var val types.AccountedPool + k.cdc.MustUnmarshal(iterator.Value(), &val) + list = append(list, val) + } + + return +} + +// PoolExists checks if a pool with the given poolId exists in the list of pools +func (k Keeper) PoolExists(ctx sdk.Context, poolId uint64) bool { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.AccountedPoolKeyPrefix)) + b := store.Get(types.AccountedPoolKey(poolId)) + return b != nil +} diff --git a/x/accountedpool/keeper/accounted_pool_initiate.go b/x/accountedpool/keeper/accounted_pool_initiate.go new file mode 100644 index 000000000..04ad1785c --- /dev/null +++ b/x/accountedpool/keeper/accounted_pool_initiate.go @@ -0,0 +1,34 @@ +package keeper + +import ( + "errors" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/elys-network/elys/x/accountedpool/types" + ammtypes "github.com/elys-network/elys/x/amm/types" +) + +func (k Keeper) InitiateAccountedPool(ctx sdk.Context, ammPool ammtypes.Pool) error { + poolId := ammPool.PoolId + // Check if already exists + exists := k.PoolExists(ctx, poolId) + if exists { + return errors.New("already existed pool!") + } + + // Initiate pool + accountedPool := types.AccountedPool{ + PoolId: poolId, + TotalShares: ammPool.TotalShares, + PoolAssets: []ammtypes.PoolAsset{}, + TotalWeight: ammPool.TotalWeight, + } + + for _, asset := range ammPool.PoolAssets { + accountedPool.PoolAssets = append(accountedPool.PoolAssets, asset) + } + // Set accounted pool + k.SetAccountedPool(ctx, accountedPool) + + return nil +} diff --git a/x/accountedpool/keeper/accounted_pool_test.go b/x/accountedpool/keeper/accounted_pool_test.go new file mode 100644 index 000000000..1700c5310 --- /dev/null +++ b/x/accountedpool/keeper/accounted_pool_test.go @@ -0,0 +1,67 @@ +package keeper_test + +import ( + "strconv" + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + keepertest "github.com/elys-network/elys/testutil/keeper" + "github.com/elys-network/elys/testutil/nullify" + "github.com/elys-network/elys/x/accountedpool/keeper" + "github.com/elys-network/elys/x/accountedpool/types" + ammtypes "github.com/elys-network/elys/x/amm/types" + "github.com/stretchr/testify/require" +) + +// Prevent strconv unused error +var _ = strconv.IntSize + +func createNAccountedPool(keeper *keeper.Keeper, ctx sdk.Context, n int) []types.AccountedPool { + items := make([]types.AccountedPool, n) + for i := range items { + items[i].PoolId = (uint64)(i) + items[i].TotalShares = sdk.NewCoin("lpshare", sdk.ZeroInt()) + items[i].PoolAssets = []ammtypes.PoolAsset{} + items[i].TotalWeight = sdk.ZeroInt() + + keeper.SetAccountedPool(ctx, items[i]) + } + return items +} + +func TestAccountedPoolGet(t *testing.T) { + keeper, ctx := keepertest.AccountedPoolKeeper(t) + items := createNAccountedPool(keeper, ctx, 10) + for _, item := range items { + rst, found := keeper.GetAccountedPool(ctx, + item.PoolId, + ) + require.True(t, found) + require.Equal(t, + nullify.Fill(&item), + nullify.Fill(&rst), + ) + } +} +func TestAccountedPoolRemove(t *testing.T) { + keeper, ctx := keepertest.AccountedPoolKeeper(t) + items := createNAccountedPool(keeper, ctx, 10) + for _, item := range items { + keeper.RemoveAccountedPool(ctx, + item.PoolId, + ) + _, found := keeper.GetAccountedPool(ctx, + item.PoolId, + ) + require.False(t, found) + } +} + +func TestAccountedPoolGetAll(t *testing.T) { + keeper, ctx := keepertest.AccountedPoolKeeper(t) + items := createNAccountedPool(keeper, ctx, 10) + require.ElementsMatch(t, + nullify.Fill(items), + nullify.Fill(keeper.GetAllAccountedPool(ctx)), + ) +} diff --git a/x/accountedpool/keeper/accounted_pool_update.go b/x/accountedpool/keeper/accounted_pool_update.go new file mode 100644 index 000000000..ace0666b7 --- /dev/null +++ b/x/accountedpool/keeper/accounted_pool_update.go @@ -0,0 +1,60 @@ +package keeper + +import ( + "errors" + + sdk "github.com/cosmos/cosmos-sdk/types" + ammtypes "github.com/elys-network/elys/x/amm/types" + margintypes "github.com/elys-network/elys/x/margin/types" +) + +// Get Amm Pool Balance +func (k Keeper) GetAmmPoolBalance(ammPool ammtypes.Pool, denom string) sdk.Int { + for _, asset := range ammPool.PoolAssets { + if asset.Token.Denom == denom { + return asset.Token.Amount + } + } + + return sdk.ZeroInt() +} + +// Get Margin Pool Balance +func (k Keeper) GetMarginPoolBalances(marginPool margintypes.Pool, denom string) (sdk.Int, sdk.Int, sdk.Int) { + for _, asset := range marginPool.PoolAssets { + if asset.AssetDenom == denom { + return asset.AssetBalance, asset.Liabilities, asset.Custody + } + } + + return sdk.ZeroInt(), sdk.ZeroInt(), sdk.ZeroInt() +} + +func (k Keeper) UpdateAccountedPool(ctx sdk.Context, ammPool ammtypes.Pool, marginPool margintypes.Pool) error { + poolId := ammPool.PoolId + // Check if already exists + exists := k.PoolExists(ctx, poolId) + if !exists { + return errors.New("pool doesn't exist!") + } + + // Get accounted pool + accountedPool, found := k.GetAccountedPool(ctx, poolId) + if !found { + return errors.New("pool doesn't exist!") + } + + // Accounted Pool balance = + // amm pool balance + margin pool balance + margin pool liabilties - margin pool custody + // But not deducting custody amount here as the balance was already deducted through TakeCustody function. + for i, asset := range accountedPool.PoolAssets { + aBalance := k.GetAmmPoolBalance(ammPool, asset.Token.Denom) + mBalance, mLiabiltiies, _ := k.GetMarginPoolBalances(marginPool, asset.Token.Denom) + accountedAmt := aBalance.Add(mBalance).Add(mLiabiltiies) + accountedPool.PoolAssets[i].Token = sdk.NewCoin(asset.Token.Denom, accountedAmt) + } + + // Update accounted pool + k.SetAccountedPool(ctx, accountedPool) + return nil +} diff --git a/x/accountedpool/keeper/accounted_pool_update_test.go b/x/accountedpool/keeper/accounted_pool_update_test.go new file mode 100644 index 000000000..46abc6f0d --- /dev/null +++ b/x/accountedpool/keeper/accounted_pool_update_test.go @@ -0,0 +1,89 @@ +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" + ammtypes "github.com/elys-network/elys/x/amm/types" + + "github.com/elys-network/elys/x/accountedpool/types" + margintypes "github.com/elys-network/elys/x/margin/types" + ptypes "github.com/elys-network/elys/x/parameter/types" + "github.com/stretchr/testify/require" +) + +func TestAccountedPoolUpdate(t *testing.T) { + app := simapp.InitElysTestApp(true) + ctx := app.BaseApp.NewContext(true, tmproto.Header{}) + + apk := app.AccountedPoolKeeper + + // Generate 1 random account with 1000stake balanced + addr := simapp.AddTestAddrs(app, ctx, 1, sdk.NewInt(1000000)) + + // Initiate pool + ammPool := ammtypes.Pool{ + PoolId: 0, + Address: addr[0].String(), + PoolParams: ammtypes.PoolParams{}, + TotalShares: sdk.NewCoin("lp-token", sdk.NewInt(100)), + PoolAssets: []ammtypes.PoolAsset{ + {Token: sdk.NewCoin(ptypes.ATOM, sdk.NewInt(100))}, + {Token: sdk.NewCoin(ptypes.USDC, sdk.NewInt(1000))}, + }, + TotalWeight: sdk.NewInt(100), + RebalanceTreasury: addr[0].String(), + } + // Initiate pool + accountedPool := types.AccountedPool{ + PoolId: 0, + TotalShares: ammPool.TotalShares, + PoolAssets: []ammtypes.PoolAsset{}, + TotalWeight: ammPool.TotalWeight, + } + + for _, asset := range ammPool.PoolAssets { + accountedPool.PoolAssets = append(accountedPool.PoolAssets, asset) + } + // Set accounted pool + apk.SetAccountedPool(ctx, accountedPool) + + marginPool := margintypes.Pool{ + AmmPoolId: 0, + Health: sdk.NewDec(1), + Enabled: true, + Closed: false, + InterestRate: sdk.NewDec(1), + PoolAssets: []margintypes.PoolAsset{ + { + Liabilities: sdk.NewInt(400), + Custody: sdk.NewInt(0), + AssetBalance: sdk.NewInt(100), + UnsettledLiabilities: sdk.NewInt(0), + BlockInterest: sdk.NewInt(0), + AssetDenom: ptypes.USDC, + }, + { + Liabilities: sdk.NewInt(0), + Custody: sdk.NewInt(50), + AssetBalance: sdk.NewInt(0), + UnsettledLiabilities: sdk.NewInt(0), + BlockInterest: sdk.NewInt(0), + AssetDenom: ptypes.ATOM, + }, + }, + } + // Update accounted pool + apk.UpdateAccountedPool(ctx, ammPool, marginPool) + + apool, found := apk.GetAccountedPool(ctx, (uint64)(0)) + require.Equal(t, found, true) + require.Equal(t, apool.PoolId, (uint64)(0)) + + usdcBalance := apk.GetAccountedBalance(ctx, (uint64)(0), ptypes.USDC) + require.Equal(t, usdcBalance, sdk.NewInt(1000+400+100)) + atomBalance := apk.GetAccountedBalance(ctx, (uint64)(0), ptypes.ATOM) + require.Equal(t, atomBalance, sdk.NewInt(100)) +} diff --git a/x/accountedpool/keeper/hooks_margin.go b/x/accountedpool/keeper/hooks_margin.go new file mode 100644 index 000000000..ba61058e3 --- /dev/null +++ b/x/accountedpool/keeper/hooks_margin.go @@ -0,0 +1,79 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + ammtypes "github.com/elys-network/elys/x/amm/types" + margintypes "github.com/elys-network/elys/x/margin/types" +) + +func (k Keeper) AfterMarginPositionOpended(ctx sdk.Context, ammPool ammtypes.Pool, marginPool margintypes.Pool) { + k.UpdateAccountedPool(ctx, ammPool, marginPool) +} + +func (k Keeper) AfterMarginPositionModified(ctx sdk.Context, ammPool ammtypes.Pool, marginPool margintypes.Pool) { + k.UpdateAccountedPool(ctx, ammPool, marginPool) +} + +func (k Keeper) AfterMarginPositionClosed(ctx sdk.Context, ammPool ammtypes.Pool, marginPool margintypes.Pool) { + k.UpdateAccountedPool(ctx, ammPool, marginPool) +} + +// AfterPoolCreated is called after CreatePool +func (k Keeper) AfterAmmPoolCreated(ctx sdk.Context, ammPool ammtypes.Pool) { + k.InitiateAccountedPool(ctx, ammPool) +} + +// AfterJoinPool is called after JoinPool, JoinSwapExternAmountIn, and JoinSwapShareAmountOut +func (k Keeper) AfterAmmJoinPool(ctx sdk.Context, ammPool ammtypes.Pool, marginPool margintypes.Pool) { + k.UpdateAccountedPool(ctx, ammPool, marginPool) +} + +// AfterExitPool is called after ExitPool, ExitSwapShareAmountIn, and ExitSwapExternAmountOut +func (k Keeper) AfterAmmExitPool(ctx sdk.Context, ammPool ammtypes.Pool, marginPool margintypes.Pool) { + k.UpdateAccountedPool(ctx, ammPool, marginPool) +} + +// AfterSwap is called after SwapExactAmountIn and SwapExactAmountOut +func (k Keeper) AfterAmmSwap(ctx sdk.Context, ammPool ammtypes.Pool, marginPool margintypes.Pool) { + k.UpdateAccountedPool(ctx, ammPool, marginPool) +} + +// Hooks wrapper struct for tvl keeper +type MarginHooks struct { + k Keeper +} + +var _ margintypes.MarginHooks = MarginHooks{} + +// Return the wrapper struct +func (k Keeper) MarginHooks() MarginHooks { + return MarginHooks{k} +} + +func (h MarginHooks) AfterMarginPositionOpended(ctx sdk.Context, ammPool ammtypes.Pool, marginPool margintypes.Pool) { + h.k.AfterMarginPositionOpended(ctx, ammPool, marginPool) +} + +func (h MarginHooks) AfterMarginPositionModified(ctx sdk.Context, ammPool ammtypes.Pool, marginPool margintypes.Pool) { + h.k.AfterMarginPositionModified(ctx, ammPool, marginPool) +} + +func (h MarginHooks) AfterMarginPositionClosed(ctx sdk.Context, ammPool ammtypes.Pool, marginPool margintypes.Pool) { + h.k.AfterMarginPositionClosed(ctx, ammPool, marginPool) +} + +func (h MarginHooks) AfterAmmPoolCreated(ctx sdk.Context, ammPool ammtypes.Pool) { + h.k.AfterAmmPoolCreated(ctx, ammPool) +} + +func (h MarginHooks) AfterAmmJoinPool(ctx sdk.Context, ammPool ammtypes.Pool, marginPool margintypes.Pool) { + h.k.AfterAmmJoinPool(ctx, ammPool, marginPool) +} + +func (h MarginHooks) AfterAmmExitPool(ctx sdk.Context, ammPool ammtypes.Pool, marginPool margintypes.Pool) { + h.k.AfterAmmExitPool(ctx, ammPool, marginPool) +} + +func (h MarginHooks) AfterAmmSwap(ctx sdk.Context, ammPool ammtypes.Pool, marginPool margintypes.Pool) { + h.k.AfterAmmSwap(ctx, ammPool, marginPool) +} diff --git a/x/accountedpool/keeper/keeper.go b/x/accountedpool/keeper/keeper.go new file mode 100644 index 000000000..0e7d7a43c --- /dev/null +++ b/x/accountedpool/keeper/keeper.go @@ -0,0 +1,64 @@ +package keeper + +import ( + "fmt" + + "github.com/cometbft/cometbft/libs/log" + "github.com/cosmos/cosmos-sdk/codec" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + + "github.com/elys-network/elys/x/accountedpool/types" +) + +type ( + Keeper struct { + cdc codec.BinaryCodec + storeKey storetypes.StoreKey + memKey storetypes.StoreKey + paramstore paramtypes.Subspace + bankKeeper types.BankKeeper + } +) + +func NewKeeper( + cdc codec.BinaryCodec, + storeKey, + memKey storetypes.StoreKey, + ps paramtypes.Subspace, + bk types.BankKeeper, +) *Keeper { + // set KeyTable if it has not already been set + if !ps.HasKeyTable() { + ps = ps.WithKeyTable(types.ParamKeyTable()) + } + + return &Keeper{ + cdc: cdc, + storeKey: storeKey, + memKey: memKey, + paramstore: ps, + bankKeeper: bk, + } +} + +func (k Keeper) Logger(ctx sdk.Context) log.Logger { + return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) +} + +// Get accounted pool balance +func (k Keeper) GetAccountedBalance(ctx sdk.Context, poolId uint64, denom string) sdk.Int { + pool, found := k.GetAccountedPool(ctx, poolId) + if !found { + return sdk.ZeroInt() + } + + for _, asset := range pool.PoolAssets { + if asset.Token.Denom == denom { + return asset.Token.Amount + } + } + + return sdk.ZeroInt() +} diff --git a/x/accountedpool/keeper/msg_server.go b/x/accountedpool/keeper/msg_server.go new file mode 100644 index 000000000..03ebaa0a4 --- /dev/null +++ b/x/accountedpool/keeper/msg_server.go @@ -0,0 +1,17 @@ +package keeper + +import ( + "github.com/elys-network/elys/x/accountedpool/types" +) + +type msgServer struct { + Keeper +} + +// NewMsgServerImpl returns an implementation of the MsgServer interface +// for the provided Keeper. +func NewMsgServerImpl(keeper Keeper) types.MsgServer { + return &msgServer{Keeper: keeper} +} + +var _ types.MsgServer = msgServer{} diff --git a/x/accountedpool/keeper/msg_server_test.go b/x/accountedpool/keeper/msg_server_test.go new file mode 100644 index 000000000..92fa44d85 --- /dev/null +++ b/x/accountedpool/keeper/msg_server_test.go @@ -0,0 +1,23 @@ +package keeper_test + +import ( + "context" + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + keepertest "github.com/elys-network/elys/testutil/keeper" + "github.com/elys-network/elys/x/accountedpool/keeper" + "github.com/elys-network/elys/x/accountedpool/types" + "github.com/stretchr/testify/require" +) + +func setupMsgServer(t testing.TB) (types.MsgServer, context.Context) { + k, ctx := keepertest.AccountedPoolKeeper(t) + return keeper.NewMsgServerImpl(*k), sdk.WrapSDKContext(ctx) +} + +func TestMsgServer(t *testing.T) { + ms, ctx := setupMsgServer(t) + require.NotNil(t, ms) + require.NotNil(t, ctx) +} diff --git a/x/accountedpool/keeper/params.go b/x/accountedpool/keeper/params.go new file mode 100644 index 000000000..d6e4b3554 --- /dev/null +++ b/x/accountedpool/keeper/params.go @@ -0,0 +1,34 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/elys-network/elys/x/accountedpool/types" +) + +// GetParams get all parameters as types.Params +func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.KeyPrefix(types.ParamsKey)) + if bz == nil { + return params + } + + k.cdc.MustUnmarshal(bz, ¶ms) + return params +} + +// SetParams set the params +func (k Keeper) SetParams(ctx sdk.Context, params *types.Params) error { + if err := params.Validate(); err != nil { + return err + } + + store := ctx.KVStore(k.storeKey) + bz, err := k.cdc.Marshal(params) + if err != nil { + return err + } + store.Set(types.KeyPrefix(types.ParamsKey), bz) + + return nil +} diff --git a/x/accountedpool/keeper/params_test.go b/x/accountedpool/keeper/params_test.go new file mode 100644 index 000000000..bc1bac9c8 --- /dev/null +++ b/x/accountedpool/keeper/params_test.go @@ -0,0 +1,18 @@ +package keeper_test + +import ( + "testing" + + testkeeper "github.com/elys-network/elys/testutil/keeper" + "github.com/elys-network/elys/x/accountedpool/types" + "github.com/stretchr/testify/require" +) + +func TestGetParams(t *testing.T) { + k, ctx := testkeeper.AccountedPoolKeeper(t) + params := types.DefaultParams() + + k.SetParams(ctx, ¶ms) + + require.EqualValues(t, params, k.GetParams(ctx)) +} diff --git a/x/accountedpool/keeper/query.go b/x/accountedpool/keeper/query.go new file mode 100644 index 000000000..84b949102 --- /dev/null +++ b/x/accountedpool/keeper/query.go @@ -0,0 +1,7 @@ +package keeper + +import ( + "github.com/elys-network/elys/x/accountedpool/types" +) + +var _ types.QueryServer = Keeper{} diff --git a/x/accountedpool/keeper/query_accounted_pool.go b/x/accountedpool/keeper/query_accounted_pool.go new file mode 100644 index 000000000..ea92ce937 --- /dev/null +++ b/x/accountedpool/keeper/query_accounted_pool.go @@ -0,0 +1,57 @@ +package keeper + +import ( + "context" + + "github.com/cosmos/cosmos-sdk/store/prefix" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/query" + "github.com/elys-network/elys/x/accountedpool/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func (k Keeper) AccountedPoolAll(goCtx context.Context, req *types.QueryAllAccountedPoolRequest) (*types.QueryAllAccountedPoolResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + + var accountedPools []types.AccountedPool + ctx := sdk.UnwrapSDKContext(goCtx) + + store := ctx.KVStore(k.storeKey) + accountedPoolStore := prefix.NewStore(store, types.KeyPrefix(types.AccountedPoolKeyPrefix)) + + pageRes, err := query.Paginate(accountedPoolStore, req.Pagination, func(key []byte, value []byte) error { + var accountedPool types.AccountedPool + if err := k.cdc.Unmarshal(value, &accountedPool); err != nil { + return err + } + + accountedPools = append(accountedPools, accountedPool) + return nil + }) + + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + + return &types.QueryAllAccountedPoolResponse{AccountedPool: accountedPools, Pagination: pageRes}, nil +} + +func (k Keeper) AccountedPool(goCtx context.Context, req *types.QueryGetAccountedPoolRequest) (*types.QueryGetAccountedPoolResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + ctx := sdk.UnwrapSDKContext(goCtx) + + val, found := k.GetAccountedPool( + ctx, + req.PoolId, + ) + if !found { + return nil, status.Error(codes.NotFound, "not found") + } + + return &types.QueryGetAccountedPoolResponse{AccountedPool: val}, nil +} diff --git a/x/accountedpool/keeper/query_accounted_pool_test.go b/x/accountedpool/keeper/query_accounted_pool_test.go new file mode 100644 index 000000000..ba55f0a3c --- /dev/null +++ b/x/accountedpool/keeper/query_accounted_pool_test.go @@ -0,0 +1,127 @@ +package keeper_test + +import ( + "strconv" + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/query" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + keepertest "github.com/elys-network/elys/testutil/keeper" + "github.com/elys-network/elys/testutil/nullify" + "github.com/elys-network/elys/x/accountedpool/types" +) + +// Prevent strconv unused error +var _ = strconv.IntSize + +func TestAccountedPoolQuerySingle(t *testing.T) { + keeper, ctx := keepertest.AccountedPoolKeeper(t) + wctx := sdk.WrapSDKContext(ctx) + msgs := createNAccountedPool(keeper, ctx, 2) + tests := []struct { + desc string + request *types.QueryGetAccountedPoolRequest + response *types.QueryGetAccountedPoolResponse + err error + }{ + { + desc: "First", + request: &types.QueryGetAccountedPoolRequest{ + PoolId: msgs[0].PoolId, + }, + response: &types.QueryGetAccountedPoolResponse{AccountedPool: msgs[0]}, + }, + { + desc: "Second", + request: &types.QueryGetAccountedPoolRequest{ + PoolId: msgs[1].PoolId, + }, + response: &types.QueryGetAccountedPoolResponse{AccountedPool: msgs[1]}, + }, + { + desc: "KeyNotFound", + request: &types.QueryGetAccountedPoolRequest{ + PoolId: (uint64)(100000), + }, + err: status.Error(codes.NotFound, "not found"), + }, + { + desc: "InvalidRequest", + err: status.Error(codes.InvalidArgument, "invalid request"), + }, + } + for _, tc := range tests { + t.Run(tc.desc, func(t *testing.T) { + response, err := keeper.AccountedPool(wctx, tc.request) + if tc.err != nil { + require.ErrorIs(t, err, tc.err) + } else { + require.NoError(t, err) + require.Equal(t, + nullify.Fill(tc.response), + nullify.Fill(response), + ) + } + }) + } +} + +func TestAccountedPoolQueryPaginated(t *testing.T) { + keeper, ctx := keepertest.AccountedPoolKeeper(t) + wctx := sdk.WrapSDKContext(ctx) + msgs := createNAccountedPool(keeper, ctx, 5) + + request := func(next []byte, offset, limit uint64, total bool) *types.QueryAllAccountedPoolRequest { + return &types.QueryAllAccountedPoolRequest{ + Pagination: &query.PageRequest{ + Key: next, + Offset: offset, + Limit: limit, + CountTotal: total, + }, + } + } + t.Run("ByOffset", func(t *testing.T) { + step := 2 + for i := 0; i < len(msgs); i += step { + resp, err := keeper.AccountedPoolAll(wctx, request(nil, uint64(i), uint64(step), false)) + require.NoError(t, err) + require.LessOrEqual(t, len(resp.AccountedPool), step) + require.Subset(t, + nullify.Fill(msgs), + nullify.Fill(resp.AccountedPool), + ) + } + }) + t.Run("ByKey", func(t *testing.T) { + step := 2 + var next []byte + for i := 0; i < len(msgs); i += step { + resp, err := keeper.AccountedPoolAll(wctx, request(next, 0, uint64(step), false)) + require.NoError(t, err) + require.LessOrEqual(t, len(resp.AccountedPool), step) + require.Subset(t, + nullify.Fill(msgs), + nullify.Fill(resp.AccountedPool), + ) + next = resp.Pagination.NextKey + } + }) + t.Run("Total", func(t *testing.T) { + resp, err := keeper.AccountedPoolAll(wctx, request(nil, 0, 0, true)) + require.NoError(t, err) + require.Equal(t, len(msgs), int(resp.Pagination.Total)) + require.ElementsMatch(t, + nullify.Fill(msgs), + nullify.Fill(resp.AccountedPool), + ) + }) + t.Run("InvalidRequest", func(t *testing.T) { + _, err := keeper.AccountedPoolAll(wctx, nil) + require.ErrorIs(t, err, status.Error(codes.InvalidArgument, "invalid request")) + }) +} diff --git a/x/accountedpool/keeper/query_params.go b/x/accountedpool/keeper/query_params.go new file mode 100644 index 000000000..6e1ae46f1 --- /dev/null +++ b/x/accountedpool/keeper/query_params.go @@ -0,0 +1,19 @@ +package keeper + +import ( + "context" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/elys-network/elys/x/accountedpool/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func (k Keeper) Params(goCtx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + ctx := sdk.UnwrapSDKContext(goCtx) + + return &types.QueryParamsResponse{Params: k.GetParams(ctx)}, nil +} diff --git a/x/accountedpool/keeper/query_params_test.go b/x/accountedpool/keeper/query_params_test.go new file mode 100644 index 000000000..a03bd5337 --- /dev/null +++ b/x/accountedpool/keeper/query_params_test.go @@ -0,0 +1,21 @@ +package keeper_test + +import ( + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + testkeeper "github.com/elys-network/elys/testutil/keeper" + "github.com/elys-network/elys/x/accountedpool/types" + "github.com/stretchr/testify/require" +) + +func TestParamsQuery(t *testing.T) { + keeper, ctx := testkeeper.AccountedPoolKeeper(t) + wctx := sdk.WrapSDKContext(ctx) + params := types.DefaultParams() + keeper.SetParams(ctx, ¶ms) + + response, err := keeper.Params(wctx, &types.QueryParamsRequest{}) + require.NoError(t, err) + require.Equal(t, &types.QueryParamsResponse{Params: params}, response) +} diff --git a/x/accountedpool/module.go b/x/accountedpool/module.go new file mode 100644 index 000000000..b878e2861 --- /dev/null +++ b/x/accountedpool/module.go @@ -0,0 +1,149 @@ +package tvl + +import ( + "context" + "encoding/json" + "fmt" + + // this line is used by starport scaffolding # 1 + + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + + abci "github.com/cometbft/cometbft/abci/types" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/elys-network/elys/x/accountedpool/client/cli" + "github.com/elys-network/elys/x/accountedpool/keeper" + "github.com/elys-network/elys/x/accountedpool/types" +) + +var ( + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} +) + +// ---------------------------------------------------------------------------- +// AppModuleBasic +// ---------------------------------------------------------------------------- + +// AppModuleBasic implements the AppModuleBasic interface that defines the independent methods a Cosmos SDK module needs to implement. +type AppModuleBasic struct { + cdc codec.BinaryCodec +} + +func NewAppModuleBasic(cdc codec.BinaryCodec) AppModuleBasic { + return AppModuleBasic{cdc: cdc} +} + +// Name returns the name of the module as a string +func (AppModuleBasic) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec registers the amino codec for the module, which is used to marshal and unmarshal structs to/from []byte in order to persist them in the module's KVStore +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + types.RegisterCodec(cdc) +} + +// RegisterInterfaces registers a module's interface types and their concrete implementations as proto.Message +func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { + types.RegisterInterfaces(reg) +} + +// DefaultGenesis returns a default GenesisState for the module, marshalled to json.RawMessage. The default GenesisState need to be defined by the module developer and is primarily used for testing +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { + return cdc.MustMarshalJSON(types.DefaultGenesis()) +} + +// ValidateGenesis used to validate the GenesisState, given in its json.RawMessage form +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { + var genState types.GenesisState + if err := cdc.UnmarshalJSON(bz, &genState); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + return genState.Validate() +} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module +func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { + types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) +} + +// GetTxCmd returns the root Tx command for the module. The subcommands of this root command are used by end-users to generate new transactions containing messages defined in the module +func (a AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd() +} + +// GetQueryCmd returns the root query command for the module. The subcommands of this root command are used by end-users to generate new queries to the subset of the state defined by the module +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd(types.StoreKey) +} + +// ---------------------------------------------------------------------------- +// AppModule +// ---------------------------------------------------------------------------- + +// AppModule implements the AppModule interface that defines the inter-dependent methods that modules need to implement +type AppModule struct { + AppModuleBasic + + keeper keeper.Keeper + accountKeeper types.AccountKeeper + bankKeeper types.BankKeeper +} + +func NewAppModule( + cdc codec.Codec, + keeper keeper.Keeper, + accountKeeper types.AccountKeeper, + bankKeeper types.BankKeeper, +) AppModule { + return AppModule{ + AppModuleBasic: NewAppModuleBasic(cdc), + keeper: keeper, + accountKeeper: accountKeeper, + bankKeeper: bankKeeper, + } +} + +// RegisterServices registers a gRPC query service to respond to the module-specific gRPC queries +func (am AppModule) RegisterServices(cfg module.Configurator) { + types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) + types.RegisterQueryServer(cfg.QueryServer(), am.keeper) +} + +// RegisterInvariants registers the invariants of the module. If an invariant deviates from its predicted value, the InvariantRegistry triggers appropriate logic (most often the chain will be halted) +func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + +// InitGenesis performs the module's genesis initialization. It returns no validator updates. +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { + var genState types.GenesisState + // Initialize global index to index in genesis state + cdc.MustUnmarshalJSON(gs, &genState) + + InitGenesis(ctx, am.keeper, genState) + + return []abci.ValidatorUpdate{} +} + +// ExportGenesis returns the module's exported genesis state as raw JSON bytes. +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { + genState := ExportGenesis(ctx, am.keeper) + return cdc.MustMarshalJSON(genState) +} + +// ConsensusVersion is a sequence number for state-breaking change of the module. It should be incremented on each consensus-breaking change introduced by the module. To avoid wrong/empty versions, the initial version should be set to 1 +func (AppModule) ConsensusVersion() uint64 { return 1 } + +// BeginBlock contains the logic that is automatically triggered at the beginning of each block +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 { + return []abci.ValidatorUpdate{} +} diff --git a/x/accountedpool/module_simulation.go b/x/accountedpool/module_simulation.go new file mode 100644 index 000000000..541e06056 --- /dev/null +++ b/x/accountedpool/module_simulation.go @@ -0,0 +1,64 @@ +package tvl + +import ( + "math/rand" + + "github.com/cosmos/cosmos-sdk/baseapp" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/elys-network/elys/testutil/sample" + tvlsimulation "github.com/elys-network/elys/x/accountedpool/simulation" + "github.com/elys-network/elys/x/accountedpool/types" +) + +// avoid unused import issue +var ( + _ = sample.AccAddress + _ = tvlsimulation.FindAccount + _ = simulation.MsgEntryKind + _ = baseapp.Paramspace + _ = rand.Rand{} +) + +const ( +// this line is used by starport scaffolding # simapp/module/const +) + +// GenerateGenesisState creates a randomized GenState of the module. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { + accs := make([]string, len(simState.Accounts)) + for i, acc := range simState.Accounts { + accs[i] = acc.Address.String() + } + tvlGenesis := types.GenesisState{ + Params: types.DefaultParams(), + // this line is used by starport scaffolding # simapp/module/genesisState + } + simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(&tvlGenesis) +} + +// RegisterStoreDecoder registers a decoder. +func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} + +// ProposalContents doesn't return any content functions for governance proposals. +func (AppModule) ProposalContents(_ module.SimulationState) []simtypes.WeightedProposalContent { + return nil +} + +// WeightedOperations returns the all the gov module operations with their respective weights. +func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { + operations := make([]simtypes.WeightedOperation, 0) + + // this line is used by starport scaffolding # simapp/module/operation + + return operations +} + +// ProposalMsgs returns msgs used for governance proposals for simulations. +func (am AppModule) ProposalMsgs(simState module.SimulationState) []simtypes.WeightedProposalMsg { + return []simtypes.WeightedProposalMsg{ + // this line is used by starport scaffolding # simapp/module/OpMsg + } +} diff --git a/x/accountedpool/simulation/helpers.go b/x/accountedpool/simulation/helpers.go new file mode 100644 index 000000000..92c437c0d --- /dev/null +++ b/x/accountedpool/simulation/helpers.go @@ -0,0 +1,15 @@ +package simulation + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" +) + +// FindAccount find a specific address from an account list +func FindAccount(accs []simtypes.Account, address string) (simtypes.Account, bool) { + creator, err := sdk.AccAddressFromBech32(address) + if err != nil { + panic(err) + } + return simtypes.FindAccount(accs, creator) +} diff --git a/x/accountedpool/types/accounted_pool.pb.go b/x/accountedpool/types/accounted_pool.pb.go new file mode 100644 index 000000000..b7edab4d8 --- /dev/null +++ b/x/accountedpool/types/accounted_pool.pb.go @@ -0,0 +1,478 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: elys/accountedpool/accounted_pool.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + types1 "github.com/elys-network/elys/x/amm/types" + 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 + +type AccountedPool struct { + PoolId uint64 `protobuf:"varint,1,opt,name=poolId,proto3" json:"poolId,omitempty"` + TotalShares types.Coin `protobuf:"bytes,2,opt,name=totalShares,proto3" json:"totalShares"` + PoolAssets []types1.PoolAsset `protobuf:"bytes,3,rep,name=poolAssets,proto3" json:"poolAssets"` + TotalWeight github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,4,opt,name=totalWeight,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"totalWeight"` +} + +func (m *AccountedPool) Reset() { *m = AccountedPool{} } +func (m *AccountedPool) String() string { return proto.CompactTextString(m) } +func (*AccountedPool) ProtoMessage() {} +func (*AccountedPool) Descriptor() ([]byte, []int) { + return fileDescriptor_237592a8964da530, []int{0} +} +func (m *AccountedPool) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *AccountedPool) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_AccountedPool.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 *AccountedPool) XXX_Merge(src proto.Message) { + xxx_messageInfo_AccountedPool.Merge(m, src) +} +func (m *AccountedPool) XXX_Size() int { + return m.Size() +} +func (m *AccountedPool) XXX_DiscardUnknown() { + xxx_messageInfo_AccountedPool.DiscardUnknown(m) +} + +var xxx_messageInfo_AccountedPool proto.InternalMessageInfo + +func (m *AccountedPool) GetPoolId() uint64 { + if m != nil { + return m.PoolId + } + return 0 +} + +func (m *AccountedPool) GetTotalShares() types.Coin { + if m != nil { + return m.TotalShares + } + return types.Coin{} +} + +func (m *AccountedPool) GetPoolAssets() []types1.PoolAsset { + if m != nil { + return m.PoolAssets + } + return nil +} + +func init() { + proto.RegisterType((*AccountedPool)(nil), "elys.accountedpool.AccountedPool") +} + +func init() { + proto.RegisterFile("elys/accountedpool/accounted_pool.proto", fileDescriptor_237592a8964da530) +} + +var fileDescriptor_237592a8964da530 = []byte{ + // 333 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x5c, 0x51, 0x3f, 0x4f, 0xc2, 0x40, + 0x14, 0xef, 0x09, 0x21, 0xb1, 0xc4, 0xa5, 0x1a, 0x53, 0x18, 0x8e, 0xc6, 0x41, 0xbb, 0x70, 0x17, + 0x70, 0x72, 0x04, 0x27, 0x12, 0x07, 0x82, 0x83, 0x89, 0x0b, 0xb9, 0x96, 0x4b, 0x69, 0xe8, 0xf5, + 0x11, 0xee, 0x50, 0xf9, 0x16, 0x7e, 0x2c, 0x46, 0x46, 0xe3, 0x40, 0x0c, 0xfd, 0x10, 0xae, 0xe6, + 0x7a, 0x47, 0xac, 0x4e, 0x7d, 0xbf, 0xfe, 0xfe, 0xf5, 0xbd, 0xba, 0x37, 0x3c, 0xdb, 0x48, 0xca, + 0xe2, 0x18, 0xd6, 0xb9, 0xe2, 0xb3, 0x25, 0x40, 0xf6, 0x8b, 0xa6, 0x1a, 0x92, 0xe5, 0x0a, 0x14, + 0x78, 0x9e, 0x16, 0x92, 0x3f, 0xc2, 0x76, 0xcb, 0x98, 0x85, 0xa0, 0x1a, 0x4e, 0x99, 0x94, 0x5c, + 0x19, 0x79, 0xfb, 0x22, 0x81, 0x04, 0xca, 0x91, 0xea, 0xc9, 0xbe, 0xc5, 0x31, 0x48, 0x01, 0x92, + 0x46, 0x4c, 0x72, 0xfa, 0xd2, 0x8b, 0xb8, 0x62, 0x3d, 0x1a, 0x43, 0x9a, 0x5b, 0xbe, 0x65, 0xf8, + 0xa9, 0x31, 0x1a, 0x60, 0xa8, 0xab, 0x6f, 0xe4, 0x9e, 0x0d, 0x8e, 0xed, 0x63, 0x80, 0xcc, 0xbb, + 0x74, 0x1b, 0xba, 0x76, 0x34, 0xf3, 0x51, 0x80, 0xc2, 0xfa, 0xc4, 0x22, 0x6f, 0xe0, 0x36, 0x15, + 0x28, 0x96, 0x3d, 0xce, 0xd9, 0x8a, 0x4b, 0xff, 0x24, 0x40, 0x61, 0xb3, 0xdf, 0x22, 0x36, 0x4d, + 0x57, 0x13, 0x5b, 0x4d, 0xee, 0x21, 0xcd, 0x87, 0xf5, 0xed, 0xbe, 0xe3, 0x4c, 0xaa, 0x1e, 0xef, + 0xce, 0x75, 0x75, 0xd8, 0x40, 0x2f, 0x24, 0xfd, 0x5a, 0x50, 0x0b, 0x9b, 0xfd, 0x73, 0x62, 0x2e, + 0x20, 0x04, 0x19, 0x1f, 0x39, 0xeb, 0xad, 0x88, 0xbd, 0xb1, 0x6d, 0x7f, 0xe2, 0x69, 0x32, 0x57, + 0x7e, 0x3d, 0x40, 0xe1, 0xe9, 0x90, 0x68, 0xd9, 0xe7, 0xbe, 0x73, 0x9d, 0xa4, 0x6a, 0xbe, 0x8e, + 0x48, 0x0c, 0xc2, 0x6e, 0x67, 0x1f, 0x5d, 0x39, 0x5b, 0x50, 0xb5, 0x59, 0x72, 0x49, 0x46, 0xb9, + 0x9a, 0x54, 0x23, 0x86, 0x0f, 0xdb, 0x03, 0x46, 0xbb, 0x03, 0x46, 0x5f, 0x07, 0x8c, 0xde, 0x0b, + 0xec, 0xec, 0x0a, 0xec, 0x7c, 0x14, 0xd8, 0x79, 0xee, 0x57, 0xe2, 0xf4, 0xc7, 0x75, 0x73, 0xae, + 0x5e, 0x61, 0xb5, 0x28, 0x01, 0x7d, 0xfb, 0xf7, 0x5b, 0xcb, 0xf8, 0xa8, 0x51, 0x9e, 0xf3, 0xf6, + 0x27, 0x00, 0x00, 0xff, 0xff, 0x51, 0x3f, 0x71, 0x78, 0xf9, 0x01, 0x00, 0x00, +} + +func (m *AccountedPool) 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 *AccountedPool) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *AccountedPool) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size := m.TotalWeight.Size() + i -= size + if _, err := m.TotalWeight.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintAccountedPool(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + if len(m.PoolAssets) > 0 { + for iNdEx := len(m.PoolAssets) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.PoolAssets[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintAccountedPool(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + { + size, err := m.TotalShares.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintAccountedPool(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if m.PoolId != 0 { + i = encodeVarintAccountedPool(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintAccountedPool(dAtA []byte, offset int, v uint64) int { + offset -= sovAccountedPool(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *AccountedPool) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PoolId != 0 { + n += 1 + sovAccountedPool(uint64(m.PoolId)) + } + l = m.TotalShares.Size() + n += 1 + l + sovAccountedPool(uint64(l)) + if len(m.PoolAssets) > 0 { + for _, e := range m.PoolAssets { + l = e.Size() + n += 1 + l + sovAccountedPool(uint64(l)) + } + } + l = m.TotalWeight.Size() + n += 1 + l + sovAccountedPool(uint64(l)) + return n +} + +func sovAccountedPool(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozAccountedPool(x uint64) (n int) { + return sovAccountedPool(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *AccountedPool) 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 ErrIntOverflowAccountedPool + } + 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: AccountedPool: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AccountedPool: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) + } + m.PoolId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowAccountedPool + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TotalShares", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowAccountedPool + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthAccountedPool + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthAccountedPool + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.TotalShares.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolAssets", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowAccountedPool + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthAccountedPool + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthAccountedPool + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PoolAssets = append(m.PoolAssets, types1.PoolAsset{}) + if err := m.PoolAssets[len(m.PoolAssets)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TotalWeight", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowAccountedPool + } + 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 ErrInvalidLengthAccountedPool + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthAccountedPool + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.TotalWeight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipAccountedPool(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthAccountedPool + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipAccountedPool(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, ErrIntOverflowAccountedPool + } + 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, ErrIntOverflowAccountedPool + } + 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, ErrIntOverflowAccountedPool + } + 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, ErrInvalidLengthAccountedPool + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupAccountedPool + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthAccountedPool + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthAccountedPool = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowAccountedPool = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupAccountedPool = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/accountedpool/types/codec.go b/x/accountedpool/types/codec.go new file mode 100644 index 000000000..844157a87 --- /dev/null +++ b/x/accountedpool/types/codec.go @@ -0,0 +1,23 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + // this line is used by starport scaffolding # 1 + "github.com/cosmos/cosmos-sdk/types/msgservice" +) + +func RegisterCodec(cdc *codec.LegacyAmino) { + // this line is used by starport scaffolding # 2 +} + +func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { + // this line is used by starport scaffolding # 3 + + msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +} + +var ( + Amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewProtoCodec(cdctypes.NewInterfaceRegistry()) +) diff --git a/x/accountedpool/types/errors.go b/x/accountedpool/types/errors.go new file mode 100644 index 000000000..01e984cd4 --- /dev/null +++ b/x/accountedpool/types/errors.go @@ -0,0 +1,12 @@ +package types + +// DONTCOVER + +import ( + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +// x/tvl module sentinel errors +var ( + ErrSample = sdkerrors.Register(ModuleName, 1100, "sample error") +) diff --git a/x/accountedpool/types/expected_keepers.go b/x/accountedpool/types/expected_keepers.go new file mode 100644 index 000000000..fe4eae176 --- /dev/null +++ b/x/accountedpool/types/expected_keepers.go @@ -0,0 +1,55 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" + ammtypes "github.com/elys-network/elys/x/amm/types" + margintypes "github.com/elys-network/elys/x/margin/types" +) + +// AccountKeeper defines the expected account keeper used for simulations (noalias) +type AccountKeeper interface { + GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI + // Methods imported from account should be defined here +} + +// AmmKeeper defines the expected interface needed to swap tokens +// +//go:generate mockery --srcpkg . --name AmmKeeper --structname AmmKeeper --filename amm_keeper.go --with-expecter +type AmmKeeper interface { + // Get pool Ids that contains the denom in pool assets + GetAllPoolIdsWithDenom(sdk.Context, string) []uint64 + // GetPool returns a pool from its index + GetPool(sdk.Context, uint64) (ammtypes.Pool, bool) + // Get all pools + GetAllPool(sdk.Context) []ammtypes.Pool + // IterateCommitments iterates over all Commitments and performs a callback. + IterateLiquidityPools(sdk.Context, func(ammtypes.Pool) bool) +} + +// BankKeeper defines the expected interface needed to retrieve account balances. +// +//go:generate mockery --srcpkg . --name BankKeeper --structname BankKeeper --filename bank_keeper.go --with-expecter +type BankKeeper interface { + GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins + GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin + + SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins + + SendCoinsFromModuleToModule(ctx sdk.Context, senderModule string, recipientModule string, amt sdk.Coins) error + SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error + SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error + + BlockedAddr(addr sdk.AccAddress) bool + HasBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coin) bool +} + +// MarginKeeper defines the expected interface needed +// +//go:generate mockery --srcpkg . --name MarginKeeper --structname MarginKeeper --filename margin_keeper.go --with-expecter +type MarginKeeper interface { + GetPool(ctx sdk.Context, poolId uint64) (margintypes.Pool, bool) + IsPoolEnabled(ctx sdk.Context, poolId uint64) bool + IsPoolClosed(ctx sdk.Context, poolId uint64) bool + GetAllMTPs(ctx sdk.Context) []margintypes.MTP +} diff --git a/x/accountedpool/types/genesis.go b/x/accountedpool/types/genesis.go new file mode 100644 index 000000000..b5d2b9ae7 --- /dev/null +++ b/x/accountedpool/types/genesis.go @@ -0,0 +1,35 @@ +package types + +import ( + "fmt" +) + +// DefaultIndex is the default global index +const DefaultIndex uint64 = 1 + +// DefaultGenesis returns the default genesis state +func DefaultGenesis() *GenesisState { + return &GenesisState{ + AccountedPoolList: []AccountedPool{}, + // this line is used by starport scaffolding # genesis/types/default + Params: DefaultParams(), + } +} + +// Validate performs basic genesis state validation returning an error upon any +// failure. +func (gs GenesisState) Validate() error { + // Check for duplicated index in accountedPool + accountedPoolIndexMap := make(map[string]struct{}) + + for _, elem := range gs.AccountedPoolList { + index := string(AccountedPoolKey(elem.PoolId)) + if _, ok := accountedPoolIndexMap[index]; ok { + return fmt.Errorf("duplicated index for accountedPool") + } + accountedPoolIndexMap[index] = struct{}{} + } + // this line is used by starport scaffolding # genesis/types/validate + + return gs.Params.Validate() +} diff --git a/x/accountedpool/types/genesis.pb.go b/x/accountedpool/types/genesis.pb.go new file mode 100644 index 000000000..933081f6c --- /dev/null +++ b/x/accountedpool/types/genesis.pb.go @@ -0,0 +1,386 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: elys/accountedpool/genesis.proto + +package types + +import ( + fmt "fmt" + _ "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 + +// GenesisState defines the tvl module's genesis state. +type GenesisState struct { + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` + AccountedPoolList []AccountedPool `protobuf:"bytes,2,rep,name=accountedPoolList,proto3" json:"accountedPoolList"` +} + +func (m *GenesisState) Reset() { *m = GenesisState{} } +func (m *GenesisState) String() string { return proto.CompactTextString(m) } +func (*GenesisState) ProtoMessage() {} +func (*GenesisState) Descriptor() ([]byte, []int) { + return fileDescriptor_365e99d543e5a5e3, []int{0} +} +func (m *GenesisState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_GenesisState.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 *GenesisState) XXX_Merge(src proto.Message) { + xxx_messageInfo_GenesisState.Merge(m, src) +} +func (m *GenesisState) XXX_Size() int { + return m.Size() +} +func (m *GenesisState) XXX_DiscardUnknown() { + xxx_messageInfo_GenesisState.DiscardUnknown(m) +} + +var xxx_messageInfo_GenesisState proto.InternalMessageInfo + +func (m *GenesisState) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +func (m *GenesisState) GetAccountedPoolList() []AccountedPool { + if m != nil { + return m.AccountedPoolList + } + return nil +} + +func init() { + proto.RegisterType((*GenesisState)(nil), "elys.accountedpool.GenesisState") +} + +func init() { proto.RegisterFile("elys/accountedpool/genesis.proto", fileDescriptor_365e99d543e5a5e3) } + +var fileDescriptor_365e99d543e5a5e3 = []byte{ + // 243 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x48, 0xcd, 0xa9, 0x2c, + 0xd6, 0x4f, 0x4c, 0x4e, 0xce, 0x2f, 0xcd, 0x2b, 0x49, 0x4d, 0x29, 0xc8, 0xcf, 0xcf, 0xd1, 0x4f, + 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x02, 0xa9, + 0xd0, 0x43, 0x51, 0x21, 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, 0x96, 0xd6, 0x07, 0xb1, 0x20, 0x2a, + 0xa5, 0xe4, 0xb1, 0x98, 0x55, 0x90, 0x58, 0x94, 0x98, 0x0b, 0x35, 0x4a, 0x4a, 0x1d, 0x8b, 0x02, + 0x38, 0x2f, 0x1e, 0xc4, 0x85, 0x28, 0x54, 0x9a, 0xcf, 0xc8, 0xc5, 0xe3, 0x0e, 0x71, 0x45, 0x70, + 0x49, 0x62, 0x49, 0xaa, 0x90, 0x05, 0x17, 0x1b, 0xc4, 0x24, 0x09, 0x46, 0x05, 0x46, 0x0d, 0x6e, + 0x23, 0x29, 0x3d, 0x4c, 0x57, 0xe9, 0x05, 0x80, 0x55, 0x38, 0xb1, 0x9c, 0xb8, 0x27, 0xcf, 0x10, + 0x04, 0x55, 0x2f, 0x14, 0xca, 0x25, 0x08, 0x57, 0x15, 0x90, 0x9f, 0x9f, 0xe3, 0x93, 0x59, 0x5c, + 0x22, 0xc1, 0xa4, 0xc0, 0xac, 0xc1, 0x6d, 0xa4, 0x88, 0xcd, 0x10, 0x47, 0x64, 0xc5, 0x50, 0xb3, + 0x30, 0x4d, 0x70, 0xf2, 0x39, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, + 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, 0xa3, + 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0x90, 0xf9, 0xba, 0x79, 0xa9, + 0x25, 0xe5, 0xf9, 0x45, 0xd9, 0x60, 0x8e, 0x7e, 0x05, 0x9a, 0xf7, 0x4b, 0x2a, 0x0b, 0x52, 0x8b, + 0x93, 0xd8, 0xc0, 0xde, 0x36, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0xad, 0x11, 0xea, 0x27, 0x8e, + 0x01, 0x00, 0x00, +} + +func (m *GenesisState) 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 *GenesisState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.AccountedPoolList) > 0 { + for iNdEx := len(m.AccountedPoolList) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.AccountedPoolList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { + offset -= sovGenesis(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *GenesisState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Params.Size() + n += 1 + l + sovGenesis(uint64(l)) + if len(m.AccountedPoolList) > 0 { + for _, e := range m.AccountedPoolList { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + return n +} + +func sovGenesis(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozGenesis(x uint64) (n int) { + return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *GenesisState) 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 ErrIntOverflowGenesis + } + 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: GenesisState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AccountedPoolList", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AccountedPoolList = append(m.AccountedPoolList, AccountedPool{}) + if err := m.AccountedPoolList[len(m.AccountedPoolList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipGenesis(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, ErrIntOverflowGenesis + } + 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, ErrIntOverflowGenesis + } + 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, ErrIntOverflowGenesis + } + 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, ErrInvalidLengthGenesis + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupGenesis + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthGenesis + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/accountedpool/types/genesis_test.go b/x/accountedpool/types/genesis_test.go new file mode 100644 index 000000000..3fbea36a2 --- /dev/null +++ b/x/accountedpool/types/genesis_test.go @@ -0,0 +1,63 @@ +package types_test + +import ( + "testing" + + "github.com/elys-network/elys/x/accountedpool/types" + "github.com/stretchr/testify/require" +) + +func TestGenesisState_Validate(t *testing.T) { + tests := []struct { + desc string + genState *types.GenesisState + valid bool + }{ + { + desc: "default is valid", + genState: types.DefaultGenesis(), + valid: true, + }, + { + desc: "valid genesis state", + genState: &types.GenesisState{ + + AccountedPoolList: []types.AccountedPool{ + { + PoolId: (uint64)(0), + }, + { + PoolId: (uint64)(1), + }, + }, + // this line is used by starport scaffolding # types/genesis/validField + }, + valid: true, + }, + { + desc: "duplicated accountedPool", + genState: &types.GenesisState{ + AccountedPoolList: []types.AccountedPool{ + { + PoolId: (uint64)(0), + }, + { + PoolId: (uint64)(0), + }, + }, + }, + valid: false, + }, + // this line is used by starport scaffolding # types/genesis/testcase + } + for _, tc := range tests { + t.Run(tc.desc, func(t *testing.T) { + err := tc.genState.Validate() + if tc.valid { + require.NoError(t, err) + } else { + require.Error(t, err) + } + }) + } +} diff --git a/x/accountedpool/types/key_accounted_pool.go b/x/accountedpool/types/key_accounted_pool.go new file mode 100644 index 000000000..331e89685 --- /dev/null +++ b/x/accountedpool/types/key_accounted_pool.go @@ -0,0 +1,24 @@ +package types + +import "encoding/binary" + +var _ binary.ByteOrder + +const ( + // AccountedPoolKeyPrefix is the prefix to retrieve all AccountedPool + AccountedPoolKeyPrefix = "AccountedPool/value/" +) + +// AccountedPoolKey returns the store key to retrieve a AccountedPool from the index fields +func AccountedPoolKey( + poolId uint64, +) []byte { + var key []byte + + poolIdBytes := make([]byte, 8) + binary.BigEndian.PutUint64(poolIdBytes, poolId) + key = append(key, poolIdBytes...) + key = append(key, []byte("/")...) + + return key +} diff --git a/x/accountedpool/types/keys.go b/x/accountedpool/types/keys.go new file mode 100644 index 000000000..65e087f95 --- /dev/null +++ b/x/accountedpool/types/keys.go @@ -0,0 +1,22 @@ +package types + +const ( + // ModuleName defines the module name + ModuleName = "poolaccounted" + + // StoreKey defines the primary module store key + StoreKey = ModuleName + + // RouterKey defines the module's message routing key + RouterKey = ModuleName + + // MemStoreKey defines the in-memory store key + MemStoreKey = "mem_poolaccounted" + + // ParamsKey is the prefix for parameters of poolaccounted module + ParamsKey = "poolaccounted_params" +) + +func KeyPrefix(p string) []byte { + return []byte(p) +} diff --git a/x/accountedpool/types/mocks/amm_keeper.go b/x/accountedpool/types/mocks/amm_keeper.go new file mode 100644 index 000000000..be50bf2d3 --- /dev/null +++ b/x/accountedpool/types/mocks/amm_keeper.go @@ -0,0 +1,213 @@ +// Code generated by mockery v2.32.4. DO NOT EDIT. + +package mocks + +import ( + ammtypes "github.com/elys-network/elys/x/amm/types" + mock "github.com/stretchr/testify/mock" + + types "github.com/cosmos/cosmos-sdk/types" +) + +// AmmKeeper is an autogenerated mock type for the AmmKeeper type +type AmmKeeper struct { + mock.Mock +} + +type AmmKeeper_Expecter struct { + mock *mock.Mock +} + +func (_m *AmmKeeper) EXPECT() *AmmKeeper_Expecter { + return &AmmKeeper_Expecter{mock: &_m.Mock} +} + +// GetAllPool provides a mock function with given fields: _a0 +func (_m *AmmKeeper) GetAllPool(_a0 types.Context) []ammtypes.Pool { + ret := _m.Called(_a0) + + var r0 []ammtypes.Pool + if rf, ok := ret.Get(0).(func(types.Context) []ammtypes.Pool); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]ammtypes.Pool) + } + } + + return r0 +} + +// AmmKeeper_GetAllPool_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAllPool' +type AmmKeeper_GetAllPool_Call struct { + *mock.Call +} + +// GetAllPool is a helper method to define mock.On call +// - _a0 types.Context +func (_e *AmmKeeper_Expecter) GetAllPool(_a0 interface{}) *AmmKeeper_GetAllPool_Call { + return &AmmKeeper_GetAllPool_Call{Call: _e.mock.On("GetAllPool", _a0)} +} + +func (_c *AmmKeeper_GetAllPool_Call) Run(run func(_a0 types.Context)) *AmmKeeper_GetAllPool_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context)) + }) + return _c +} + +func (_c *AmmKeeper_GetAllPool_Call) Return(_a0 []ammtypes.Pool) *AmmKeeper_GetAllPool_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *AmmKeeper_GetAllPool_Call) RunAndReturn(run func(types.Context) []ammtypes.Pool) *AmmKeeper_GetAllPool_Call { + _c.Call.Return(run) + return _c +} + +// GetAllPoolIdsWithDenom provides a mock function with given fields: _a0, _a1 +func (_m *AmmKeeper) GetAllPoolIdsWithDenom(_a0 types.Context, _a1 string) []uint64 { + ret := _m.Called(_a0, _a1) + + var r0 []uint64 + if rf, ok := ret.Get(0).(func(types.Context, string) []uint64); ok { + r0 = rf(_a0, _a1) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]uint64) + } + } + + return r0 +} + +// AmmKeeper_GetAllPoolIdsWithDenom_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAllPoolIdsWithDenom' +type AmmKeeper_GetAllPoolIdsWithDenom_Call struct { + *mock.Call +} + +// GetAllPoolIdsWithDenom is a helper method to define mock.On call +// - _a0 types.Context +// - _a1 string +func (_e *AmmKeeper_Expecter) GetAllPoolIdsWithDenom(_a0 interface{}, _a1 interface{}) *AmmKeeper_GetAllPoolIdsWithDenom_Call { + return &AmmKeeper_GetAllPoolIdsWithDenom_Call{Call: _e.mock.On("GetAllPoolIdsWithDenom", _a0, _a1)} +} + +func (_c *AmmKeeper_GetAllPoolIdsWithDenom_Call) Run(run func(_a0 types.Context, _a1 string)) *AmmKeeper_GetAllPoolIdsWithDenom_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(string)) + }) + return _c +} + +func (_c *AmmKeeper_GetAllPoolIdsWithDenom_Call) Return(_a0 []uint64) *AmmKeeper_GetAllPoolIdsWithDenom_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *AmmKeeper_GetAllPoolIdsWithDenom_Call) RunAndReturn(run func(types.Context, string) []uint64) *AmmKeeper_GetAllPoolIdsWithDenom_Call { + _c.Call.Return(run) + return _c +} + +// GetPool provides a mock function with given fields: _a0, _a1 +func (_m *AmmKeeper) GetPool(_a0 types.Context, _a1 uint64) (ammtypes.Pool, bool) { + ret := _m.Called(_a0, _a1) + + var r0 ammtypes.Pool + var r1 bool + if rf, ok := ret.Get(0).(func(types.Context, uint64) (ammtypes.Pool, bool)); ok { + return rf(_a0, _a1) + } + if rf, ok := ret.Get(0).(func(types.Context, uint64) ammtypes.Pool); ok { + r0 = rf(_a0, _a1) + } else { + r0 = ret.Get(0).(ammtypes.Pool) + } + + if rf, ok := ret.Get(1).(func(types.Context, uint64) bool); ok { + r1 = rf(_a0, _a1) + } else { + r1 = ret.Get(1).(bool) + } + + return r0, r1 +} + +// AmmKeeper_GetPool_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPool' +type AmmKeeper_GetPool_Call struct { + *mock.Call +} + +// GetPool is a helper method to define mock.On call +// - _a0 types.Context +// - _a1 uint64 +func (_e *AmmKeeper_Expecter) GetPool(_a0 interface{}, _a1 interface{}) *AmmKeeper_GetPool_Call { + return &AmmKeeper_GetPool_Call{Call: _e.mock.On("GetPool", _a0, _a1)} +} + +func (_c *AmmKeeper_GetPool_Call) Run(run func(_a0 types.Context, _a1 uint64)) *AmmKeeper_GetPool_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(uint64)) + }) + return _c +} + +func (_c *AmmKeeper_GetPool_Call) Return(_a0 ammtypes.Pool, _a1 bool) *AmmKeeper_GetPool_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *AmmKeeper_GetPool_Call) RunAndReturn(run func(types.Context, uint64) (ammtypes.Pool, bool)) *AmmKeeper_GetPool_Call { + _c.Call.Return(run) + return _c +} + +// IterateLiquidityPools provides a mock function with given fields: _a0, _a1 +func (_m *AmmKeeper) IterateLiquidityPools(_a0 types.Context, _a1 func(ammtypes.Pool) bool) { + _m.Called(_a0, _a1) +} + +// AmmKeeper_IterateLiquidityPools_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IterateLiquidityPools' +type AmmKeeper_IterateLiquidityPools_Call struct { + *mock.Call +} + +// IterateLiquidityPools is a helper method to define mock.On call +// - _a0 types.Context +// - _a1 func(ammtypes.Pool) bool +func (_e *AmmKeeper_Expecter) IterateLiquidityPools(_a0 interface{}, _a1 interface{}) *AmmKeeper_IterateLiquidityPools_Call { + return &AmmKeeper_IterateLiquidityPools_Call{Call: _e.mock.On("IterateLiquidityPools", _a0, _a1)} +} + +func (_c *AmmKeeper_IterateLiquidityPools_Call) Run(run func(_a0 types.Context, _a1 func(ammtypes.Pool) bool)) *AmmKeeper_IterateLiquidityPools_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(func(ammtypes.Pool) bool)) + }) + return _c +} + +func (_c *AmmKeeper_IterateLiquidityPools_Call) Return() *AmmKeeper_IterateLiquidityPools_Call { + _c.Call.Return() + return _c +} + +func (_c *AmmKeeper_IterateLiquidityPools_Call) RunAndReturn(run func(types.Context, func(ammtypes.Pool) bool)) *AmmKeeper_IterateLiquidityPools_Call { + _c.Call.Return(run) + return _c +} + +// NewAmmKeeper creates a new instance of AmmKeeper. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAmmKeeper(t interface { + mock.TestingT + Cleanup(func()) +}) *AmmKeeper { + mock := &AmmKeeper{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/x/accountedpool/types/mocks/bank_keeper.go b/x/accountedpool/types/mocks/bank_keeper.go new file mode 100644 index 000000000..6a6e79279 --- /dev/null +++ b/x/accountedpool/types/mocks/bank_keeper.go @@ -0,0 +1,390 @@ +// Code generated by mockery v2.32.4. DO NOT EDIT. + +package mocks + +import ( + types "github.com/cosmos/cosmos-sdk/types" + mock "github.com/stretchr/testify/mock" +) + +// BankKeeper is an autogenerated mock type for the BankKeeper type +type BankKeeper struct { + mock.Mock +} + +type BankKeeper_Expecter struct { + mock *mock.Mock +} + +func (_m *BankKeeper) EXPECT() *BankKeeper_Expecter { + return &BankKeeper_Expecter{mock: &_m.Mock} +} + +// BlockedAddr provides a mock function with given fields: addr +func (_m *BankKeeper) BlockedAddr(addr types.AccAddress) bool { + ret := _m.Called(addr) + + var r0 bool + if rf, ok := ret.Get(0).(func(types.AccAddress) bool); ok { + r0 = rf(addr) + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// BankKeeper_BlockedAddr_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockedAddr' +type BankKeeper_BlockedAddr_Call struct { + *mock.Call +} + +// BlockedAddr is a helper method to define mock.On call +// - addr types.AccAddress +func (_e *BankKeeper_Expecter) BlockedAddr(addr interface{}) *BankKeeper_BlockedAddr_Call { + return &BankKeeper_BlockedAddr_Call{Call: _e.mock.On("BlockedAddr", addr)} +} + +func (_c *BankKeeper_BlockedAddr_Call) Run(run func(addr types.AccAddress)) *BankKeeper_BlockedAddr_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.AccAddress)) + }) + return _c +} + +func (_c *BankKeeper_BlockedAddr_Call) Return(_a0 bool) *BankKeeper_BlockedAddr_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_BlockedAddr_Call) RunAndReturn(run func(types.AccAddress) bool) *BankKeeper_BlockedAddr_Call { + _c.Call.Return(run) + return _c +} + +// GetAllBalances provides a mock function with given fields: ctx, addr +func (_m *BankKeeper) GetAllBalances(ctx types.Context, addr types.AccAddress) types.Coins { + ret := _m.Called(ctx, addr) + + var r0 types.Coins + if rf, ok := ret.Get(0).(func(types.Context, types.AccAddress) types.Coins); ok { + r0 = rf(ctx, addr) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(types.Coins) + } + } + + return r0 +} + +// BankKeeper_GetAllBalances_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAllBalances' +type BankKeeper_GetAllBalances_Call struct { + *mock.Call +} + +// GetAllBalances is a helper method to define mock.On call +// - ctx types.Context +// - addr types.AccAddress +func (_e *BankKeeper_Expecter) GetAllBalances(ctx interface{}, addr interface{}) *BankKeeper_GetAllBalances_Call { + return &BankKeeper_GetAllBalances_Call{Call: _e.mock.On("GetAllBalances", ctx, addr)} +} + +func (_c *BankKeeper_GetAllBalances_Call) Run(run func(ctx types.Context, addr types.AccAddress)) *BankKeeper_GetAllBalances_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(types.AccAddress)) + }) + return _c +} + +func (_c *BankKeeper_GetAllBalances_Call) Return(_a0 types.Coins) *BankKeeper_GetAllBalances_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_GetAllBalances_Call) RunAndReturn(run func(types.Context, types.AccAddress) types.Coins) *BankKeeper_GetAllBalances_Call { + _c.Call.Return(run) + return _c +} + +// GetBalance provides a mock function with given fields: ctx, addr, denom +func (_m *BankKeeper) GetBalance(ctx types.Context, addr types.AccAddress, denom string) types.Coin { + ret := _m.Called(ctx, addr, denom) + + var r0 types.Coin + if rf, ok := ret.Get(0).(func(types.Context, types.AccAddress, string) types.Coin); ok { + r0 = rf(ctx, addr, denom) + } else { + r0 = ret.Get(0).(types.Coin) + } + + return r0 +} + +// BankKeeper_GetBalance_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBalance' +type BankKeeper_GetBalance_Call struct { + *mock.Call +} + +// GetBalance is a helper method to define mock.On call +// - ctx types.Context +// - addr types.AccAddress +// - denom string +func (_e *BankKeeper_Expecter) GetBalance(ctx interface{}, addr interface{}, denom interface{}) *BankKeeper_GetBalance_Call { + return &BankKeeper_GetBalance_Call{Call: _e.mock.On("GetBalance", ctx, addr, denom)} +} + +func (_c *BankKeeper_GetBalance_Call) Run(run func(ctx types.Context, addr types.AccAddress, denom string)) *BankKeeper_GetBalance_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(types.AccAddress), args[2].(string)) + }) + return _c +} + +func (_c *BankKeeper_GetBalance_Call) Return(_a0 types.Coin) *BankKeeper_GetBalance_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_GetBalance_Call) RunAndReturn(run func(types.Context, types.AccAddress, string) types.Coin) *BankKeeper_GetBalance_Call { + _c.Call.Return(run) + return _c +} + +// HasBalance provides a mock function with given fields: ctx, addr, amt +func (_m *BankKeeper) HasBalance(ctx types.Context, addr types.AccAddress, amt types.Coin) bool { + ret := _m.Called(ctx, addr, amt) + + var r0 bool + if rf, ok := ret.Get(0).(func(types.Context, types.AccAddress, types.Coin) bool); ok { + r0 = rf(ctx, addr, amt) + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// BankKeeper_HasBalance_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HasBalance' +type BankKeeper_HasBalance_Call struct { + *mock.Call +} + +// HasBalance is a helper method to define mock.On call +// - ctx types.Context +// - addr types.AccAddress +// - amt types.Coin +func (_e *BankKeeper_Expecter) HasBalance(ctx interface{}, addr interface{}, amt interface{}) *BankKeeper_HasBalance_Call { + return &BankKeeper_HasBalance_Call{Call: _e.mock.On("HasBalance", ctx, addr, amt)} +} + +func (_c *BankKeeper_HasBalance_Call) Run(run func(ctx types.Context, addr types.AccAddress, amt types.Coin)) *BankKeeper_HasBalance_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(types.AccAddress), args[2].(types.Coin)) + }) + return _c +} + +func (_c *BankKeeper_HasBalance_Call) Return(_a0 bool) *BankKeeper_HasBalance_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_HasBalance_Call) RunAndReturn(run func(types.Context, types.AccAddress, types.Coin) bool) *BankKeeper_HasBalance_Call { + _c.Call.Return(run) + return _c +} + +// SendCoinsFromAccountToModule provides a mock function with given fields: ctx, senderAddr, recipientModule, amt +func (_m *BankKeeper) SendCoinsFromAccountToModule(ctx types.Context, senderAddr types.AccAddress, recipientModule string, amt types.Coins) error { + ret := _m.Called(ctx, senderAddr, recipientModule, amt) + + var r0 error + if rf, ok := ret.Get(0).(func(types.Context, types.AccAddress, string, types.Coins) error); ok { + r0 = rf(ctx, senderAddr, recipientModule, amt) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// BankKeeper_SendCoinsFromAccountToModule_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendCoinsFromAccountToModule' +type BankKeeper_SendCoinsFromAccountToModule_Call struct { + *mock.Call +} + +// SendCoinsFromAccountToModule is a helper method to define mock.On call +// - ctx types.Context +// - senderAddr types.AccAddress +// - recipientModule string +// - amt types.Coins +func (_e *BankKeeper_Expecter) SendCoinsFromAccountToModule(ctx interface{}, senderAddr interface{}, recipientModule interface{}, amt interface{}) *BankKeeper_SendCoinsFromAccountToModule_Call { + return &BankKeeper_SendCoinsFromAccountToModule_Call{Call: _e.mock.On("SendCoinsFromAccountToModule", ctx, senderAddr, recipientModule, amt)} +} + +func (_c *BankKeeper_SendCoinsFromAccountToModule_Call) Run(run func(ctx types.Context, senderAddr types.AccAddress, recipientModule string, amt types.Coins)) *BankKeeper_SendCoinsFromAccountToModule_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(types.AccAddress), args[2].(string), args[3].(types.Coins)) + }) + return _c +} + +func (_c *BankKeeper_SendCoinsFromAccountToModule_Call) Return(_a0 error) *BankKeeper_SendCoinsFromAccountToModule_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_SendCoinsFromAccountToModule_Call) RunAndReturn(run func(types.Context, types.AccAddress, string, types.Coins) error) *BankKeeper_SendCoinsFromAccountToModule_Call { + _c.Call.Return(run) + return _c +} + +// SendCoinsFromModuleToAccount provides a mock function with given fields: ctx, senderModule, recipientAddr, amt +func (_m *BankKeeper) SendCoinsFromModuleToAccount(ctx types.Context, senderModule string, recipientAddr types.AccAddress, amt types.Coins) error { + ret := _m.Called(ctx, senderModule, recipientAddr, amt) + + var r0 error + if rf, ok := ret.Get(0).(func(types.Context, string, types.AccAddress, types.Coins) error); ok { + r0 = rf(ctx, senderModule, recipientAddr, amt) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// BankKeeper_SendCoinsFromModuleToAccount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendCoinsFromModuleToAccount' +type BankKeeper_SendCoinsFromModuleToAccount_Call struct { + *mock.Call +} + +// SendCoinsFromModuleToAccount is a helper method to define mock.On call +// - ctx types.Context +// - senderModule string +// - recipientAddr types.AccAddress +// - amt types.Coins +func (_e *BankKeeper_Expecter) SendCoinsFromModuleToAccount(ctx interface{}, senderModule interface{}, recipientAddr interface{}, amt interface{}) *BankKeeper_SendCoinsFromModuleToAccount_Call { + return &BankKeeper_SendCoinsFromModuleToAccount_Call{Call: _e.mock.On("SendCoinsFromModuleToAccount", ctx, senderModule, recipientAddr, amt)} +} + +func (_c *BankKeeper_SendCoinsFromModuleToAccount_Call) Run(run func(ctx types.Context, senderModule string, recipientAddr types.AccAddress, amt types.Coins)) *BankKeeper_SendCoinsFromModuleToAccount_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(string), args[2].(types.AccAddress), args[3].(types.Coins)) + }) + return _c +} + +func (_c *BankKeeper_SendCoinsFromModuleToAccount_Call) Return(_a0 error) *BankKeeper_SendCoinsFromModuleToAccount_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_SendCoinsFromModuleToAccount_Call) RunAndReturn(run func(types.Context, string, types.AccAddress, types.Coins) error) *BankKeeper_SendCoinsFromModuleToAccount_Call { + _c.Call.Return(run) + return _c +} + +// SendCoinsFromModuleToModule provides a mock function with given fields: ctx, senderModule, recipientModule, amt +func (_m *BankKeeper) SendCoinsFromModuleToModule(ctx types.Context, senderModule string, recipientModule string, amt types.Coins) error { + ret := _m.Called(ctx, senderModule, recipientModule, amt) + + var r0 error + if rf, ok := ret.Get(0).(func(types.Context, string, string, types.Coins) error); ok { + r0 = rf(ctx, senderModule, recipientModule, amt) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// BankKeeper_SendCoinsFromModuleToModule_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendCoinsFromModuleToModule' +type BankKeeper_SendCoinsFromModuleToModule_Call struct { + *mock.Call +} + +// SendCoinsFromModuleToModule is a helper method to define mock.On call +// - ctx types.Context +// - senderModule string +// - recipientModule string +// - amt types.Coins +func (_e *BankKeeper_Expecter) SendCoinsFromModuleToModule(ctx interface{}, senderModule interface{}, recipientModule interface{}, amt interface{}) *BankKeeper_SendCoinsFromModuleToModule_Call { + return &BankKeeper_SendCoinsFromModuleToModule_Call{Call: _e.mock.On("SendCoinsFromModuleToModule", ctx, senderModule, recipientModule, amt)} +} + +func (_c *BankKeeper_SendCoinsFromModuleToModule_Call) Run(run func(ctx types.Context, senderModule string, recipientModule string, amt types.Coins)) *BankKeeper_SendCoinsFromModuleToModule_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(string), args[2].(string), args[3].(types.Coins)) + }) + return _c +} + +func (_c *BankKeeper_SendCoinsFromModuleToModule_Call) Return(_a0 error) *BankKeeper_SendCoinsFromModuleToModule_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_SendCoinsFromModuleToModule_Call) RunAndReturn(run func(types.Context, string, string, types.Coins) error) *BankKeeper_SendCoinsFromModuleToModule_Call { + _c.Call.Return(run) + return _c +} + +// SpendableCoins provides a mock function with given fields: ctx, addr +func (_m *BankKeeper) SpendableCoins(ctx types.Context, addr types.AccAddress) types.Coins { + ret := _m.Called(ctx, addr) + + var r0 types.Coins + if rf, ok := ret.Get(0).(func(types.Context, types.AccAddress) types.Coins); ok { + r0 = rf(ctx, addr) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(types.Coins) + } + } + + return r0 +} + +// BankKeeper_SpendableCoins_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SpendableCoins' +type BankKeeper_SpendableCoins_Call struct { + *mock.Call +} + +// SpendableCoins is a helper method to define mock.On call +// - ctx types.Context +// - addr types.AccAddress +func (_e *BankKeeper_Expecter) SpendableCoins(ctx interface{}, addr interface{}) *BankKeeper_SpendableCoins_Call { + return &BankKeeper_SpendableCoins_Call{Call: _e.mock.On("SpendableCoins", ctx, addr)} +} + +func (_c *BankKeeper_SpendableCoins_Call) Run(run func(ctx types.Context, addr types.AccAddress)) *BankKeeper_SpendableCoins_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(types.AccAddress)) + }) + return _c +} + +func (_c *BankKeeper_SpendableCoins_Call) Return(_a0 types.Coins) *BankKeeper_SpendableCoins_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_SpendableCoins_Call) RunAndReturn(run func(types.Context, types.AccAddress) types.Coins) *BankKeeper_SpendableCoins_Call { + _c.Call.Return(run) + return _c +} + +// NewBankKeeper creates a new instance of BankKeeper. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBankKeeper(t interface { + mock.TestingT + Cleanup(func()) +}) *BankKeeper { + mock := &BankKeeper{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/x/accountedpool/types/mocks/invariant_check.go b/x/accountedpool/types/mocks/invariant_check.go new file mode 100644 index 000000000..1a44b8d14 --- /dev/null +++ b/x/accountedpool/types/mocks/invariant_check.go @@ -0,0 +1,77 @@ +// Code generated by mockery v2.32.4. DO NOT EDIT. + +package mocks + +import ( + types "github.com/cosmos/cosmos-sdk/types" + mock "github.com/stretchr/testify/mock" +) + +// InvariantChecker is an autogenerated mock type for the InvariantChecker type +type InvariantChecker struct { + mock.Mock +} + +type InvariantChecker_Expecter struct { + mock *mock.Mock +} + +func (_m *InvariantChecker) EXPECT() *InvariantChecker_Expecter { + return &InvariantChecker_Expecter{mock: &_m.Mock} +} + +// InvariantCheck provides a mock function with given fields: ctx +func (_m *InvariantChecker) InvariantCheck(ctx types.Context) error { + ret := _m.Called(ctx) + + var r0 error + if rf, ok := ret.Get(0).(func(types.Context) error); ok { + r0 = rf(ctx) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// InvariantChecker_InvariantCheck_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InvariantCheck' +type InvariantChecker_InvariantCheck_Call struct { + *mock.Call +} + +// InvariantCheck is a helper method to define mock.On call +// - ctx types.Context +func (_e *InvariantChecker_Expecter) InvariantCheck(ctx interface{}) *InvariantChecker_InvariantCheck_Call { + return &InvariantChecker_InvariantCheck_Call{Call: _e.mock.On("InvariantCheck", ctx)} +} + +func (_c *InvariantChecker_InvariantCheck_Call) Run(run func(ctx types.Context)) *InvariantChecker_InvariantCheck_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context)) + }) + return _c +} + +func (_c *InvariantChecker_InvariantCheck_Call) Return(_a0 error) *InvariantChecker_InvariantCheck_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *InvariantChecker_InvariantCheck_Call) RunAndReturn(run func(types.Context) error) *InvariantChecker_InvariantCheck_Call { + _c.Call.Return(run) + return _c +} + +// NewInvariantChecker creates a new instance of InvariantChecker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewInvariantChecker(t interface { + mock.TestingT + Cleanup(func()) +}) *InvariantChecker { + mock := &InvariantChecker{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/x/accountedpool/types/mocks/margin_keeper.go b/x/accountedpool/types/mocks/margin_keeper.go new file mode 100644 index 000000000..e2224a92c --- /dev/null +++ b/x/accountedpool/types/mocks/margin_keeper.go @@ -0,0 +1,220 @@ +// Code generated by mockery v2.32.4. DO NOT EDIT. + +package mocks + +import ( + margintypes "github.com/elys-network/elys/x/margin/types" + mock "github.com/stretchr/testify/mock" + + types "github.com/cosmos/cosmos-sdk/types" +) + +// MarginKeeper is an autogenerated mock type for the MarginKeeper type +type MarginKeeper struct { + mock.Mock +} + +type MarginKeeper_Expecter struct { + mock *mock.Mock +} + +func (_m *MarginKeeper) EXPECT() *MarginKeeper_Expecter { + return &MarginKeeper_Expecter{mock: &_m.Mock} +} + +// GetAllMTPs provides a mock function with given fields: ctx +func (_m *MarginKeeper) GetAllMTPs(ctx types.Context) []margintypes.MTP { + ret := _m.Called(ctx) + + var r0 []margintypes.MTP + if rf, ok := ret.Get(0).(func(types.Context) []margintypes.MTP); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]margintypes.MTP) + } + } + + return r0 +} + +// MarginKeeper_GetAllMTPs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAllMTPs' +type MarginKeeper_GetAllMTPs_Call struct { + *mock.Call +} + +// GetAllMTPs is a helper method to define mock.On call +// - ctx types.Context +func (_e *MarginKeeper_Expecter) GetAllMTPs(ctx interface{}) *MarginKeeper_GetAllMTPs_Call { + return &MarginKeeper_GetAllMTPs_Call{Call: _e.mock.On("GetAllMTPs", ctx)} +} + +func (_c *MarginKeeper_GetAllMTPs_Call) Run(run func(ctx types.Context)) *MarginKeeper_GetAllMTPs_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context)) + }) + return _c +} + +func (_c *MarginKeeper_GetAllMTPs_Call) Return(_a0 []margintypes.MTP) *MarginKeeper_GetAllMTPs_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MarginKeeper_GetAllMTPs_Call) RunAndReturn(run func(types.Context) []margintypes.MTP) *MarginKeeper_GetAllMTPs_Call { + _c.Call.Return(run) + return _c +} + +// GetPool provides a mock function with given fields: ctx, poolId +func (_m *MarginKeeper) GetPool(ctx types.Context, poolId uint64) (margintypes.Pool, bool) { + ret := _m.Called(ctx, poolId) + + var r0 margintypes.Pool + var r1 bool + if rf, ok := ret.Get(0).(func(types.Context, uint64) (margintypes.Pool, bool)); ok { + return rf(ctx, poolId) + } + if rf, ok := ret.Get(0).(func(types.Context, uint64) margintypes.Pool); ok { + r0 = rf(ctx, poolId) + } else { + r0 = ret.Get(0).(margintypes.Pool) + } + + if rf, ok := ret.Get(1).(func(types.Context, uint64) bool); ok { + r1 = rf(ctx, poolId) + } else { + r1 = ret.Get(1).(bool) + } + + return r0, r1 +} + +// MarginKeeper_GetPool_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPool' +type MarginKeeper_GetPool_Call struct { + *mock.Call +} + +// GetPool is a helper method to define mock.On call +// - ctx types.Context +// - poolId uint64 +func (_e *MarginKeeper_Expecter) GetPool(ctx interface{}, poolId interface{}) *MarginKeeper_GetPool_Call { + return &MarginKeeper_GetPool_Call{Call: _e.mock.On("GetPool", ctx, poolId)} +} + +func (_c *MarginKeeper_GetPool_Call) Run(run func(ctx types.Context, poolId uint64)) *MarginKeeper_GetPool_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(uint64)) + }) + return _c +} + +func (_c *MarginKeeper_GetPool_Call) Return(_a0 margintypes.Pool, _a1 bool) *MarginKeeper_GetPool_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MarginKeeper_GetPool_Call) RunAndReturn(run func(types.Context, uint64) (margintypes.Pool, bool)) *MarginKeeper_GetPool_Call { + _c.Call.Return(run) + return _c +} + +// IsPoolClosed provides a mock function with given fields: ctx, poolId +func (_m *MarginKeeper) IsPoolClosed(ctx types.Context, poolId uint64) bool { + ret := _m.Called(ctx, poolId) + + var r0 bool + if rf, ok := ret.Get(0).(func(types.Context, uint64) bool); ok { + r0 = rf(ctx, poolId) + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// MarginKeeper_IsPoolClosed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsPoolClosed' +type MarginKeeper_IsPoolClosed_Call struct { + *mock.Call +} + +// IsPoolClosed is a helper method to define mock.On call +// - ctx types.Context +// - poolId uint64 +func (_e *MarginKeeper_Expecter) IsPoolClosed(ctx interface{}, poolId interface{}) *MarginKeeper_IsPoolClosed_Call { + return &MarginKeeper_IsPoolClosed_Call{Call: _e.mock.On("IsPoolClosed", ctx, poolId)} +} + +func (_c *MarginKeeper_IsPoolClosed_Call) Run(run func(ctx types.Context, poolId uint64)) *MarginKeeper_IsPoolClosed_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(uint64)) + }) + return _c +} + +func (_c *MarginKeeper_IsPoolClosed_Call) Return(_a0 bool) *MarginKeeper_IsPoolClosed_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MarginKeeper_IsPoolClosed_Call) RunAndReturn(run func(types.Context, uint64) bool) *MarginKeeper_IsPoolClosed_Call { + _c.Call.Return(run) + return _c +} + +// IsPoolEnabled provides a mock function with given fields: ctx, poolId +func (_m *MarginKeeper) IsPoolEnabled(ctx types.Context, poolId uint64) bool { + ret := _m.Called(ctx, poolId) + + var r0 bool + if rf, ok := ret.Get(0).(func(types.Context, uint64) bool); ok { + r0 = rf(ctx, poolId) + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// MarginKeeper_IsPoolEnabled_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsPoolEnabled' +type MarginKeeper_IsPoolEnabled_Call struct { + *mock.Call +} + +// IsPoolEnabled is a helper method to define mock.On call +// - ctx types.Context +// - poolId uint64 +func (_e *MarginKeeper_Expecter) IsPoolEnabled(ctx interface{}, poolId interface{}) *MarginKeeper_IsPoolEnabled_Call { + return &MarginKeeper_IsPoolEnabled_Call{Call: _e.mock.On("IsPoolEnabled", ctx, poolId)} +} + +func (_c *MarginKeeper_IsPoolEnabled_Call) Run(run func(ctx types.Context, poolId uint64)) *MarginKeeper_IsPoolEnabled_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(uint64)) + }) + return _c +} + +func (_c *MarginKeeper_IsPoolEnabled_Call) Return(_a0 bool) *MarginKeeper_IsPoolEnabled_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MarginKeeper_IsPoolEnabled_Call) RunAndReturn(run func(types.Context, uint64) bool) *MarginKeeper_IsPoolEnabled_Call { + _c.Call.Return(run) + return _c +} + +// NewMarginKeeper creates a new instance of MarginKeeper. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMarginKeeper(t interface { + mock.TestingT + Cleanup(func()) +}) *MarginKeeper { + mock := &MarginKeeper{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/x/accountedpool/types/params.go b/x/accountedpool/types/params.go new file mode 100644 index 000000000..c1d2dce16 --- /dev/null +++ b/x/accountedpool/types/params.go @@ -0,0 +1,41 @@ +package types + +import ( + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + "gopkg.in/yaml.v2" +) + +var ( + _ paramtypes.ParamSet = (*Params)(nil) +) + +// ParamKeyTable the param key table for launch module +func ParamKeyTable() paramtypes.KeyTable { + return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) +} + +// NewParams creates a new Params instance +func NewParams() Params { + return Params{} +} + +// DefaultParams returns a default set of parameters +func DefaultParams() Params { + return NewParams() +} + +// ParamSetPairs get the params.ParamSet +func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { + return paramtypes.ParamSetPairs{} +} + +// Validate validates the set of params +func (p Params) Validate() error { + return nil +} + +// String implements the Stringer interface. +func (p Params) String() string { + out, _ := yaml.Marshal(p) + return string(out) +} diff --git a/x/accountedpool/types/params.pb.go b/x/accountedpool/types/params.pb.go new file mode 100644 index 000000000..32c1d1ae6 --- /dev/null +++ b/x/accountedpool/types/params.pb.go @@ -0,0 +1,264 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: elys/accountedpool/params.proto + +package types + +import ( + fmt "fmt" + _ "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 + +// Params defines the parameters for the module. +type Params struct { +} + +func (m *Params) Reset() { *m = Params{} } +func (*Params) ProtoMessage() {} +func (*Params) Descriptor() ([]byte, []int) { + return fileDescriptor_5584d9bd0669ed47, []int{0} +} +func (m *Params) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Params.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 *Params) XXX_Merge(src proto.Message) { + xxx_messageInfo_Params.Merge(m, src) +} +func (m *Params) XXX_Size() int { + return m.Size() +} +func (m *Params) XXX_DiscardUnknown() { + xxx_messageInfo_Params.DiscardUnknown(m) +} + +var xxx_messageInfo_Params proto.InternalMessageInfo + +func init() { + proto.RegisterType((*Params)(nil), "elys.accountedpool.Params") +} + +func init() { proto.RegisterFile("elys/accountedpool/params.proto", fileDescriptor_5584d9bd0669ed47) } + +var fileDescriptor_5584d9bd0669ed47 = []byte{ + // 157 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xcd, 0xa9, 0x2c, + 0xd6, 0x4f, 0x4c, 0x4e, 0xce, 0x2f, 0xcd, 0x2b, 0x49, 0x4d, 0x29, 0xc8, 0xcf, 0xcf, 0xd1, 0x2f, + 0x48, 0x2c, 0x4a, 0xcc, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x02, 0x29, 0xd0, + 0x43, 0x51, 0x20, 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, 0x96, 0xd6, 0x07, 0xb1, 0x20, 0x2a, 0x95, + 0xf8, 0xb8, 0xd8, 0x02, 0xc0, 0x3a, 0xad, 0x58, 0x66, 0x2c, 0x90, 0x67, 0x70, 0xf2, 0x39, 0xf1, + 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, + 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, 0xa3, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, + 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0x90, 0xf1, 0xba, 0x79, 0xa9, 0x25, 0xe5, 0xf9, 0x45, 0xd9, 0x60, + 0x8e, 0x7e, 0x05, 0x9a, 0x73, 0x4a, 0x2a, 0x0b, 0x52, 0x8b, 0x93, 0xd8, 0xc0, 0x96, 0x18, 0x03, + 0x02, 0x00, 0x00, 0xff, 0xff, 0x8d, 0xc0, 0x6a, 0xe6, 0xb1, 0x00, 0x00, 0x00, +} + +func (m *Params) 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 *Params) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func encodeVarintParams(dAtA []byte, offset int, v uint64) int { + offset -= sovParams(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Params) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func sovParams(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozParams(x uint64) (n int) { + return sovParams(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Params) 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 ErrIntOverflowParams + } + 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: Params: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipParams(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthParams + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipParams(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, ErrIntOverflowParams + } + 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, ErrIntOverflowParams + } + 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, ErrIntOverflowParams + } + 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, ErrInvalidLengthParams + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupParams + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthParams + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthParams = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowParams = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupParams = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/accountedpool/types/pool_asset.pb.go b/x/accountedpool/types/pool_asset.pb.go new file mode 100644 index 000000000..10f726209 --- /dev/null +++ b/x/accountedpool/types/pool_asset.pb.go @@ -0,0 +1,373 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: elys/tvl/pool_asset.proto + +package types + +import ( + fmt "fmt" + github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" + 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 + +type PoolAsset struct { + Token types.Coin `protobuf:"bytes,1,opt,name=token,proto3" json:"token"` + Weight github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=weight,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"weight"` +} + +func (m *PoolAsset) Reset() { *m = PoolAsset{} } +func (m *PoolAsset) String() string { return proto.CompactTextString(m) } +func (*PoolAsset) ProtoMessage() {} +func (*PoolAsset) Descriptor() ([]byte, []int) { + return fileDescriptor_6805af7a13dc8985, []int{0} +} +func (m *PoolAsset) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PoolAsset) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PoolAsset.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 *PoolAsset) XXX_Merge(src proto.Message) { + xxx_messageInfo_PoolAsset.Merge(m, src) +} +func (m *PoolAsset) XXX_Size() int { + return m.Size() +} +func (m *PoolAsset) XXX_DiscardUnknown() { + xxx_messageInfo_PoolAsset.DiscardUnknown(m) +} + +var xxx_messageInfo_PoolAsset proto.InternalMessageInfo + +func (m *PoolAsset) GetToken() types.Coin { + if m != nil { + return m.Token + } + return types.Coin{} +} + +func init() { + proto.RegisterType((*PoolAsset)(nil), "elys.tvl.PoolAsset") +} + +func init() { proto.RegisterFile("elys/tvl/pool_asset.proto", fileDescriptor_6805af7a13dc8985) } + +var fileDescriptor_6805af7a13dc8985 = []byte{ + // 263 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x90, 0xbd, 0x4e, 0xc3, 0x30, + 0x14, 0x85, 0x63, 0x04, 0x15, 0x0d, 0x5b, 0xc4, 0xd0, 0x76, 0x70, 0x2b, 0x06, 0x94, 0xa5, 0xbe, + 0x2a, 0x88, 0x07, 0x20, 0x48, 0x48, 0x6c, 0xa8, 0x23, 0x0b, 0x4a, 0x82, 0x95, 0x46, 0x71, 0x7d, + 0xa3, 0xfa, 0x92, 0xd2, 0x57, 0x60, 0xe2, 0xb1, 0x3a, 0x76, 0x44, 0x0c, 0x15, 0x4a, 0x5e, 0x04, + 0xd9, 0xce, 0xc0, 0xe4, 0x9f, 0xcf, 0xdf, 0x91, 0xcf, 0x0d, 0xc7, 0x52, 0xed, 0x0c, 0x50, 0xa3, + 0xa0, 0x46, 0x54, 0xaf, 0xa9, 0x31, 0x92, 0x44, 0xbd, 0x41, 0xc2, 0xe8, 0xdc, 0x22, 0x41, 0x8d, + 0x9a, 0x5c, 0x16, 0x58, 0xa0, 0xbb, 0x04, 0xbb, 0xf3, 0x7c, 0xc2, 0x73, 0x34, 0x6b, 0x34, 0x90, + 0xa5, 0x46, 0x42, 0xb3, 0xc8, 0x24, 0xa5, 0x0b, 0xc8, 0xb1, 0xd4, 0x9e, 0x5f, 0x7d, 0xb2, 0x70, + 0xf8, 0x8c, 0xa8, 0xee, 0x6d, 0x66, 0x74, 0x17, 0x9e, 0x11, 0x56, 0x52, 0x8f, 0xd8, 0x8c, 0xc5, + 0x17, 0x37, 0x63, 0xe1, 0x6d, 0x61, 0x6d, 0xd1, 0xdb, 0xe2, 0x01, 0x4b, 0x9d, 0x9c, 0xee, 0x8f, + 0xd3, 0x60, 0xe9, 0x5f, 0x47, 0x8f, 0xe1, 0x60, 0x2b, 0xcb, 0x62, 0x45, 0xa3, 0x93, 0x19, 0x8b, + 0x87, 0x89, 0xb0, 0xf0, 0xe7, 0x38, 0xbd, 0x2e, 0x4a, 0x5a, 0xbd, 0x67, 0x22, 0xc7, 0x35, 0xf4, + 0xff, 0xf0, 0xcb, 0xdc, 0xbc, 0x55, 0x40, 0xbb, 0x5a, 0x1a, 0xf1, 0xa4, 0x69, 0xd9, 0xdb, 0x49, + 0xb2, 0x6f, 0x39, 0x3b, 0xb4, 0x9c, 0xfd, 0xb6, 0x9c, 0x7d, 0x75, 0x3c, 0x38, 0x74, 0x3c, 0xf8, + 0xee, 0x78, 0xf0, 0x12, 0xff, 0x4b, 0xb2, 0x8d, 0xe7, 0x5a, 0xd2, 0x16, 0x37, 0x95, 0x3b, 0xc0, + 0x87, 0x9b, 0x8d, 0xcb, 0xcb, 0x06, 0xae, 0xd7, 0xed, 0x5f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xba, + 0x59, 0xf8, 0x08, 0x34, 0x01, 0x00, 0x00, +} + +func (m *PoolAsset) 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 *PoolAsset) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PoolAsset) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size := m.Weight.Size() + i -= size + if _, err := m.Weight.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintPoolAsset(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + { + size, err := m.Token.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintPoolAsset(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintPoolAsset(dAtA []byte, offset int, v uint64) int { + offset -= sovPoolAsset(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *PoolAsset) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Token.Size() + n += 1 + l + sovPoolAsset(uint64(l)) + l = m.Weight.Size() + n += 1 + l + sovPoolAsset(uint64(l)) + return n +} + +func sovPoolAsset(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozPoolAsset(x uint64) (n int) { + return sovPoolAsset(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *PoolAsset) 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 ErrIntOverflowPoolAsset + } + 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: PoolAsset: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PoolAsset: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Token", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPoolAsset + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPoolAsset + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthPoolAsset + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Token.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Weight", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPoolAsset + } + 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 ErrInvalidLengthPoolAsset + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPoolAsset + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Weight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipPoolAsset(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthPoolAsset + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipPoolAsset(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, ErrIntOverflowPoolAsset + } + 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, ErrIntOverflowPoolAsset + } + 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, ErrIntOverflowPoolAsset + } + 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, ErrInvalidLengthPoolAsset + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupPoolAsset + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthPoolAsset + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthPoolAsset = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowPoolAsset = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupPoolAsset = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/accountedpool/types/query.pb.go b/x/accountedpool/types/query.pb.go new file mode 100644 index 000000000..3ad30c3a5 --- /dev/null +++ b/x/accountedpool/types/query.pb.go @@ -0,0 +1,1370 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: elys/accountedpool/query.proto + +package types + +import ( + context "context" + fmt "fmt" + query "github.com/cosmos/cosmos-sdk/types/query" + _ "github.com/cosmos/gogoproto/gogoproto" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + _ "google.golang.org/genproto/googleapis/api/annotations" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + 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 + +// QueryParamsRequest is request type for the Query/Params RPC method. +type QueryParamsRequest struct { +} + +func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } +func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } +func (*QueryParamsRequest) ProtoMessage() {} +func (*QueryParamsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_2ec06194af40e0c7, []int{0} +} +func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryParamsRequest.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 *QueryParamsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryParamsRequest.Merge(m, src) +} +func (m *QueryParamsRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryParamsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo + +// QueryParamsResponse is response type for the Query/Params RPC method. +type QueryParamsResponse struct { + // params holds all the parameters of this module. + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` +} + +func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } +func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } +func (*QueryParamsResponse) ProtoMessage() {} +func (*QueryParamsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_2ec06194af40e0c7, []int{1} +} +func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryParamsResponse.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 *QueryParamsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryParamsResponse.Merge(m, src) +} +func (m *QueryParamsResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryParamsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo + +func (m *QueryParamsResponse) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +type QueryGetAccountedPoolRequest struct { + PoolId uint64 `protobuf:"varint,1,opt,name=poolId,proto3" json:"poolId,omitempty"` +} + +func (m *QueryGetAccountedPoolRequest) Reset() { *m = QueryGetAccountedPoolRequest{} } +func (m *QueryGetAccountedPoolRequest) String() string { return proto.CompactTextString(m) } +func (*QueryGetAccountedPoolRequest) ProtoMessage() {} +func (*QueryGetAccountedPoolRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_2ec06194af40e0c7, []int{2} +} +func (m *QueryGetAccountedPoolRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryGetAccountedPoolRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryGetAccountedPoolRequest.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 *QueryGetAccountedPoolRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryGetAccountedPoolRequest.Merge(m, src) +} +func (m *QueryGetAccountedPoolRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryGetAccountedPoolRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryGetAccountedPoolRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryGetAccountedPoolRequest proto.InternalMessageInfo + +func (m *QueryGetAccountedPoolRequest) GetPoolId() uint64 { + if m != nil { + return m.PoolId + } + return 0 +} + +type QueryGetAccountedPoolResponse struct { + AccountedPool AccountedPool `protobuf:"bytes,1,opt,name=accountedPool,proto3" json:"accountedPool"` +} + +func (m *QueryGetAccountedPoolResponse) Reset() { *m = QueryGetAccountedPoolResponse{} } +func (m *QueryGetAccountedPoolResponse) String() string { return proto.CompactTextString(m) } +func (*QueryGetAccountedPoolResponse) ProtoMessage() {} +func (*QueryGetAccountedPoolResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_2ec06194af40e0c7, []int{3} +} +func (m *QueryGetAccountedPoolResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryGetAccountedPoolResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryGetAccountedPoolResponse.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 *QueryGetAccountedPoolResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryGetAccountedPoolResponse.Merge(m, src) +} +func (m *QueryGetAccountedPoolResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryGetAccountedPoolResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryGetAccountedPoolResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryGetAccountedPoolResponse proto.InternalMessageInfo + +func (m *QueryGetAccountedPoolResponse) GetAccountedPool() AccountedPool { + if m != nil { + return m.AccountedPool + } + return AccountedPool{} +} + +type QueryAllAccountedPoolRequest struct { + Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryAllAccountedPoolRequest) Reset() { *m = QueryAllAccountedPoolRequest{} } +func (m *QueryAllAccountedPoolRequest) String() string { return proto.CompactTextString(m) } +func (*QueryAllAccountedPoolRequest) ProtoMessage() {} +func (*QueryAllAccountedPoolRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_2ec06194af40e0c7, []int{4} +} +func (m *QueryAllAccountedPoolRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryAllAccountedPoolRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryAllAccountedPoolRequest.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 *QueryAllAccountedPoolRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryAllAccountedPoolRequest.Merge(m, src) +} +func (m *QueryAllAccountedPoolRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryAllAccountedPoolRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryAllAccountedPoolRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryAllAccountedPoolRequest proto.InternalMessageInfo + +func (m *QueryAllAccountedPoolRequest) GetPagination() *query.PageRequest { + if m != nil { + return m.Pagination + } + return nil +} + +type QueryAllAccountedPoolResponse struct { + AccountedPool []AccountedPool `protobuf:"bytes,1,rep,name=accountedPool,proto3" json:"accountedPool"` + Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryAllAccountedPoolResponse) Reset() { *m = QueryAllAccountedPoolResponse{} } +func (m *QueryAllAccountedPoolResponse) String() string { return proto.CompactTextString(m) } +func (*QueryAllAccountedPoolResponse) ProtoMessage() {} +func (*QueryAllAccountedPoolResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_2ec06194af40e0c7, []int{5} +} +func (m *QueryAllAccountedPoolResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryAllAccountedPoolResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryAllAccountedPoolResponse.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 *QueryAllAccountedPoolResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryAllAccountedPoolResponse.Merge(m, src) +} +func (m *QueryAllAccountedPoolResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryAllAccountedPoolResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryAllAccountedPoolResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryAllAccountedPoolResponse proto.InternalMessageInfo + +func (m *QueryAllAccountedPoolResponse) GetAccountedPool() []AccountedPool { + if m != nil { + return m.AccountedPool + } + return nil +} + +func (m *QueryAllAccountedPoolResponse) GetPagination() *query.PageResponse { + if m != nil { + return m.Pagination + } + return nil +} + +func init() { + proto.RegisterType((*QueryParamsRequest)(nil), "elys.accountedpool.QueryParamsRequest") + proto.RegisterType((*QueryParamsResponse)(nil), "elys.accountedpool.QueryParamsResponse") + proto.RegisterType((*QueryGetAccountedPoolRequest)(nil), "elys.accountedpool.QueryGetAccountedPoolRequest") + proto.RegisterType((*QueryGetAccountedPoolResponse)(nil), "elys.accountedpool.QueryGetAccountedPoolResponse") + proto.RegisterType((*QueryAllAccountedPoolRequest)(nil), "elys.accountedpool.QueryAllAccountedPoolRequest") + proto.RegisterType((*QueryAllAccountedPoolResponse)(nil), "elys.accountedpool.QueryAllAccountedPoolResponse") +} + +func init() { proto.RegisterFile("elys/accountedpool/query.proto", fileDescriptor_2ec06194af40e0c7) } + +var fileDescriptor_2ec06194af40e0c7 = []byte{ + // 506 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x94, 0x41, 0x8b, 0x13, 0x31, + 0x14, 0xc7, 0x9b, 0xb5, 0xf6, 0x10, 0x59, 0x90, 0xb8, 0x88, 0x0c, 0xeb, 0xac, 0xe6, 0xb0, 0x55, + 0xc1, 0xc4, 0x56, 0xd0, 0xc5, 0x93, 0xdd, 0x83, 0x8b, 0xa0, 0x58, 0x7b, 0xf4, 0x22, 0x69, 0x37, + 0x8e, 0xc5, 0x69, 0xde, 0x6c, 0x93, 0x51, 0x8b, 0x08, 0xe2, 0xd1, 0x93, 0xe0, 0x17, 0xf1, 0xa4, + 0x5f, 0x61, 0x8f, 0x0b, 0x5e, 0x3c, 0x89, 0xb4, 0x7e, 0x10, 0x99, 0x24, 0xab, 0x8d, 0x9d, 0xd9, + 0x52, 0x6f, 0x4d, 0xdf, 0xff, 0xff, 0xfe, 0xbf, 0xcc, 0x7b, 0x33, 0x38, 0x96, 0xe9, 0x44, 0x73, + 0x31, 0x18, 0x40, 0xae, 0x8c, 0xdc, 0xcf, 0x00, 0x52, 0x7e, 0x90, 0xcb, 0xf1, 0x84, 0x65, 0x63, + 0x30, 0x40, 0x48, 0x51, 0x67, 0x41, 0x3d, 0xda, 0x48, 0x20, 0x01, 0x5b, 0xe6, 0xc5, 0x2f, 0xa7, + 0x8c, 0x36, 0x13, 0x80, 0x24, 0x95, 0x5c, 0x64, 0x43, 0x2e, 0x94, 0x02, 0x23, 0xcc, 0x10, 0x94, + 0xf6, 0xd5, 0x6b, 0x03, 0xd0, 0x23, 0xd0, 0xbc, 0x2f, 0xb4, 0x74, 0x01, 0xfc, 0x65, 0xab, 0x2f, + 0x8d, 0x68, 0xf1, 0x4c, 0x24, 0x43, 0x65, 0xc5, 0x5e, 0xbb, 0x55, 0xc2, 0x94, 0x89, 0xb1, 0x18, + 0x1d, 0x37, 0x6b, 0x96, 0x08, 0xfe, 0x9c, 0x9e, 0x16, 0x47, 0x27, 0xa4, 0x1b, 0x98, 0x3c, 0x2e, + 0xb2, 0xba, 0xd6, 0xdd, 0x93, 0x07, 0xb9, 0xd4, 0x86, 0x3e, 0xc2, 0xe7, 0x82, 0x7f, 0x75, 0x06, + 0x4a, 0x4b, 0xb2, 0x83, 0x1b, 0x2e, 0xe5, 0x02, 0xba, 0x84, 0xae, 0x9c, 0x69, 0x47, 0x6c, 0xf1, + 0xee, 0xcc, 0x79, 0x76, 0xeb, 0x87, 0x3f, 0xb6, 0x6a, 0x3d, 0xaf, 0xa7, 0xb7, 0xf0, 0xa6, 0x6d, + 0xb8, 0x27, 0x4d, 0xe7, 0x58, 0xdd, 0x05, 0x48, 0x7d, 0x20, 0x39, 0x8f, 0x1b, 0x85, 0xf9, 0xfe, + 0xbe, 0xed, 0x5c, 0xef, 0xf9, 0x13, 0x55, 0xf8, 0x62, 0x85, 0xcf, 0x23, 0x3d, 0xc4, 0xeb, 0x62, + 0xbe, 0xe0, 0xc9, 0x2e, 0x97, 0x91, 0x05, 0x1d, 0x3c, 0x60, 0xe8, 0xa6, 0xcf, 0x3c, 0x67, 0x27, + 0x4d, 0x4b, 0x39, 0xef, 0x61, 0xfc, 0x77, 0x18, 0x3e, 0x6b, 0x9b, 0xb9, 0xc9, 0xb1, 0x62, 0x72, + 0xcc, 0xad, 0x86, 0x9f, 0x1c, 0xeb, 0x8a, 0x44, 0x7a, 0x6f, 0x6f, 0xce, 0x49, 0xbf, 0x22, 0x7f, + 0xb1, 0xc5, 0xa0, 0xea, 0x8b, 0x9d, 0xfa, 0xff, 0x8b, 0x91, 0xbd, 0x00, 0x7c, 0xcd, 0x82, 0x37, + 0x97, 0x82, 0x3b, 0x96, 0x79, 0xf2, 0xf6, 0xbb, 0x3a, 0x3e, 0x6d, 0xc9, 0xc9, 0x07, 0x84, 0x1b, + 0x6e, 0xd8, 0x64, 0xbb, 0x8c, 0x6a, 0x71, 0xaf, 0xa2, 0xe6, 0x52, 0x9d, 0x4b, 0xa4, 0xfc, 0xfd, + 0xb7, 0x5f, 0x9f, 0xd6, 0xae, 0x92, 0x26, 0x2f, 0x0c, 0xd7, 0x95, 0x34, 0xaf, 0x60, 0xfc, 0x82, + 0x57, 0xae, 0x3d, 0xf9, 0x82, 0xf0, 0x7a, 0xf0, 0x18, 0xc8, 0x8d, 0xca, 0xac, 0x8a, 0x25, 0x8c, + 0x5a, 0x2b, 0x38, 0x3c, 0xe7, 0x5d, 0xcb, 0x79, 0x87, 0xec, 0x2c, 0xe5, 0x0c, 0xdf, 0x3e, 0xfe, + 0xc6, 0x2d, 0xf8, 0x5b, 0xf2, 0x19, 0xe1, 0xb3, 0x41, 0xef, 0x4e, 0x7a, 0x12, 0x7b, 0xc5, 0x62, + 0x9e, 0xc0, 0x5e, 0xb5, 0x61, 0xf4, 0xb6, 0x65, 0x6f, 0x11, 0xbe, 0x22, 0xfb, 0xee, 0x83, 0xc3, + 0x69, 0x8c, 0x8e, 0xa6, 0x31, 0xfa, 0x39, 0x8d, 0xd1, 0xc7, 0x59, 0x5c, 0x3b, 0x9a, 0xc5, 0xb5, + 0xef, 0xb3, 0xb8, 0xf6, 0xa4, 0x9d, 0x0c, 0xcd, 0xf3, 0xbc, 0xcf, 0x06, 0x30, 0x2a, 0x69, 0xfa, + 0xfa, 0x9f, 0xb6, 0x66, 0x92, 0x49, 0xdd, 0x6f, 0xd8, 0x0f, 0xd1, 0xcd, 0xdf, 0x01, 0x00, 0x00, + 0xff, 0xff, 0x70, 0x88, 0x97, 0xe9, 0x68, 0x05, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// QueryClient is the client API for Query service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type QueryClient interface { + // Parameters queries the parameters of the module. + Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) + // Queries a list of AccountedPool items. + AccountedPool(ctx context.Context, in *QueryGetAccountedPoolRequest, opts ...grpc.CallOption) (*QueryGetAccountedPoolResponse, error) + AccountedPoolAll(ctx context.Context, in *QueryAllAccountedPoolRequest, opts ...grpc.CallOption) (*QueryAllAccountedPoolResponse, error) +} + +type queryClient struct { + cc grpc1.ClientConn +} + +func NewQueryClient(cc grpc1.ClientConn) QueryClient { + return &queryClient{cc} +} + +func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { + out := new(QueryParamsResponse) + err := c.cc.Invoke(ctx, "/elys.accountedpool.Query/Params", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) AccountedPool(ctx context.Context, in *QueryGetAccountedPoolRequest, opts ...grpc.CallOption) (*QueryGetAccountedPoolResponse, error) { + out := new(QueryGetAccountedPoolResponse) + err := c.cc.Invoke(ctx, "/elys.accountedpool.Query/AccountedPool", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) AccountedPoolAll(ctx context.Context, in *QueryAllAccountedPoolRequest, opts ...grpc.CallOption) (*QueryAllAccountedPoolResponse, error) { + out := new(QueryAllAccountedPoolResponse) + err := c.cc.Invoke(ctx, "/elys.accountedpool.Query/AccountedPoolAll", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +type QueryServer interface { + // Parameters queries the parameters of the module. + Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) + // Queries a list of AccountedPool items. + AccountedPool(context.Context, *QueryGetAccountedPoolRequest) (*QueryGetAccountedPoolResponse, error) + AccountedPoolAll(context.Context, *QueryAllAccountedPoolRequest) (*QueryAllAccountedPoolResponse, error) +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct { +} + +func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") +} +func (*UnimplementedQueryServer) AccountedPool(ctx context.Context, req *QueryGetAccountedPoolRequest) (*QueryGetAccountedPoolResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method AccountedPool not implemented") +} +func (*UnimplementedQueryServer) AccountedPoolAll(ctx context.Context, req *QueryAllAccountedPoolRequest) (*QueryAllAccountedPoolResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method AccountedPoolAll not implemented") +} + +func RegisterQueryServer(s grpc1.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryParamsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Params(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/elys.accountedpool.Query/Params", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_AccountedPool_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryGetAccountedPoolRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).AccountedPool(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/elys.accountedpool.Query/AccountedPool", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).AccountedPool(ctx, req.(*QueryGetAccountedPoolRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_AccountedPoolAll_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryAllAccountedPoolRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).AccountedPoolAll(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/elys.accountedpool.Query/AccountedPoolAll", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).AccountedPoolAll(ctx, req.(*QueryAllAccountedPoolRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "elys.accountedpool.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Params", + Handler: _Query_Params_Handler, + }, + { + MethodName: "AccountedPool", + Handler: _Query_AccountedPool_Handler, + }, + { + MethodName: "AccountedPoolAll", + Handler: _Query_AccountedPoolAll_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "elys/accountedpool/query.proto", +} + +func (m *QueryParamsRequest) 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 *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *QueryParamsResponse) 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 *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *QueryGetAccountedPoolRequest) 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 *QueryGetAccountedPoolRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryGetAccountedPoolRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.PoolId != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *QueryGetAccountedPoolResponse) 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 *QueryGetAccountedPoolResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryGetAccountedPoolResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.AccountedPool.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *QueryAllAccountedPoolRequest) 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 *QueryAllAccountedPoolRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryAllAccountedPoolRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryAllAccountedPoolResponse) 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 *QueryAllAccountedPoolResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryAllAccountedPoolResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.AccountedPool) > 0 { + for iNdEx := len(m.AccountedPool) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.AccountedPool[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { + offset -= sovQuery(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *QueryParamsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *QueryParamsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Params.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func (m *QueryGetAccountedPoolRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PoolId != 0 { + n += 1 + sovQuery(uint64(m.PoolId)) + } + return n +} + +func (m *QueryGetAccountedPoolResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.AccountedPool.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func (m *QueryAllAccountedPoolRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryAllAccountedPoolResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.AccountedPool) > 0 { + for _, e := range m.AccountedPool { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func sovQuery(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozQuery(x uint64) (n int) { + return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *QueryParamsRequest) 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 ErrIntOverflowQuery + } + 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: QueryParamsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryParamsResponse) 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 ErrIntOverflowQuery + } + 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: QueryParamsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryGetAccountedPoolRequest) 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 ErrIntOverflowQuery + } + 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: QueryGetAccountedPoolRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryGetAccountedPoolRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) + } + m.PoolId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryGetAccountedPoolResponse) 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 ErrIntOverflowQuery + } + 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: QueryGetAccountedPoolResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryGetAccountedPoolResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AccountedPool", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.AccountedPool.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryAllAccountedPoolRequest) 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 ErrIntOverflowQuery + } + 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: QueryAllAccountedPoolRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryAllAccountedPoolRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Pagination == nil { + m.Pagination = &query.PageRequest{} + } + if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryAllAccountedPoolResponse) 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 ErrIntOverflowQuery + } + 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: QueryAllAccountedPoolResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryAllAccountedPoolResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AccountedPool", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AccountedPool = append(m.AccountedPool, AccountedPool{}) + if err := m.AccountedPool[len(m.AccountedPool)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Pagination == nil { + m.Pagination = &query.PageResponse{} + } + if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipQuery(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, ErrIntOverflowQuery + } + 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, ErrIntOverflowQuery + } + 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, ErrIntOverflowQuery + } + 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, ErrInvalidLengthQuery + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupQuery + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthQuery + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/accountedpool/types/query.pb.gw.go b/x/accountedpool/types/query.pb.gw.go new file mode 100644 index 000000000..e7763d22b --- /dev/null +++ b/x/accountedpool/types/query.pb.gw.go @@ -0,0 +1,337 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: elys/accountedpool/query.proto + +/* +Package types is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package types + +import ( + "context" + "io" + "net/http" + + "github.com/golang/protobuf/descriptor" + "github.com/golang/protobuf/proto" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/grpc-ecosystem/grpc-gateway/utilities" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +// Suppress "imported and not used" errors +var _ codes.Code +var _ io.Reader +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 + var metadata runtime.ServerMetadata + + msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryParamsRequest + var metadata runtime.ServerMetadata + + msg, err := server.Params(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_AccountedPool_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryGetAccountedPoolRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["poolId"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "poolId") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "poolId", err) + } + + msg, err := client.AccountedPool(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_AccountedPool_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryGetAccountedPoolRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["poolId"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "poolId") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "poolId", err) + } + + msg, err := server.AccountedPool(ctx, &protoReq) + return msg, metadata, err + +} + +var ( + filter_Query_AccountedPoolAll_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} +) + +func request_Query_AccountedPoolAll_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryAllAccountedPoolRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_AccountedPoolAll_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.AccountedPoolAll(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_AccountedPoolAll_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryAllAccountedPoolRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_AccountedPoolAll_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.AccountedPoolAll(ctx, &protoReq) + return msg, metadata, err + +} + +// 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 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 { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + 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) + return + } + + forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_AccountedPool_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 { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_AccountedPool_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) + return + } + + forward_Query_AccountedPool_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_AccountedPoolAll_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 { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_AccountedPoolAll_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) + return + } + + forward_Query_AccountedPoolAll_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.Dial(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + + return RegisterQueryHandler(ctx, mux, conn) +} + +// RegisterQueryHandler registers the http handlers for service Query to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) +} + +// RegisterQueryHandlerClient registers the http handlers for service Query +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "QueryClient" to call the correct interceptors. +func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) 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() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_AccountedPool_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_AccountedPool_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_AccountedPool_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_AccountedPoolAll_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_AccountedPoolAll_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_AccountedPoolAll_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"elys-network", "elys", "accountedpool", "params"}, "", runtime.AssumeColonVerbOpt(true))) + + pattern_Query_AccountedPool_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"elys-network", "elys", "accountedpool", "accounted_pool", "poolId"}, "", runtime.AssumeColonVerbOpt(true))) + + pattern_Query_AccountedPoolAll_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"elys-network", "elys", "accountedpool", "accounted_pool"}, "", runtime.AssumeColonVerbOpt(true))) +) + +var ( + forward_Query_Params_0 = runtime.ForwardResponseMessage + + forward_Query_AccountedPool_0 = runtime.ForwardResponseMessage + + forward_Query_AccountedPoolAll_0 = runtime.ForwardResponseMessage +) diff --git a/x/accountedpool/types/tx.pb.go b/x/accountedpool/types/tx.pb.go new file mode 100644 index 000000000..67fae349e --- /dev/null +++ b/x/accountedpool/types/tx.pb.go @@ -0,0 +1,81 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: elys/accountedpool/tx.proto + +package types + +import ( + context "context" + fmt "fmt" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + grpc "google.golang.org/grpc" + math "math" +) + +// 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 + +func init() { proto.RegisterFile("elys/accountedpool/tx.proto", fileDescriptor_8792482078796b08) } + +var fileDescriptor_8792482078796b08 = []byte{ + // 133 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4e, 0xcd, 0xa9, 0x2c, + 0xd6, 0x4f, 0x4c, 0x4e, 0xce, 0x2f, 0xcd, 0x2b, 0x49, 0x4d, 0x29, 0xc8, 0xcf, 0xcf, 0xd1, 0x2f, + 0xa9, 0xd0, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x02, 0x49, 0xea, 0xa1, 0x48, 0x1a, 0xb1, + 0x72, 0x31, 0xfb, 0x16, 0xa7, 0x3b, 0xf9, 0x9c, 0x78, 0x24, 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, + 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, 0x31, 0x5c, 0x78, 0x2c, 0xc7, 0x70, 0xe3, 0xb1, 0x1c, + 0x43, 0x94, 0x51, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x3e, 0x48, 0xbf, + 0x6e, 0x5e, 0x6a, 0x49, 0x79, 0x7e, 0x51, 0x36, 0x98, 0xa3, 0x5f, 0x81, 0x6e, 0x57, 0x65, 0x41, + 0x6a, 0x71, 0x12, 0x1b, 0xd8, 0x3e, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xf6, 0x9b, 0x0e, + 0x1d, 0x8e, 0x00, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// MsgClient is the client API for Msg service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type MsgClient interface { +} + +type msgClient struct { + cc grpc1.ClientConn +} + +func NewMsgClient(cc grpc1.ClientConn) MsgClient { + return &msgClient{cc} +} + +// MsgServer is the server API for Msg service. +type MsgServer interface { +} + +// UnimplementedMsgServer can be embedded to have forward compatible implementations. +type UnimplementedMsgServer struct { +} + +func RegisterMsgServer(s grpc1.Server, srv MsgServer) { + s.RegisterService(&_Msg_serviceDesc, srv) +} + +var _Msg_serviceDesc = grpc.ServiceDesc{ + ServiceName: "elys.accountedpool.Msg", + HandlerType: (*MsgServer)(nil), + Methods: []grpc.MethodDesc{}, + Streams: []grpc.StreamDesc{}, + Metadata: "elys/accountedpool/tx.proto", +} diff --git a/x/accountedpool/types/types.go b/x/accountedpool/types/types.go new file mode 100644 index 000000000..ab1254f4c --- /dev/null +++ b/x/accountedpool/types/types.go @@ -0,0 +1 @@ +package types diff --git a/x/amm/keeper/apply_exit_pool_state_change.go b/x/amm/keeper/apply_exit_pool_state_change.go index 8ab28bd06..3f772a3ad 100644 --- a/x/amm/keeper/apply_exit_pool_state_change.go +++ b/x/amm/keeper/apply_exit_pool_state_change.go @@ -50,7 +50,7 @@ func (k Keeper) applyExitPoolStateChange(ctx sdk.Context, pool types.Pool, exite types.EmitRemoveLiquidityEvent(ctx, exiter, pool.GetPoolId(), exitCoins) if k.hooks != nil { - k.hooks.AfterExitPool(ctx, exiter, pool.GetPoolId(), numShares, exitCoins) + k.hooks.AfterExitPool(ctx, exiter, pool, numShares, exitCoins) } k.RecordTotalLiquidityDecrease(ctx, exitCoins) return nil diff --git a/x/amm/keeper/apply_join_pool_state_change.go b/x/amm/keeper/apply_join_pool_state_change.go index 3494b0e0b..ba55f7aeb 100644 --- a/x/amm/keeper/apply_join_pool_state_change.go +++ b/x/amm/keeper/apply_join_pool_state_change.go @@ -20,7 +20,7 @@ func (k Keeper) applyJoinPoolStateChange(ctx sdk.Context, pool types.Pool, joine types.EmitAddLiquidityEvent(ctx, joiner, pool.GetPoolId(), joinCoins) if k.hooks != nil { - k.hooks.AfterJoinPool(ctx, joiner, pool.GetPoolId(), joinCoins, numShares) + k.hooks.AfterJoinPool(ctx, joiner, pool, joinCoins, numShares) } k.RecordTotalLiquidityIncrease(ctx, joinCoins) return nil diff --git a/x/amm/keeper/calc_in_amt_given_out.go b/x/amm/keeper/calc_in_amt_given_out.go new file mode 100644 index 000000000..27668b568 --- /dev/null +++ b/x/amm/keeper/calc_in_amt_given_out.go @@ -0,0 +1,25 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/elys-network/elys/x/amm/types" +) + +// CalcInAmtGivenOut calculates token to be provided, fee added, +// given the swapped out amount, using solveConstantFunctionInvariant. +func (k Keeper) CalcInAmtGivenOut( + ctx sdk.Context, + poolId uint64, + oracle types.OracleKeeper, + snapshot *types.Pool, + tokensOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) ( + tokenIn sdk.Coin, err error, +) { + p, found := k.GetPool(ctx, poolId) + if !found { + return sdk.Coin{}, sdkerrors.Wrapf(types.ErrInvalidPool, "invalid pool") + } + + return p.CalcInAmtGivenOut(ctx, oracle, snapshot, tokensOut, tokenInDenom, swapFee, k.accountedPoolKeeper) +} diff --git a/x/amm/keeper/calc_out_amt_given_in.go b/x/amm/keeper/calc_out_amt_given_in.go new file mode 100644 index 000000000..62f71439b --- /dev/null +++ b/x/amm/keeper/calc_out_amt_given_in.go @@ -0,0 +1,26 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/elys-network/elys/x/amm/types" +) + +// CalcOutAmtGivenIn calculates tokens to be swapped out given the provided +// amount and fee deducted, using solveConstantFunctionInvariant. +func (k Keeper) CalcOutAmtGivenIn( + ctx sdk.Context, + poolId uint64, + oracle types.OracleKeeper, + snapshot *types.Pool, + tokensIn sdk.Coins, + tokenOutDenom string, + swapFee sdk.Dec, +) (sdk.Coin, error) { + p, found := k.GetPool(ctx, poolId) + if !found { + return sdk.Coin{}, sdkerrors.Wrapf(types.ErrInvalidPool, "invalid pool") + } + + return p.CalcOutAmtGivenIn(ctx, oracle, snapshot, tokensIn, tokenOutDenom, swapFee, k.accountedPoolKeeper) +} diff --git a/x/amm/keeper/create_elys_multihop_expected_swap_outs.go b/x/amm/keeper/create_elys_multihop_expected_swap_outs.go index 0b1bc5b49..ac45408b7 100644 --- a/x/amm/keeper/create_elys_multihop_expected_swap_outs.go +++ b/x/amm/keeper/create_elys_multihop_expected_swap_outs.go @@ -28,7 +28,7 @@ func (k Keeper) createElysMultihopExpectedSwapOuts( } snapshot := k.GetPoolSnapshotOrSet(ctx, pool) - tokenIn, err := pool.CalcInAmtGivenOut(ctx, k.oracleKeeper, &snapshot, sdk.NewCoins(tokenOut), route.TokenInDenom, actualSwapFee) + tokenIn, err := pool.CalcInAmtGivenOut(ctx, k.oracleKeeper, &snapshot, sdk.NewCoins(tokenOut), route.TokenInDenom, actualSwapFee, k.accountedPoolKeeper) if err != nil { return nil, err } diff --git a/x/amm/keeper/create_multihop_expected_swap_outs.go b/x/amm/keeper/create_multihop_expected_swap_outs.go index 0ee5ca7a4..3e1cf5fbf 100644 --- a/x/amm/keeper/create_multihop_expected_swap_outs.go +++ b/x/amm/keeper/create_multihop_expected_swap_outs.go @@ -27,7 +27,7 @@ func (k Keeper) createMultihopExpectedSwapOuts( } snapshot := k.GetPoolSnapshotOrSet(ctx, pool) - tokenIn, err := pool.CalcInAmtGivenOut(ctx, k.oracleKeeper, &snapshot, sdk.NewCoins(tokenOut), route.TokenInDenom, pool.GetPoolParams().SwapFee) + tokenIn, err := pool.CalcInAmtGivenOut(ctx, k.oracleKeeper, &snapshot, sdk.NewCoins(tokenOut), route.TokenInDenom, pool.GetPoolParams().SwapFee, k.accountedPoolKeeper) if err != nil { return nil, err } diff --git a/x/amm/keeper/fee.go b/x/amm/keeper/fee.go index c78138e4f..1be5778f9 100644 --- a/x/amm/keeper/fee.go +++ b/x/amm/keeper/fee.go @@ -41,7 +41,7 @@ func (k Keeper) SwapFeesToRevenueToken(ctx sdk.Context, pool types.Pool, fee sdk // Executes the swap in the pool and stores the output. Updates pool assets but // does not actually transfer any tokens to or from the pool. snapshot := k.GetPoolSnapshotOrSet(ctx, pool) - tokenOutCoin, _, err := pool.SwapOutAmtGivenIn(ctx, k.oracleKeeper, &snapshot, sdk.Coins{tokenIn}, pool.PoolParams.FeeDenom, sdk.ZeroDec()) + tokenOutCoin, _, err := pool.SwapOutAmtGivenIn(ctx, k.oracleKeeper, &snapshot, sdk.Coins{tokenIn}, pool.PoolParams.FeeDenom, sdk.ZeroDec(), k.accountedPoolKeeper) if err != nil { return err } diff --git a/x/amm/keeper/initialize_pool.go b/x/amm/keeper/initialize_pool.go index d4ac70ddd..e67163a52 100644 --- a/x/amm/keeper/initialize_pool.go +++ b/x/amm/keeper/initialize_pool.go @@ -58,7 +58,7 @@ func (k Keeper) InitializePool(ctx sdk.Context, pool *types.Pool, sender sdk.Acc } if k.hooks != nil { - k.hooks.AfterPoolCreated(ctx, sender, pool.GetPoolId()) + k.hooks.AfterPoolCreated(ctx, sender, *pool) } return nil } diff --git a/x/amm/keeper/keeper.go b/x/amm/keeper/keeper.go index a1e6e7c81..c2f72f49b 100644 --- a/x/amm/keeper/keeper.go +++ b/x/amm/keeper/keeper.go @@ -21,11 +21,12 @@ type ( paramstore paramtypes.Subspace hooks types.AmmHooks - bankKeeper types.BankKeeper - accountKeeper types.AccountKeeper - oracleKeeper types.OracleKeeper - commitmentKeeper *commitmentkeeper.Keeper - apKeeper types.AssetProfileKeeper + bankKeeper types.BankKeeper + accountKeeper types.AccountKeeper + oracleKeeper types.OracleKeeper + commitmentKeeper *commitmentkeeper.Keeper + apKeeper types.AssetProfileKeeper + accountedPoolKeeper types.AccountedPoolKeeper } ) @@ -40,6 +41,7 @@ func NewKeeper( oracleKeeper types.OracleKeeper, commitmentKeeper *commitmentkeeper.Keeper, apKeeper types.AssetProfileKeeper, + accountedPoolKeeper types.AccountedPoolKeeper, ) *Keeper { // set KeyTable if it has not already been set if !ps.HasKeyTable() { @@ -57,6 +59,7 @@ func NewKeeper( oracleKeeper: oracleKeeper, commitmentKeeper: commitmentKeeper, apKeeper: apKeeper, + accountedPoolKeeper: accountedPoolKeeper, } } diff --git a/x/amm/keeper/keeper_exit_pool.go b/x/amm/keeper/keeper_exit_pool.go index 3da8b817a..0fa875f39 100644 --- a/x/amm/keeper/keeper_exit_pool.go +++ b/x/amm/keeper/keeper_exit_pool.go @@ -25,7 +25,7 @@ func (k Keeper) ExitPool( } else if shareInAmount.LTE(sdk.ZeroInt()) { return sdk.Coins{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, "Trying to exit a negative amount of shares") } - exitCoins, err = pool.ExitPool(ctx, k.oracleKeeper, shareInAmount, tokenOutDenom) + exitCoins, err = pool.ExitPool(ctx, k.oracleKeeper, k.accountedPoolKeeper, shareInAmount, tokenOutDenom) if err != nil { return sdk.Coins{}, err } diff --git a/x/amm/keeper/keeper_join_pool_no_swap.go b/x/amm/keeper/keeper_join_pool_no_swap.go index 5cc4f171f..f8a53c5e2 100644 --- a/x/amm/keeper/keeper_join_pool_no_swap.go +++ b/x/amm/keeper/keeper_join_pool_no_swap.go @@ -60,7 +60,7 @@ func (k Keeper) JoinPoolNoSwap( } } - sharesOut, err = pool.JoinPoolNoSwap(ctx, k.oracleKeeper, neededLpLiquidity) + sharesOut, err = pool.JoinPoolNoSwap(ctx, k.oracleKeeper, k.accountedPoolKeeper, neededLpLiquidity) if err != nil { return nil, sdk.ZeroInt(), err } @@ -80,7 +80,7 @@ func (k Keeper) JoinPoolNoSwap( } // on oracle pool, full tokenInMaxs are used regardless shareOutAmount - sharesOut, err = pool.JoinPoolNoSwap(ctx, k.oracleKeeper, tokenInMaxs) + sharesOut, err = pool.JoinPoolNoSwap(ctx, k.oracleKeeper, k.accountedPoolKeeper, tokenInMaxs) if err != nil { return nil, sdk.ZeroInt(), err } diff --git a/x/amm/keeper/keeper_swap_exact_amount_in.go b/x/amm/keeper/keeper_swap_exact_amount_in.go index bab174d1b..55009e52e 100644 --- a/x/amm/keeper/keeper_swap_exact_amount_in.go +++ b/x/amm/keeper/keeper_swap_exact_amount_in.go @@ -44,7 +44,7 @@ func (k Keeper) SwapExactAmountIn( // Executes the swap in the pool and stores the output. Updates pool assets but // does not actually transfer any tokens to or from the pool. snapshot := k.GetPoolSnapshotOrSet(ctx, pool) - tokenOutCoin, weightBalanceBonus, err := pool.SwapOutAmtGivenIn(ctx, k.oracleKeeper, &snapshot, tokensIn, tokenOutDenom, swapFee) + tokenOutCoin, weightBalanceBonus, err := pool.SwapOutAmtGivenIn(ctx, k.oracleKeeper, &snapshot, tokensIn, tokenOutDenom, swapFee, k.accountedPoolKeeper) if err != nil { return math.Int{}, err } diff --git a/x/amm/keeper/keeper_swap_exact_amount_out.go b/x/amm/keeper/keeper_swap_exact_amount_out.go index 985236652..d8eba3105 100644 --- a/x/amm/keeper/keeper_swap_exact_amount_out.go +++ b/x/amm/keeper/keeper_swap_exact_amount_out.go @@ -40,7 +40,7 @@ func (k Keeper) SwapExactAmountOut( } snapshot := k.GetPoolSnapshotOrSet(ctx, pool) - tokenIn, weightBalanceBonus, err := pool.SwapInAmtGivenOut(ctx, k.oracleKeeper, &snapshot, sdk.Coins{tokenOut}, tokenInDenom, swapFee) + tokenIn, weightBalanceBonus, err := pool.SwapInAmtGivenOut(ctx, k.oracleKeeper, &snapshot, sdk.Coins{tokenOut}, tokenInDenom, swapFee, k.accountedPoolKeeper) if err != nil { return math.Int{}, err } diff --git a/x/amm/keeper/swap_in_amt_given_out.go b/x/amm/keeper/swap_in_amt_given_out.go new file mode 100644 index 000000000..ee6cfe48a --- /dev/null +++ b/x/amm/keeper/swap_in_amt_given_out.go @@ -0,0 +1,22 @@ +package keeper + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/elys-network/elys/x/amm/types" +) + +// SwapInAmtGivenOut is a mutative method for CalcOutAmtGivenIn, which includes the actual swap. +func (k Keeper) SwapInAmtGivenOut( + ctx sdk.Context, poolId uint64, oracleKeeper types.OracleKeeper, snapshot *types.Pool, + tokensOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) ( + tokenIn sdk.Coin, weightBalanceBonus sdk.Dec, err error, +) { + ammPool, found := k.GetPool(ctx, poolId) + if !found { + return sdk.Coin{}, sdk.ZeroDec(), fmt.Errorf("invalid pool: %d", poolId) + } + + return ammPool.SwapInAmtGivenOut(ctx, oracleKeeper, snapshot, tokensOut, tokenInDenom, swapFee, k.accountedPoolKeeper) +} diff --git a/x/amm/keeper/swap_out_amt_given_in.go b/x/amm/keeper/swap_out_amt_given_in.go new file mode 100644 index 000000000..e10bf44de --- /dev/null +++ b/x/amm/keeper/swap_out_amt_given_in.go @@ -0,0 +1,25 @@ +package keeper + +import ( + fmt "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/elys-network/elys/x/amm/types" +) + +// SwapOutAmtGivenIn is a mutative method for CalcOutAmtGivenIn, which includes the actual swap. +func (k Keeper) SwapOutAmtGivenIn( + ctx sdk.Context, poolId uint64, + oracleKeeper types.OracleKeeper, + snapshot *types.Pool, + tokensIn sdk.Coins, + tokenOutDenom string, + swapFee sdk.Dec, +) (tokenOut sdk.Coin, weightBalanceBonus sdk.Dec, err error) { + ammPool, found := k.GetPool(ctx, poolId) + if !found { + return sdk.Coin{}, sdk.ZeroDec(), fmt.Errorf("invalid pool: %d", poolId) + } + + return ammPool.SwapOutAmtGivenIn(ctx, oracleKeeper, snapshot, tokensIn, tokenOutDenom, swapFee, k.accountedPoolKeeper) +} diff --git a/x/amm/keeper/update_pool_for_swap.go b/x/amm/keeper/update_pool_for_swap.go index 8f434f733..b36053cd7 100644 --- a/x/amm/keeper/update_pool_for_swap.go +++ b/x/amm/keeper/update_pool_for_swap.go @@ -93,7 +93,7 @@ func (k Keeper) UpdatePoolForSwap( types.EmitSwapEvent(ctx, sender, pool.GetPoolId(), tokensIn, tokensOut) if k.hooks != nil { - k.hooks.AfterSwap(ctx, sender, pool.GetPoolId(), tokensIn, tokensOut) + k.hooks.AfterSwap(ctx, sender, pool, tokensIn, tokensOut) } k.RecordTotalLiquidityIncrease(ctx, tokensIn) k.RecordTotalLiquidityDecrease(ctx, tokensOut) diff --git a/x/amm/types/apply_swap.go b/x/amm/types/apply_swap.go index a3eb9ac3c..f8f84d06a 100644 --- a/x/amm/types/apply_swap.go +++ b/x/amm/types/apply_swap.go @@ -3,7 +3,7 @@ package types import sdk "github.com/cosmos/cosmos-sdk/types" // ApplySwap. -func (p *Pool) applySwap(ctx sdk.Context, tokensIn sdk.Coins, tokensOut sdk.Coins, swapFeeIn, swapFeeOut sdk.Dec) error { +func (p *Pool) applySwap(ctx sdk.Context, tokensIn sdk.Coins, tokensOut sdk.Coins, swapFeeIn, swapFeeOut sdk.Dec, accPoolKeeper AccountedPoolKeeper) error { // Fixed gas consumption per swap to prevent spam ctx.GasMeter().ConsumeGas(BalancerGasFeeForSwap, "balancer swap computation") // Also ensures that len(tokensIn) = 1 = len(tokensOut) diff --git a/x/amm/types/calc_exit_pool.go b/x/amm/types/calc_exit_pool.go index e470e0ddf..848de46bc 100644 --- a/x/amm/types/calc_exit_pool.go +++ b/x/amm/types/calc_exit_pool.go @@ -8,7 +8,7 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -func CalcExitValueWithoutSlippage(ctx sdk.Context, oracleKeeper OracleKeeper, pool Pool, exitingShares sdk.Int, tokenOutDenom string) (sdk.Dec, error) { +func CalcExitValueWithoutSlippage(ctx sdk.Context, oracleKeeper OracleKeeper, accPoolKeeper AccountedPoolKeeper, pool Pool, exitingShares sdk.Int, tokenOutDenom string) (sdk.Dec, error) { tvl, err := pool.TVL(ctx, oracleKeeper) if err != nil { return sdk.ZeroDec(), err @@ -57,6 +57,7 @@ func CalcExitValueWithoutSlippage(ctx sdk.Context, oracleKeeper OracleKeeper, po &pool, sdk.Coins{sdk.NewCoin(exitedCoin.Denom, resizedAmount)}, tokenOutDenom, + accPoolKeeper, ) if err != nil { return sdk.ZeroDec(), err @@ -69,7 +70,7 @@ func CalcExitValueWithoutSlippage(ctx sdk.Context, oracleKeeper OracleKeeper, po } // CalcExitPool returns how many tokens should come out, when exiting k LP shares against a "standard" CFMM -func CalcExitPool(ctx sdk.Context, oracleKeeper OracleKeeper, pool Pool, exitingShares sdk.Int, tokenOutDenom string) (sdk.Coins, error) { +func CalcExitPool(ctx sdk.Context, oracleKeeper OracleKeeper, pool Pool, accountedPoolKeeper AccountedPoolKeeper, exitingShares sdk.Int, tokenOutDenom string) (sdk.Coins, error) { totalShares := pool.GetTotalShares() if exitingShares.GTE(totalShares.Amount) { return sdk.Coins{}, sdkerrors.Wrapf(ErrLimitMaxAmount, ErrMsgFormatSharesLargerThanMax, exitingShares, totalShares) @@ -88,7 +89,7 @@ func CalcExitPool(ctx sdk.Context, oracleKeeper OracleKeeper, pool Pool, exiting if pool.PoolParams.UseOracle && tokenOutDenom != "" { initialWeightDistance := pool.WeightDistanceFromTarget(ctx, oracleKeeper, pool.PoolAssets) tokenPrice := oracleKeeper.GetAssetPriceFromDenom(ctx, tokenOutDenom) - exitValueWithoutSlippage, err := CalcExitValueWithoutSlippage(ctx, oracleKeeper, pool, exitingShares, tokenOutDenom) + exitValueWithoutSlippage, err := CalcExitValueWithoutSlippage(ctx, oracleKeeper, accountedPoolKeeper, pool, exitingShares, tokenOutDenom) if err != nil { return sdk.Coins{}, err } diff --git a/x/amm/types/calc_exit_pool_coins_from_shares.go b/x/amm/types/calc_exit_pool_coins_from_shares.go index 7a1651121..eaff1891a 100644 --- a/x/amm/types/calc_exit_pool_coins_from_shares.go +++ b/x/amm/types/calc_exit_pool_coins_from_shares.go @@ -5,6 +5,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -func (p *Pool) CalcExitPoolCoinsFromShares(ctx sdk.Context, oracleKeeper OracleKeeper, exitingShares math.Int, tokenOutDenom string) (exitedCoins sdk.Coins, err error) { - return CalcExitPool(ctx, oracleKeeper, *p, exitingShares, tokenOutDenom) +func (p *Pool) CalcExitPoolCoinsFromShares(ctx sdk.Context, oracleKeeper OracleKeeper, accountedPoolKeeper AccountedPoolKeeper, exitingShares math.Int, tokenOutDenom string) (exitedCoins sdk.Coins, err error) { + return CalcExitPool(ctx, oracleKeeper, *p, accountedPoolKeeper, exitingShares, tokenOutDenom) } diff --git a/x/amm/types/calc_in_amt_given_out.go b/x/amm/types/calc_in_amt_given_out.go index a0dc25d0d..3e902d12e 100644 --- a/x/amm/types/calc_in_amt_given_out.go +++ b/x/amm/types/calc_in_amt_given_out.go @@ -11,7 +11,7 @@ func (p Pool) CalcInAmtGivenOut( ctx sdk.Context, oracle OracleKeeper, snapshot *Pool, - tokensOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) ( + tokensOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec, accountedPool AccountedPoolKeeper) ( tokenIn sdk.Coin, err error, ) { tokenOut, poolAssetOut, poolAssetIn, err := p.parsePoolAssets(tokensOut, tokenInDenom) @@ -33,12 +33,25 @@ func (p Pool) CalcInAmtGivenOut( // delta balanceOut is positive(tokens inside the pool decreases) poolTokenOutBalance := sdk.NewDecFromInt(poolAssetOut.Token.Amount) + // accounted pool balance + acountedPoolAssetOutAmt := accountedPool.GetAccountedBalance(ctx, p.PoolId, poolAssetOut.Token.Denom) + if acountedPoolAssetOutAmt.GT(sdk.ZeroInt()) { + poolTokenOutBalance = sdk.NewDecFromInt(acountedPoolAssetOutAmt) + } + + poolTokenInBalance := sdk.NewDecFromInt(poolAssetIn.Token.Amount) + // accounted pool balance + acountedPoolAssetInAmt := accountedPool.GetAccountedBalance(ctx, p.PoolId, poolAssetIn.Token.Denom) + if acountedPoolAssetInAmt.GT(sdk.ZeroInt()) { + poolTokenInBalance = sdk.NewDecFromInt(acountedPoolAssetInAmt) + } + poolPostSwapOutBalance := poolTokenOutBalance.Sub(sdk.NewDecFromInt(tokenOut.Amount)) // (x_0)(y_0) = (x_0 + in)(y_0 - out) tokenAmountIn := solveConstantFunctionInvariant( poolTokenOutBalance, poolPostSwapOutBalance, outWeight, - sdk.NewDecFromInt(poolAssetIn.Token.Amount), + poolTokenInBalance, inWeight, ).Neg() diff --git a/x/amm/types/calc_out_amt_given_in.go b/x/amm/types/calc_out_amt_given_in.go index 0e38b932a..e7ae4a9ba 100644 --- a/x/amm/types/calc_out_amt_given_in.go +++ b/x/amm/types/calc_out_amt_given_in.go @@ -14,6 +14,7 @@ func (p Pool) CalcOutAmtGivenIn( tokensIn sdk.Coins, tokenOutDenom string, swapFee sdk.Dec, + accountedPool AccountedPoolKeeper, ) (sdk.Coin, error) { tokenIn, poolAssetIn, poolAssetOut, err := p.parsePoolAssets(tokensIn, tokenOutDenom) if err != nil { @@ -22,6 +23,19 @@ func (p Pool) CalcOutAmtGivenIn( tokenAmountInAfterFee := sdk.NewDecFromInt(tokenIn.Amount).Mul(sdk.OneDec().Sub(swapFee)) poolTokenInBalance := sdk.NewDecFromInt(poolAssetIn.Token.Amount) + // accounted pool balance + acountedPoolAssetInAmt := accountedPool.GetAccountedBalance(ctx, p.PoolId, poolAssetIn.Token.Denom) + if acountedPoolAssetInAmt.GT(sdk.ZeroInt()) { + poolTokenInBalance = sdk.NewDecFromInt(acountedPoolAssetInAmt) + } + + poolTokenOutBalance := sdk.NewDecFromInt(poolAssetOut.Token.Amount) + // accounted pool balance + acountedPoolAssetOutAmt := accountedPool.GetAccountedBalance(ctx, p.PoolId, poolAssetOut.Token.Denom) + if acountedPoolAssetOutAmt.GT(sdk.ZeroInt()) { + poolTokenOutBalance = sdk.NewDecFromInt(acountedPoolAssetOutAmt) + } + poolPostSwapInBalance := poolTokenInBalance.Add(tokenAmountInAfterFee) outWeight := sdk.NewDecFromInt(poolAssetOut.Weight) @@ -42,7 +56,7 @@ func (p Pool) CalcOutAmtGivenIn( poolTokenInBalance, poolPostSwapInBalance, inWeight, - sdk.NewDecFromInt(poolAssetOut.Token.Amount), + poolTokenOutBalance, outWeight, ) diff --git a/x/amm/types/expected_keepers.go b/x/amm/types/expected_keepers.go index ec4f99d39..c335e18a6 100644 --- a/x/amm/types/expected_keepers.go +++ b/x/amm/types/expected_keepers.go @@ -40,3 +40,8 @@ type AssetProfileKeeper interface { // GetEntry returns a entry from its index GetEntry(ctx sdk.Context, baseDenom string) (val atypes.Entry, found bool) } + +// AccountedPoolKeeper defines the expected interfaces +type AccountedPoolKeeper interface { + GetAccountedBalance(sdk.Context, uint64, string) sdk.Int +} diff --git a/x/amm/types/hooks.go b/x/amm/types/hooks.go index bd1e944b0..55a7f1e42 100644 --- a/x/amm/types/hooks.go +++ b/x/amm/types/hooks.go @@ -4,16 +4,16 @@ import sdk "github.com/cosmos/cosmos-sdk/types" type AmmHooks interface { // AfterPoolCreated is called after CreatePool - AfterPoolCreated(ctx sdk.Context, sender sdk.AccAddress, poolId uint64) + AfterPoolCreated(ctx sdk.Context, sender sdk.AccAddress, pool Pool) // AfterJoinPool is called after JoinPool, JoinSwapExternAmountIn, and JoinSwapShareAmountOut - AfterJoinPool(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, enterCoins sdk.Coins, shareOutAmount sdk.Int) + AfterJoinPool(ctx sdk.Context, sender sdk.AccAddress, pool Pool, enterCoins sdk.Coins, shareOutAmount sdk.Int) // AfterExitPool is called after ExitPool, ExitSwapShareAmountIn, and ExitSwapExternAmountOut - AfterExitPool(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, shareInAmount sdk.Int, exitCoins sdk.Coins) + AfterExitPool(ctx sdk.Context, sender sdk.AccAddress, pool Pool, shareInAmount sdk.Int, exitCoins sdk.Coins) // AfterSwap is called after SwapExactAmountIn and SwapExactAmountOut - AfterSwap(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, input sdk.Coins, output sdk.Coins) + AfterSwap(ctx sdk.Context, sender sdk.AccAddress, pool Pool, input sdk.Coins, output sdk.Coins) } var _ AmmHooks = MultiAmmHooks{} @@ -26,26 +26,26 @@ func NewMultiAmmHooks(hooks ...AmmHooks) MultiAmmHooks { return hooks } -func (h MultiAmmHooks) AfterPoolCreated(ctx sdk.Context, sender sdk.AccAddress, poolId uint64) { +func (h MultiAmmHooks) AfterPoolCreated(ctx sdk.Context, sender sdk.AccAddress, pool Pool) { for i := range h { - h[i].AfterPoolCreated(ctx, sender, poolId) + h[i].AfterPoolCreated(ctx, sender, pool) } } -func (h MultiAmmHooks) AfterJoinPool(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, enterCoins sdk.Coins, shareOutAmount sdk.Int) { +func (h MultiAmmHooks) AfterJoinPool(ctx sdk.Context, sender sdk.AccAddress, pool Pool, enterCoins sdk.Coins, shareOutAmount sdk.Int) { for i := range h { - h[i].AfterJoinPool(ctx, sender, poolId, enterCoins, shareOutAmount) + h[i].AfterJoinPool(ctx, sender, pool, enterCoins, shareOutAmount) } } -func (h MultiAmmHooks) AfterExitPool(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, shareInAmount sdk.Int, exitCoins sdk.Coins) { +func (h MultiAmmHooks) AfterExitPool(ctx sdk.Context, sender sdk.AccAddress, pool Pool, shareInAmount sdk.Int, exitCoins sdk.Coins) { for i := range h { - h[i].AfterExitPool(ctx, sender, poolId, shareInAmount, exitCoins) + h[i].AfterExitPool(ctx, sender, pool, shareInAmount, exitCoins) } } -func (h MultiAmmHooks) AfterSwap(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, input sdk.Coins, output sdk.Coins) { +func (h MultiAmmHooks) AfterSwap(ctx sdk.Context, sender sdk.AccAddress, pool Pool, input sdk.Coins, output sdk.Coins) { for i := range h { - h[i].AfterSwap(ctx, sender, poolId, input, output) + h[i].AfterSwap(ctx, sender, pool, input, output) } } diff --git a/x/amm/types/pool_exit_pool.go b/x/amm/types/pool_exit_pool.go index 1fe7d7175..448aa60fd 100644 --- a/x/amm/types/pool_exit_pool.go +++ b/x/amm/types/pool_exit_pool.go @@ -4,8 +4,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -func (p *Pool) ExitPool(ctx sdk.Context, oracleKeeper OracleKeeper, exitingShares sdk.Int, tokenOutDenom string) (exitingCoins sdk.Coins, err error) { - exitingCoins, err = p.CalcExitPoolCoinsFromShares(ctx, oracleKeeper, exitingShares, tokenOutDenom) +func (p *Pool) ExitPool(ctx sdk.Context, oracleKeeper OracleKeeper, accountedPoolKeeepr AccountedPoolKeeper, exitingShares sdk.Int, tokenOutDenom string) (exitingCoins sdk.Coins, err error) { + exitingCoins, err = p.CalcExitPoolCoinsFromShares(ctx, oracleKeeper, accountedPoolKeeepr, exitingShares, tokenOutDenom) if err != nil { return sdk.Coins{}, err } diff --git a/x/amm/types/pool_join_pool_no_swap.go b/x/amm/types/pool_join_pool_no_swap.go index 0fc951cf1..bb4f00cd9 100644 --- a/x/amm/types/pool_join_pool_no_swap.go +++ b/x/amm/types/pool_join_pool_no_swap.go @@ -17,7 +17,7 @@ type InternalSwapRequest struct { OutToken string } -func (p *Pool) CalcJoinValueWithoutSlippage(ctx sdk.Context, oracleKeeper OracleKeeper, tokensIn sdk.Coins) (math.LegacyDec, error) { +func (p *Pool) CalcJoinValueWithoutSlippage(ctx sdk.Context, oracleKeeper OracleKeeper, accountedPoolKeeper AccountedPoolKeeper, tokensIn sdk.Coins) (math.LegacyDec, error) { joinValue := sdk.ZeroDec() for _, asset := range tokensIn { tokenPrice := oracleKeeper.GetAssetPriceFromDenom(ctx, asset.Denom) @@ -99,6 +99,7 @@ func (p *Pool) CalcJoinValueWithoutSlippage(ctx sdk.Context, oracleKeeper Oracle p, sdk.Coins{sdk.NewCoin(req.InAmount.Denom, resizedAmount)}, req.OutToken, + accountedPoolKeeper, ) if err != nil { return sdk.ZeroDec(), err @@ -112,7 +113,7 @@ func (p *Pool) CalcJoinValueWithoutSlippage(ctx sdk.Context, oracleKeeper Oracle // JoinPoolNoSwap calculates the number of shares needed for an all-asset join given tokensIn with swapFee applied. // It updates the liquidity if the pool is joined successfully. If not, returns error. -func (p *Pool) JoinPoolNoSwap(ctx sdk.Context, oracleKeeper OracleKeeper, tokensIn sdk.Coins) (numShares math.Int, err error) { +func (p *Pool) JoinPoolNoSwap(ctx sdk.Context, oracleKeeper OracleKeeper, accountedPoolKeeper AccountedPoolKeeper, tokensIn sdk.Coins) (numShares math.Int, err error) { if !p.PoolParams.UseOracle { numShares, tokensJoined, err := p.CalcJoinPoolNoSwapShares(tokensIn) if err != nil { @@ -124,7 +125,7 @@ func (p *Pool) JoinPoolNoSwap(ctx sdk.Context, oracleKeeper OracleKeeper, tokens return numShares, nil } - joinValueWithoutSlippage, err := p.CalcJoinValueWithoutSlippage(ctx, oracleKeeper, tokensIn) + joinValueWithoutSlippage, err := p.CalcJoinValueWithoutSlippage(ctx, oracleKeeper, accountedPoolKeeper, tokensIn) if err != nil { return sdk.ZeroInt(), err } diff --git a/x/amm/types/swap_in_amt_given_out.go b/x/amm/types/swap_in_amt_given_out.go index c351e6a41..d45e5105a 100644 --- a/x/amm/types/swap_in_amt_given_out.go +++ b/x/amm/types/swap_in_amt_given_out.go @@ -12,8 +12,9 @@ func (p Pool) CalcGivenOutSlippage( snapshot *Pool, tokensOut sdk.Coins, tokenInDenom string, + accPoolKeeper AccountedPoolKeeper, ) (sdk.Dec, error) { - balancerInCoin, err := p.CalcInAmtGivenOut(ctx, oracleKeeper, snapshot, tokensOut, tokenInDenom, sdk.ZeroDec()) + balancerInCoin, err := p.CalcInAmtGivenOut(ctx, oracleKeeper, snapshot, tokensOut, tokenInDenom, sdk.ZeroDec(), accPoolKeeper) if err != nil { return sdk.ZeroDec(), err } @@ -46,17 +47,17 @@ func (p Pool) CalcGivenOutSlippage( // SwapInAmtGivenOut is a mutative method for CalcOutAmtGivenIn, which includes the actual swap. func (p *Pool) SwapInAmtGivenOut( ctx sdk.Context, oracleKeeper OracleKeeper, snapshot *Pool, - tokensOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) ( + tokensOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec, accPoolKeeper AccountedPoolKeeper) ( tokenIn sdk.Coin, weightBalanceBonus sdk.Dec, err error, ) { // early return with balancer swap if normal amm pool if !p.PoolParams.UseOracle { - balancerInCoin, err := p.CalcInAmtGivenOut(ctx, oracleKeeper, snapshot, tokensOut, tokenInDenom, swapFee) + balancerInCoin, err := p.CalcInAmtGivenOut(ctx, oracleKeeper, snapshot, tokensOut, tokenInDenom, swapFee, accPoolKeeper) if err != nil { return sdk.Coin{}, sdk.ZeroDec(), err } - err = p.applySwap(ctx, sdk.Coins{balancerInCoin}, tokensOut, swapFee, sdk.ZeroDec()) + err = p.applySwap(ctx, sdk.Coins{balancerInCoin}, tokensOut, swapFee, sdk.ZeroDec(), accPoolKeeper) if err != nil { return sdk.Coin{}, sdk.ZeroDec(), err } @@ -93,6 +94,7 @@ func (p *Pool) SwapInAmtGivenOut( snapshot, sdk.Coins{sdk.NewCoin(tokenOut.Denom, resizedAmount)}, tokenInDenom, + accPoolKeeper, ) inAmountAfterSlippage := oracleInAmount.Add(slippageAmount) @@ -123,7 +125,7 @@ func (p *Pool) SwapInAmtGivenOut( Quo(sdk.OneDec().Sub(swapFee)). TruncateInt() oracleInCoin := sdk.NewCoin(tokenInDenom, tokenAmountInInt) - err = p.applySwap(ctx, sdk.Coins{oracleInCoin}, tokensOut, swapFee, sdk.ZeroDec()) + err = p.applySwap(ctx, sdk.Coins{oracleInCoin}, tokensOut, swapFee, sdk.ZeroDec(), accPoolKeeper) if err != nil { return sdk.Coin{}, sdk.ZeroDec(), err } diff --git a/x/amm/types/swap_in_amt_given_out_test.go b/x/amm/types/swap_in_amt_given_out_test.go index 79124bb89..e3fd4acdf 100644 --- a/x/amm/types/swap_in_amt_given_out_test.go +++ b/x/amm/types/swap_in_amt_given_out_test.go @@ -188,7 +188,7 @@ func (suite *TestSuite) TestSwapInAmtGivenOut() { PoolAssets: tc.poolAssets, TotalWeight: sdk.ZeroInt(), } - tokenOut, weightBonus, err := pool.SwapInAmtGivenOut(suite.ctx, suite.app.OracleKeeper, &pool, sdk.Coins{tc.tokenOut}, tc.inTokenDenom, tc.swapFee) + tokenOut, weightBonus, err := pool.SwapInAmtGivenOut(suite.ctx, suite.app.OracleKeeper, &pool, sdk.Coins{tc.tokenOut}, tc.inTokenDenom, tc.swapFee, suite.app.AccountedPoolKeeper) if tc.expErr { suite.Require().Error(err) } else { diff --git a/x/amm/types/swap_out_amt_given_in.go b/x/amm/types/swap_out_amt_given_in.go index c64e64628..594becdb7 100644 --- a/x/amm/types/swap_out_amt_given_in.go +++ b/x/amm/types/swap_out_amt_given_in.go @@ -102,8 +102,9 @@ func (p Pool) CalcGivenInSlippage( snapshot *Pool, tokensIn sdk.Coins, tokenOutDenom string, + accPoolKeeper AccountedPoolKeeper, ) (sdk.Dec, error) { - balancerOutCoin, err := p.CalcOutAmtGivenIn(ctx, oracleKeeper, snapshot, tokensIn, tokenOutDenom, sdk.ZeroDec()) + balancerOutCoin, err := p.CalcOutAmtGivenIn(ctx, oracleKeeper, snapshot, tokensIn, tokenOutDenom, sdk.ZeroDec(), accPoolKeeper) if err != nil { return sdk.ZeroDec(), err } @@ -140,15 +141,16 @@ func (p *Pool) SwapOutAmtGivenIn( tokensIn sdk.Coins, tokenOutDenom string, swapFee sdk.Dec, + accPoolKeeper AccountedPoolKeeper, ) (tokenOut sdk.Coin, weightBalanceBonus sdk.Dec, err error) { - balancerOutCoin, err := p.CalcOutAmtGivenIn(ctx, oracleKeeper, snapshot, tokensIn, tokenOutDenom, swapFee) + balancerOutCoin, err := p.CalcOutAmtGivenIn(ctx, oracleKeeper, snapshot, tokensIn, tokenOutDenom, swapFee, accPoolKeeper) if err != nil { return sdk.Coin{}, sdk.ZeroDec(), err } // early return with balancer swap if normal amm pool if !p.PoolParams.UseOracle { - err = p.applySwap(ctx, tokensIn, sdk.Coins{balancerOutCoin}, sdk.ZeroDec(), swapFee) + err = p.applySwap(ctx, tokensIn, sdk.Coins{balancerOutCoin}, sdk.ZeroDec(), swapFee, accPoolKeeper) if err != nil { return sdk.Coin{}, sdk.ZeroDec(), err } @@ -184,6 +186,7 @@ func (p *Pool) SwapOutAmtGivenIn( snapshot, sdk.Coins{sdk.NewCoin(tokenIn.Denom, resizedAmount)}, tokenOutDenom, + accPoolKeeper, ) if err != nil { return sdk.Coin{}, sdk.ZeroDec(), err @@ -258,7 +261,7 @@ func (p *Pool) SwapOutAmtGivenIn( Mul(sdk.OneDec().Sub(weightBreakingFee)). Mul(sdk.OneDec().Sub(swapFee)).TruncateInt() oracleOutCoin := sdk.NewCoin(tokenOutDenom, tokenAmountOutInt) - err = p.applySwap(ctx, tokensIn, sdk.Coins{oracleOutCoin}, sdk.ZeroDec(), swapFee) + err = p.applySwap(ctx, tokensIn, sdk.Coins{oracleOutCoin}, sdk.ZeroDec(), swapFee, accPoolKeeper) if err != nil { return sdk.Coin{}, sdk.ZeroDec(), err } diff --git a/x/amm/types/swap_out_amt_given_in_test.go b/x/amm/types/swap_out_amt_given_in_test.go index 06116ca9c..0542fcabe 100644 --- a/x/amm/types/swap_out_amt_given_in_test.go +++ b/x/amm/types/swap_out_amt_given_in_test.go @@ -598,7 +598,7 @@ func (suite *TestSuite) TestSwapOutAmtGivenIn() { PoolAssets: tc.poolAssets, TotalWeight: sdk.ZeroInt(), } - tokenOut, weightBonus, err := pool.SwapOutAmtGivenIn(suite.ctx, suite.app.OracleKeeper, &pool, sdk.Coins{tc.tokenIn}, tc.outTokenDenom, tc.swapFee) + tokenOut, weightBonus, err := pool.SwapOutAmtGivenIn(suite.ctx, suite.app.OracleKeeper, &pool, sdk.Coins{tc.tokenIn}, tc.outTokenDenom, tc.swapFee, suite.app.AccountedPoolKeeper) if tc.expErr { suite.Require().Error(err) } else { diff --git a/x/incentive/keeper/hooks_amm.go b/x/incentive/keeper/hooks_amm.go index 5cbc859a2..25d4d6249 100644 --- a/x/incentive/keeper/hooks_amm.go +++ b/x/incentive/keeper/hooks_amm.go @@ -38,21 +38,21 @@ func (k Keeper) AmmHooks() AmmHooks { } // AfterPoolCreated is called after CreatePool -func (h AmmHooks) AfterPoolCreated(ctx sdk.Context, sender sdk.AccAddress, poolId uint64) { - h.k.AfterPoolCreated(ctx, sender, poolId) +func (h AmmHooks) AfterPoolCreated(ctx sdk.Context, sender sdk.AccAddress, pool ammtypes.Pool) { + h.k.AfterPoolCreated(ctx, sender, pool.PoolId) } // AfterJoinPool is called after JoinPool, JoinSwapExternAmountIn, and JoinSwapShareAmountOut -func (h AmmHooks) AfterJoinPool(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, enterCoins sdk.Coins, shareOutAmount sdk.Int) { - h.k.AfterJoinPool(ctx, sender, poolId, enterCoins, shareOutAmount) +func (h AmmHooks) AfterJoinPool(ctx sdk.Context, sender sdk.AccAddress, pool ammtypes.Pool, enterCoins sdk.Coins, shareOutAmount sdk.Int) { + h.k.AfterJoinPool(ctx, sender, pool.PoolId, enterCoins, shareOutAmount) } // AfterExitPool is called after ExitPool, ExitSwapShareAmountIn, and ExitSwapExternAmountOut -func (h AmmHooks) AfterExitPool(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, shareInAmount sdk.Int, exitCoins sdk.Coins) { - h.k.AfterExitPool(ctx, sender, poolId, shareInAmount, exitCoins) +func (h AmmHooks) AfterExitPool(ctx sdk.Context, sender sdk.AccAddress, pool ammtypes.Pool, shareInAmount sdk.Int, exitCoins sdk.Coins) { + h.k.AfterExitPool(ctx, sender, pool.PoolId, shareInAmount, exitCoins) } // AfterSwap is called after SwapExactAmountIn and SwapExactAmountOut -func (h AmmHooks) AfterSwap(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, input sdk.Coins, output sdk.Coins) { - h.k.AfterSwap(ctx, sender, poolId, input, output) +func (h AmmHooks) AfterSwap(ctx sdk.Context, sender sdk.AccAddress, pool ammtypes.Pool, input sdk.Coins, output sdk.Coins) { + h.k.AfterSwap(ctx, sender, pool.PoolId, input, output) } diff --git a/x/incentive/keeper/keeper_fees.go b/x/incentive/keeper/keeper_fees.go index 6b12ccd7e..764b2f188 100644 --- a/x/incentive/keeper/keeper_fees.go +++ b/x/incentive/keeper/keeper_fees.go @@ -73,7 +73,7 @@ func (k Keeper) CollectGasFeesToIncentiveModule(ctx sdk.Context) sdk.Coins { // Executes the swap in the pool and stores the output. Updates pool assets but // does not actually transfer any tokens to or from the pool. snapshot := k.amm.GetPoolSnapshotOrSet(ctx, pool) - tokenOutCoin, _, err := pool.SwapOutAmtGivenIn(ctx, k.oracleKeeper, &snapshot, sdk.Coins{tokenIn}, ptypes.USDC, sdk.ZeroDec()) + tokenOutCoin, _, err := k.amm.SwapOutAmtGivenIn(ctx, pool.PoolId, k.oracleKeeper, &snapshot, sdk.Coins{tokenIn}, ptypes.USDC, sdk.ZeroDec()) if err != nil { continue } diff --git a/x/incentive/types/expected_keepers.go b/x/incentive/types/expected_keepers.go index b1427796e..7ed4191fe 100644 --- a/x/incentive/types/expected_keepers.go +++ b/x/incentive/types/expected_keepers.go @@ -92,9 +92,23 @@ type AmmKeeper interface { // IterateCommitments iterates over all Commitments and performs a callback. IterateLiquidityPools(sdk.Context, func(ammtypes.Pool) bool) GetPoolSnapshotOrSet(ctx sdk.Context, pool ammtypes.Pool) (val ammtypes.Pool) + + SwapOutAmtGivenIn( + ctx sdk.Context, poolId uint64, + oracleKeeper ammtypes.OracleKeeper, + snapshot *ammtypes.Pool, + tokensIn sdk.Coins, + tokenOutDenom string, + swapFee sdk.Dec, + ) (tokenOut sdk.Coin, weightBalanceBonus sdk.Dec, err error) } // OracleKeeper defines the expected interface needed to retrieve price info type OracleKeeper interface { GetAssetPriceFromDenom(ctx sdk.Context, denom string) sdk.Dec } + +// AccountedPoolKeeper +type AccountedPoolKeeper interface { + GetAccountedBalance(sdk.Context, uint64, string) sdk.Int +} diff --git a/x/margin/keeper/check_max_open_positions_test.go b/x/margin/keeper/check_max_open_positions_test.go index 891452846..7afb95d8d 100644 --- a/x/margin/keeper/check_max_open_positions_test.go +++ b/x/margin/keeper/check_max_open_positions_test.go @@ -24,7 +24,7 @@ func TestCheckMaxOpenPositions_OpenPositionsBelowMax(t *testing.T) { // Mock behavior mockChecker.On("GetOpenMTPCount", ctx).Return(uint64(5)) - mockChecker.On("GetMaxOpenPositions", ctx).Return(10) + mockChecker.On("GetMaxOpenPositions", ctx).Return(uint64(10)) err := k.CheckMaxOpenPositions(ctx) @@ -46,7 +46,7 @@ func TestCheckMaxOpenPositions_OpenPositionsEqualToMax(t *testing.T) { // Mock behavior mockChecker.On("GetOpenMTPCount", ctx).Return(uint64(10)) - mockChecker.On("GetMaxOpenPositions", ctx).Return(10) + mockChecker.On("GetMaxOpenPositions", ctx).Return(uint64(10)) err := k.CheckMaxOpenPositions(ctx) @@ -68,7 +68,7 @@ func TestCheckMaxOpenPositions_OpenPositionsExceedMax(t *testing.T) { // Mock behavior mockChecker.On("GetOpenMTPCount", ctx).Return(uint64(11)) - mockChecker.On("GetMaxOpenPositions", ctx).Return(10) + mockChecker.On("GetMaxOpenPositions", ctx).Return(uint64(10)) err := k.CheckMaxOpenPositions(ctx) diff --git a/x/margin/keeper/close.go b/x/margin/keeper/close.go new file mode 100644 index 000000000..165db7022 --- /dev/null +++ b/x/margin/keeper/close.go @@ -0,0 +1,47 @@ +package keeper + +import ( + "strconv" + + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/elys-network/elys/x/margin/types" +) + +func (k Keeper) Close(ctx sdk.Context, msg *types.MsgClose) (*types.MsgCloseResponse, error) { + mtp, err := k.GetMTP(ctx, msg.Creator, msg.Id) + if err != nil { + return nil, err + } + + var closedMtp *types.MTP + var repayAmount sdk.Int + switch mtp.Position { + case types.Position_LONG: + closedMtp, repayAmount, err = k.CloseLong(ctx, msg) + if err != nil { + return nil, err + } + default: + return nil, sdkerrors.Wrap(types.ErrInvalidPosition, mtp.Position.String()) + } + + ctx.EventManager().EmitEvent(sdk.NewEvent(types.EventClose, + sdk.NewAttribute("id", strconv.FormatInt(int64(closedMtp.Id), 10)), + sdk.NewAttribute("position", closedMtp.Position.String()), + sdk.NewAttribute("address", closedMtp.Address), + sdk.NewAttribute("collateral_asset", closedMtp.CollateralAsset), + sdk.NewAttribute("collateral_amount", closedMtp.CollateralAmount.String()), + sdk.NewAttribute("custody_asset", closedMtp.CustodyAsset), + sdk.NewAttribute("custody_amount", closedMtp.CustodyAmount.String()), + sdk.NewAttribute("repay_amount", repayAmount.String()), + sdk.NewAttribute("leverage", closedMtp.Leverage.String()), + sdk.NewAttribute("liabilities", closedMtp.Liabilities.String()), + sdk.NewAttribute("interest_paid_collateral", mtp.InterestPaidCollateral.String()), + sdk.NewAttribute("interest_paid_custody", mtp.InterestPaidCustody.String()), + sdk.NewAttribute("interest_unpaid_collateral", closedMtp.InterestUnpaidCollateral.String()), + sdk.NewAttribute("health", closedMtp.MtpHealth.String()), + )) + + return &types.MsgCloseResponse{}, nil +} diff --git a/x/margin/keeper/close_long.go b/x/margin/keeper/close_long.go new file mode 100644 index 000000000..00cc5658b --- /dev/null +++ b/x/margin/keeper/close_long.go @@ -0,0 +1,67 @@ +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" +) + +func (k Keeper) CloseLong(ctx sdk.Context, msg *types.MsgClose) (*types.MTP, sdk.Int, error) { + mtp, err := k.GetMTP(ctx, msg.Creator, msg.Id) + if err != nil { + return nil, sdk.ZeroInt(), err + } + + // Amm pool Id + poolId := mtp.AmmPoolId + + // Get pool from pool Id + pool, found := k.GetPool(ctx, poolId) + if !found { + return nil, sdk.ZeroInt(), sdkerrors.Wrap(types.ErrInvalidBorrowingAsset, "invalid pool id") + } + + ammPool, found := k.amm.GetPool(ctx, poolId) + if !found { + return nil, sdk.ZeroInt(), sdkerrors.Wrap(types.ErrPoolDoesNotExist, mtp.CustodyAsset) + } + + epochLength := k.GetEpochLength(ctx) + epochPosition := GetEpochPosition(ctx, epochLength) + if epochPosition > 0 { + interestPayment := CalcMTPInterestLiabilities(&mtp, pool.InterestRate, epochPosition, epochLength) + finalInterestPayment := k.HandleInterestPayment(ctx, interestPayment, &mtp, &pool, ammPool) + + err = pool.UpdateBlockInterest(ctx, mtp.CollateralAsset, finalInterestPayment, true) + if err != nil { + return nil, sdk.ZeroInt(), err + } + + mtp.MtpHealth, err = k.UpdateMTPHealth(ctx, mtp, ammPool) + if err != nil { + return nil, sdk.ZeroInt(), err + } + } + + err = k.TakeOutCustody(ctx, mtp, &pool) + if err != nil { + return nil, sdk.ZeroInt(), err + } + + cutodyAmtTokenIn := sdk.NewCoin(mtp.CustodyAsset, mtp.CustodyAmount) + repayAmount, err := k.EstimateSwap(ctx, cutodyAmtTokenIn, mtp.CollateralAsset, ammPool) + if err != nil { + return nil, sdk.ZeroInt(), err + } + + err = k.Repay(ctx, &mtp, &pool, ammPool, repayAmount, false) + if err != nil { + return nil, sdk.ZeroInt(), err + } + + if k.hooks != nil { + k.hooks.AfterMarginPositionClosed(ctx, ammPool, pool) + } + + return &mtp, repayAmount, nil +} diff --git a/x/margin/keeper/get_margin_pool_balance.go b/x/margin/keeper/get_margin_pool_balance.go new file mode 100644 index 000000000..d955d5340 --- /dev/null +++ b/x/margin/keeper/get_margin_pool_balance.go @@ -0,0 +1,17 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/elys-network/elys/x/margin/types" +) + +// Get Margin Pool Balance +func (k Keeper) GetMarginPoolBalances(marginPool types.Pool, denom string) (sdk.Int, sdk.Int, sdk.Int) { + for _, asset := range marginPool.PoolAssets { + if asset.AssetDenom == denom { + return asset.AssetBalance, asset.Liabilities, asset.Custody + } + } + + return sdk.ZeroInt(), sdk.ZeroInt(), sdk.ZeroInt() +} diff --git a/x/margin/keeper/hooks_amm.go b/x/margin/keeper/hooks_amm.go new file mode 100644 index 000000000..26fd476fd --- /dev/null +++ b/x/margin/keeper/hooks_amm.go @@ -0,0 +1,80 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + ammtypes "github.com/elys-network/elys/x/amm/types" +) + +// AfterPoolCreated is called after CreatePool +func (k Keeper) AfterPoolCreated(ctx sdk.Context, sender sdk.AccAddress, ammPool ammtypes.Pool) { + if k.hooks != nil { + k.hooks.AfterAmmPoolCreated(ctx, ammPool) + } +} + +// AfterJoinPool is called after JoinPool, JoinSwapExternAmountIn, and JoinSwapShareAmountOut +func (k Keeper) AfterJoinPool(ctx sdk.Context, sender sdk.AccAddress, ammPool ammtypes.Pool, enterCoins sdk.Coins, shareOutAmount sdk.Int) { + marginPool, found := k.GetPool(ctx, ammPool.PoolId) + if !found { + return + } + + if k.hooks != nil { + k.hooks.AfterAmmJoinPool(ctx, ammPool, marginPool) + } +} + +// AfterExitPool is called after ExitPool, ExitSwapShareAmountIn, and ExitSwapExternAmountOut +func (k Keeper) AfterExitPool(ctx sdk.Context, sender sdk.AccAddress, ammPool ammtypes.Pool, shareInAmount sdk.Int, exitCoins sdk.Coins) { + marginPool, found := k.GetPool(ctx, ammPool.PoolId) + if !found { + return + } + + if k.hooks != nil { + k.hooks.AfterAmmExitPool(ctx, ammPool, marginPool) + } +} + +// AfterSwap is called after SwapExactAmountIn and SwapExactAmountOut +func (k Keeper) AfterSwap(ctx sdk.Context, sender sdk.AccAddress, ammPool ammtypes.Pool, input sdk.Coins, output sdk.Coins) { + marginPool, found := k.GetPool(ctx, ammPool.PoolId) + if !found { + return + } + if k.hooks != nil { + k.hooks.AfterAmmSwap(ctx, ammPool, marginPool) + } +} + +// Hooks wrapper struct for tvl keeper +type AmmHooks struct { + k Keeper +} + +var _ ammtypes.AmmHooks = AmmHooks{} + +// Return the wrapper struct +func (k Keeper) AmmHooks() AmmHooks { + return AmmHooks{k} +} + +// AfterPoolCreated is called after CreatePool +func (h AmmHooks) AfterPoolCreated(ctx sdk.Context, sender sdk.AccAddress, pool ammtypes.Pool) { + h.k.AfterPoolCreated(ctx, sender, pool) +} + +// AfterJoinPool is called after JoinPool, JoinSwapExternAmountIn, and JoinSwapShareAmountOut +func (h AmmHooks) AfterJoinPool(ctx sdk.Context, sender sdk.AccAddress, pool ammtypes.Pool, enterCoins sdk.Coins, shareOutAmount sdk.Int) { + h.k.AfterJoinPool(ctx, sender, pool, enterCoins, shareOutAmount) +} + +// AfterExitPool is called after ExitPool, ExitSwapShareAmountIn, and ExitSwapExternAmountOut +func (h AmmHooks) AfterExitPool(ctx sdk.Context, sender sdk.AccAddress, pool ammtypes.Pool, shareInAmount sdk.Int, exitCoins sdk.Coins) { + h.k.AfterExitPool(ctx, sender, pool, shareInAmount, exitCoins) +} + +// AfterSwap is called after SwapExactAmountIn and SwapExactAmountOut +func (h AmmHooks) AfterSwap(ctx sdk.Context, sender sdk.AccAddress, pool ammtypes.Pool, input sdk.Coins, output sdk.Coins) { + h.k.AfterSwap(ctx, sender, pool, input, output) +} diff --git a/x/margin/keeper/hooks_epoch.go b/x/margin/keeper/hooks_epoch.go new file mode 100644 index 000000000..2617a523c --- /dev/null +++ b/x/margin/keeper/hooks_epoch.go @@ -0,0 +1,46 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + epochstypes "github.com/elys-network/elys/x/epochs/types" +) + +// BeforeEpochStart performs a no-op +func (k Keeper) BeforeEpochStart(ctx sdk.Context, epochIdentifier string, epochNumber int64) { + +} + +// AfterEpochEnd distributes vested tokens at the end of each epoch +func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, _ int64) { + params := k.GetParams(ctx) + if epochIdentifier == params.InvariantCheckEpoch { + err := k.InvariantCheck(ctx) + if err != nil { + panic(err) + } + } +} + +// ___________________________________________________________________________________________________ + +// Hooks wrapper struct for incentive keeper +type Hooks struct { + k Keeper +} + +var _ epochstypes.EpochHooks = Hooks{} + +// Return the wrapper struct +func (k Keeper) Hooks() Hooks { + return Hooks{k} +} + +// BeforeEpochStart implements EpochHooks +func (h Hooks) BeforeEpochStart(ctx sdk.Context, epochIdentifier string, epochNumber int64) { + h.k.BeforeEpochStart(ctx, epochIdentifier, epochNumber) +} + +// AfterEpochEnd implements EpochHooks +func (h Hooks) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber int64) { + h.k.AfterEpochEnd(ctx, epochIdentifier, epochNumber) +} diff --git a/x/margin/keeper/invariant_check.go b/x/margin/keeper/invariant_check.go new file mode 100644 index 000000000..ef8fe0842 --- /dev/null +++ b/x/margin/keeper/invariant_check.go @@ -0,0 +1,51 @@ +package keeper + +import ( + "errors" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func (k Keeper) AmmPoolBalanceCheck(ctx sdk.Context, poolId uint64) error { + ammPool, found := k.amm.GetPool(ctx, poolId) + if !found { + return errors.New("pool doesn't exist!") + } + + marginPool, found := k.GetPool(ctx, poolId) + if !found { + return errors.New("pool doesn't exist!") + } + + address, err := sdk.AccAddressFromBech32(ammPool.GetAddress()) + if err != nil { + return err + } + + // bank balance should be ammPool balance + margin pool balance + balances := k.bankKeeper.GetAllBalances(ctx, address) + for _, balance := range balances { + ammBalance, _ := k.GetAmmPoolBalance(ctx, ammPool, balance.Denom) + marginBalance, _, _ := k.GetMarginPoolBalances(marginPool, balance.Denom) + + diff := ammBalance.Add(marginBalance).Sub(balance.Amount) + if !diff.IsZero() { + return errors.New("balance mismatch!") + } + } + return nil +} + +// Check if amm pool balance in bank module is correct +func (k Keeper) InvariantCheck(ctx sdk.Context) error { + mtps := k.GetAllMTPs(ctx) + for _, mtp := range mtps { + ammPoolId := mtp.AmmPoolId + err := k.AmmPoolBalanceCheck(ctx, ammPoolId) + if err != nil { + return err + } + } + + return nil +} diff --git a/x/margin/keeper/invariant_check_test.go b/x/margin/keeper/invariant_check_test.go new file mode 100644 index 000000000..71390b35d --- /dev/null +++ b/x/margin/keeper/invariant_check_test.go @@ -0,0 +1,136 @@ +package keeper_test + +import ( + "errors" + "testing" + + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + sdk "github.com/cosmos/cosmos-sdk/types" + simapp "github.com/elys-network/elys/app" + "github.com/elys-network/elys/x/amm/types" + ammtypes "github.com/elys-network/elys/x/amm/types" + ptypes "github.com/elys-network/elys/x/parameter/types" + "github.com/stretchr/testify/require" + + margintypes "github.com/elys-network/elys/x/margin/types" +) + +func TestCheckBalanceInvariant_InvalidBalance(t *testing.T) { + app := simapp.InitElysTestApp(true) + ctx := app.BaseApp.NewContext(true, tmproto.Header{}) + + mk, amm, oracle := app.MarginKeeper, app.AmmKeeper, app.OracleKeeper + + // Setup coin prices + SetupStableCoinPrices(ctx, oracle) + + // Generate 1 random account with 1000stake balanced + addr := simapp.AddTestAddrs(app, ctx, 1, sdk.NewInt(1000000)) + + // Create a pool + // Mint 100000USDC + usdcToken := sdk.NewCoins(sdk.NewCoin(ptypes.USDC, sdk.NewInt(100000))) + // Mint 100000ATOM + atomToken := sdk.NewCoins(sdk.NewCoin(ptypes.ATOM, sdk.NewInt(100000))) + + err := app.BankKeeper.MintCoins(ctx, types.ModuleName, usdcToken) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr[0], usdcToken) + require.NoError(t, err) + + err = app.BankKeeper.MintCoins(ctx, types.ModuleName, atomToken) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr[0], atomToken) + require.NoError(t, err) + + poolAssets := []ammtypes.PoolAsset{ + { + Weight: sdk.NewInt(50), + Token: sdk.NewCoin(ptypes.ATOM, sdk.NewInt(100000)), + }, + { + Weight: sdk.NewInt(50), + Token: sdk.NewCoin(ptypes.USDC, sdk.NewInt(10000)), + }, + } + + argSwapFee := sdk.MustNewDecFromStr("0.0") + argExitFee := sdk.MustNewDecFromStr("0.0") + + poolParams := &ammtypes.PoolParams{ + SwapFee: argSwapFee, + ExitFee: argExitFee, + } + + msg := types.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(0)) + + 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) + + // Balance check before create a margin position + balances := app.BankKeeper.GetAllBalances(ctx, poolAddress) + require.Equal(t, balances.AmountOf(ptypes.USDC), sdk.NewInt(10000)) + require.Equal(t, balances.AmountOf(ptypes.ATOM), sdk.NewInt(100000)) + + // Create a margin position open msg + msg2 := margintypes.NewMsgOpen( + addr[0].String(), + ptypes.USDC, + sdk.NewInt(100), + ptypes.ATOM, + margintypes.Position_LONG, + sdk.NewDec(5), + ) + + _, err = mk.Open(ctx, msg2) + 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.USDC), sdk.NewInt(10100)) + require.Equal(t, balances.AmountOf(ptypes.ATOM), sdk.NewInt(100000)) + + // Check balance invariant check + err = mk.InvariantCheck(ctx) + require.Equal(t, err, errors.New("balance mismatch!")) + + mtpId := mtps[0].Id + // Create a margin position close msg + msg3 := margintypes.NewMsgClose( + addr[0].String(), + mtpId, + ) + + _, err = mk.Close(ctx, msg3) + require.NoError(t, err) + + balances = app.BankKeeper.GetAllBalances(ctx, poolAddress) + require.Equal(t, balances.AmountOf(ptypes.USDC), sdk.NewInt(10046)) + require.Equal(t, balances.AmountOf(ptypes.ATOM), sdk.NewInt(100000)) + + // Check balance invariant check + err = mk.InvariantCheck(ctx) + require.NoError(t, err) +} diff --git a/x/margin/keeper/keeper.go b/x/margin/keeper/keeper.go index 8bb36cef4..d2f0bc157 100644 --- a/x/margin/keeper/keeper.go +++ b/x/margin/keeper/keeper.go @@ -33,6 +33,8 @@ type ( amm types.AmmKeeper bankKeeper types.BankKeeper oracleKeeper ammtypes.OracleKeeper + + hooks types.MarginHooks } ) @@ -50,7 +52,7 @@ func NewKeeper( panic("authority is not a valid acc address") } - return &Keeper{ + keeper := &Keeper{ cdc: cdc, storeKey: storeKey, memKey: memKey, @@ -59,6 +61,13 @@ func NewKeeper( bankKeeper: bk, oracleKeeper: oracleKeeper, } + + keeper.AuthorizationChecker = keeper + keeper.PositionChecker = keeper + keeper.PoolChecker = keeper + keeper.OpenLongChecker = keeper + + return keeper } func (k Keeper) Logger(ctx sdk.Context) log.Logger { @@ -102,7 +111,7 @@ func (k Keeper) EstimateSwap(ctx sdk.Context, tokenInAmount sdk.Coin, tokenOutDe tokensIn := sdk.Coins{tokenInAmount} // Estimate swap snapshot := k.amm.GetPoolSnapshotOrSet(ctx, ammPool) - swapResult, err := ammPool.CalcOutAmtGivenIn(ctx, k.oracleKeeper, &snapshot, tokensIn, tokenOutDenom, sdk.ZeroDec()) + swapResult, err := k.amm.CalcOutAmtGivenIn(ctx, ammPool.PoolId, k.oracleKeeper, &snapshot, tokensIn, tokenOutDenom, sdk.ZeroDec()) if err != nil { return sdk.ZeroInt(), err @@ -143,8 +152,14 @@ func (k Keeper) Borrow(ctx sdk.Context, collateralAsset string, collateralAmount } mtp.MtpHealth = h + ammPoolAddr, err := sdk.AccAddressFromBech32(ammPool.Address) + if err != nil { + return err + } + collateralCoins := sdk.NewCoins(collateralCoin) - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, mtpAddress, ammPool.Address, collateralCoins) + err = k.bankKeeper.SendCoins(ctx, mtpAddress, ammPoolAddr, collateralCoins) + if err != nil { return err } @@ -477,7 +492,13 @@ func (k Keeper) Repay(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool if err != nil { return err } - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, ammPool.Address, addr, returnCoins) + + ammPoolAddr, err := sdk.AccAddressFromBech32(ammPool.Address) + if err != nil { + return err + } + + err = k.bankKeeper.SendCoins(ctx, ammPoolAddr, addr, returnCoins) if err != nil { return err } @@ -777,3 +798,14 @@ func (k Keeper) DewhitelistAddress(ctx sdk.Context, address string) { store := ctx.KVStore(k.storeKey) store.Delete(types.GetWhitelistKey(address)) } + +// Set the margin hooks. +func (k *Keeper) SetHooks(gh types.MarginHooks) *Keeper { + if k.hooks != nil { + panic("cannot set margin hooks twice") + } + + k.hooks = gh + + return k +} diff --git a/x/margin/keeper/keeper_test.go b/x/margin/keeper/keeper_test.go index 63d65ec46..d9a17af5f 100644 --- a/x/margin/keeper/keeper_test.go +++ b/x/margin/keeper/keeper_test.go @@ -10,6 +10,11 @@ import ( "github.com/elys-network/elys/x/margin/types" paramtypes "github.com/elys-network/elys/x/parameter/types" "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto/ed25519" + oraclekeeper "github.com/elys-network/elys/x/oracle/keeper" + oracletypes "github.com/elys-network/elys/x/oracle/types" + ptypes "github.com/elys-network/elys/x/parameter/types" ) func TestSetGetMTP(t *testing.T) { @@ -79,3 +84,57 @@ func TestGetAllWhitelistedAddress(t *testing.T) { addr[1].String(), ) } + +func SetupStableCoinPrices(ctx sdk.Context, oracle oraclekeeper.Keeper) { + // prices set for USDT and USDC + provider := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) + oracle.SetAssetInfo(ctx, oracletypes.AssetInfo{ + Denom: ptypes.USDC, + Display: "USDC", + Decimal: 6, + }) + oracle.SetAssetInfo(ctx, oracletypes.AssetInfo{ + Denom: ptypes.USDT, + Display: "USDT", + Decimal: 6, + }) + oracle.SetAssetInfo(ctx, oracletypes.AssetInfo{ + Denom: ptypes.Elys, + Display: "ELYS", + Decimal: 6, + }) + oracle.SetAssetInfo(ctx, oracletypes.AssetInfo{ + Denom: ptypes.ATOM, + Display: "ATOM", + Decimal: 6, + }) + + oracle.SetPrice(ctx, oracletypes.Price{ + Asset: "USDC", + Price: sdk.NewDec(1000000), + Source: "elys", + Provider: provider.String(), + Timestamp: uint64(ctx.BlockTime().Unix()), + }) + oracle.SetPrice(ctx, oracletypes.Price{ + Asset: "USDT", + Price: sdk.NewDec(1000000), + Source: "elys", + Provider: provider.String(), + Timestamp: uint64(ctx.BlockTime().Unix()), + }) + oracle.SetPrice(ctx, oracletypes.Price{ + Asset: "ELYS", + Price: sdk.NewDec(100), + Source: "elys", + Provider: provider.String(), + Timestamp: uint64(ctx.BlockTime().Unix()), + }) + oracle.SetPrice(ctx, oracletypes.Price{ + Asset: "ATOM", + Price: sdk.NewDec(100), + Source: "atom", + Provider: provider.String(), + Timestamp: uint64(ctx.BlockTime().Unix()), + }) +} diff --git a/x/margin/keeper/msg_server_close.go b/x/margin/keeper/msg_server_close.go index b6925a96d..f4b9c9c87 100644 --- a/x/margin/keeper/msg_server_close.go +++ b/x/margin/keeper/msg_server_close.go @@ -2,109 +2,13 @@ package keeper import ( "context" - "strconv" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/elys-network/elys/x/margin/types" ) func (k msgServer) Close(goCtx context.Context, msg *types.MsgClose) (*types.MsgCloseResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - mtp, err := k.GetMTP(ctx, msg.Creator, msg.Id) - if err != nil { - return nil, err - } - - var closedMtp *types.MTP - var repayAmount sdk.Int - switch mtp.Position { - case types.Position_LONG: - closedMtp, repayAmount, err = k.CloseLong(ctx, msg) - if err != nil { - return nil, err - } - default: - return nil, sdkerrors.Wrap(types.ErrInvalidPosition, mtp.Position.String()) - } - - ctx.EventManager().EmitEvent(sdk.NewEvent(types.EventClose, - sdk.NewAttribute("id", strconv.FormatInt(int64(closedMtp.Id), 10)), - sdk.NewAttribute("position", closedMtp.Position.String()), - sdk.NewAttribute("address", closedMtp.Address), - sdk.NewAttribute("collateral_asset", closedMtp.CollateralAsset), - sdk.NewAttribute("collateral_amount", closedMtp.CollateralAmount.String()), - sdk.NewAttribute("custody_asset", closedMtp.CustodyAsset), - sdk.NewAttribute("custody_amount", closedMtp.CustodyAmount.String()), - sdk.NewAttribute("repay_amount", repayAmount.String()), - sdk.NewAttribute("leverage", closedMtp.Leverage.String()), - sdk.NewAttribute("liabilities", closedMtp.Liabilities.String()), - sdk.NewAttribute("interest_paid_collateral", mtp.InterestPaidCollateral.String()), - sdk.NewAttribute("interest_paid_custody", mtp.InterestPaidCustody.String()), - sdk.NewAttribute("interest_unpaid_collateral", closedMtp.InterestUnpaidCollateral.String()), - sdk.NewAttribute("health", closedMtp.MtpHealth.String()), - )) - return &types.MsgCloseResponse{}, nil -} - -func (k msgServer) CloseLong(ctx sdk.Context, msg *types.MsgClose) (*types.MTP, sdk.Int, error) { - mtp, err := k.GetMTP(ctx, msg.Creator, msg.Id) - if err != nil { - return nil, sdk.ZeroInt(), err - } - // Get pool Ids which can support borrowing asset - poolIds := k.amm.GetAllPoolIdsWithDenom(ctx, mtp.CustodyAsset) - if len(poolIds) < 1 { - return nil, sdk.ZeroInt(), sdkerrors.Wrap(types.ErrInvalidBorrowingAsset, "invalid collateral asset") - } - - // Assume choose the first pool - poolId := poolIds[0] - - // Get pool from pool Id - pool, found := k.GetPool(ctx, poolId) - if !found { - return nil, sdk.ZeroInt(), sdkerrors.Wrap(types.ErrInvalidBorrowingAsset, "invalid collateral asset") - } - - ammPool, found := k.amm.GetPool(ctx, poolId) - if !found { - return nil, sdk.ZeroInt(), sdkerrors.Wrap(types.ErrPoolDoesNotExist, mtp.CustodyAsset) - } - - epochLength := k.GetEpochLength(ctx) - epochPosition := GetEpochPosition(ctx, epochLength) - if epochPosition > 0 { - interestPayment := CalcMTPInterestLiabilities(&mtp, pool.InterestRate, epochPosition, epochLength) - finalInterestPayment := k.HandleInterestPayment(ctx, interestPayment, &mtp, &pool, ammPool) - - err = pool.UpdateBlockInterest(ctx, mtp.CollateralAsset, finalInterestPayment, true) - if err != nil { - return nil, sdk.ZeroInt(), err - } - - mtp.MtpHealth, err = k.UpdateMTPHealth(ctx, mtp, ammPool) - if err != nil { - return nil, sdk.ZeroInt(), err - } - } - - err = k.TakeOutCustody(ctx, mtp, &pool) - if err != nil { - return nil, sdk.ZeroInt(), err - } - - cutodyAmtTokenIn := sdk.NewCoin(mtp.CustodyAsset, mtp.CustodyAmount) - repayAmount, err := k.EstimateSwap(ctx, cutodyAmtTokenIn, mtp.CollateralAsset, ammPool) - if err != nil { - return nil, sdk.ZeroInt(), err - } - - err = k.Repay(ctx, &mtp, &pool, ammPool, repayAmount, false) - if err != nil { - return nil, sdk.ZeroInt(), err - } - - return &mtp, repayAmount, nil + return k.Keeper.Close(ctx, msg) } diff --git a/x/margin/keeper/msg_server_open.go b/x/margin/keeper/msg_server_open.go index 437983ff4..e1a373409 100644 --- a/x/margin/keeper/msg_server_open.go +++ b/x/margin/keeper/msg_server_open.go @@ -4,59 +4,11 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/elys-network/elys/x/margin/types" ) func (k msgServer) Open(goCtx context.Context, msg *types.MsgOpen) (*types.MsgOpenResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - if err := k.CheckUserAuthorization(ctx, msg); err != nil { - return nil, err - } - - if err := k.CheckMaxOpenPositions(ctx); err != nil { - return nil, err - } - - // Get token asset other than USDC - nonNativeAsset := k.GetNonNativeAsset(msg.CollateralAsset, msg.BorrowAsset) - - // Get the first valid pool - poolId, err := k.GetFirstValidPool(ctx, nonNativeAsset) - if err != nil { - return nil, err - } - - ammPool, err := k.OpenLongChecker.GetAmmPool(ctx, poolId, nonNativeAsset) - if err != nil { - return nil, err - } - - pool, found := k.PoolChecker.GetPool(ctx, poolId) - // If margin pool doesn't exist yet, we should initiate it according to its corresponding ammPool - if !found { - pool = types.NewPool(poolId) - pool.InitiatePool(ctx, &ammPool) - - k.OpenLongChecker.SetPool(ctx, pool) - } - - if err := k.CheckPoolHealth(ctx, poolId); err != nil { - return nil, err - } - - var mtp *types.MTP - switch msg.Position { - case types.Position_LONG: - mtp, err = k.OpenLong(ctx, poolId, msg) - if err != nil { - return nil, err - } - default: - return nil, sdkerrors.Wrap(types.ErrInvalidPosition, msg.Position.String()) - } - - ctx.EventManager().EmitEvent(k.GenerateOpenEvent(mtp)) - return &types.MsgOpenResponse{}, nil + return k.Keeper.Open(ctx, msg) } diff --git a/x/margin/keeper/open.go b/x/margin/keeper/open.go new file mode 100644 index 000000000..108dfe4c1 --- /dev/null +++ b/x/margin/keeper/open.go @@ -0,0 +1,63 @@ +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" +) + +func (k Keeper) Open(ctx sdk.Context, msg *types.MsgOpen) (*types.MsgOpenResponse, error) { + if err := k.CheckUserAuthorization(ctx, msg); err != nil { + return nil, err + } + + if err := k.CheckMaxOpenPositions(ctx); err != nil { + return nil, err + } + + // Get token asset other than USDC + nonNativeAsset := k.GetNonNativeAsset(msg.CollateralAsset, msg.BorrowAsset) + + // Get the first valid pool + poolId, err := k.GetFirstValidPool(ctx, nonNativeAsset) + if err != nil { + return nil, err + } + + ammPool, err := k.OpenLongChecker.GetAmmPool(ctx, poolId, nonNativeAsset) + if err != nil { + return nil, err + } + + pool, found := k.PoolChecker.GetPool(ctx, poolId) + // If margin pool doesn't exist yet, we should initiate it according to its corresponding ammPool + if !found { + pool = types.NewPool(poolId) + pool.InitiatePool(ctx, &ammPool) + + k.OpenLongChecker.SetPool(ctx, pool) + } + + if err := k.CheckPoolHealth(ctx, poolId); err != nil { + return nil, err + } + + var mtp *types.MTP + switch msg.Position { + case types.Position_LONG: + mtp, err = k.OpenLong(ctx, poolId, msg) + if err != nil { + return nil, err + } + default: + return nil, sdkerrors.Wrap(types.ErrInvalidPosition, msg.Position.String()) + } + + ctx.EventManager().EmitEvent(k.GenerateOpenEvent(mtp)) + + if k.hooks != nil { + k.hooks.AfterMarginPositionOpended(ctx, ammPool, pool) + } + + return &types.MsgOpenResponse{}, nil +} diff --git a/x/margin/keeper/params.go b/x/margin/keeper/params.go index 0c83fa3ef..404ae750a 100644 --- a/x/margin/keeper/params.go +++ b/x/margin/keeper/params.go @@ -95,8 +95,8 @@ func (k Keeper) GetIncrementalInterestPaymentFundAddress(ctx sdk.Context) sdk.Ac return addr } -func (k Keeper) GetMaxOpenPositions(ctx sdk.Context) int64 { - return k.GetParams(ctx).MaxOpenPositions +func (k Keeper) GetMaxOpenPositions(ctx sdk.Context) uint64 { + return (uint64)(k.GetParams(ctx).MaxOpenPositions) } func (k Keeper) GetIncrementalInterestPaymentEnabled(ctx sdk.Context) bool { diff --git a/x/margin/types/expected_keepers.go b/x/margin/types/expected_keepers.go index 47a6845c0..1e67c13bf 100644 --- a/x/margin/types/expected_keepers.go +++ b/x/margin/types/expected_keepers.go @@ -16,7 +16,7 @@ type AuthorizationChecker interface { //go:generate mockery --srcpkg . --name PositionChecker --structname PositionChecker --filename position_checker.go --with-expecter type PositionChecker interface { GetOpenMTPCount(ctx sdk.Context) uint64 - GetMaxOpenPositions(ctx sdk.Context) int + GetMaxOpenPositions(ctx sdk.Context) uint64 } //go:generate mockery --srcpkg . --name PoolChecker --structname PoolChecker --filename pool_checker.go --with-expecter @@ -66,6 +66,8 @@ type AmmKeeper interface { // IterateCommitments iterates over all Commitments and performs a callback. IterateLiquidityPools(sdk.Context, func(ammtypes.Pool) bool) GetPoolSnapshotOrSet(ctx sdk.Context, pool ammtypes.Pool) (val ammtypes.Pool) + + CalcOutAmtGivenIn(ctx sdk.Context, poolId uint64, oracle ammtypes.OracleKeeper, snapshot *ammtypes.Pool, tokensIn sdk.Coins, tokenOutDenom string, swapFee sdk.Dec) (sdk.Coin, error) } // BankKeeper defines the expected interface needed to retrieve account balances. @@ -80,6 +82,7 @@ type BankKeeper interface { SendCoinsFromModuleToModule(ctx sdk.Context, senderModule string, recipientModule string, amt sdk.Coins) error SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error + SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error BlockedAddr(addr sdk.AccAddress) bool HasBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coin) bool diff --git a/x/margin/types/hooks.go b/x/margin/types/hooks.go new file mode 100644 index 000000000..adde87679 --- /dev/null +++ b/x/margin/types/hooks.go @@ -0,0 +1,81 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + ammtypes "github.com/elys-network/elys/x/amm/types" +) + +type MarginHooks interface { + // AfterMarginPositionOpended is called after OpenLong or OpenShort position. + AfterMarginPositionOpended(ctx sdk.Context, ammPool ammtypes.Pool, marginPool Pool) + + // AfterMarginPositionModified is called after a position gets modified. + AfterMarginPositionModified(ctx sdk.Context, ammPool ammtypes.Pool, marginPool Pool) + + // AfterMarginPositionClosed is called after a position gets closed. + AfterMarginPositionClosed(ctx sdk.Context, ammPool ammtypes.Pool, marginPool Pool) + + // AfterPoolCreated is called after CreatePool + AfterAmmPoolCreated(ctx sdk.Context, ammPool ammtypes.Pool) + + // AfterJoinPool is called after JoinPool, JoinSwapExternAmountIn, and JoinSwapShareAmountOut + AfterAmmJoinPool(ctx sdk.Context, ammPool ammtypes.Pool, marginPool Pool) + + // AfterExitPool is called after ExitPool, ExitSwapShareAmountIn, and ExitSwapExternAmountOut + AfterAmmExitPool(ctx sdk.Context, ammPool ammtypes.Pool, marginPool Pool) + + // AfterSwap is called after SwapExactAmountIn and SwapExactAmountOut + AfterAmmSwap(ctx sdk.Context, ammPool ammtypes.Pool, marginPool Pool) +} + +var _ MarginHooks = MultiMarginHooks{} + +// combine multiple margin hooks, all hook functions are run in array sequence. +type MultiMarginHooks []MarginHooks + +// Creates hooks for the Amm Module. +func NewMultiMarginHooks(hooks ...MarginHooks) MultiMarginHooks { + return hooks +} + +func (h MultiMarginHooks) AfterMarginPositionOpended(ctx sdk.Context, ammPool ammtypes.Pool, marginPool Pool) { + for i := range h { + h[i].AfterMarginPositionOpended(ctx, ammPool, marginPool) + } +} + +func (h MultiMarginHooks) AfterMarginPositionModified(ctx sdk.Context, ammPool ammtypes.Pool, marginPool Pool) { + for i := range h { + h[i].AfterMarginPositionModified(ctx, ammPool, marginPool) + } +} + +func (h MultiMarginHooks) AfterMarginPositionClosed(ctx sdk.Context, ammPool ammtypes.Pool, marginPool Pool) { + for i := range h { + h[i].AfterMarginPositionClosed(ctx, ammPool, marginPool) + } +} + +func (h MultiMarginHooks) AfterAmmPoolCreated(ctx sdk.Context, ammPool ammtypes.Pool) { + for i := range h { + h[i].AfterAmmPoolCreated(ctx, ammPool) + } +} + +func (h MultiMarginHooks) AfterAmmJoinPool(ctx sdk.Context, ammPool ammtypes.Pool, marginPool Pool) { + for i := range h { + h[i].AfterAmmJoinPool(ctx, ammPool, marginPool) + } +} + +func (h MultiMarginHooks) AfterAmmExitPool(ctx sdk.Context, ammPool ammtypes.Pool, marginPool Pool) { + for i := range h { + h[i].AfterAmmExitPool(ctx, ammPool, marginPool) + } +} + +func (h MultiMarginHooks) AfterAmmSwap(ctx sdk.Context, ammPool ammtypes.Pool, marginPool Pool) { + for i := range h { + h[i].AfterAmmSwap(ctx, ammPool, marginPool) + } +} diff --git a/x/margin/types/mocks/amm_keeper.go b/x/margin/types/mocks/amm_keeper.go index 8d9cc0ee6..5083cc634 100644 --- a/x/margin/types/mocks/amm_keeper.go +++ b/x/margin/types/mocks/amm_keeper.go @@ -5,6 +5,8 @@ package mocks import ( ammtypes "github.com/elys-network/elys/x/amm/types" + math "cosmossdk.io/math" + mock "github.com/stretchr/testify/mock" types "github.com/cosmos/cosmos-sdk/types" @@ -23,6 +25,64 @@ func (_m *AmmKeeper) EXPECT() *AmmKeeper_Expecter { return &AmmKeeper_Expecter{mock: &_m.Mock} } +// CalcOutAmtGivenIn provides a mock function with given fields: ctx, poolId, oracle, snapshot, tokensIn, tokenOutDenom, swapFee +func (_m *AmmKeeper) CalcOutAmtGivenIn(ctx types.Context, poolId uint64, oracle ammtypes.OracleKeeper, snapshot *ammtypes.Pool, tokensIn types.Coins, tokenOutDenom string, swapFee math.LegacyDec) (types.Coin, error) { + ret := _m.Called(ctx, poolId, oracle, snapshot, tokensIn, tokenOutDenom, swapFee) + + var r0 types.Coin + var r1 error + if rf, ok := ret.Get(0).(func(types.Context, uint64, ammtypes.OracleKeeper, *ammtypes.Pool, types.Coins, string, math.LegacyDec) (types.Coin, error)); ok { + return rf(ctx, poolId, oracle, snapshot, tokensIn, tokenOutDenom, swapFee) + } + if rf, ok := ret.Get(0).(func(types.Context, uint64, ammtypes.OracleKeeper, *ammtypes.Pool, types.Coins, string, math.LegacyDec) types.Coin); ok { + r0 = rf(ctx, poolId, oracle, snapshot, tokensIn, tokenOutDenom, swapFee) + } else { + r0 = ret.Get(0).(types.Coin) + } + + if rf, ok := ret.Get(1).(func(types.Context, uint64, ammtypes.OracleKeeper, *ammtypes.Pool, types.Coins, string, math.LegacyDec) error); ok { + r1 = rf(ctx, poolId, oracle, snapshot, tokensIn, tokenOutDenom, swapFee) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// AmmKeeper_CalcOutAmtGivenIn_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CalcOutAmtGivenIn' +type AmmKeeper_CalcOutAmtGivenIn_Call struct { + *mock.Call +} + +// CalcOutAmtGivenIn is a helper method to define mock.On call +// - ctx types.Context +// - poolId uint64 +// - oracle ammtypes.OracleKeeper +// - snapshot *ammtypes.Pool +// - tokensIn types.Coins +// - tokenOutDenom string +// - swapFee math.LegacyDec +func (_e *AmmKeeper_Expecter) CalcOutAmtGivenIn(ctx interface{}, poolId interface{}, oracle interface{}, snapshot interface{}, tokensIn interface{}, tokenOutDenom interface{}, swapFee interface{}) *AmmKeeper_CalcOutAmtGivenIn_Call { + return &AmmKeeper_CalcOutAmtGivenIn_Call{Call: _e.mock.On("CalcOutAmtGivenIn", ctx, poolId, oracle, snapshot, tokensIn, tokenOutDenom, swapFee)} +} + +func (_c *AmmKeeper_CalcOutAmtGivenIn_Call) Run(run func(ctx types.Context, poolId uint64, oracle ammtypes.OracleKeeper, snapshot *ammtypes.Pool, tokensIn types.Coins, tokenOutDenom string, swapFee math.LegacyDec)) *AmmKeeper_CalcOutAmtGivenIn_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(uint64), args[2].(ammtypes.OracleKeeper), args[3].(*ammtypes.Pool), args[4].(types.Coins), args[5].(string), args[6].(math.LegacyDec)) + }) + return _c +} + +func (_c *AmmKeeper_CalcOutAmtGivenIn_Call) Return(_a0 types.Coin, _a1 error) *AmmKeeper_CalcOutAmtGivenIn_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *AmmKeeper_CalcOutAmtGivenIn_Call) RunAndReturn(run func(types.Context, uint64, ammtypes.OracleKeeper, *ammtypes.Pool, types.Coins, string, math.LegacyDec) (types.Coin, error)) *AmmKeeper_CalcOutAmtGivenIn_Call { + _c.Call.Return(run) + return _c +} + // GetAllPool provides a mock function with given fields: _a0 func (_m *AmmKeeper) GetAllPool(_a0 types.Context) []ammtypes.Pool { ret := _m.Called(_a0) @@ -39,10 +99,6 @@ func (_m *AmmKeeper) GetAllPool(_a0 types.Context) []ammtypes.Pool { return r0 } -func (_m *AmmKeeper) GetPoolSnapshotOrSet(ctx types.Context, pool ammtypes.Pool) ammtypes.Pool { - return ammtypes.Pool{} -} - // AmmKeeper_GetAllPool_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAllPool' type AmmKeeper_GetAllPool_Call struct { *mock.Call @@ -169,6 +225,49 @@ func (_c *AmmKeeper_GetPool_Call) RunAndReturn(run func(types.Context, uint64) ( return _c } +// GetPoolSnapshotOrSet provides a mock function with given fields: ctx, pool +func (_m *AmmKeeper) GetPoolSnapshotOrSet(ctx types.Context, pool ammtypes.Pool) ammtypes.Pool { + ret := _m.Called(ctx, pool) + + var r0 ammtypes.Pool + if rf, ok := ret.Get(0).(func(types.Context, ammtypes.Pool) ammtypes.Pool); ok { + r0 = rf(ctx, pool) + } else { + r0 = ret.Get(0).(ammtypes.Pool) + } + + return r0 +} + +// AmmKeeper_GetPoolSnapshotOrSet_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPoolSnapshotOrSet' +type AmmKeeper_GetPoolSnapshotOrSet_Call struct { + *mock.Call +} + +// GetPoolSnapshotOrSet is a helper method to define mock.On call +// - ctx types.Context +// - pool ammtypes.Pool +func (_e *AmmKeeper_Expecter) GetPoolSnapshotOrSet(ctx interface{}, pool interface{}) *AmmKeeper_GetPoolSnapshotOrSet_Call { + return &AmmKeeper_GetPoolSnapshotOrSet_Call{Call: _e.mock.On("GetPoolSnapshotOrSet", ctx, pool)} +} + +func (_c *AmmKeeper_GetPoolSnapshotOrSet_Call) Run(run func(ctx types.Context, pool ammtypes.Pool)) *AmmKeeper_GetPoolSnapshotOrSet_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(ammtypes.Pool)) + }) + return _c +} + +func (_c *AmmKeeper_GetPoolSnapshotOrSet_Call) Return(val ammtypes.Pool) *AmmKeeper_GetPoolSnapshotOrSet_Call { + _c.Call.Return(val) + return _c +} + +func (_c *AmmKeeper_GetPoolSnapshotOrSet_Call) RunAndReturn(run func(types.Context, ammtypes.Pool) ammtypes.Pool) *AmmKeeper_GetPoolSnapshotOrSet_Call { + _c.Call.Return(run) + return _c +} + // IterateLiquidityPools provides a mock function with given fields: _a0, _a1 func (_m *AmmKeeper) IterateLiquidityPools(_a0 types.Context, _a1 func(ammtypes.Pool) bool) { _m.Called(_a0, _a1) diff --git a/x/margin/types/mocks/bank_keeper.go b/x/margin/types/mocks/bank_keeper.go index 6a6e79279..03d64abb9 100644 --- a/x/margin/types/mocks/bank_keeper.go +++ b/x/margin/types/mocks/bank_keeper.go @@ -195,6 +195,51 @@ func (_c *BankKeeper_HasBalance_Call) RunAndReturn(run func(types.Context, types return _c } +// SendCoins provides a mock function with given fields: ctx, fromAddr, toAddr, amt +func (_m *BankKeeper) SendCoins(ctx types.Context, fromAddr types.AccAddress, toAddr types.AccAddress, amt types.Coins) error { + ret := _m.Called(ctx, fromAddr, toAddr, amt) + + var r0 error + if rf, ok := ret.Get(0).(func(types.Context, types.AccAddress, types.AccAddress, types.Coins) error); ok { + r0 = rf(ctx, fromAddr, toAddr, amt) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// BankKeeper_SendCoins_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendCoins' +type BankKeeper_SendCoins_Call struct { + *mock.Call +} + +// SendCoins is a helper method to define mock.On call +// - ctx types.Context +// - fromAddr types.AccAddress +// - toAddr types.AccAddress +// - amt types.Coins +func (_e *BankKeeper_Expecter) SendCoins(ctx interface{}, fromAddr interface{}, toAddr interface{}, amt interface{}) *BankKeeper_SendCoins_Call { + return &BankKeeper_SendCoins_Call{Call: _e.mock.On("SendCoins", ctx, fromAddr, toAddr, amt)} +} + +func (_c *BankKeeper_SendCoins_Call) Run(run func(ctx types.Context, fromAddr types.AccAddress, toAddr types.AccAddress, amt types.Coins)) *BankKeeper_SendCoins_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(types.AccAddress), args[2].(types.AccAddress), args[3].(types.Coins)) + }) + return _c +} + +func (_c *BankKeeper_SendCoins_Call) Return(_a0 error) *BankKeeper_SendCoins_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_SendCoins_Call) RunAndReturn(run func(types.Context, types.AccAddress, types.AccAddress, types.Coins) error) *BankKeeper_SendCoins_Call { + _c.Call.Return(run) + return _c +} + // SendCoinsFromAccountToModule provides a mock function with given fields: ctx, senderAddr, recipientModule, amt func (_m *BankKeeper) SendCoinsFromAccountToModule(ctx types.Context, senderAddr types.AccAddress, recipientModule string, amt types.Coins) error { ret := _m.Called(ctx, senderAddr, recipientModule, amt) diff --git a/x/margin/types/mocks/position_checker.go b/x/margin/types/mocks/position_checker.go index 2a47de92d..ee18ecc89 100644 --- a/x/margin/types/mocks/position_checker.go +++ b/x/margin/types/mocks/position_checker.go @@ -21,14 +21,14 @@ func (_m *PositionChecker) EXPECT() *PositionChecker_Expecter { } // GetMaxOpenPositions provides a mock function with given fields: ctx -func (_m *PositionChecker) GetMaxOpenPositions(ctx types.Context) int { +func (_m *PositionChecker) GetMaxOpenPositions(ctx types.Context) uint64 { ret := _m.Called(ctx) - var r0 int - if rf, ok := ret.Get(0).(func(types.Context) int); ok { + var r0 uint64 + if rf, ok := ret.Get(0).(func(types.Context) uint64); ok { r0 = rf(ctx) } else { - r0 = ret.Get(0).(int) + r0 = ret.Get(0).(uint64) } return r0 @@ -52,12 +52,12 @@ func (_c *PositionChecker_GetMaxOpenPositions_Call) Run(run func(ctx types.Conte return _c } -func (_c *PositionChecker_GetMaxOpenPositions_Call) Return(_a0 int) *PositionChecker_GetMaxOpenPositions_Call { +func (_c *PositionChecker_GetMaxOpenPositions_Call) Return(_a0 uint64) *PositionChecker_GetMaxOpenPositions_Call { _c.Call.Return(_a0) return _c } -func (_c *PositionChecker_GetMaxOpenPositions_Call) RunAndReturn(run func(types.Context) int) *PositionChecker_GetMaxOpenPositions_Call { +func (_c *PositionChecker_GetMaxOpenPositions_Call) RunAndReturn(run func(types.Context) uint64) *PositionChecker_GetMaxOpenPositions_Call { _c.Call.Return(run) return _c } diff --git a/x/margin/types/params.go b/x/margin/types/params.go index 557d14373..e2674ed99 100644 --- a/x/margin/types/params.go +++ b/x/margin/types/params.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + epochtypes "github.com/elys-network/elys/x/epochs/types" "gopkg.in/yaml.v2" ) @@ -29,6 +30,7 @@ var ( KeySafetyFactor = []byte("SafetyFactor") KeyIncrementalInterestPaymentEnabled = []byte("IncrementalInterestPaymentEnabled") KeyWhitelistingEnabled = []byte("WhitelistingEnabled") + KeyInvariantCheckEpoch = []byte("InvariantCheckEpoch") ) // ParamKeyTable the param key table for launch module @@ -56,7 +58,8 @@ func NewParams() Params { SqModifier: sdk.NewDec(1), SafetyFactor: sdk.NewDec(1), IncrementalInterestPaymentEnabled: true, - WhitelistingEnabled: true, + WhitelistingEnabled: false, + InvariantCheckEpoch: epochtypes.DayEpochID, } } @@ -86,6 +89,7 @@ func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { paramtypes.NewParamSetPair(KeySafetyFactor, &p.SafetyFactor, validateSafetyFactor), paramtypes.NewParamSetPair(KeyIncrementalInterestPaymentEnabled, &p.IncrementalInterestPaymentEnabled, validateIncrementalInterestPaymentEnabled), paramtypes.NewParamSetPair(KeyWhitelistingEnabled, &p.WhitelistingEnabled, validateWhitelistingEnabled), + paramtypes.NewParamSetPair(KeyInvariantCheckEpoch, &p.InvariantCheckEpoch, validateInvariantCheckEpoch), } } @@ -145,7 +149,9 @@ func (p Params) Validate() error { if err := validateWhitelistingEnabled(p.WhitelistingEnabled); err != nil { return err } - + if err := validateInvariantCheckEpoch(p.InvariantCheckEpoch); err != nil { + return err + } return nil } @@ -403,3 +409,16 @@ func validatePoolOpenThreshold(i interface{}) error { return nil } + +func validateInvariantCheckEpoch(i interface{}) error { + epoch, ok := i.(string) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if epoch != epochtypes.DayEpochID && epoch != epochtypes.WeekEpochID && epoch != epochtypes.HourEpochID { + return fmt.Errorf("invalid parameter type: %T", i) + } + + return nil +} diff --git a/x/margin/types/params.pb.go b/x/margin/types/params.pb.go index 175a9dd6c..d1eff1945 100644 --- a/x/margin/types/params.pb.go +++ b/x/margin/types/params.pb.go @@ -44,6 +44,7 @@ type Params struct { SafetyFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,16,opt,name=safety_factor,json=safetyFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"safety_factor"` IncrementalInterestPaymentEnabled bool `protobuf:"varint,17,opt,name=incremental_interest_payment_enabled,json=incrementalInterestPaymentEnabled,proto3" json:"incremental_interest_payment_enabled,omitempty"` WhitelistingEnabled bool `protobuf:"varint,18,opt,name=whitelisting_enabled,json=whitelistingEnabled,proto3" json:"whitelisting_enabled,omitempty"` + InvariantCheckEpoch string `protobuf:"bytes,19,opt,name=invariant_check_epoch,json=invariantCheckEpoch,proto3" json:"invariant_check_epoch,omitempty"` } func (m *Params) Reset() { *m = Params{} } @@ -120,6 +121,13 @@ func (m *Params) GetWhitelistingEnabled() bool { return false } +func (m *Params) GetInvariantCheckEpoch() string { + if m != nil { + return m.InvariantCheckEpoch + } + return "" +} + func init() { proto.RegisterType((*Params)(nil), "elys.margin.Params") } @@ -127,47 +135,49 @@ func init() { func init() { proto.RegisterFile("elys/margin/params.proto", fileDescriptor_f427d3667a99d828) } var fileDescriptor_f427d3667a99d828 = []byte{ - // 625 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x95, 0x41, 0x4f, 0x13, 0x41, - 0x14, 0xc7, 0xbb, 0x82, 0x08, 0xd3, 0x22, 0x30, 0x80, 0x4e, 0x34, 0x29, 0x60, 0xd4, 0xd4, 0x08, - 0x6d, 0x8c, 0x07, 0x13, 0x6f, 0x22, 0x60, 0x48, 0x24, 0x94, 0xea, 0xc1, 0x10, 0xe3, 0x64, 0xd8, - 0x7d, 0xbb, 0x3b, 0x61, 0x77, 0x66, 0x99, 0x99, 0x42, 0xfb, 0x25, 0x8c, 0x47, 0xbd, 0xf9, 0x71, - 0x38, 0x72, 0x34, 0x1e, 0x88, 0x81, 0x2f, 0x62, 0x76, 0x76, 0x17, 0x8a, 0x04, 0x4c, 0x56, 0x4f, - 0xed, 0xbe, 0x37, 0xef, 0xf7, 0xff, 0xff, 0x93, 0x99, 0x3c, 0x44, 0x20, 0xea, 0xeb, 0x56, 0xcc, - 0x54, 0xc0, 0x45, 0x2b, 0x61, 0x8a, 0xc5, 0xba, 0x99, 0x28, 0x69, 0x24, 0xae, 0xa6, 0x9d, 0x66, - 0xd6, 0xb9, 0x37, 0x13, 0xc8, 0x40, 0xda, 0x7a, 0x2b, 0xfd, 0x97, 0x1d, 0x79, 0xf0, 0xad, 0x86, - 0x46, 0xda, 0x76, 0x06, 0x6f, 0xa1, 0x5a, 0x04, 0xfb, 0xa0, 0x58, 0x00, 0x34, 0x66, 0x3d, 0xe2, - 0xcc, 0x3b, 0x8d, 0xb1, 0xe5, 0xe6, 0xe1, 0xf1, 0x5c, 0xe5, 0xe7, 0xf1, 0xdc, 0xe3, 0x80, 0x9b, - 0xb0, 0xbb, 0xd3, 0x74, 0x65, 0xdc, 0x72, 0xa5, 0x8e, 0xa5, 0xce, 0x7f, 0x96, 0xb4, 0xb7, 0xdb, - 0x32, 0xfd, 0x04, 0x74, 0x73, 0x05, 0xdc, 0x4e, 0xb5, 0x60, 0x6c, 0xb0, 0x1e, 0xde, 0x46, 0x53, - 0x5c, 0x18, 0x50, 0xa0, 0x0d, 0x55, 0xcc, 0x64, 0xdc, 0x1b, 0xa5, 0xb8, 0x13, 0x05, 0xa8, 0xc3, - 0xcc, 0x15, 0x6c, 0x2e, 0xc8, 0xd0, 0x7f, 0x60, 0x73, 0x81, 0x3d, 0x74, 0xe7, 0x22, 0x9b, 0x0b, - 0x57, 0x01, 0xd3, 0x40, 0x86, 0x4b, 0x09, 0xcc, 0x0c, 0x0a, 0xac, 0xe7, 0xac, 0xcb, 0x2a, 0x1e, - 0xe4, 0x2a, 0x37, 0xff, 0x5d, 0x65, 0x25, 0x67, 0xe1, 0x8f, 0x08, 0x87, 0xc0, 0x22, 0x13, 0xd2, - 0x80, 0x71, 0x41, 0x7d, 0xe6, 0x1a, 0xa9, 0xc8, 0x48, 0x29, 0x85, 0xc9, 0x8c, 0xf4, 0x86, 0x71, - 0xb1, 0x66, 0x39, 0x78, 0x01, 0xd5, 0x20, 0x91, 0x6e, 0x48, 0x23, 0x10, 0x81, 0x09, 0xc9, 0xad, - 0x79, 0xa7, 0x31, 0xd4, 0xa9, 0xda, 0xda, 0x5b, 0x5b, 0xc2, 0x3e, 0xba, 0xab, 0x20, 0x96, 0xfb, - 0x2c, 0xa2, 0x7b, 0x5d, 0xe8, 0x02, 0x35, 0xa1, 0x02, 0x1d, 0xca, 0xc8, 0x23, 0xa3, 0xa5, 0x5c, - 0xcc, 0xe6, 0xb8, 0xad, 0x94, 0xf6, 0xbe, 0x80, 0xe1, 0x45, 0x84, 0x63, 0xd6, 0xa3, 0x32, 0x01, - 0x41, 0x13, 0xa9, 0xb9, 0xe1, 0x52, 0x68, 0x32, 0x66, 0x0d, 0x4d, 0xc6, 0xac, 0xb7, 0x99, 0x80, - 0x68, 0x17, 0x75, 0xfc, 0x09, 0x4d, 0x27, 0x52, 0x46, 0xd9, 0xf1, 0x73, 0x47, 0xa8, 0x94, 0xa3, - 0xa9, 0x14, 0x95, 0xf2, 0xcf, 0xdd, 0xc4, 0xe8, 0xbe, 0x2f, 0x95, 0x0b, 0xd4, 0x8d, 0xa4, 0x06, - 0xea, 0x77, 0x85, 0x47, 0x13, 0x50, 0x2e, 0x08, 0xc3, 0x02, 0x20, 0xd5, 0x52, 0x3a, 0xc4, 0x22, - 0x5f, 0xa7, 0xc4, 0xb5, 0xae, 0xf0, 0xda, 0x67, 0x3c, 0xfc, 0x02, 0x91, 0x4b, 0x72, 0xcc, 0xf3, - 0x14, 0x68, 0x4d, 0x6a, 0xa9, 0x56, 0x67, 0xf6, 0xe2, 0xec, 0xab, 0xac, 0x89, 0x3f, 0x3b, 0x68, - 0xd1, 0xde, 0xee, 0x38, 0x25, 0x45, 0xf4, 0xec, 0x46, 0x26, 0xac, 0x9f, 0x96, 0x2e, 0x39, 0x1f, - 0x2f, 0xe5, 0xbc, 0x31, 0xa0, 0xb1, 0x9e, 0x4b, 0xb4, 0x33, 0x85, 0x3f, 0x92, 0x7c, 0x40, 0x4f, - 0xfe, 0xee, 0xa7, 0x88, 0x76, 0xdb, 0x46, 0x7b, 0x74, 0x3d, 0xbc, 0x88, 0xba, 0x89, 0xaa, 0x7a, - 0x8f, 0xc6, 0xd2, 0xe3, 0x3e, 0x07, 0x45, 0x26, 0x4a, 0x05, 0x41, 0x7a, 0x6f, 0x23, 0x27, 0xe0, - 0x77, 0x68, 0x5c, 0x33, 0x1f, 0x4c, 0xbf, 0x78, 0x55, 0x93, 0xa5, 0x90, 0xb5, 0x0c, 0x92, 0xbf, - 0xa8, 0x4d, 0xf4, 0xf0, 0xda, 0xfc, 0x20, 0xd8, 0x4e, 0x04, 0x1e, 0x99, 0x9a, 0x77, 0x1a, 0xa3, - 0x9d, 0x85, 0xab, 0xa3, 0xaf, 0x66, 0x07, 0xf1, 0x33, 0x34, 0x73, 0x10, 0x72, 0x03, 0x11, 0xd7, - 0x86, 0x8b, 0xe0, 0x0c, 0x80, 0x2d, 0x60, 0x7a, 0xb0, 0x97, 0x8f, 0xbc, 0x1c, 0xfe, 0xfa, 0x7d, - 0xae, 0xb2, 0xbc, 0x7a, 0x78, 0x52, 0x77, 0x8e, 0x4e, 0xea, 0xce, 0xaf, 0x93, 0xba, 0xf3, 0xe5, - 0xb4, 0x5e, 0x39, 0x3a, 0xad, 0x57, 0x7e, 0x9c, 0xd6, 0x2b, 0xdb, 0x4f, 0x07, 0x92, 0xa5, 0x3b, - 0x66, 0x49, 0x80, 0x39, 0x90, 0x6a, 0xd7, 0x7e, 0xb4, 0x7a, 0xc5, 0x32, 0xb2, 0x11, 0x77, 0x46, - 0xec, 0xa6, 0x79, 0xfe, 0x3b, 0x00, 0x00, 0xff, 0xff, 0x81, 0x56, 0x93, 0x14, 0xa8, 0x06, 0x00, - 0x00, + // 658 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x95, 0x5f, 0x4f, 0x13, 0x4b, + 0x18, 0xc6, 0xbb, 0x07, 0x0e, 0x07, 0xa6, 0xe5, 0x00, 0x53, 0xd0, 0x89, 0x26, 0x05, 0x8c, 0x9a, + 0x1a, 0xa1, 0x8d, 0x7a, 0x61, 0xe2, 0x9d, 0xfc, 0x33, 0x24, 0x12, 0x4a, 0xf5, 0xc2, 0x10, 0xe3, + 0x64, 0xd8, 0x7d, 0xbb, 0x3b, 0x61, 0x77, 0x66, 0x99, 0x99, 0x42, 0xfb, 0x25, 0x8c, 0x97, 0x5e, + 0xfa, 0x71, 0xb8, 0x31, 0xe1, 0xd2, 0x78, 0x41, 0x0c, 0x7c, 0x11, 0xb3, 0xb3, 0xbb, 0xa5, 0x48, + 0xc0, 0x64, 0xf5, 0xaa, 0xdd, 0xf7, 0x9d, 0xf9, 0x3d, 0xcf, 0x33, 0x99, 0xc9, 0x8b, 0x08, 0x84, + 0x7d, 0xdd, 0x8c, 0x98, 0xf2, 0xb9, 0x68, 0xc6, 0x4c, 0xb1, 0x48, 0x37, 0x62, 0x25, 0x8d, 0xc4, + 0xe5, 0xa4, 0xd3, 0x48, 0x3b, 0x77, 0x66, 0x7d, 0xe9, 0x4b, 0x5b, 0x6f, 0x26, 0xff, 0xd2, 0x25, + 0xf7, 0xbe, 0x56, 0xd0, 0x58, 0xcb, 0xee, 0xc1, 0x3b, 0xa8, 0x12, 0xc2, 0x21, 0x28, 0xe6, 0x03, + 0x8d, 0x58, 0x8f, 0x38, 0x0b, 0x4e, 0x7d, 0x62, 0xa5, 0x71, 0x7c, 0x3a, 0x5f, 0xfa, 0x7e, 0x3a, + 0xff, 0xd0, 0xe7, 0x26, 0xe8, 0xee, 0x35, 0x5c, 0x19, 0x35, 0x5d, 0xa9, 0x23, 0xa9, 0xb3, 0x9f, + 0x65, 0xed, 0xed, 0x37, 0x4d, 0x3f, 0x06, 0xdd, 0x58, 0x03, 0xb7, 0x5d, 0xce, 0x19, 0x5b, 0xac, + 0x87, 0x77, 0xd1, 0x0c, 0x17, 0x06, 0x14, 0x68, 0x43, 0x15, 0x33, 0x29, 0xf7, 0x9f, 0x42, 0xdc, + 0xa9, 0x1c, 0xd4, 0x66, 0xe6, 0x1a, 0x36, 0x17, 0x64, 0xe4, 0x2f, 0xb0, 0xb9, 0xc0, 0x1e, 0xba, + 0x75, 0x99, 0xcd, 0x85, 0xab, 0x80, 0x69, 0x20, 0xa3, 0x85, 0x04, 0x66, 0x87, 0x05, 0x36, 0x33, + 0xd6, 0x55, 0x15, 0x0f, 0x32, 0x95, 0x7f, 0xff, 0x5c, 0x65, 0x2d, 0x63, 0xe1, 0xf7, 0x08, 0x07, + 0xc0, 0x42, 0x13, 0x50, 0x9f, 0x71, 0x41, 0x3b, 0xcc, 0x35, 0x52, 0x91, 0xb1, 0x42, 0x0a, 0xd3, + 0x29, 0xe9, 0x15, 0xe3, 0x62, 0xc3, 0x72, 0xf0, 0x22, 0xaa, 0x40, 0x2c, 0xdd, 0x80, 0x86, 0x20, + 0x7c, 0x13, 0x90, 0xff, 0x16, 0x9c, 0xfa, 0x48, 0xbb, 0x6c, 0x6b, 0xaf, 0x6d, 0x09, 0x77, 0xd0, + 0x6d, 0x05, 0x91, 0x3c, 0x64, 0x21, 0x3d, 0xe8, 0x42, 0x17, 0xa8, 0x09, 0x14, 0xe8, 0x40, 0x86, + 0x1e, 0x19, 0x2f, 0xe4, 0x62, 0x2e, 0xc3, 0xed, 0x24, 0xb4, 0xb7, 0x39, 0x0c, 0x2f, 0x21, 0x1c, + 0xb1, 0x1e, 0x95, 0x31, 0x08, 0x1a, 0x4b, 0xcd, 0x0d, 0x97, 0x42, 0x93, 0x09, 0x6b, 0x68, 0x3a, + 0x62, 0xbd, 0xed, 0x18, 0x44, 0x2b, 0xaf, 0xe3, 0x0f, 0xa8, 0x1a, 0x4b, 0x19, 0xa6, 0xcb, 0x2f, + 0x1c, 0xa1, 0x42, 0x8e, 0x66, 0x12, 0x54, 0xc2, 0xbf, 0x70, 0x13, 0xa1, 0xbb, 0x1d, 0xa9, 0x5c, + 0xa0, 0x6e, 0x28, 0x35, 0xd0, 0x4e, 0x57, 0x78, 0x34, 0x06, 0xe5, 0x82, 0x30, 0xcc, 0x07, 0x52, + 0x2e, 0xa4, 0x43, 0x2c, 0x72, 0x35, 0x21, 0x6e, 0x74, 0x85, 0xd7, 0x1a, 0xf0, 0xf0, 0x73, 0x44, + 0xae, 0xc8, 0x31, 0xcf, 0x53, 0xa0, 0x35, 0xa9, 0x24, 0x5a, 0xed, 0xb9, 0xcb, 0x7b, 0x5f, 0xa6, + 0x4d, 0xfc, 0xd1, 0x41, 0x4b, 0xf6, 0x76, 0x47, 0x09, 0x29, 0xa4, 0x83, 0x1b, 0x19, 0xb3, 0x7e, + 0x52, 0xba, 0xe2, 0x7c, 0xb2, 0x90, 0xf3, 0xfa, 0x90, 0xc6, 0x66, 0x26, 0xd1, 0x4a, 0x15, 0x7e, + 0x49, 0xf2, 0x0e, 0x3d, 0xfa, 0xbd, 0x9f, 0x3c, 0xda, 0xff, 0x36, 0xda, 0x83, 0x9b, 0xe1, 0x79, + 0xd4, 0x6d, 0x54, 0xd6, 0x07, 0x34, 0x92, 0x1e, 0xef, 0x70, 0x50, 0x64, 0xaa, 0x50, 0x10, 0xa4, + 0x0f, 0xb6, 0x32, 0x02, 0x7e, 0x83, 0x26, 0x35, 0xeb, 0x80, 0xe9, 0xe7, 0xaf, 0x6a, 0xba, 0x10, + 0xb2, 0x92, 0x42, 0xb2, 0x17, 0xb5, 0x8d, 0xee, 0xdf, 0x98, 0x1f, 0x04, 0xdb, 0x0b, 0xc1, 0x23, + 0x33, 0x0b, 0x4e, 0x7d, 0xbc, 0xbd, 0x78, 0x7d, 0xf4, 0xf5, 0x74, 0x21, 0x7e, 0x82, 0x66, 0x8f, + 0x02, 0x6e, 0x20, 0xe4, 0xda, 0x70, 0xe1, 0x0f, 0x00, 0xd8, 0x02, 0xaa, 0xc3, 0xbd, 0x7c, 0xcb, + 0x53, 0x34, 0xc7, 0xc5, 0x21, 0x53, 0x9c, 0x09, 0x43, 0xdd, 0x00, 0xdc, 0x7d, 0x6a, 0x5f, 0x34, + 0xa9, 0xda, 0xf3, 0xae, 0x0e, 0x9a, 0xab, 0x49, 0x6f, 0x3d, 0x69, 0xbd, 0x18, 0xfd, 0xfc, 0x65, + 0xbe, 0xb4, 0xb2, 0x7e, 0x7c, 0x56, 0x73, 0x4e, 0xce, 0x6a, 0xce, 0x8f, 0xb3, 0x9a, 0xf3, 0xe9, + 0xbc, 0x56, 0x3a, 0x39, 0xaf, 0x95, 0xbe, 0x9d, 0xd7, 0x4a, 0xbb, 0x8f, 0x87, 0x4e, 0x23, 0x99, + 0x4b, 0xcb, 0x02, 0xcc, 0x91, 0x54, 0xfb, 0xf6, 0xa3, 0xd9, 0xcb, 0x07, 0x98, 0x3d, 0x96, 0xbd, + 0x31, 0x3b, 0x9d, 0x9e, 0xfd, 0x0c, 0x00, 0x00, 0xff, 0xff, 0x49, 0x67, 0xdf, 0xbd, 0xdc, 0x06, + 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { @@ -190,6 +200,15 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.InvariantCheckEpoch) > 0 { + i -= len(m.InvariantCheckEpoch) + copy(dAtA[i:], m.InvariantCheckEpoch) + i = encodeVarintParams(dAtA, i, uint64(len(m.InvariantCheckEpoch))) + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x9a + } if m.WhitelistingEnabled { i-- if m.WhitelistingEnabled { @@ -424,6 +443,10 @@ func (m *Params) Size() (n int) { if m.WhitelistingEnabled { n += 3 } + l = len(m.InvariantCheckEpoch) + if l > 0 { + n += 2 + l + sovParams(uint64(l)) + } return n } @@ -1012,6 +1035,38 @@ func (m *Params) Unmarshal(dAtA []byte) error { } } m.WhitelistingEnabled = bool(v != 0) + case 19: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InvariantCheckEpoch", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + 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 ErrInvalidLengthParams + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthParams + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.InvariantCheckEpoch = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipParams(dAtA[iNdEx:]) diff --git a/x/margin/types/pool.go b/x/margin/types/pool.go index 44d6f1ede..66e98dd65 100644 --- a/x/margin/types/pool.go +++ b/x/margin/types/pool.go @@ -9,10 +9,10 @@ import ( func NewPool(poolId uint64) Pool { return Pool{ AmmPoolId: poolId, - Health: sdk.ZeroDec(), + Health: sdk.NewDec(100), Enabled: true, Closed: false, - InterestRate: sdk.ZeroDec(), + InterestRate: sdk.NewDecFromIntWithPrec(sdk.NewInt(1), 1), PoolAssets: []PoolAsset{}, } }