diff --git a/.gitignore b/.gitignore index a2a2088c..195c68db 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,4 @@ build/linux # Go workspace files go.work go.work.sum +.build/0gchaind diff --git a/Dockerfile b/Dockerfile index 11d30e41..fa00e240 100644 --- a/Dockerfile +++ b/Dockerfile @@ -7,7 +7,7 @@ FROM golang:1.21-alpine AS build-env RUN apk add bash git make libc-dev gcc linux-headers eudev-dev jq curl # Set working directory for the build -WORKDIR /root/kava +WORKDIR /root/0g-chain # default home directory is /root # Copy dependency files first to facilitate dependency caching @@ -32,6 +32,6 @@ RUN --mount=type=cache,target=/root/.cache/go-build \ FROM alpine:3.15 RUN apk add bash jq curl -COPY --from=build-env /go/bin/kava /bin/kava +COPY --from=build-env /go/bin/0gchaind /bin/0gchaind -CMD ["kava"] +CMD ["0gchaind"] diff --git a/Dockerfile-rocksdb b/Dockerfile-rocksdb index 89d0f3d2..b432486b 100644 --- a/Dockerfile-rocksdb +++ b/Dockerfile-rocksdb @@ -1,4 +1,4 @@ -FROM golang:1.21-bullseye AS kava-builder +FROM golang:1.21-bullseye AS chain-builder # Set up dependencies RUN apt-get update \ @@ -19,7 +19,7 @@ RUN git clone https://github.com/facebook/rocksdb.git \ && make -j$(nproc) install-shared \ && ldconfig -WORKDIR /root/kava +WORKDIR /root/0gchain # Copy dependency files first to facilitate dependency caching COPY ./go.mod ./ COPY ./go.sum ./ @@ -32,13 +32,13 @@ RUN --mount=type=cache,target=/root/.cache/go-build \ # Add source files COPY . . -ARG kava_database_backend=rocksdb -ENV KAVA_DATABASE_BACKEND=$kava_database_backend +ARG 0gchain_database_backend=rocksdb +ENV 0GCHAIN_DATABASE_BACKEND=$0gchain_database_backend # Mount go build and mod caches as container caches, persisted between builder invocations RUN --mount=type=cache,target=/root/.cache/go-build \ --mount=type=cache,target=/go/pkg/mod \ - make install COSMOS_BUILD_OPTIONS=$KAVA_DATABASE_BACKEND + make install COSMOS_BUILD_OPTIONS=$0GCHAIN_DATABASE_BACKEND FROM ubuntu:22.04 @@ -48,10 +48,10 @@ RUN apt-get update \ && rm -rf /var/lib/apt/lists/* # copy rocksdb shared objects -COPY --from=kava-builder /usr/local/lib/ /usr/local/lib/ +COPY --from=chain-builder /usr/local/lib/ /usr/local/lib/ RUN ldconfig -# copy kava binary -COPY --from=kava-builder /go/bin/kava /bin/kava +# copy 0g-chain binary +COPY --from=chain-builder /go/bin/0gchaind /bin/0gchaind -CMD ["kava"] +CMD ["0gchaind"] diff --git a/Makefile b/Makefile index d44d1ea9..0304132c 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,10 @@ ################################################################################ ### Project Info ### ################################################################################ -PROJECT_NAME := kava# unique namespace for project - +PROJECT_NAME := 0g-chain# unique namespace for project +BINARY_NAME := 0gchaind +MAIN_ENTRY := ./cmd/$(BINARY_NAME) +DOCKER_IMAGE_NAME := 0glabs/$(PROJECT_NAME) GO_BIN ?= go GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD) @@ -37,7 +39,7 @@ print-git-info: .PHONY: print-version print-version: - @echo "kava $(VERSION)\ntendermint $(TENDERMINT_VERSION)\ncosmos $(COSMOS_SDK_VERSION)" + @echo "$(BINARY_NAME) $(VERSION)\ntendermint $(TENDERMINT_VERSION)\ncosmos $(COSMOS_SDK_VERSION)" ################################################################################ ### Project Settings ### @@ -45,7 +47,7 @@ print-version: LEDGER_ENABLED ?= true DOCKER:=docker DOCKER_BUF := $(DOCKER) run --rm -v $(CURDIR):/workspace --workdir /workspace bufbuild/buf -HTTPS_GIT := https://github.com/Kava-Labs/kava.git +HTTPS_GIT := https://github.com/0glabs/0g-chain.git ################################################################################ ### Machine Info ### @@ -142,8 +144,8 @@ build_tags_comma_sep := $(subst $(whitespace),$(comma),$(build_tags)) # process linker flags -ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=kava \ - -X github.com/cosmos/cosmos-sdk/version.AppName=kava \ +ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=$(PROJECT_NAME) \ + -X github.com/cosmos/cosmos-sdk/version.AppName=$(PROJECT_NAME) \ -X github.com/cosmos/cosmos-sdk/version.Version=$(VERSION_NUMBER) \ -X github.com/cosmos/cosmos-sdk/version.Commit=$(GIT_COMMIT) \ -X "github.com/cosmos/cosmos-sdk/version.BuildTags=$(build_tags_comma_sep)" \ @@ -188,15 +190,15 @@ all: install build: go.sum ifeq ($(OS), Windows_NT) - $(GO_BIN) build -mod=readonly $(BUILD_FLAGS) -o out/$(shell $(GO_BIN) env GOOS)/kava.exe ./cmd/kava + $(GO_BIN) build -mod=readonly $(BUILD_FLAGS) -o out/$(shell $(GO_BIN) env GOOS)/$(BINARY_NAME).exe $(MAIN_ENTRY) else - $(GO_BIN) build -mod=readonly $(BUILD_FLAGS) -o out/$(shell $(GO_BIN) env GOOS)/kava ./cmd/kava + $(GO_BIN) build -mod=readonly $(BUILD_FLAGS) -o out/$(shell $(GO_BIN) env GOOS)/$(BINARY_NAME) $(MAIN_ENTRY) endif build-linux: go.sum LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build -# build on rocksdb-backed kava on macOS with shared libs from brew +# build on rocksdb-backed 0gchaind on macOS with shared libs from brew # this assumes you are on macOS & these deps have been installed with brew: # rocksdb, snappy, lz4, and zstd # use like `make build-rocksdb-brew COSMOS_BUILD_OPTIONS=rocksdb` @@ -205,7 +207,7 @@ build-rocksdb-brew: export CGO_LDFLAGS := -L$(shell brew --prefix rocksdb)/lib -lrocksdb -lstdc++ -lm -lz -L$(shell brew --prefix snappy)/lib -L$(shell brew --prefix lz4)/lib -L$(shell brew --prefix zstd)/lib install: go.sum - $(GO_BIN) install -mod=readonly $(BUILD_FLAGS) ./cmd/kava + $(GO_BIN) install -mod=readonly $(BUILD_FLAGS) $(MAIN_ENTRY) ######################################## ### Tools & dependencies @@ -227,6 +229,7 @@ go.sum: go.mod # Set to exclude riot links as they trigger false positives link-check: @$(GO_BIN) get -u github.com/raviqqe/liche@f57a5d1c5be4856454cb26de155a65a4fd856ee3 + # TODO: replace kava in following line with project name liche -r . --exclude "^http://127.*|^https://riot.im/app*|^http://kava-testnet*|^https://testnet-dex*|^https://kava3.data.kava.io*|^https://ipfs.io*|^https://apps.apple.com*|^https://kava.quicksync.io*" @@ -241,26 +244,26 @@ format: find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs misspell -w find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs goimports -w -local github.com/tendermint find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs goimports -w -local github.com/cosmos/cosmos-sdk - find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs goimports -w -local github.com/kava-labs/kava + find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -name '*.pb.go' | xargs goimports -w -local github.com/0glabs/0g-chain .PHONY: format ############################################################################### ### Localnet ### ############################################################################### -# Build docker image and tag as kava/kava:local +# Build docker image and tag as 0glabs/0g-chain:local docker-build: - DOCKER_BUILDKIT=1 $(DOCKER) build -t kava/kava:local . + DOCKER_BUILDKIT=1 $(DOCKER) build -t $(DOCKER_IMAGE_NAME):local . docker-build-rocksdb: - DOCKER_BUILDKIT=1 $(DOCKER) build -f Dockerfile-rocksdb -t kava/kava:local . + DOCKER_BUILDKIT=1 $(DOCKER) build -f Dockerfile-rocksdb -t $(DOCKER_IMAGE_NAME):local . -build-docker-local-kava: +build-docker-local-0gchain: @$(MAKE) -C networks/local # Run a 4-node testnet locally localnet-start: build-linux localnet-stop - @if ! [ -f build/node0/kvd/config/genesis.json ]; then docker run --rm -v $(CURDIR)/build:/kvd:Z kava/kavanode testnet --v 4 -o . --starting-ip-address 192.168.10.2 --keyring-backend=test ; fi + @if ! [ -f build/node0/kvd/config/genesis.json ]; then docker run --rm -v $(CURDIR)/build:/kvd:Z $(DOCKER_IMAGE_NAME)-node testnet --v 4 -o . --starting-ip-address 192.168.10.2 --keyring-backend=test ; fi docker-compose up -d localnet-stop: @@ -269,7 +272,7 @@ localnet-stop: # Launch a new single validator chain start: ./contrib/devnet/init-new-chain.sh - kava start + $(BINARY_NAME) start #proto-format: #@echo "Formatting Protobuf files" @@ -310,7 +313,7 @@ test: @$(GO_BIN) test $$($(GO_BIN) list ./... | grep -v 'contrib' | grep -v 'tests/e2e') test-rocksdb: - @go test -tags=rocksdb ./cmd/kava/opendb + @go test -tags=rocksdb $(MAIN_ENTRY)/opendb # Run cli integration tests # `-p 4` to use 4 cores, `-tags cli_test` to tell $(GO_BIN) not to ignore the cli package @@ -326,15 +329,15 @@ test-migrate: # This submits an AWS Batch job to run a lot of sims, each within a docker image. Results are uploaded to S3 start-remote-sims: # build the image used for running sims in, and tag it - docker build -f simulations/Dockerfile -t kava/kava-sim:master . + docker build -f simulations/Dockerfile -t $(DOCKER_IMAGE_NAME)-sim:master . # push that image to the hub - docker push kava/kava-sim:master + docker push $(DOCKER_IMAGE_NAME)-sim:master # submit an array job on AWS Batch, using 1000 seeds, spot instances aws batch submit-job \ -—job-name "master-$(VERSION)" \ -—job-queue “simulation-1-queue-spot" \ -—array-properties size=1000 \ - -—job-definition kava-sim-master \ + -—job-definition $(BINARY_NAME)-sim-master \ -—container-override environment=[{SIM_NAME=master-$(VERSION)}] update-kvtool: diff --git a/app/_sim_test.go b/app/_sim_test.go index 0b75637f..feb8dff4 100644 --- a/app/_sim_test.go +++ b/app/_sim_test.go @@ -32,15 +32,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/supply" - "github.com/kava-labs/kava/x/auction" - "github.com/kava-labs/kava/x/bep3" - "github.com/kava-labs/kava/x/cdp" - "github.com/kava-labs/kava/x/committee" - "github.com/kava-labs/kava/x/incentive" - "github.com/kava-labs/kava/x/kavadist" - "github.com/kava-labs/kava/x/pricefeed" - "github.com/kava-labs/kava/x/swap" - validatorvesting "github.com/kava-labs/kava/x/validator-vesting" + validatorvesting "github.com/0glabs/0g-chain/x/validator-vesting" ) type StoreKeysPrefixes struct { diff --git a/app/_simulate_tx_test.go b/app/_simulate_tx_test.go index a6136020..5bf63ed9 100644 --- a/app/_simulate_tx_test.go +++ b/app/_simulate_tx_test.go @@ -9,7 +9,8 @@ import ( "testing" sdkmath "cosmossdk.io/math" - "github.com/kava-labs/kava/app" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/chaincfg" abci "github.com/cometbft/cometbft/abci/types" tmbytes "github.com/cometbft/cometbft/libs/bytes" @@ -52,9 +53,9 @@ func (suite *SimulateRequestTestSuite) TearDownTest() { } func (suite *SimulateRequestTestSuite) TestSimulateRequest() { - fromAddr, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") + fromAddr, err := sdk.AccAddressFromBech32("0g1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") suite.Require().NoError(err) - toAddr, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") + toAddr, err := sdk.AccAddressFromBech32("0g1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") suite.Require().NoError(err) simRequest := app.SimulateRequest{ @@ -62,11 +63,11 @@ func (suite *SimulateRequestTestSuite) TestSimulateRequest() { bank.MsgSend{ FromAddress: fromAddr, ToAddress: toAddr, - Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), + Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))), }, }, Fee: auth.StdFee{ - Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(5e4))), + Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(5e4))), Gas: 1e6, }, Memo: "test memo", diff --git a/app/ante/ante_test.go b/app/ante/ante_test.go index fd4af13f..20436a2b 100644 --- a/app/ante/ante_test.go +++ b/app/ante/ante_test.go @@ -6,12 +6,10 @@ import ( "testing" "time" - sdkmath "cosmossdk.io/math" tmdb "github.com/cometbft/cometbft-db" abci "github.com/cometbft/cometbft/abci/types" "github.com/cometbft/cometbft/libs/log" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" @@ -22,13 +20,14 @@ import ( evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/stretchr/testify/require" - "github.com/kava-labs/kava/app" - bep3types "github.com/kava-labs/kava/x/bep3/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/chaincfg" + // bep3types "github.com/0glabs/0g-chain/x/bep3/types" + // pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" ) func TestMain(m *testing.M) { - app.SetSDKConfig() + chaincfg.SetSDKConfig() os.Exit(m.Run()) } @@ -36,10 +35,10 @@ func TestAppAnteHandler_AuthorizedMempool(t *testing.T) { testPrivKeys, testAddresses := app.GeneratePrivKeyAddressPairs(10) unauthed := testAddresses[0:2] unauthedKeys := testPrivKeys[0:2] - deputy := testAddresses[2] - deputyKey := testPrivKeys[2] - oracles := testAddresses[3:6] - oraclesKeys := testPrivKeys[3:6] + // deputy := testAddresses[2] + // deputyKey := testPrivKeys[2] + // oracles := testAddresses[3:6] + // oraclesKeys := testPrivKeys[3:6] manual := testAddresses[6:] manualKeys := testPrivKeys[6:] @@ -53,7 +52,7 @@ func TestAppAnteHandler_AuthorizedMempool(t *testing.T) { App: *app.NewApp( log.NewNopLogger(), tmdb.NewMemDB(), - app.DefaultNodeHome, + chaincfg.DefaultNodeHome, nil, encodingConfig, opts, @@ -67,11 +66,11 @@ func TestAppAnteHandler_AuthorizedMempool(t *testing.T) { chainID, app.NewFundedGenStateWithSameCoins( tApp.AppCodec(), - sdk.NewCoins(sdk.NewInt64Coin("ukava", 1e9)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 1e9)), testAddresses, ), - newBep3GenStateMulti(tApp.AppCodec(), deputy), - newPricefeedGenStateMulti(tApp.AppCodec(), oracles), + // newBep3GenStateMulti(tApp.AppCodec(), deputy), + // newPricefeedGenStateMulti(tApp.AppCodec(), oracles), ) testcases := []struct { @@ -86,18 +85,18 @@ func TestAppAnteHandler_AuthorizedMempool(t *testing.T) { privKey: unauthedKeys[1], expectPass: false, }, - { - name: "oracle", - address: oracles[1], - privKey: oraclesKeys[1], - expectPass: true, - }, - { - name: "deputy", - address: deputy, - privKey: deputyKey, - expectPass: true, - }, + // { + // name: "oracle", + // address: oracles[1], + // privKey: oraclesKeys[1], + // expectPass: true, + // }, + // { + // name: "deputy", + // address: deputy, + // privKey: deputyKey, + // expectPass: true, + // }, { name: "manual", address: manual[1], @@ -115,7 +114,7 @@ func TestAppAnteHandler_AuthorizedMempool(t *testing.T) { banktypes.NewMsgSend( tc.address, testAddresses[0], - sdk.NewCoins(sdk.NewInt64Coin("ukava", 1_000_000)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 1_000_000)), ), }, sdk.NewCoins(), // no fee @@ -145,53 +144,53 @@ func TestAppAnteHandler_AuthorizedMempool(t *testing.T) { } } -func newPricefeedGenStateMulti(cdc codec.JSONCodec, oracles []sdk.AccAddress) app.GenesisState { - pfGenesis := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "btc:usd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: oracles, Active: true}, - }, - }, - } - return app.GenesisState{pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pfGenesis)} -} +// func newPricefeedGenStateMulti(cdc codec.JSONCodec, oracles []sdk.AccAddress) app.GenesisState { +// pfGenesis := pricefeedtypes.GenesisState{ +// Params: pricefeedtypes.Params{ +// Markets: []pricefeedtypes.Market{ +// {MarketID: "btc:usd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: oracles, Active: true}, +// }, +// }, +// } +// return app.GenesisState{pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pfGenesis)} +// } -func newBep3GenStateMulti(cdc codec.JSONCodec, deputyAddress sdk.AccAddress) app.GenesisState { - bep3Genesis := bep3types.GenesisState{ - Params: bep3types.Params{ - AssetParams: bep3types.AssetParams{ - bep3types.AssetParam{ - Denom: "bnb", - CoinID: 714, - SupplyLimit: bep3types.SupplyLimit{ - Limit: sdkmath.NewInt(350000000000000), - TimeLimited: false, - TimeBasedLimit: sdk.ZeroInt(), - TimePeriod: time.Hour, - }, - Active: true, - DeputyAddress: deputyAddress, - FixedFee: sdkmath.NewInt(1000), - MinSwapAmount: sdk.OneInt(), - MaxSwapAmount: sdkmath.NewInt(1000000000000), - MinBlockLock: bep3types.DefaultMinBlockLock, - MaxBlockLock: bep3types.DefaultMaxBlockLock, - }, - }, - }, - Supplies: bep3types.AssetSupplies{ - bep3types.NewAssetSupply( - sdk.NewCoin("bnb", sdk.ZeroInt()), - sdk.NewCoin("bnb", sdk.ZeroInt()), - sdk.NewCoin("bnb", sdk.ZeroInt()), - sdk.NewCoin("bnb", sdk.ZeroInt()), - time.Duration(0), - ), - }, - PreviousBlockTime: bep3types.DefaultPreviousBlockTime, - } - return app.GenesisState{bep3types.ModuleName: cdc.MustMarshalJSON(&bep3Genesis)} -} +// func newBep3GenStateMulti(cdc codec.JSONCodec, deputyAddress sdk.AccAddress) app.GenesisState { +// bep3Genesis := bep3types.GenesisState{ +// Params: bep3types.Params{ +// AssetParams: bep3types.AssetParams{ +// bep3types.AssetParam{ +// Denom: "bnb", +// CoinID: 714, +// SupplyLimit: bep3types.SupplyLimit{ +// Limit: sdkmath.NewInt(350000000000000), +// TimeLimited: false, +// TimeBasedLimit: sdk.ZeroInt(), +// TimePeriod: time.Hour, +// }, +// Active: true, +// DeputyAddress: deputyAddress, +// FixedFee: sdkmath.NewInt(1000), +// MinSwapAmount: sdk.OneInt(), +// MaxSwapAmount: sdkmath.NewInt(1000000000000), +// MinBlockLock: bep3types.DefaultMinBlockLock, +// MaxBlockLock: bep3types.DefaultMaxBlockLock, +// }, +// }, +// }, +// Supplies: bep3types.AssetSupplies{ +// bep3types.NewAssetSupply( +// sdk.NewCoin("bnb", sdk.ZeroInt()), +// sdk.NewCoin("bnb", sdk.ZeroInt()), +// sdk.NewCoin("bnb", sdk.ZeroInt()), +// sdk.NewCoin("bnb", sdk.ZeroInt()), +// time.Duration(0), +// ), +// }, +// PreviousBlockTime: bep3types.DefaultPreviousBlockTime, +// } +// return app.GenesisState{bep3types.ModuleName: cdc.MustMarshalJSON(&bep3Genesis)} +// } func TestAppAnteHandler_RejectMsgsInAuthz(t *testing.T) { testPrivKeys, testAddresses := app.GeneratePrivKeyAddressPairs(10) diff --git a/app/ante/authorized_test.go b/app/ante/authorized_test.go index 2cca0a75..41c44cb4 100644 --- a/app/ante/authorized_test.go +++ b/app/ante/authorized_test.go @@ -10,8 +10,9 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/stretchr/testify/require" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/app/ante" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/app/ante" + "github.com/0glabs/0g-chain/chaincfg" ) var _ sdk.AnteHandler = (&MockAnteHandler{}).AnteHandle @@ -45,7 +46,7 @@ func TestAuthenticatedMempoolDecorator_AnteHandle_NotCheckTx(t *testing.T) { banktypes.NewMsgSend( testAddresses[0], testAddresses[1], - sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_000_000)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 100_000_000)), ), }, sdk.NewCoins(), // no fee @@ -80,12 +81,12 @@ func TestAuthenticatedMempoolDecorator_AnteHandle_Pass(t *testing.T) { banktypes.NewMsgSend( testAddresses[0], testAddresses[1], - sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_000_000)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 100_000_000)), ), banktypes.NewMsgSend( testAddresses[2], testAddresses[1], - sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_000_000)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 100_000_000)), ), }, sdk.NewCoins(), // no fee @@ -121,7 +122,7 @@ func TestAuthenticatedMempoolDecorator_AnteHandle_Reject(t *testing.T) { banktypes.NewMsgSend( testAddresses[0], testAddresses[1], - sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_000_000)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 100_000_000)), ), }, sdk.NewCoins(), // no fee diff --git a/app/ante/authz_test.go b/app/ante/authz_test.go index 452da4d2..b1f890e6 100644 --- a/app/ante/authz_test.go +++ b/app/ante/authz_test.go @@ -14,8 +14,9 @@ import ( evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/stretchr/testify/require" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/app/ante" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/app/ante" + "github.com/0glabs/0g-chain/chaincfg" ) func newMsgGrant(granter sdk.AccAddress, grantee sdk.AccAddress, a authz.Authorization, expiration time.Time) *authz.MsgGrant { @@ -58,7 +59,7 @@ func TestAuthzLimiterDecorator(t *testing.T) { banktypes.NewMsgSend( testAddresses[0], testAddresses[1], - sdk.NewCoins(sdk.NewInt64Coin("ukava", 100e6)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 100e6)), ), }, checkTx: false, @@ -128,7 +129,7 @@ func TestAuthzLimiterDecorator(t *testing.T) { []sdk.Msg{banktypes.NewMsgSend( testAddresses[0], testAddresses[3], - sdk.NewCoins(sdk.NewInt64Coin("ukava", 100e6)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 100e6)), )}), }, checkTx: false, @@ -161,7 +162,7 @@ func TestAuthzLimiterDecorator(t *testing.T) { banktypes.NewMsgSend( testAddresses[0], testAddresses[3], - sdk.NewCoins(sdk.NewInt64Coin("ukava", 100e6)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 100e6)), ), &evmtypes.MsgEthereumTx{}, }, diff --git a/app/ante/eip712_test.go b/app/ante/eip712_test.go index 91504d69..6c346d43 100644 --- a/app/ante/eip712_test.go +++ b/app/ante/eip712_test.go @@ -33,13 +33,15 @@ import ( feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" "github.com/stretchr/testify/suite" - "github.com/kava-labs/kava/app" - cdptypes "github.com/kava-labs/kava/x/cdp/types" - evmutilkeeper "github.com/kava-labs/kava/x/evmutil/keeper" - evmutiltestutil "github.com/kava-labs/kava/x/evmutil/testutil" - evmutiltypes "github.com/kava-labs/kava/x/evmutil/types" - hardtypes "github.com/kava-labs/kava/x/hard/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/chaincfg" + + // cdptypes "github.com/0glabs/0g-chain/x/cdp/types" + evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper" + evmutiltestutil "github.com/0glabs/0g-chain/x/evmutil/testutil" + evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types" + // hardtypes "github.com/0glabs/0g-chain/x/hard/types" + // pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" ) const ( @@ -158,7 +160,7 @@ func (suite *EIP712TestSuite) SetupTest() { // Genesis states evmGs := evmtypes.NewGenesisState( evmtypes.NewParams( - "akava", // evmDenom + chaincfg.BaseDenom, // evmDenom false, // allowedUnprotectedTxs true, // enableCreate true, // enableCall @@ -173,104 +175,104 @@ func (suite *EIP712TestSuite) SetupTest() { feemarketGenesis.Params.EnableHeight = 1 feemarketGenesis.Params.NoBaseFee = false - cdpGenState := cdptypes.DefaultGenesisState() - cdpGenState.Params.GlobalDebtLimit = sdk.NewInt64Coin("usdx", 53000000000000) - cdpGenState.Params.CollateralParams = cdptypes.CollateralParams{ - { - Denom: USDCCoinDenom, - Type: USDCCDPType, - LiquidationRatio: sdk.MustNewDecFromStr("1.01"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.OneDec(), - AuctionSize: sdkmath.NewIntFromUint64(10000000000), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - SpotMarketID: "usdc:usd", - LiquidationMarketID: "usdc:usd:30", - ConversionFactor: sdkmath.NewInt(18), - }, - } + // cdpGenState := cdptypes.DefaultGenesisState() + // cdpGenState.Params.GlobalDebtLimit = sdk.NewInt64Coin("usdx", 53000000000000) + // cdpGenState.Params.CollateralParams = cdptypes.CollateralParams{ + // { + // Denom: USDCCoinDenom, + // Type: USDCCDPType, + // LiquidationRatio: sdk.MustNewDecFromStr("1.01"), + // DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), + // StabilityFee: sdk.OneDec(), + // AuctionSize: sdkmath.NewIntFromUint64(10000000000), + // LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), + // CheckCollateralizationIndexCount: sdkmath.NewInt(10), + // KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), + // SpotMarketID: "usdc:usd", + // LiquidationMarketID: "usdc:usd:30", + // ConversionFactor: sdkmath.NewInt(18), + // }, + // } - hardGenState := hardtypes.DefaultGenesisState() - hardGenState.Params.MoneyMarkets = []hardtypes.MoneyMarket{ - { - Denom: "usdx", - BorrowLimit: hardtypes.BorrowLimit{ - HasMaxLimit: true, - MaximumLimit: sdk.MustNewDecFromStr("100000000000"), - LoanToValue: sdk.MustNewDecFromStr("1"), - }, - SpotMarketID: "usdx:usd", - ConversionFactor: sdkmath.NewInt(1_000_000), - InterestRateModel: hardtypes.InterestRateModel{ - BaseRateAPY: sdk.MustNewDecFromStr("0.05"), - BaseMultiplier: sdk.MustNewDecFromStr("2"), - Kink: sdk.MustNewDecFromStr("0.8"), - JumpMultiplier: sdk.MustNewDecFromStr("10"), - }, - ReserveFactor: sdk.MustNewDecFromStr("0.05"), - KeeperRewardPercentage: sdk.ZeroDec(), - }, - } + // hardGenState := hardtypes.DefaultGenesisState() + // hardGenState.Params.MoneyMarkets = []hardtypes.MoneyMarket{ + // { + // Denom: "usdx", + // BorrowLimit: hardtypes.BorrowLimit{ + // HasMaxLimit: true, + // MaximumLimit: sdk.MustNewDecFromStr("100000000000"), + // LoanToValue: sdk.MustNewDecFromStr("1"), + // }, + // SpotMarketID: "usdx:usd", + // ConversionFactor: sdkmath.NewInt(1_000_000), + // InterestRateModel: hardtypes.InterestRateModel{ + // BaseRateAPY: sdk.MustNewDecFromStr("0.05"), + // BaseMultiplier: sdk.MustNewDecFromStr("2"), + // Kink: sdk.MustNewDecFromStr("0.8"), + // JumpMultiplier: sdk.MustNewDecFromStr("10"), + // }, + // ReserveFactor: sdk.MustNewDecFromStr("0.05"), + // KeeperRewardPercentage: sdk.ZeroDec(), + // }, + // } - pricefeedGenState := pricefeedtypes.DefaultGenesisState() - pricefeedGenState.Params.Markets = []pricefeedtypes.Market{ - { - MarketID: "usdx:usd", - BaseAsset: "usdx", - QuoteAsset: "usd", - Oracles: []sdk.AccAddress{}, - Active: true, - }, - { - MarketID: "usdc:usd", - BaseAsset: "usdc", - QuoteAsset: "usd", - Oracles: []sdk.AccAddress{}, - Active: true, - }, - { - MarketID: "usdc:usd:30", - BaseAsset: "usdc", - QuoteAsset: "usd", - Oracles: []sdk.AccAddress{}, - Active: true, - }, - } - pricefeedGenState.PostedPrices = []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "usdc:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "usdc:usd:30", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - } + // pricefeedGenState := pricefeedtypes.DefaultGenesisState() + // pricefeedGenState.Params.Markets = []pricefeedtypes.Market{ + // { + // MarketID: "usdx:usd", + // BaseAsset: "usdx", + // QuoteAsset: "usd", + // Oracles: []sdk.AccAddress{}, + // Active: true, + // }, + // { + // MarketID: "usdc:usd", + // BaseAsset: "usdc", + // QuoteAsset: "usd", + // Oracles: []sdk.AccAddress{}, + // Active: true, + // }, + // { + // MarketID: "usdc:usd:30", + // BaseAsset: "usdc", + // QuoteAsset: "usd", + // Oracles: []sdk.AccAddress{}, + // Active: true, + // }, + // } + // pricefeedGenState.PostedPrices = []pricefeedtypes.PostedPrice{ + // { + // MarketID: "usdx:usd", + // OracleAddress: sdk.AccAddress{}, + // Price: sdk.MustNewDecFromStr("1.00"), + // Expiry: time.Now().Add(1 * time.Hour), + // }, + // { + // MarketID: "usdc:usd", + // OracleAddress: sdk.AccAddress{}, + // Price: sdk.MustNewDecFromStr("1.00"), + // Expiry: time.Now().Add(1 * time.Hour), + // }, + // { + // MarketID: "usdc:usd:30", + // OracleAddress: sdk.AccAddress{}, + // Price: sdk.MustNewDecFromStr("1.00"), + // Expiry: time.Now().Add(1 * time.Hour), + // }, + // } genState := app.GenesisState{ evmtypes.ModuleName: cdc.MustMarshalJSON(evmGs), feemarkettypes.ModuleName: cdc.MustMarshalJSON(feemarketGenesis), - cdptypes.ModuleName: cdc.MustMarshalJSON(&cdpGenState), - hardtypes.ModuleName: cdc.MustMarshalJSON(&hardGenState), - pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pricefeedGenState), + // cdptypes.ModuleName: cdc.MustMarshalJSON(&cdpGenState), + // hardtypes.ModuleName: cdc.MustMarshalJSON(&hardGenState), + // pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pricefeedGenState), } - // funds our test accounts with some ukava + // funds our test accounts with some a0gi coinsGenState := app.NewFundedGenStateWithSameCoins( tApp.AppCodec(), - sdk.NewCoins(sdk.NewInt64Coin("ukava", 1e9)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 1e9)), []sdk.AccAddress{suite.testAddr, suite.testAddr2}, ) @@ -357,45 +359,17 @@ func (suite *EIP712TestSuite) SetupTest() { params := evmKeeper.GetParams(suite.ctx) params.EIP712AllowedMsgs = []evmtypes.EIP712AllowedMsg{ { - MsgTypeUrl: "/kava.evmutil.v1beta1.MsgConvertERC20ToCoin", + MsgTypeUrl: "/0g-chain.evmutil.v1beta1.MsgConvertERC20ToCoin", MsgValueTypeName: "MsgValueEVMConvertERC20ToCoin", ValueTypes: []evmtypes.EIP712MsgAttrType{ {Name: "initiator", Type: "string"}, {Name: "receiver", Type: "string"}, - {Name: "kava_erc20_address", Type: "string"}, + {Name: "0gchain_erc20_address", Type: "string"}, {Name: "amount", Type: "string"}, }, }, { - MsgTypeUrl: "/kava.cdp.v1beta1.MsgCreateCDP", - MsgValueTypeName: "MsgValueCDPCreate", - ValueTypes: []evmtypes.EIP712MsgAttrType{ - {Name: "sender", Type: "string"}, - {Name: "collateral", Type: "Coin"}, - {Name: "principal", Type: "Coin"}, - {Name: "collateral_type", Type: "string"}, - }, - }, - { - MsgTypeUrl: "/kava.cdp.v1beta1.MsgDeposit", - MsgValueTypeName: "MsgValueCDPDeposit", - ValueTypes: []evmtypes.EIP712MsgAttrType{ - {Name: "depositor", Type: "string"}, - {Name: "owner", Type: "string"}, - {Name: "collateral", Type: "Coin"}, - {Name: "collateral_type", Type: "string"}, - }, - }, - { - MsgTypeUrl: "/kava.hard.v1beta1.MsgDeposit", - MsgValueTypeName: "MsgValueHardDeposit", - ValueTypes: []evmtypes.EIP712MsgAttrType{ - {Name: "depositor", Type: "string"}, - {Name: "amount", Type: "Coin[]"}, - }, - }, - { - MsgTypeUrl: "/kava.evmutil.v1beta1.MsgConvertCoinToERC20", + MsgTypeUrl: "/0g-chain.evmutil.v1beta1.MsgConvertCoinToERC20", MsgValueTypeName: "MsgValueEVMConvertCoinToERC20", ValueTypes: []evmtypes.EIP712MsgAttrType{ {Name: "initiator", Type: "string"}, @@ -403,23 +377,6 @@ func (suite *EIP712TestSuite) SetupTest() { {Name: "amount", Type: "Coin"}, }, }, - { - MsgTypeUrl: "/kava.cdp.v1beta1.MsgRepayDebt", - MsgValueTypeName: "MsgValueCDPRepayDebt", - ValueTypes: []evmtypes.EIP712MsgAttrType{ - {Name: "sender", Type: "string"}, - {Name: "collateral_type", Type: "string"}, - {Name: "payment", Type: "Coin"}, - }, - }, - { - MsgTypeUrl: "/kava.hard.v1beta1.MsgWithdraw", - MsgValueTypeName: "MsgValueHardWithdraw", - ValueTypes: []evmtypes.EIP712MsgAttrType{ - {Name: "depositor", Type: "string"}, - {Name: "amount", Type: "Coin[]"}, - }, - }, } evmKeeper.SetParams(suite.ctx, params) @@ -465,7 +422,7 @@ func (suite *EIP712TestSuite) deployUSDCERC20(app app.TestApp, ctx sdk.Context) suite.tApp.FundModuleAccount( suite.ctx, evmutiltypes.ModuleName, - sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(0))), + sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(0))), ) contractAddr, err := suite.evmutilKeeper.DeployTestMintableERC20Contract(suite.ctx, "USDC", "USDC", uint8(18)) @@ -487,40 +444,43 @@ func (suite *EIP712TestSuite) TestEIP712Tx() { failCheckTx bool errMsg string }{ - { - name: "processes deposit eip712 messages successfully", - usdcDepositAmt: 100, - usdxToMintAmt: 99, - }, + // TODO: need fix + // { + // name: "processes deposit eip712 messages successfully", + // usdcDepositAmt: 100, + // usdxToMintAmt: 99, + // }, { name: "fails when convertion more erc20 usdc than balance", usdcDepositAmt: 51_000, usdxToMintAmt: 100, errMsg: "transfer amount exceeds balance", }, - { - name: "fails when minting more usdx than allowed", - usdcDepositAmt: 100, - usdxToMintAmt: 100, - errMsg: "proposed collateral ratio is below liquidation ratio", - }, - { - name: "fails when trying to convert usdc for another address", - usdcDepositAmt: 100, - usdxToMintAmt: 90, - errMsg: "unauthorized", - failCheckTx: true, - updateMsgs: func(msgs []sdk.Msg) []sdk.Msg { - convertMsg := evmutiltypes.NewMsgConvertERC20ToCoin( - suite.testEVMAddr2, - suite.testAddr, - suite.usdcEVMAddr, - suite.getEVMAmount(100), - ) - msgs[0] = &convertMsg - return msgs - }, - }, + // TODO: need fix + // { + // name: "fails when minting more usdx than allowed", + // usdcDepositAmt: 100, + // usdxToMintAmt: 100, + // errMsg: "proposed collateral ratio is below liquidation ratio", + // }, + // TODO: need fix + // { + // name: "fails when trying to convert usdc for another address", + // usdcDepositAmt: 100, + // usdxToMintAmt: 90, + // errMsg: "unauthorized", + // failCheckTx: true, + // updateMsgs: func(msgs []sdk.Msg) []sdk.Msg { + // convertMsg := evmutiltypes.NewMsgConvertERC20ToCoin( + // suite.testEVMAddr2, + // suite.testAddr, + // suite.usdcEVMAddr, + // suite.getEVMAmount(100), + // ) + // msgs[0] = &convertMsg + // return msgs + // }, + // }, { name: "fails when trying to convert erc20 for non-whitelisted contract", usdcDepositAmt: 100, @@ -562,7 +522,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx() { errMsg: "insufficient funds", updateTx: func(txBuilder client.TxBuilder, msgs []sdk.Msg) client.TxBuilder { bk := suite.tApp.GetBankKeeper() - gasCoins := bk.GetBalance(suite.ctx, suite.testAddr, "ukava") + gasCoins := bk.GetBalance(suite.ctx, suite.testAddr, chaincfg.DisplayDenom) suite.tApp.GetBankKeeper().SendCoins(suite.ctx, suite.testAddr, suite.testAddr2, sdk.NewCoins(gasCoins)) return txBuilder }, @@ -574,9 +534,9 @@ func (suite *EIP712TestSuite) TestEIP712Tx() { failCheckTx: true, errMsg: "invalid chain-id", updateTx: func(txBuilder client.TxBuilder, msgs []sdk.Msg) client.TxBuilder { - gasAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20))) + gasAmt := sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(20))) return suite.createTestEIP712CosmosTxBuilder( - suite.testAddr, suite.testPrivKey, "kavatest_12-1", uint64(sims.DefaultGenTxGas*10), gasAmt, msgs, + suite.testAddr, suite.testPrivKey, "0gchaintest_12-1", uint64(sims.DefaultGenTxGas*10), gasAmt, msgs, ) }, }, @@ -587,7 +547,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx() { failCheckTx: true, errMsg: "invalid pubkey", updateTx: func(txBuilder client.TxBuilder, msgs []sdk.Msg) client.TxBuilder { - gasAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20))) + gasAmt := sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(20))) return suite.createTestEIP712CosmosTxBuilder( suite.testAddr2, suite.testPrivKey2, ChainID, uint64(sims.DefaultGenTxGas*10), gasAmt, msgs, ) @@ -607,27 +567,27 @@ func (suite *EIP712TestSuite) TestEIP712Tx() { suite.usdcEVMAddr, usdcAmt, ) - usdxAmt := sdkmath.NewInt(1_000_000).Mul(sdkmath.NewInt(tc.usdxToMintAmt)) - mintMsg := cdptypes.NewMsgCreateCDP( - suite.testAddr, - sdk.NewCoin(USDCCoinDenom, usdcAmt), - sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt), - USDCCDPType, - ) - lendMsg := hardtypes.NewMsgDeposit( - suite.testAddr, - sdk.NewCoins(sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt)), - ) + // usdxAmt := sdkmath.NewInt(1_000_000).Mul(sdkmath.NewInt(tc.usdxToMintAmt)) + // mintMsg := cdptypes.NewMsgCreateCDP( + // suite.testAddr, + // sdk.NewCoin(USDCCoinDenom, usdcAmt), + // sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt), + // USDCCDPType, + // ) + // lendMsg := hardtypes.NewMsgDeposit( + // suite.testAddr, + // sdk.NewCoins(sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt)), + // ) msgs := []sdk.Msg{ &convertMsg, - &mintMsg, - &lendMsg, + // &mintMsg, + // &lendMsg, } if tc.updateMsgs != nil { msgs = tc.updateMsgs(msgs) } - gasAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20))) + gasAmt := sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(20))) txBuilder := suite.createTestEIP712CosmosTxBuilder( suite.testAddr, suite.testPrivKey, ChainID, uint64(sims.DefaultGenTxGas*10), gasAmt, msgs, ) @@ -665,17 +625,17 @@ func (suite *EIP712TestSuite) TestEIP712Tx() { suite.Require().Equal(sdk.ZeroInt(), amt.Amount) // validate cdp - cdp, found := suite.tApp.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.ctx, suite.testAddr, USDCCDPType) - suite.Require().True(found) - suite.Require().Equal(suite.testAddr, cdp.Owner) - suite.Require().Equal(sdk.NewCoin(USDCCoinDenom, suite.getEVMAmount(100)), cdp.Collateral) - suite.Require().Equal(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000)), cdp.Principal) + // cdp, found := suite.tApp.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.ctx, suite.testAddr, USDCCDPType) + // suite.Require().True(found) + // suite.Require().Equal(suite.testAddr, cdp.Owner) + // suite.Require().Equal(sdk.NewCoin(USDCCoinDenom, suite.getEVMAmount(100)), cdp.Collateral) + // suite.Require().Equal(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000)), cdp.Principal) - // validate hard - hardDeposit, found := suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr) - suite.Require().True(found) - suite.Require().Equal(suite.testAddr, hardDeposit.Depositor) - suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000))), hardDeposit.Amount) + // // validate hard + // hardDeposit, found := suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr) + // suite.Require().True(found) + // suite.Require().Equal(suite.testAddr, hardDeposit.Depositor) + // suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000))), hardDeposit.Amount) } else { suite.Require().NotEqual(resDeliverTx.Code, uint32(0), resCheckTx.Log) suite.Require().Contains(resDeliverTx.Log, tc.errMsg) @@ -695,25 +655,25 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() { suite.usdcEVMAddr, usdcAmt, ) - usdxAmt := sdkmath.NewInt(1_000_000).Mul(sdkmath.NewInt(99)) - mintMsg := cdptypes.NewMsgCreateCDP( - suite.testAddr, - sdk.NewCoin(USDCCoinDenom, usdcAmt), - sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt), - USDCCDPType, - ) - lendMsg := hardtypes.NewMsgDeposit( - suite.testAddr, - sdk.NewCoins(sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt)), - ) + // usdxAmt := sdkmath.NewInt(1_000_000).Mul(sdkmath.NewInt(99)) + // mintMsg := cdptypes.NewMsgCreateCDP( + // suite.testAddr, + // sdk.NewCoin(USDCCoinDenom, usdcAmt), + // sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt), + // USDCCDPType, + // ) + // lendMsg := hardtypes.NewMsgDeposit( + // suite.testAddr, + // sdk.NewCoins(sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt)), + // ) depositMsgs := []sdk.Msg{ &convertMsg, - &mintMsg, - &lendMsg, + // &mintMsg, + // &lendMsg, } // deliver deposit msg - gasAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20))) + gasAmt := sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(20))) txBuilder := suite.createTestEIP712CosmosTxBuilder( suite.testAddr, suite.testPrivKey, ChainID, uint64(sims.DefaultGenTxGas*10), gasAmt, depositMsgs, ) @@ -726,11 +686,11 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() { ) suite.Require().Equal(resDeliverTx.Code, uint32(0), resDeliverTx.Log) - // validate hard - hardDeposit, found := suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr) - suite.Require().True(found) - suite.Require().Equal(suite.testAddr, hardDeposit.Depositor) - suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000))), hardDeposit.Amount) + // // validate hard + // hardDeposit, found := suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr) + // suite.Require().True(found) + // suite.Require().Equal(suite.testAddr, hardDeposit.Depositor) + // suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000))), hardDeposit.Amount) // validate erc20 balance coinBal, err := suite.evmutilKeeper.QueryERC20BalanceOf(suite.ctx, suite.usdcEVMAddr, suite.testEVMAddr) @@ -743,18 +703,18 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() { suite.testEVMAddr.String(), sdk.NewCoin(USDCCoinDenom, usdcAmt), ) - cdpWithdrawMsg := cdptypes.NewMsgRepayDebt( - suite.testAddr, - USDCCDPType, - sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt), - ) - hardWithdrawMsg := hardtypes.NewMsgWithdraw( - suite.testAddr, - sdk.NewCoins(sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt)), - ) + // cdpWithdrawMsg := cdptypes.NewMsgRepayDebt( + // suite.testAddr, + // USDCCDPType, + // sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt), + // ) + // hardWithdrawMsg := hardtypes.NewMsgWithdraw( + // suite.testAddr, + // sdk.NewCoins(sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt)), + // ) withdrawMsgs := []sdk.Msg{ - &hardWithdrawMsg, - &cdpWithdrawMsg, + // &hardWithdrawMsg, + // &cdpWithdrawMsg, &withdrawConvertMsg, } @@ -772,10 +732,10 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() { suite.Require().Equal(resDeliverTx.Code, uint32(0), resDeliverTx.Log) // validate hard & cdp should be repayed - _, found = suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr) - suite.Require().False(found) - _, found = suite.tApp.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.ctx, suite.testAddr, USDCCDPType) - suite.Require().False(found) + // _, found = suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr) + // suite.Require().False(found) + // _, found = suite.tApp.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.ctx, suite.testAddr, USDCCDPType) + // suite.Require().False(found) // validate user cosmos erc20/usd balance bk := suite.tApp.GetBankKeeper() diff --git a/app/ante/min_gas_filter_test.go b/app/ante/min_gas_filter_test.go index b8f00df3..f17024ea 100644 --- a/app/ante/min_gas_filter_test.go +++ b/app/ante/min_gas_filter_test.go @@ -11,8 +11,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/app/ante" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/app/ante" + "github.com/0glabs/0g-chain/chaincfg" ) func mustParseDecCoins(value string) sdk.DecCoins { @@ -30,7 +31,7 @@ func TestEvmMinGasFilter(t *testing.T) { ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) tApp.GetEvmKeeper().SetParams(ctx, evmtypes.Params{ - EvmDenom: "akava", + EvmDenom: chaincfg.BaseDenom, }) testCases := []struct { @@ -44,29 +45,29 @@ func TestEvmMinGasFilter(t *testing.T) { mustParseDecCoins(""), }, { - "zero ukava gas price", - mustParseDecCoins("0ukava"), - mustParseDecCoins("0ukava"), + "zero a0gi gas price", + mustParseDecCoins("0a0gi"), + mustParseDecCoins("0a0gi"), }, { - "non-zero ukava gas price", - mustParseDecCoins("0.001ukava"), - mustParseDecCoins("0.001ukava"), + "non-zero a0gi gas price", + mustParseDecCoins("0.001a0gi"), + mustParseDecCoins("0.001a0gi"), }, { - "zero ukava gas price, min akava price", - mustParseDecCoins("0ukava;100000akava"), - mustParseDecCoins("0ukava"), // akava is removed + "zero a0gi gas price, min neuron price", + mustParseDecCoins("0a0gi;100000neuron"), + mustParseDecCoins("0a0gi"), // neuron is removed }, { - "zero ukava gas price, min akava price, other token", - mustParseDecCoins("0ukava;100000akava;0.001other"), - mustParseDecCoins("0ukava;0.001other"), // akava is removed + "zero a0gi gas price, min neuron price, other token", + mustParseDecCoins("0a0gi;100000neuron;0.001other"), + mustParseDecCoins("0a0gi;0.001other"), // neuron is removed }, { - "non-zero ukava gas price, min akava price", - mustParseDecCoins("0.25ukava;100000akava;0.001other"), - mustParseDecCoins("0.25ukava;0.001other"), // akava is removed + "non-zero a0gi gas price, min neuron price", + mustParseDecCoins("0.25a0gi;100000neuron;0.001other"), + mustParseDecCoins("0.25a0gi;0.001other"), // neuron is removed }, } diff --git a/app/ante/vesting_test.go b/app/ante/vesting_test.go index f0216655..b504d811 100644 --- a/app/ante/vesting_test.go +++ b/app/ante/vesting_test.go @@ -12,8 +12,9 @@ import ( vesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/app/ante" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/app/ante" + "github.com/0glabs/0g-chain/chaincfg" ) func TestVestingMempoolDecorator_MsgCreateVestingAccount_Unauthorized(t *testing.T) { @@ -33,7 +34,7 @@ func TestVestingMempoolDecorator_MsgCreateVestingAccount_Unauthorized(t *testing "MsgCreateVestingAccount", vesting.NewMsgCreateVestingAccount( testAddresses[0], testAddresses[1], - sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_000_000)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 100_000_000)), time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC).Unix(), false, ), @@ -44,7 +45,7 @@ func TestVestingMempoolDecorator_MsgCreateVestingAccount_Unauthorized(t *testing "MsgCreateVestingAccount", vesting.NewMsgCreatePermanentLockedAccount( testAddresses[0], testAddresses[1], - sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_000_000)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 100_000_000)), ), true, "MsgTypeURL /cosmos.vesting.v1beta1.MsgCreatePermanentLockedAccount not supported", @@ -63,7 +64,7 @@ func TestVestingMempoolDecorator_MsgCreateVestingAccount_Unauthorized(t *testing "other messages not affected", banktypes.NewMsgSend( testAddresses[0], testAddresses[1], - sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_000_000)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 100_000_000)), ), false, "", diff --git a/app/app.go b/app/app.go index 563ac76b..62e57ca7 100644 --- a/app/app.go +++ b/app/app.go @@ -3,10 +3,6 @@ package app import ( "fmt" "io" - stdlog "log" - "net/http" - "os" - "path/filepath" dbm "github.com/cometbft/cometbft-db" abci "github.com/cometbft/cometbft/abci/types" @@ -103,77 +99,27 @@ import ( "github.com/evmos/ethermint/x/feemarket" feemarketkeeper "github.com/evmos/ethermint/x/feemarket/keeper" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" - "github.com/gorilla/mux" - "github.com/kava-labs/kava/app/ante" - kavaparams "github.com/kava-labs/kava/app/params" - "github.com/kava-labs/kava/x/auction" - auctionkeeper "github.com/kava-labs/kava/x/auction/keeper" - auctiontypes "github.com/kava-labs/kava/x/auction/types" - "github.com/kava-labs/kava/x/bep3" - bep3keeper "github.com/kava-labs/kava/x/bep3/keeper" - bep3types "github.com/kava-labs/kava/x/bep3/types" - "github.com/kava-labs/kava/x/cdp" - cdpkeeper "github.com/kava-labs/kava/x/cdp/keeper" - cdptypes "github.com/kava-labs/kava/x/cdp/types" - "github.com/kava-labs/kava/x/committee" - committeeclient "github.com/kava-labs/kava/x/committee/client" - committeekeeper "github.com/kava-labs/kava/x/committee/keeper" - committeetypes "github.com/kava-labs/kava/x/committee/types" - "github.com/kava-labs/kava/x/community" - communityclient "github.com/kava-labs/kava/x/community/client" - communitykeeper "github.com/kava-labs/kava/x/community/keeper" - communitytypes "github.com/kava-labs/kava/x/community/types" - earn "github.com/kava-labs/kava/x/earn" - earnclient "github.com/kava-labs/kava/x/earn/client" - earnkeeper "github.com/kava-labs/kava/x/earn/keeper" - earntypes "github.com/kava-labs/kava/x/earn/types" - evmutil "github.com/kava-labs/kava/x/evmutil" - evmutilkeeper "github.com/kava-labs/kava/x/evmutil/keeper" - evmutiltypes "github.com/kava-labs/kava/x/evmutil/types" - "github.com/kava-labs/kava/x/hard" - hardkeeper "github.com/kava-labs/kava/x/hard/keeper" - hardtypes "github.com/kava-labs/kava/x/hard/types" - "github.com/kava-labs/kava/x/incentive" - incentivekeeper "github.com/kava-labs/kava/x/incentive/keeper" - incentivetypes "github.com/kava-labs/kava/x/incentive/types" - issuance "github.com/kava-labs/kava/x/issuance" - issuancekeeper "github.com/kava-labs/kava/x/issuance/keeper" - issuancetypes "github.com/kava-labs/kava/x/issuance/types" - "github.com/kava-labs/kava/x/kavadist" - kavadistclient "github.com/kava-labs/kava/x/kavadist/client" - kavadistkeeper "github.com/kava-labs/kava/x/kavadist/keeper" - kavadisttypes "github.com/kava-labs/kava/x/kavadist/types" - "github.com/kava-labs/kava/x/liquid" - liquidkeeper "github.com/kava-labs/kava/x/liquid/keeper" - liquidtypes "github.com/kava-labs/kava/x/liquid/types" - metrics "github.com/kava-labs/kava/x/metrics" - metricstypes "github.com/kava-labs/kava/x/metrics/types" - pricefeed "github.com/kava-labs/kava/x/pricefeed" - pricefeedkeeper "github.com/kava-labs/kava/x/pricefeed/keeper" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" - "github.com/kava-labs/kava/x/router" - routerkeeper "github.com/kava-labs/kava/x/router/keeper" - routertypes "github.com/kava-labs/kava/x/router/types" - savings "github.com/kava-labs/kava/x/savings" - savingskeeper "github.com/kava-labs/kava/x/savings/keeper" - savingstypes "github.com/kava-labs/kava/x/savings/types" - "github.com/kava-labs/kava/x/swap" - swapkeeper "github.com/kava-labs/kava/x/swap/keeper" - swaptypes "github.com/kava-labs/kava/x/swap/types" - validatorvesting "github.com/kava-labs/kava/x/validator-vesting" - validatorvestingrest "github.com/kava-labs/kava/x/validator-vesting/client/rest" - validatorvestingtypes "github.com/kava-labs/kava/x/validator-vesting/types" -) + "github.com/0glabs/0g-chain/app/ante" + chainparams "github.com/0glabs/0g-chain/app/params" + "github.com/0glabs/0g-chain/chaincfg" -const ( - appName = "kava" + evmutil "github.com/0glabs/0g-chain/x/evmutil" + evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper" + evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types" + + committee "github.com/0glabs/0g-chain/x/committee/v1" + committeekeeper "github.com/0glabs/0g-chain/x/committee/v1/keeper" + committeetypes "github.com/0glabs/0g-chain/x/committee/v1/types" + das "github.com/0glabs/0g-chain/x/das/v1" + daskeeper "github.com/0glabs/0g-chain/x/das/v1/keeper" + dastypes "github.com/0glabs/0g-chain/x/das/v1/types" + validatorvesting "github.com/0glabs/0g-chain/x/validator-vesting" + validatorvestingrest "github.com/0glabs/0g-chain/x/validator-vesting/client/rest" + validatorvestingtypes "github.com/0glabs/0g-chain/x/validator-vesting/types" ) var ( - // DefaultNodeHome default home directories for the application daemon - DefaultNodeHome string - // ModuleBasics manages simple versions of full app modules. // It's used for things such as codec registration and genesis file verification. ModuleBasics = module.NewBasicManager( @@ -189,12 +135,6 @@ var ( upgradeclient.LegacyCancelProposalHandler, ibcclientclient.UpdateClientProposalHandler, ibcclientclient.UpgradeProposalHandler, - kavadistclient.ProposalHandler, - committeeclient.ProposalHandler, - earnclient.DepositProposalHandler, - earnclient.WithdrawProposalHandler, - communityclient.LendDepositProposalHandler, - communityclient.LendWithdrawProposalHandler, }), params.AppModuleBasic{}, crisis.AppModuleBasic{}, @@ -210,54 +150,27 @@ var ( vesting.AppModuleBasic{}, evm.AppModuleBasic{}, feemarket.AppModuleBasic{}, - kavadist.AppModuleBasic{}, - auction.AppModuleBasic{}, - issuance.AppModuleBasic{}, - bep3.AppModuleBasic{}, - pricefeed.AppModuleBasic{}, - swap.AppModuleBasic{}, - cdp.AppModuleBasic{}, - hard.AppModuleBasic{}, - committee.AppModuleBasic{}, - incentive.AppModuleBasic{}, - savings.AppModuleBasic{}, validatorvesting.AppModuleBasic{}, evmutil.AppModuleBasic{}, - liquid.AppModuleBasic{}, - earn.AppModuleBasic{}, - router.AppModuleBasic{}, mint.AppModuleBasic{}, - community.AppModuleBasic{}, - metrics.AppModuleBasic{}, consensus.AppModuleBasic{}, + committee.AppModuleBasic{}, + das.AppModuleBasic{}, ) // module account permissions // If these are changed, the permissions stored in accounts // must also be migrated during a chain upgrade. mAccPerms = map[string][]string{ - authtypes.FeeCollectorName: nil, - distrtypes.ModuleName: nil, - stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, - stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, - govtypes.ModuleName: {authtypes.Burner}, - ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, - evmtypes.ModuleName: {authtypes.Minter, authtypes.Burner}, // used for secure addition and subtraction of balance using module account - evmutiltypes.ModuleName: {authtypes.Minter, authtypes.Burner}, - kavadisttypes.KavaDistMacc: {authtypes.Minter}, - auctiontypes.ModuleName: nil, - issuancetypes.ModuleAccountName: {authtypes.Minter, authtypes.Burner}, - bep3types.ModuleName: {authtypes.Burner, authtypes.Minter}, - swaptypes.ModuleName: nil, - cdptypes.ModuleName: {authtypes.Minter, authtypes.Burner}, - cdptypes.LiquidatorMacc: {authtypes.Minter, authtypes.Burner}, - hardtypes.ModuleAccountName: {authtypes.Minter}, - savingstypes.ModuleAccountName: nil, - liquidtypes.ModuleAccountName: {authtypes.Minter, authtypes.Burner}, - earntypes.ModuleAccountName: nil, - kavadisttypes.FundModuleAccount: nil, - minttypes.ModuleName: {authtypes.Minter}, - communitytypes.ModuleName: nil, + authtypes.FeeCollectorName: nil, + distrtypes.ModuleName: nil, + stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, + stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, + govtypes.ModuleName: {authtypes.Burner}, + ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + evmtypes.ModuleName: {authtypes.Minter, authtypes.Burner}, // used for secure addition and subtraction of balance using module account + evmutiltypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + minttypes.ModuleName: {authtypes.Minter}, } ) @@ -276,7 +189,6 @@ type Options struct { MempoolAuthAddresses []sdk.AccAddress EVMTrace string EVMMaxGasWanted uint64 - TelemetryOptions metricstypes.TelemetryOptions } // DefaultOptions is a sensible default Options value. @@ -285,7 +197,7 @@ var DefaultOptions = Options{ EVMMaxGasWanted: ethermintconfig.DefaultMaxTxGasWanted, } -// App is the Kava ABCI application. +// App is the 0gChain ABCI application. type App struct { *baseapp.BaseApp @@ -318,23 +230,10 @@ type App struct { upgradeKeeper upgradekeeper.Keeper evidenceKeeper evidencekeeper.Keeper transferKeeper ibctransferkeeper.Keeper - kavadistKeeper kavadistkeeper.Keeper - auctionKeeper auctionkeeper.Keeper - issuanceKeeper issuancekeeper.Keeper - bep3Keeper bep3keeper.Keeper - pricefeedKeeper pricefeedkeeper.Keeper - swapKeeper swapkeeper.Keeper - cdpKeeper cdpkeeper.Keeper - hardKeeper hardkeeper.Keeper - committeeKeeper committeekeeper.Keeper - incentiveKeeper incentivekeeper.Keeper - savingsKeeper savingskeeper.Keeper - liquidKeeper liquidkeeper.Keeper - earnKeeper earnkeeper.Keeper - routerKeeper routerkeeper.Keeper mintKeeper mintkeeper.Keeper - communityKeeper communitykeeper.Keeper consensusParamsKeeper consensusparamkeeper.Keeper + CommitteeKeeper committeekeeper.Keeper + DasKeeper daskeeper.Keeper // make scoped keepers public for test purposes ScopedIBCKeeper capabilitykeeper.ScopedKeeper @@ -350,22 +249,13 @@ type App struct { configurator module.Configurator } -func init() { - userHomeDir, err := os.UserHomeDir() - if err != nil { - stdlog.Printf("Failed to get home dir %v", err) - } - - DefaultNodeHome = filepath.Join(userHomeDir, ".kava") -} - // NewApp returns a reference to an initialized App. func NewApp( logger tmlog.Logger, db dbm.DB, homePath string, traceStore io.Writer, - encodingConfig kavaparams.EncodingConfig, + encodingConfig chainparams.EncodingConfig, options Options, baseAppOptions ...func(*baseapp.BaseApp), ) *App { @@ -373,23 +263,34 @@ func NewApp( legacyAmino := encodingConfig.Amino interfaceRegistry := encodingConfig.InterfaceRegistry - bApp := baseapp.NewBaseApp(appName, logger, db, encodingConfig.TxConfig.TxDecoder(), baseAppOptions...) + bApp := baseapp.NewBaseApp(chaincfg.AppName, logger, db, encodingConfig.TxConfig.TxDecoder(), baseAppOptions...) bApp.SetCommitMultiStoreTracer(traceStore) bApp.SetVersion(version.Version) bApp.SetInterfaceRegistry(interfaceRegistry) keys := sdk.NewKVStoreKeys( - authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, - distrtypes.StoreKey, slashingtypes.StoreKey, packetforwardtypes.StoreKey, - govtypes.StoreKey, paramstypes.StoreKey, ibcexported.StoreKey, - upgradetypes.StoreKey, evidencetypes.StoreKey, ibctransfertypes.StoreKey, - evmtypes.StoreKey, feemarkettypes.StoreKey, authzkeeper.StoreKey, - capabilitytypes.StoreKey, kavadisttypes.StoreKey, auctiontypes.StoreKey, - issuancetypes.StoreKey, bep3types.StoreKey, pricefeedtypes.StoreKey, - swaptypes.StoreKey, cdptypes.StoreKey, hardtypes.StoreKey, communitytypes.StoreKey, - committeetypes.StoreKey, incentivetypes.StoreKey, evmutiltypes.StoreKey, - savingstypes.StoreKey, earntypes.StoreKey, minttypes.StoreKey, - consensusparamtypes.StoreKey, crisistypes.StoreKey, + authtypes.StoreKey, + banktypes.StoreKey, + stakingtypes.StoreKey, + distrtypes.StoreKey, + slashingtypes.StoreKey, + packetforwardtypes.StoreKey, + govtypes.StoreKey, + paramstypes.StoreKey, + ibcexported.StoreKey, + upgradetypes.StoreKey, + evidencetypes.StoreKey, + ibctransfertypes.StoreKey, + evmtypes.StoreKey, + feemarkettypes.StoreKey, + authzkeeper.StoreKey, + capabilitytypes.StoreKey, + evmutiltypes.StoreKey, + minttypes.StoreKey, + consensusparamtypes.StoreKey, + crisistypes.StoreKey, + committeetypes.StoreKey, + dastypes.StoreKey, ) tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey, evmtypes.TransientKey, feemarkettypes.TransientKey) memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) @@ -422,23 +323,12 @@ func NewApp( slashingSubspace := app.paramsKeeper.Subspace(slashingtypes.ModuleName) govSubspace := app.paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govv1.ParamKeyTable()) crisisSubspace := app.paramsKeeper.Subspace(crisistypes.ModuleName) - kavadistSubspace := app.paramsKeeper.Subspace(kavadisttypes.ModuleName) - auctionSubspace := app.paramsKeeper.Subspace(auctiontypes.ModuleName) - issuanceSubspace := app.paramsKeeper.Subspace(issuancetypes.ModuleName) - bep3Subspace := app.paramsKeeper.Subspace(bep3types.ModuleName) - pricefeedSubspace := app.paramsKeeper.Subspace(pricefeedtypes.ModuleName) - swapSubspace := app.paramsKeeper.Subspace(swaptypes.ModuleName) - cdpSubspace := app.paramsKeeper.Subspace(cdptypes.ModuleName) - hardSubspace := app.paramsKeeper.Subspace(hardtypes.ModuleName) - incentiveSubspace := app.paramsKeeper.Subspace(incentivetypes.ModuleName) - savingsSubspace := app.paramsKeeper.Subspace(savingstypes.ModuleName) ibcSubspace := app.paramsKeeper.Subspace(ibcexported.ModuleName) ibctransferSubspace := app.paramsKeeper.Subspace(ibctransfertypes.ModuleName) packetforwardSubspace := app.paramsKeeper.Subspace(packetforwardtypes.ModuleName).WithKeyTable(packetforwardtypes.ParamKeyTable()) feemarketSubspace := app.paramsKeeper.Subspace(feemarkettypes.ModuleName) evmSubspace := app.paramsKeeper.Subspace(evmtypes.ModuleName) evmutilSubspace := app.paramsKeeper.Subspace(evmutiltypes.ModuleName) - earnSubspace := app.paramsKeeper.Subspace(earntypes.ModuleName) mintSubspace := app.paramsKeeper.Subspace(minttypes.ModuleName) // set the BaseApp's parameter store @@ -602,96 +492,6 @@ func NewApp( ibcRouter.AddRoute(ibctransfertypes.ModuleName, transferStack) app.ibcKeeper.SetRouter(ibcRouter) - app.auctionKeeper = auctionkeeper.NewKeeper( - appCodec, - keys[auctiontypes.StoreKey], - auctionSubspace, - app.bankKeeper, - app.accountKeeper, - ) - app.issuanceKeeper = issuancekeeper.NewKeeper( - appCodec, - keys[issuancetypes.StoreKey], - issuanceSubspace, - app.accountKeeper, - app.bankKeeper, - ) - app.bep3Keeper = bep3keeper.NewKeeper( - appCodec, - keys[bep3types.StoreKey], - app.bankKeeper, - app.accountKeeper, - bep3Subspace, - app.ModuleAccountAddrs(), - ) - app.pricefeedKeeper = pricefeedkeeper.NewKeeper( - appCodec, - keys[pricefeedtypes.StoreKey], - pricefeedSubspace, - ) - swapKeeper := swapkeeper.NewKeeper( - appCodec, - keys[swaptypes.StoreKey], - swapSubspace, - app.accountKeeper, - app.bankKeeper, - ) - cdpKeeper := cdpkeeper.NewKeeper( - appCodec, - keys[cdptypes.StoreKey], - cdpSubspace, - app.pricefeedKeeper, - app.auctionKeeper, - app.bankKeeper, - app.accountKeeper, - mAccPerms, - ) - hardKeeper := hardkeeper.NewKeeper( - appCodec, - keys[hardtypes.StoreKey], - hardSubspace, - app.accountKeeper, - app.bankKeeper, - app.pricefeedKeeper, - app.auctionKeeper, - ) - app.liquidKeeper = liquidkeeper.NewDefaultKeeper( - appCodec, - app.accountKeeper, - app.bankKeeper, - app.stakingKeeper, - &app.distrKeeper, - ) - savingsKeeper := savingskeeper.NewKeeper( - appCodec, - keys[savingstypes.StoreKey], - savingsSubspace, - app.accountKeeper, - app.bankKeeper, - app.liquidKeeper, - ) - earnKeeper := earnkeeper.NewKeeper( - appCodec, - keys[earntypes.StoreKey], - earnSubspace, - app.accountKeeper, - app.bankKeeper, - &app.liquidKeeper, - &hardKeeper, - &savingsKeeper, - &app.distrKeeper, - ) - - app.kavadistKeeper = kavadistkeeper.NewKeeper( - appCodec, - keys[kavadisttypes.StoreKey], - kavadistSubspace, - app.bankKeeper, - app.accountKeeper, - app.distrKeeper, - app.loadBlockedMaccAddrs(), - ) - app.mintKeeper = mintkeeper.NewKeeper( appCodec, keys[minttypes.StoreKey], @@ -702,76 +502,13 @@ func NewApp( govAuthAddrStr, ) - // x/community's deposit/withdraw to lend proposals depend on hard keeper. - app.communityKeeper = communitykeeper.NewKeeper( - appCodec, - keys[communitytypes.StoreKey], - app.accountKeeper, - app.bankKeeper, - &cdpKeeper, - app.distrKeeper, - &hardKeeper, - &app.mintKeeper, - &app.kavadistKeeper, - app.stakingKeeper, - govAuthAddr, - ) - - app.incentiveKeeper = incentivekeeper.NewKeeper( - appCodec, - keys[incentivetypes.StoreKey], - incentiveSubspace, - app.bankKeeper, - &cdpKeeper, - &hardKeeper, - app.accountKeeper, - app.stakingKeeper, - &swapKeeper, - &savingsKeeper, - &app.liquidKeeper, - &earnKeeper, - app.mintKeeper, - app.distrKeeper, - app.pricefeedKeeper, - ) - app.routerKeeper = routerkeeper.NewKeeper( - &app.earnKeeper, - app.liquidKeeper, - app.stakingKeeper, - ) - - // create committee keeper with router - committeeGovRouter := govv1beta1.NewRouter() - committeeGovRouter. - AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). - AddRoute(communitytypes.RouterKey, community.NewCommunityPoolProposalHandler(app.communityKeeper)). - AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)). - AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(&app.upgradeKeeper)) - // Note: the committee proposal handler is not registered on the committee router. This means committees cannot create or update other committees. - // Adding the committee proposal handler to the router is possible but awkward as the handler depends on the keeper which depends on the handler. - app.committeeKeeper = committeekeeper.NewKeeper( - appCodec, - keys[committeetypes.StoreKey], - committeeGovRouter, - app.paramsKeeper, - app.accountKeeper, - app.bankKeeper, - ) - // register the staking hooks app.stakingKeeper.SetHooks( stakingtypes.NewMultiStakingHooks( app.distrKeeper.Hooks(), app.slashingKeeper.Hooks(), - app.incentiveKeeper.Hooks(), )) - app.swapKeeper = *swapKeeper.SetHooks(app.incentiveKeeper.Hooks()) - app.cdpKeeper = *cdpKeeper.SetHooks(cdptypes.NewMultiCDPHooks(app.incentiveKeeper.Hooks())) - app.hardKeeper = *hardKeeper.SetHooks(hardtypes.NewMultiHARDHooks(app.incentiveKeeper.Hooks())) - app.savingsKeeper = savingsKeeper // savings incentive hooks disabled - app.earnKeeper = *earnKeeper.SetHooks(app.incentiveKeeper.Hooks()) - // create gov keeper with router // NOTE this must be done after any keepers referenced in the gov router (ie committee) are defined govRouter := govv1beta1.NewRouter() @@ -779,11 +516,7 @@ func NewApp( AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)). AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(&app.upgradeKeeper)). - AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(app.ibcKeeper.ClientKeeper)). - AddRoute(kavadisttypes.RouterKey, kavadist.NewCommunityPoolMultiSpendProposalHandler(app.kavadistKeeper)). - AddRoute(earntypes.RouterKey, earn.NewCommunityPoolProposalHandler(app.earnKeeper)). - AddRoute(communitytypes.RouterKey, community.NewCommunityPoolProposalHandler(app.communityKeeper)). - AddRoute(committeetypes.RouterKey, committee.NewProposalHandler(app.committeeKeeper)) + AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(app.ibcKeeper.ClientKeeper)) govConfig := govtypes.DefaultConfig() govKeeper := govkeeper.NewKeeper( @@ -799,12 +532,10 @@ func NewApp( govKeeper.SetLegacyRouter(govRouter) app.govKeeper = *govKeeper - // override x/gov tally handler with custom implementation - tallyHandler := NewTallyHandler( - app.govKeeper, *app.stakingKeeper, app.savingsKeeper, app.earnKeeper, - app.liquidKeeper, app.bankKeeper, + app.CommitteeKeeper = committeekeeper.NewKeeper( + keys[committeetypes.StoreKey], appCodec, app.stakingKeeper, ) - app.govKeeper.SetTallyHandler(tallyHandler) + app.DasKeeper = daskeeper.NewKeeper(keys[dastypes.StoreKey], appCodec, app.stakingKeeper) // create the module manager (Note: Any module instantiated in the module manager that is later modified // must be passed by reference here.) @@ -829,41 +560,17 @@ func NewApp( transferModule, vesting.NewAppModule(app.accountKeeper, app.bankKeeper), authzmodule.NewAppModule(appCodec, app.authzKeeper, app.accountKeeper, app.bankKeeper, app.interfaceRegistry), - kavadist.NewAppModule(app.kavadistKeeper, app.accountKeeper), - auction.NewAppModule(app.auctionKeeper, app.accountKeeper, app.bankKeeper), - issuance.NewAppModule(app.issuanceKeeper, app.accountKeeper, app.bankKeeper), - bep3.NewAppModule(app.bep3Keeper, app.accountKeeper, app.bankKeeper), - pricefeed.NewAppModule(app.pricefeedKeeper, app.accountKeeper), validatorvesting.NewAppModule(app.bankKeeper), - swap.NewAppModule(app.swapKeeper, app.accountKeeper), - cdp.NewAppModule(app.cdpKeeper, app.accountKeeper, app.pricefeedKeeper, app.bankKeeper), - hard.NewAppModule(app.hardKeeper, app.accountKeeper, app.bankKeeper, app.pricefeedKeeper), - committee.NewAppModule(app.committeeKeeper, app.accountKeeper), - incentive.NewAppModule(app.incentiveKeeper, app.accountKeeper, app.bankKeeper, app.cdpKeeper), evmutil.NewAppModule(app.evmutilKeeper, app.bankKeeper, app.accountKeeper), - savings.NewAppModule(app.savingsKeeper, app.accountKeeper, app.bankKeeper), - liquid.NewAppModule(app.liquidKeeper), - earn.NewAppModule(app.earnKeeper, app.accountKeeper, app.bankKeeper), - router.NewAppModule(app.routerKeeper), - // nil InflationCalculationFn, use SDK's default inflation function mint.NewAppModule(appCodec, app.mintKeeper, app.accountKeeper, nil, mintSubspace), - community.NewAppModule(app.communityKeeper, app.accountKeeper), - metrics.NewAppModule(options.TelemetryOptions), ) // Warning: Some begin blockers must run before others. Ensure the dependencies are understood before modifying this list. app.mm.SetOrderBeginBlockers( - metricstypes.ModuleName, // Upgrade begin blocker runs migrations on the first block after an upgrade. It should run before any other module. upgradetypes.ModuleName, // Capability begin blocker runs non state changing initialization. capabilitytypes.ModuleName, - // Committee begin blocker changes module params by enacting proposals. - // Run before to ensure params are updated together before state changes. - committeetypes.ModuleName, - // Community begin blocker should run before x/mint and x/kavadist since - // the disable inflation upgrade will update those modules' params. - communitytypes.ModuleName, minttypes.ModuleName, distrtypes.ModuleName, // During begin block slashing happens after distr.BeginBlocker so that @@ -874,20 +581,9 @@ func NewApp( stakingtypes.ModuleName, feemarkettypes.ModuleName, evmtypes.ModuleName, - kavadisttypes.ModuleName, - // Auction begin blocker will close out expired auctions and pay debt back to cdp. - // It should be run before cdp begin blocker which cancels out debt with stable and starts more auctions. - auctiontypes.ModuleName, - cdptypes.ModuleName, - bep3types.ModuleName, - hardtypes.ModuleName, - issuancetypes.ModuleName, - incentivetypes.ModuleName, ibcexported.ModuleName, // Add all remaining modules with an empty begin blocker below since cosmos 0.45.0 requires it - swaptypes.ModuleName, vestingtypes.ModuleName, - pricefeedtypes.ModuleName, validatorvestingtypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, @@ -898,12 +594,11 @@ func NewApp( paramstypes.ModuleName, authz.ModuleName, evmutiltypes.ModuleName, - savingstypes.ModuleName, - liquidtypes.ModuleName, - earntypes.ModuleName, - routertypes.ModuleName, consensusparamtypes.ModuleName, packetforwardtypes.ModuleName, + + committeetypes.ModuleName, + dastypes.ModuleName, ) // Warning: Some end blockers must run before others. Ensure the dependencies are understood before modifying this list. @@ -914,22 +609,12 @@ func NewApp( evmtypes.ModuleName, // fee market module must go after evm module in order to retrieve the block gas used. feemarkettypes.ModuleName, - pricefeedtypes.ModuleName, // Add all remaining modules with an empty end blocker below since cosmos 0.45.0 requires it capabilitytypes.ModuleName, - incentivetypes.ModuleName, - issuancetypes.ModuleName, slashingtypes.ModuleName, distrtypes.ModuleName, - auctiontypes.ModuleName, - bep3types.ModuleName, - cdptypes.ModuleName, - hardtypes.ModuleName, - committeetypes.ModuleName, upgradetypes.ModuleName, evidencetypes.ModuleName, - kavadisttypes.ModuleName, - swaptypes.ModuleName, vestingtypes.ModuleName, ibcexported.ModuleName, validatorvestingtypes.ModuleName, @@ -940,15 +625,11 @@ func NewApp( paramstypes.ModuleName, authz.ModuleName, evmutiltypes.ModuleName, - savingstypes.ModuleName, - liquidtypes.ModuleName, - earntypes.ModuleName, - routertypes.ModuleName, minttypes.ModuleName, - communitytypes.ModuleName, - metricstypes.ModuleName, consensusparamtypes.ModuleName, packetforwardtypes.ModuleName, + committeetypes.ModuleName, + dastypes.ModuleName, ) // Warning: Some init genesis methods must run before others. Ensure the dependencies are understood before modifying this list @@ -967,32 +648,18 @@ func NewApp( ibctransfertypes.ModuleName, evmtypes.ModuleName, feemarkettypes.ModuleName, - kavadisttypes.ModuleName, - auctiontypes.ModuleName, - issuancetypes.ModuleName, - savingstypes.ModuleName, - bep3types.ModuleName, - pricefeedtypes.ModuleName, - swaptypes.ModuleName, - cdptypes.ModuleName, // reads market prices, so must run after pricefeed genesis - hardtypes.ModuleName, - incentivetypes.ModuleName, // reads cdp params, so must run after cdp genesis - committeetypes.ModuleName, evmutiltypes.ModuleName, - earntypes.ModuleName, - communitytypes.ModuleName, genutiltypes.ModuleName, // runs arbitrary txs included in genisis state, so run after modules have been initialized // Add all remaining modules with an empty InitGenesis below since cosmos 0.45.0 requires it vestingtypes.ModuleName, paramstypes.ModuleName, upgradetypes.ModuleName, validatorvestingtypes.ModuleName, - liquidtypes.ModuleName, - routertypes.ModuleName, - metricstypes.ModuleName, consensusparamtypes.ModuleName, packetforwardtypes.ModuleName, crisistypes.ModuleName, // runs the invariants at genesis, should run after other modules + committeetypes.ModuleName, + dastypes.ModuleName, ) app.mm.RegisterInvariants(&app.crisisKeeper) @@ -1031,8 +698,6 @@ func NewApp( if options.MempoolEnableAuth { fetchers = append(fetchers, func(sdk.Context) []sdk.AccAddress { return options.MempoolAuthAddresses }, - app.bep3Keeper.GetAuthorizedAddresses, - app.pricefeedKeeper.GetAuthorizedAddresses, ) } @@ -1094,7 +759,7 @@ func (app *App) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.Res panic(err) } - // Store current module versions in kava-10 to setup future in-place upgrades. + // Store current module versions in 0gChain-10 to setup future in-place upgrades. // During in-place migrations, the old module versions in the store will be referenced to determine which migrations to run. app.upgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap()) @@ -1133,9 +798,6 @@ func (app *App) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig // Register custom REST routes validatorvestingrest.RegisterRoutes(clientCtx, apiSvr.Router) - // Register rewrite routes - RegisterAPIRouteRewrites(apiSvr.Router) - // Register GRPC Gateway routes tmservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) authtx.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) @@ -1145,33 +807,6 @@ func (app *App) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig // Swagger API configuration is ignored } -// RegisterAPIRouteRewrites registers overwritten API routes that are -// registered after this function is called. This must be called before any -// other route registrations on the router in order for rewrites to take effect. -// The first route that matches in the mux router wins, so any registrations -// here will be prioritized over the later registrations in modules. -func RegisterAPIRouteRewrites(router *mux.Router) { - // Mapping of client path to backend path. Similar to nginx rewrite rules, - // but does not return a 301 or 302 redirect. - // Eg: querying /cosmos/distribution/v1beta1/community_pool will return - // the same response as querying /kava/community/v1beta1/total_balance - routeMap := map[string]string{ - "/cosmos/distribution/v1beta1/community_pool": "/kava/community/v1beta1/total_balance", - } - - for clientPath, backendPath := range routeMap { - router.HandleFunc( - clientPath, - func(w http.ResponseWriter, r *http.Request) { - r.URL.Path = backendPath - - // Use handler of the new path - router.ServeHTTP(w, r) - }, - ).Methods("GET") - } -} - // RegisterTxService implements the Application.RegisterTxService method. // It registers transaction related endpoints on the app's grpc server. func (app *App) RegisterTxService(clientCtx client.Context) { @@ -1196,19 +831,7 @@ func (app *App) RegisterNodeService(clientCtx client.Context) { // loadBlockedMaccAddrs returns a map indicating the blocked status of each module account address func (app *App) loadBlockedMaccAddrs() map[string]bool { modAccAddrs := app.ModuleAccountAddrs() - allowedMaccs := map[string]bool{ - // kavadist - app.accountKeeper.GetModuleAddress(kavadisttypes.ModuleName).String(): true, - // earn - app.accountKeeper.GetModuleAddress(earntypes.ModuleName).String(): true, - // liquid - app.accountKeeper.GetModuleAddress(liquidtypes.ModuleName).String(): true, - // kavadist fund - app.accountKeeper.GetModuleAddress(kavadisttypes.FundModuleAccount).String(): true, - // community - app.accountKeeper.GetModuleAddress(communitytypes.ModuleAccountName).String(): true, - // NOTE: if adding evmutil, adjust the cosmos-coins-fully-backed-invariant accordingly. - } + allowedMaccs := map[string]bool{} for addr := range modAccAddrs { // Set allowed module accounts as unblocked diff --git a/app/app_test.go b/app/app_test.go index 20ee39be..7ab5b262 100644 --- a/app/app_test.go +++ b/app/app_test.go @@ -8,6 +8,7 @@ import ( "testing" "time" + "github.com/0glabs/0g-chain/chaincfg" db "github.com/cometbft/cometbft-db" abci "github.com/cometbft/cometbft/abci/types" "github.com/cometbft/cometbft/libs/log" @@ -25,11 +26,11 @@ import ( ) func TestNewApp(t *testing.T) { - SetSDKConfig() + chaincfg.SetSDKConfig() NewApp( log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db.NewMemDB(), - DefaultNodeHome, + chaincfg.DefaultNodeHome, nil, MakeEncodingConfig(), DefaultOptions, @@ -37,9 +38,9 @@ func TestNewApp(t *testing.T) { } func TestExport(t *testing.T) { - SetSDKConfig() + chaincfg.SetSDKConfig() db := db.NewMemDB() - app := NewApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, DefaultNodeHome, nil, MakeEncodingConfig(), DefaultOptions, baseapp.SetChainID(TestChainId)) + app := NewApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, chaincfg.DefaultNodeHome, nil, MakeEncodingConfig(), DefaultOptions, baseapp.SetChainID(TestChainId)) genesisState := GenesisStateWithSingleValidator(&TestApp{App: *app}, NewDefaultGenesisState()) diff --git a/app/config.go b/app/config.go deleted file mode 100644 index fa00e72d..00000000 --- a/app/config.go +++ /dev/null @@ -1,41 +0,0 @@ -package app - -import sdk "github.com/cosmos/cosmos-sdk/types" - -const ( - // Bech32MainPrefix defines the Bech32 prefix for account addresses - Bech32MainPrefix = "kava" - // Bech32PrefixAccPub defines the Bech32 prefix of an account's public key - Bech32PrefixAccPub = Bech32MainPrefix + "pub" - // Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address - Bech32PrefixValAddr = Bech32MainPrefix + "val" + "oper" - // Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key - Bech32PrefixValPub = Bech32MainPrefix + "val" + "oper" + "pub" - // Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address - Bech32PrefixConsAddr = Bech32MainPrefix + "val" + "cons" - // Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key - Bech32PrefixConsPub = Bech32MainPrefix + "val" + "cons" + "pub" - - Bip44CoinType = 459 // see https://github.com/satoshilabs/slips/blob/master/slip-0044.md -) - -// SetSDKConfig configures the global config with kava app specific parameters. -// It does not seal the config to allow modification in tests. -func SetSDKConfig() *sdk.Config { - config := sdk.GetConfig() - SetBech32AddressPrefixes(config) - SetBip44CoinType(config) - return config -} - -// SetBech32AddressPrefixes sets the global prefix to be used when serializing addresses to bech32 strings. -func SetBech32AddressPrefixes(config *sdk.Config) { - config.SetBech32PrefixForAccount(Bech32MainPrefix, Bech32PrefixAccPub) - config.SetBech32PrefixForValidator(Bech32PrefixValAddr, Bech32PrefixValPub) - config.SetBech32PrefixForConsensusNode(Bech32PrefixConsAddr, Bech32PrefixConsPub) -} - -// SetBip44CoinType sets the global coin type to be used in hierarchical deterministic wallets. -func SetBip44CoinType(config *sdk.Config) { - config.SetCoinType(Bip44CoinType) -} diff --git a/app/encoding.go b/app/encoding.go index 17445f10..ac95666f 100644 --- a/app/encoding.go +++ b/app/encoding.go @@ -3,7 +3,7 @@ package app import ( enccodec "github.com/evmos/ethermint/encoding/codec" - "github.com/kava-labs/kava/app/params" + "github.com/0glabs/0g-chain/app/params" ) // MakeEncodingConfig creates an EncodingConfig and registers the app's types on it. diff --git a/app/params/doc.go b/app/params/doc.go index c8efce8f..5eb101c1 100644 --- a/app/params/doc.go +++ b/app/params/doc.go @@ -1,5 +1,5 @@ /* -Package params defines the simulation parameters for the Kava app. +Package params defines the simulation parameters for the 0gChain app. It contains the default weights used for each transaction used on the module's simulation. These weights define the chance for a transaction to be simulated at diff --git a/app/tally_handler.go b/app/tally_handler.go deleted file mode 100644 index 5a341c7e..00000000 --- a/app/tally_handler.go +++ /dev/null @@ -1,256 +0,0 @@ -package app - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" - govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - earnkeeper "github.com/kava-labs/kava/x/earn/keeper" - liquidkeeper "github.com/kava-labs/kava/x/liquid/keeper" - liquidtypes "github.com/kava-labs/kava/x/liquid/types" - savingskeeper "github.com/kava-labs/kava/x/savings/keeper" -) - -var _ govv1.TallyHandler = TallyHandler{} - -// TallyHandler is the tally handler for kava -type TallyHandler struct { - gk govkeeper.Keeper - stk stakingkeeper.Keeper - svk savingskeeper.Keeper - ek earnkeeper.Keeper - lk liquidkeeper.Keeper - bk bankkeeper.Keeper -} - -// NewTallyHandler creates a new tally handler. -func NewTallyHandler( - gk govkeeper.Keeper, stk stakingkeeper.Keeper, svk savingskeeper.Keeper, - ek earnkeeper.Keeper, lk liquidkeeper.Keeper, bk bankkeeper.Keeper, -) TallyHandler { - return TallyHandler{ - gk: gk, - stk: stk, - svk: svk, - ek: ek, - lk: lk, - bk: bk, - } -} - -func (th TallyHandler) Tally( - ctx sdk.Context, - proposal govv1.Proposal, -) (passes bool, burnDeposits bool, tallyResults govv1.TallyResult) { - results := make(map[govv1.VoteOption]sdk.Dec) - results[govv1.OptionYes] = sdk.ZeroDec() - results[govv1.OptionAbstain] = sdk.ZeroDec() - results[govv1.OptionNo] = sdk.ZeroDec() - results[govv1.OptionNoWithVeto] = sdk.ZeroDec() - - totalVotingPower := sdk.ZeroDec() - currValidators := make(map[string]govv1.ValidatorGovInfo) - - // fetch all the bonded validators, insert them into currValidators - th.stk.IterateBondedValidatorsByPower(ctx, func(index int64, validator stakingtypes.ValidatorI) (stop bool) { - currValidators[validator.GetOperator().String()] = govv1.NewValidatorGovInfo( - validator.GetOperator(), - validator.GetBondedTokens(), - validator.GetDelegatorShares(), - sdk.ZeroDec(), - govv1.WeightedVoteOptions{}, - ) - - return false - }) - - th.gk.IterateVotes(ctx, proposal.Id, func(vote govv1.Vote) bool { - // if validator, just record it in the map - voter, err := sdk.AccAddressFromBech32(vote.Voter) - - if err != nil { - panic(err) - } - - valAddrStr := sdk.ValAddress(voter.Bytes()).String() - if val, ok := currValidators[valAddrStr]; ok { - val.Vote = vote.Options - currValidators[valAddrStr] = val - } - - // iterate over all delegations from voter, deduct from any delegated-to validators - th.stk.IterateDelegations(ctx, voter, func(index int64, delegation stakingtypes.DelegationI) (stop bool) { - valAddrStr := delegation.GetValidatorAddr().String() - - if val, ok := currValidators[valAddrStr]; ok { - // There is no need to handle the special case that validator address equal to voter address. - // Because voter's voting power will tally again even if there will deduct voter's voting power from validator. - val.DelegatorDeductions = val.DelegatorDeductions.Add(delegation.GetShares()) - currValidators[valAddrStr] = val - - // delegation shares * bonded / total shares - votingPower := delegation.GetShares().MulInt(val.BondedTokens).Quo(val.DelegatorShares) - - for _, option := range vote.Options { - subPower := votingPower.Mul(sdk.MustNewDecFromStr(option.Weight)) - results[option.Option] = results[option.Option].Add(subPower) - } - totalVotingPower = totalVotingPower.Add(votingPower) - } - - return false - }) - - // get voter bkava and update total voting power and results - addrBkava := th.getAddrBkava(ctx, voter).toCoins() - for _, coin := range addrBkava { - valAddr, err := liquidtypes.ParseLiquidStakingTokenDenom(coin.Denom) - if err != nil { - break - } - - // reduce delegator shares by the amount of voter bkava for the validator - valAddrStr := valAddr.String() - if val, ok := currValidators[valAddrStr]; ok { - val.DelegatorDeductions = val.DelegatorDeductions.Add(sdk.NewDecFromInt(coin.Amount)) - currValidators[valAddrStr] = val - } - - // votingPower = amount of ukava coin - stakedCoins, err := th.lk.GetStakedTokensForDerivatives(ctx, sdk.NewCoins(coin)) - if err != nil { - // error is returned only if the bkava denom is incorrect, which should never happen here. - panic(err) - } - votingPower := sdk.NewDecFromInt(stakedCoins.Amount) - - for _, option := range vote.Options { - subPower := votingPower.Mul(sdk.MustNewDecFromStr(option.Weight)) - results[option.Option] = results[option.Option].Add(subPower) - } - totalVotingPower = totalVotingPower.Add(votingPower) - } - - th.gk.DeleteVote(ctx, vote.ProposalId, voter) - return false - }) - - // iterate over the validators again to tally their voting power - for _, val := range currValidators { - if len(val.Vote) == 0 { - continue - } - - sharesAfterDeductions := val.DelegatorShares.Sub(val.DelegatorDeductions) - votingPower := sharesAfterDeductions.MulInt(val.BondedTokens).Quo(val.DelegatorShares) - - for _, option := range val.Vote { - subPower := votingPower.Mul(sdk.MustNewDecFromStr(option.Weight)) - results[option.Option] = results[option.Option].Add(subPower) - } - totalVotingPower = totalVotingPower.Add(votingPower) - } - - tallyParams := th.gk.GetParams(ctx) - tallyResults = govv1.NewTallyResultFromMap(results) - - // TODO: Upgrade the spec to cover all of these cases & remove pseudocode. - // If there is no staked coins, the proposal fails - if th.stk.TotalBondedTokens(ctx).IsZero() { - return false, false, tallyResults - } - - // If there is not enough quorum of votes, the proposal fails - percentVoting := totalVotingPower.Quo(sdk.NewDecFromInt(th.stk.TotalBondedTokens(ctx))) - if percentVoting.LT(sdk.MustNewDecFromStr(tallyParams.Quorum)) { - return false, tallyParams.BurnVoteQuorum, tallyResults - } - - // If no one votes (everyone abstains), proposal fails - if totalVotingPower.Sub(results[govv1.OptionAbstain]).Equal(sdk.ZeroDec()) { - return false, false, tallyResults - } - - // If more than 1/3 of voters veto, proposal fails - if results[govv1.OptionNoWithVeto].Quo(totalVotingPower).GT(sdk.MustNewDecFromStr(tallyParams.VetoThreshold)) { - return false, tallyParams.BurnVoteVeto, tallyResults - } - - // If more than 1/2 of non-abstaining voters vote Yes, proposal passes - if results[govv1.OptionYes].Quo(totalVotingPower.Sub(results[govv1.OptionAbstain])).GT(sdk.MustNewDecFromStr(tallyParams.Threshold)) { - return true, false, tallyResults - } - - // If more than 1/2 of non-abstaining voters vote No, proposal fails - return false, false, tallyResults -} - -// bkavaByDenom a map of the bkava denom and the amount of bkava for that denom. -type bkavaByDenom map[string]sdkmath.Int - -func (bkavaMap bkavaByDenom) add(coin sdk.Coin) { - _, found := bkavaMap[coin.Denom] - if !found { - bkavaMap[coin.Denom] = sdk.ZeroInt() - } - bkavaMap[coin.Denom] = bkavaMap[coin.Denom].Add(coin.Amount) -} - -func (bkavaMap bkavaByDenom) toCoins() sdk.Coins { - coins := sdk.Coins{} - for denom, amt := range bkavaMap { - coins = coins.Add(sdk.NewCoin(denom, amt)) - } - return coins.Sort() -} - -// getAddrBkava returns a map of validator address & the amount of bkava -// of the addr for each validator. -func (th TallyHandler) getAddrBkava(ctx sdk.Context, addr sdk.AccAddress) bkavaByDenom { - results := make(bkavaByDenom) - th.addBkavaFromWallet(ctx, addr, results) - th.addBkavaFromSavings(ctx, addr, results) - th.addBkavaFromEarn(ctx, addr, results) - return results -} - -// addBkavaFromWallet adds all addr balances of bkava in x/bank. -func (th TallyHandler) addBkavaFromWallet(ctx sdk.Context, addr sdk.AccAddress, bkava bkavaByDenom) { - coins := th.bk.GetAllBalances(ctx, addr) - for _, coin := range coins { - if th.lk.IsDerivativeDenom(ctx, coin.Denom) { - bkava.add(coin) - } - } -} - -// addBkavaFromSavings adds all addr deposits of bkava in x/savings. -func (th TallyHandler) addBkavaFromSavings(ctx sdk.Context, addr sdk.AccAddress, bkava bkavaByDenom) { - deposit, found := th.svk.GetDeposit(ctx, addr) - if !found { - return - } - for _, coin := range deposit.Amount { - if th.lk.IsDerivativeDenom(ctx, coin.Denom) { - bkava.add(coin) - } - } -} - -// addBkavaFromEarn adds all addr deposits of bkava in x/earn. -func (th TallyHandler) addBkavaFromEarn(ctx sdk.Context, addr sdk.AccAddress, bkava bkavaByDenom) { - shares, found := th.ek.GetVaultAccountShares(ctx, addr) - if !found { - return - } - for _, share := range shares { - if th.lk.IsDerivativeDenom(ctx, share.Denom) { - if coin, err := th.ek.ConvertToAssets(ctx, share); err == nil { - bkava.add(coin) - } - } - } -} diff --git a/app/tally_handler_test.go b/app/tally_handler_test.go deleted file mode 100644 index 42344562..00000000 --- a/app/tally_handler_test.go +++ /dev/null @@ -1,415 +0,0 @@ -package app - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" - govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - - earntypes "github.com/kava-labs/kava/x/earn/types" - liquidtypes "github.com/kava-labs/kava/x/liquid/types" -) - -// d is an alias for sdk.MustNewDecFromStr -var d = sdk.MustNewDecFromStr - -type tallyHandlerSuite struct { - suite.Suite - app TestApp - ctx sdk.Context - - staking stakingHelper - - tallier TallyHandler -} - -func TestTallyHandlerSuite(t *testing.T) { - suite.Run(t, new(tallyHandlerSuite)) -} - -func (suite *tallyHandlerSuite) SetupTest() { - suite.app = NewTestApp() - suite.app.InitializeFromGenesisStates() - genesisTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.app.NewContext(false, tmproto.Header{Height: 1, Time: genesisTime}) - - stakingKeeper := *suite.app.GetStakingKeeper() - suite.staking = stakingHelper{stakingKeeper} - suite.staking.setBondDenom(suite.ctx, "ukava") - - suite.tallier = NewTallyHandler( - suite.app.GetGovKeeper(), - stakingKeeper, - suite.app.GetSavingsKeeper(), - suite.app.GetEarnKeeper(), - suite.app.GetLiquidKeeper(), - suite.app.GetBankKeeper(), - ) -} - -func (suite *tallyHandlerSuite) TestVotePower_AllSourcesCounted() { - user := suite.createAccount(suite.newBondCoin(sdkmath.NewInt(1e9))) - - validator := suite.delegateToNewBondedValidator(user.GetAddress(), sdkmath.NewInt(1e9)) - - derivatives := suite.mintDerivative(user.GetAddress(), validator.GetOperator(), sdkmath.NewInt(500e6)) - - suite.allowBKavaEarnDeposits() - suite.earnDeposit( - user.GetAddress(), - sdk.NewCoin(derivatives.Denom, sdkmath.NewInt(250e6)), - ) - - proposal := suite.createProposal() - suite.voteOnProposal(user.GetAddress(), proposal.Id, govv1beta1.OptionYes) - - _, _, results := suite.tallier.Tally(suite.ctx, proposal) - suite.Equal(sdkmath.NewInt(500e6+250e6+250e6).String(), results.YesCount) - suite.Equal(sdk.ZeroInt().String(), results.NoCount) - suite.Equal(sdk.ZeroInt().String(), results.NoWithVetoCount) - suite.Equal(sdk.ZeroInt().String(), results.AbstainCount) -} - -func (suite *tallyHandlerSuite) TestVotePower_UserOverridesValidator() { - user := suite.createAccount(suite.newBondCoin(sdkmath.NewInt(1e9))) - - delegated := sdkmath.NewInt(1e9) - validator := suite.delegateToNewBondedValidator(user.GetAddress(), delegated) - selfDelegated := validator.GetTokens().Sub(delegated) - - derivatives := suite.mintDerivative(user.GetAddress(), validator.GetOperator(), sdkmath.NewInt(500e6)) - - suite.allowBKavaEarnDeposits() - suite.earnDeposit( - user.GetAddress(), - sdk.NewCoin(derivatives.Denom, sdkmath.NewInt(250e6)), - ) - - proposal := suite.createProposal() - - // Validator votes, inheriting user's stake and bkava. - suite.voteOnProposal(validator.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionYes) - - // use wrapped context to discard the state changes - readOnlyCtx, _ := suite.ctx.CacheContext() - _, _, results := suite.tallier.Tally(readOnlyCtx, proposal) - userPower := sdkmath.NewInt(500e6 + 250e6 + 250e6) - suite.Equal( - selfDelegated.Add(userPower).String(), - results.YesCount, - ) - suite.Equal(sdk.ZeroInt().String(), results.NoCount) - suite.Equal(sdk.ZeroInt().String(), results.NoWithVetoCount) - suite.Equal(sdk.ZeroInt().String(), results.AbstainCount) - - // User votes, taking power away from validator. - suite.voteOnProposal(user.GetAddress(), proposal.Id, govv1beta1.OptionNo) - - _, _, results = suite.tallier.Tally(suite.ctx, proposal) - suite.Equal(selfDelegated.String(), results.YesCount) - suite.Equal(userPower.String(), results.NoCount) - suite.Equal(sdk.ZeroInt().String(), results.NoWithVetoCount) - suite.Equal(sdk.ZeroInt().String(), results.AbstainCount) -} - -func (suite *tallyHandlerSuite) TestTallyOutcomes() { - suite.Run("VotedPowerBelowQuorumFails", func() { - suite.SetupTest() - suite.setTallyParams(d("0.4"), d("0.5"), d("0.334")) - proposal := suite.createProposal() - - v1 := suite.createNewBondedValidator(sdkmath.NewInt(399_999_999)) - suite.createNewBondedValidator(sdkmath.NewInt(600_000_001)) - - suite.voteOnProposal(v1.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionYes) - - passes, burns, tally := suite.tallier.Tally(suite.ctx, proposal) - suite.Falsef(passes, "expected proposal to fail, tally: %v", tally) - suite.Truef(burns, "expected desposit to be burned, tally: %v", tally) - }) - suite.Run("VetoedFails", func() { - suite.SetupTest() - suite.setTallyParams(d("0.4"), d("0.5"), d("0.334")) - proposal := suite.createProposal() - - v1 := suite.createNewBondedValidator(sdkmath.NewInt(334_000_001)) - v2 := suite.createNewBondedValidator(sdkmath.NewInt(665_999_999)) - - suite.voteOnProposal(v1.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionNoWithVeto) - suite.voteOnProposal(v2.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionYes) - - passes, burns, tally := suite.tallier.Tally(suite.ctx, proposal) - suite.Falsef(passes, "expected proposal to fail, tally: %v", tally) - suite.Truef(burns, "expected desposit to be burned, tally: %v", tally) - }) - suite.Run("UnvetoedAndYesAboveThresholdPasses", func() { - suite.SetupTest() - suite.setTallyParams(d("0.4"), d("0.5"), d("0.334")) - proposal := suite.createProposal() - - v1 := suite.createNewBondedValidator(sdkmath.NewInt(900_000_000)) - v2 := suite.createNewBondedValidator(sdkmath.NewInt(50_000_001)) - v3 := suite.createNewBondedValidator(sdkmath.NewInt(49_999_999)) - - suite.voteOnProposal(v1.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionAbstain) - suite.voteOnProposal(v2.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionYes) - suite.voteOnProposal(v3.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionNo) - - passes, burns, tally := suite.tallier.Tally(suite.ctx, proposal) - suite.Truef(passes, "expected proposal to pass, tally: %v", tally) - suite.Falsef(burns, "expected desposit to not burn, tally: %v", tally) - }) - suite.Run("UnvetoedAndYesBelowThresholdFails", func() { - suite.SetupTest() - suite.setTallyParams(d("0.4"), d("0.5"), d("0.334")) - proposal := suite.createProposal() - - v1 := suite.createNewBondedValidator(sdkmath.NewInt(900_000_000)) - v2 := suite.createNewBondedValidator(sdkmath.NewInt(49_999_999)) - v3 := suite.createNewBondedValidator(sdkmath.NewInt(50_000_001)) - - suite.voteOnProposal(v1.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionAbstain) - suite.voteOnProposal(v2.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionYes) - suite.voteOnProposal(v3.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionNo) - - passes, burns, tally := suite.tallier.Tally(suite.ctx, proposal) - suite.Falsef(passes, "expected proposal to pass, tally: %v", tally) - suite.Falsef(burns, "expected desposit to not burn, tally: %v", tally) - }) - suite.Run("NotEnoughStakeFails", func() { - suite.SetupTest() - suite.setTallyParams(d("0.4"), d("0.5"), d("0.334")) - proposal := suite.createProposal() - - // no stake - suite.app.DeleteGenesisValidator(suite.T(), suite.ctx) - - passes, burns, tally := suite.tallier.Tally(suite.ctx, proposal) - suite.Falsef(passes, "expected proposal to pass, tally: %v", tally) - suite.Falsef(burns, "expected desposit to not burn, tally: %v", tally) - }) - suite.Run("UnvetoedAndAllAbstainedFails", func() { - suite.SetupTest() - suite.setTallyParams(d("0.4"), d("0.5"), d("0.334")) - proposal := suite.createProposal() - - v1 := suite.createNewBondedValidator(sdkmath.NewInt(1e9)) - - suite.voteOnProposal(v1.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionAbstain) - - passes, burns, tally := suite.tallier.Tally(suite.ctx, proposal) - suite.Falsef(passes, "expected proposal to pass, tally: %v", tally) - suite.Falsef(burns, "expected desposit to not burn, tally: %v", tally) - }) - -} - -func (suite *tallyHandlerSuite) setTallyParams(quorum, threshold, veto sdk.Dec) { - params := suite.app.GetGovKeeper().GetParams(suite.ctx) - params.Quorum = quorum.String() - params.Threshold = threshold.String() - params.VetoThreshold = veto.String() - params.BurnVoteQuorum = true - suite.app.GetGovKeeper().SetParams(suite.ctx, params) -} - -func (suite *tallyHandlerSuite) voteOnProposal( - voter sdk.AccAddress, - proposalID uint64, - option govv1beta1.VoteOption, -) { - gk := suite.app.GetGovKeeper() - - err := gk.AddVote(suite.ctx, - proposalID, - voter, - govv1.NewNonSplitVoteOption(govv1.VoteOption(option)), - "", - ) - suite.Require().NoError(err) -} - -func (suite *tallyHandlerSuite) createProposal() govv1.Proposal { - gk := suite.app.GetGovKeeper() - deposit := gk.GetParams(suite.ctx).MinDeposit - proposer := suite.createAccount(deposit...) - - msg, err := govv1beta1.NewMsgSubmitProposal( - govv1beta1.NewTextProposal("a title", "a description"), - deposit, - proposer.GetAddress(), - ) - suite.Require().NoError(err) - - msgServerv1 := govkeeper.NewMsgServerImpl(&gk) - - govAcct := gk.GetGovernanceAccount(suite.ctx).GetAddress() - msgServer := govkeeper.NewLegacyMsgServerImpl(govAcct.String(), msgServerv1) - res, err := msgServer.SubmitProposal(sdk.WrapSDKContext(suite.ctx), msg) - suite.Require().NoError(err) - - proposal, found := gk.GetProposal(suite.ctx, res.ProposalId) - if !found { - panic("proposal not found") - } - return proposal -} - -func (suite *tallyHandlerSuite) newBondCoin(amount sdkmath.Int) sdk.Coin { - return suite.staking.newBondCoin(suite.ctx, amount) -} - -func (suite *tallyHandlerSuite) allowBKavaEarnDeposits() { - ek := suite.app.GetEarnKeeper() - earnParams := ek.GetParams(suite.ctx) - - vault := earntypes.NewAllowedVault( - liquidtypes.DefaultDerivativeDenom, - earntypes.StrategyTypes{earntypes.STRATEGY_TYPE_SAVINGS}, - false, - nil, - ) - - earnParams.AllowedVaults = append(earnParams.AllowedVaults, vault) - ek.SetParams(suite.ctx, earnParams) - - sk := suite.app.GetSavingsKeeper() - savingsParams := sk.GetParams(suite.ctx) - savingsParams.SupportedDenoms = append(savingsParams.SupportedDenoms, liquidtypes.DefaultDerivativeDenom) - sk.SetParams(suite.ctx, savingsParams) -} - -func (suite *tallyHandlerSuite) earnDeposit(owner sdk.AccAddress, derivative sdk.Coin) { - ek := suite.app.GetEarnKeeper() - - err := ek.Deposit(suite.ctx, owner, derivative, earntypes.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) -} - -func (suite *tallyHandlerSuite) mintDerivative(owner sdk.AccAddress, validator sdk.ValAddress, amount sdkmath.Int) sdk.Coin { - lk := suite.app.GetLiquidKeeper() - - minted, err := lk.MintDerivative(suite.ctx, owner, validator, suite.newBondCoin(amount)) - suite.Require().NoError(err) - - return minted -} - -func (suite *tallyHandlerSuite) delegateToNewBondedValidator(delegator sdk.AccAddress, amount sdkmath.Int) stakingtypes.ValidatorI { - valAcc := suite.createAccount(suite.newBondCoin(sdkmath.NewInt(1e9))) - validator, err := suite.staking.createUnbondedValidator(suite.ctx, valAcc.GetAddress().Bytes(), sdkmath.NewInt(1e9)) - suite.Require().NoError(err) - - _, err = suite.staking.delegate(suite.ctx, delegator, validator.GetOperator(), amount) - suite.Require().NoError(err) - - // bond the validator - sk := suite.app.GetStakingKeeper() - staking.EndBlocker(suite.ctx, sk) - - validator, found := sk.GetValidator(suite.ctx, validator.GetOperator()) - if !found { - panic("validator not found") - } - return validator -} - -func (suite *tallyHandlerSuite) createNewBondedValidator(selfDelegation sdkmath.Int) stakingtypes.ValidatorI { - valAcc := suite.createAccount(suite.newBondCoin(selfDelegation)) - validator, err := suite.staking.createUnbondedValidator(suite.ctx, valAcc.GetAddress().Bytes(), selfDelegation) - suite.Require().NoError(err) - - // bond the validator - sk := suite.app.GetStakingKeeper() - staking.EndBlocker(suite.ctx, sk) - - validator, found := sk.GetValidator(suite.ctx, validator.GetOperator()) - if !found { - panic("validator not found") - } - return validator -} - -func (suite *tallyHandlerSuite) createAccount(initialBalance ...sdk.Coin) authtypes.AccountI { - ak := suite.app.GetAccountKeeper() - - acc := ak.NewAccountWithAddress(suite.ctx, RandomAddress()) - ak.SetAccount(suite.ctx, acc) - - err := suite.app.FundAccount(suite.ctx, acc.GetAddress(), initialBalance) - suite.Require().NoError(err) - - return acc -} - -// stakingHelper wraps the staking keeper with helper functions for testing. -type stakingHelper struct { - keeper stakingkeeper.Keeper -} - -func (h stakingHelper) createUnbondedValidator(ctx sdk.Context, address sdk.ValAddress, selfDelegation sdkmath.Int) (stakingtypes.ValidatorI, error) { - msg, err := stakingtypes.NewMsgCreateValidator( - address, - ed25519.GenPrivKey().PubKey(), - h.newBondCoin(ctx, selfDelegation), - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - sdkmath.NewInt(1e6), - ) - if err != nil { - return nil, err - } - - msgServer := stakingkeeper.NewMsgServerImpl(&h.keeper) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(ctx), msg) - if err != nil { - return nil, err - } - - validator, found := h.keeper.GetValidator(ctx, address) - if !found { - panic("validator not found") - } - return validator, nil -} - -func (h stakingHelper) delegate(ctx sdk.Context, delegator sdk.AccAddress, validator sdk.ValAddress, amount sdkmath.Int) (sdk.Dec, error) { - msg := stakingtypes.NewMsgDelegate( - delegator, - validator, - h.newBondCoin(ctx, amount), - ) - - msgServer := stakingkeeper.NewMsgServerImpl(&h.keeper) - _, err := msgServer.Delegate(sdk.WrapSDKContext(ctx), msg) - if err != nil { - return sdk.Dec{}, err - } - - del, found := h.keeper.GetDelegation(ctx, delegator, validator) - if !found { - panic("delegation not found") - } - return del.Shares, nil -} - -func (h stakingHelper) newBondCoin(ctx sdk.Context, amount sdkmath.Int) sdk.Coin { - return sdk.NewCoin(h.keeper.BondDenom(ctx), amount) -} - -func (h stakingHelper) setBondDenom(ctx sdk.Context, denom string) { - params := h.keeper.GetParams(ctx) - params.BondDenom = denom - h.keeper.SetParams(ctx, params) -} diff --git a/app/test_common.go b/app/test_common.go index 725a245c..c859cd6e 100644 --- a/app/test_common.go +++ b/app/test_common.go @@ -41,22 +41,8 @@ import ( feemarketkeeper "github.com/evmos/ethermint/x/feemarket/keeper" "github.com/stretchr/testify/require" - auctionkeeper "github.com/kava-labs/kava/x/auction/keeper" - bep3keeper "github.com/kava-labs/kava/x/bep3/keeper" - cdpkeeper "github.com/kava-labs/kava/x/cdp/keeper" - committeekeeper "github.com/kava-labs/kava/x/committee/keeper" - communitykeeper "github.com/kava-labs/kava/x/community/keeper" - earnkeeper "github.com/kava-labs/kava/x/earn/keeper" - evmutilkeeper "github.com/kava-labs/kava/x/evmutil/keeper" - hardkeeper "github.com/kava-labs/kava/x/hard/keeper" - incentivekeeper "github.com/kava-labs/kava/x/incentive/keeper" - issuancekeeper "github.com/kava-labs/kava/x/issuance/keeper" - kavadistkeeper "github.com/kava-labs/kava/x/kavadist/keeper" - liquidkeeper "github.com/kava-labs/kava/x/liquid/keeper" - pricefeedkeeper "github.com/kava-labs/kava/x/pricefeed/keeper" - routerkeeper "github.com/kava-labs/kava/x/router/keeper" - savingskeeper "github.com/kava-labs/kava/x/savings/keeper" - swapkeeper "github.com/kava-labs/kava/x/swap/keeper" + "github.com/0glabs/0g-chain/chaincfg" + evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper" ) var ( @@ -64,7 +50,7 @@ var ( defaultInitialHeight int64 = 1 ) -const TestChainId = "kavatest_2221-1" +const TestChainId = "0gchaintest_2221-1" // TestApp is a simple wrapper around an App. It exposes internal keepers for use in integration tests. // This file also contains test helpers. Ideally they would be in separate package. @@ -89,7 +75,7 @@ type TestApp struct { // // Note, it also sets the sdk config with the app's address prefix, coin type, etc. func NewTestApp() TestApp { - SetSDKConfig() + chaincfg.SetSDKConfig() return NewTestAppFromSealed() } @@ -101,7 +87,7 @@ func NewTestAppFromSealed() TestApp { encCfg := MakeEncodingConfig() app := NewApp( - log.NewNopLogger(), db, DefaultNodeHome, nil, + log.NewNopLogger(), db, chaincfg.DefaultNodeHome, nil, encCfg, DefaultOptions, baseapp.SetChainID(TestChainId), ) return TestApp{App: *app} @@ -117,24 +103,11 @@ func (tApp TestApp) GetDistrKeeper() distkeeper.Keeper { return tApp.di func (tApp TestApp) GetGovKeeper() govkeeper.Keeper { return tApp.govKeeper } func (tApp TestApp) GetCrisisKeeper() crisiskeeper.Keeper { return tApp.crisisKeeper } func (tApp TestApp) GetParamsKeeper() paramskeeper.Keeper { return tApp.paramsKeeper } -func (tApp TestApp) GetKavadistKeeper() kavadistkeeper.Keeper { return tApp.kavadistKeeper } -func (tApp TestApp) GetAuctionKeeper() auctionkeeper.Keeper { return tApp.auctionKeeper } -func (tApp TestApp) GetIssuanceKeeper() issuancekeeper.Keeper { return tApp.issuanceKeeper } -func (tApp TestApp) GetBep3Keeper() bep3keeper.Keeper { return tApp.bep3Keeper } -func (tApp TestApp) GetPriceFeedKeeper() pricefeedkeeper.Keeper { return tApp.pricefeedKeeper } -func (tApp TestApp) GetSwapKeeper() swapkeeper.Keeper { return tApp.swapKeeper } -func (tApp TestApp) GetCDPKeeper() cdpkeeper.Keeper { return tApp.cdpKeeper } -func (tApp TestApp) GetHardKeeper() hardkeeper.Keeper { return tApp.hardKeeper } -func (tApp TestApp) GetCommitteeKeeper() committeekeeper.Keeper { return tApp.committeeKeeper } -func (tApp TestApp) GetIncentiveKeeper() incentivekeeper.Keeper { return tApp.incentiveKeeper } -func (tApp TestApp) GetEvmutilKeeper() evmutilkeeper.Keeper { return tApp.evmutilKeeper } -func (tApp TestApp) GetEvmKeeper() *evmkeeper.Keeper { return tApp.evmKeeper } -func (tApp TestApp) GetSavingsKeeper() savingskeeper.Keeper { return tApp.savingsKeeper } + +func (tApp TestApp) GetEvmutilKeeper() evmutilkeeper.Keeper { return tApp.evmutilKeeper } +func (tApp TestApp) GetEvmKeeper() *evmkeeper.Keeper { return tApp.evmKeeper } + func (tApp TestApp) GetFeeMarketKeeper() feemarketkeeper.Keeper { return tApp.feeMarketKeeper } -func (tApp TestApp) GetLiquidKeeper() liquidkeeper.Keeper { return tApp.liquidKeeper } -func (tApp TestApp) GetEarnKeeper() earnkeeper.Keeper { return tApp.earnKeeper } -func (tApp TestApp) GetRouterKeeper() routerkeeper.Keeper { return tApp.routerKeeper } -func (tApp TestApp) GetCommunityKeeper() communitykeeper.Keeper { return tApp.communityKeeper } func (tApp TestApp) GetKVStoreKey(key string) *storetypes.KVStoreKey { return tApp.keys[key] @@ -174,7 +147,7 @@ func GenesisStateWithSingleValidator( balances := []banktypes.Balance{ { Address: acc.GetAddress().String(), - Coins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100000000000000))), + Coins: sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(100000000000000))), }, } @@ -237,7 +210,7 @@ func genesisStateWithValSet( } // set validators and delegations currentStakingGenesis := stakingtypes.GetGenesisStateFromAppState(app.appCodec, genesisState) - currentStakingGenesis.Params.BondDenom = "ukava" + currentStakingGenesis.Params.BondDenom = chaincfg.DisplayDenom stakingGenesis := stakingtypes.NewGenesisState( currentStakingGenesis.Params, @@ -257,13 +230,13 @@ func genesisStateWithValSet( for range delegations { // add delegated tokens to total supply - totalSupply = totalSupply.Add(sdk.NewCoin("ukava", bondAmt)) + totalSupply = totalSupply.Add(sdk.NewCoin(chaincfg.DisplayDenom, bondAmt)) } // add bonded amount to bonded pool module account balances = append(balances, banktypes.Balance{ Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), - Coins: sdk.Coins{sdk.NewCoin("ukava", bondAmt)}, + Coins: sdk.Coins{sdk.NewCoin(chaincfg.DisplayDenom, bondAmt)}, }) bankGenesis := banktypes.NewGenesisState( diff --git a/build/proto.mk b/build/proto.mk index 8a9a924c..c8cde8ff 100644 --- a/build/proto.mk +++ b/build/proto.mk @@ -7,7 +7,7 @@ proto-lint check-proto-lint: install-build-deps proto-gen: install-build-deps @echo "Generating go proto files" @$(BUF) generate --template proto/buf.gen.gogo.yaml proto - @cp -r out/github.com/kava-labs/kava/* ./ + @cp -r out/github.com/0glabs/0g-chain/* ./ @rm -rf out/github.com .PHONY: check-proto-gen diff --git a/chaincfg/coin.go b/chaincfg/coin.go new file mode 100644 index 00000000..05cf16ab --- /dev/null +++ b/chaincfg/coin.go @@ -0,0 +1,22 @@ +package chaincfg + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var ( + // Bip44CoinType satisfies EIP84. See https://github.com/ethereum/EIPs/issues/84 for more info. + Bip44CoinType uint32 = 459 // TODO: need new coin type for 0g-chain (a0gi) + // eth = 60 + // kava = 459 // see https://github.com/satoshilabs/slips/blob/master/slip-0044.md + // BIP44HDPath is the default BIP44 HD path used on Ethereum. + //BIP44HDPath = ethaccounts.DefaultBaseDerivationPath.String() +) + +// TODO: Implement BIP44CoinType and BIP44HDPath +// SetBip44CoinType sets the global coin type to be used in hierarchical deterministic wallets. +func setBip44CoinType(config *sdk.Config) { + config.SetCoinType(Bip44CoinType) + //config.SetPurpose(sdk.Purpose) // Shared + //config.SetFullFundraiserPath(BIP44HDPath) //nolint: staticcheck +} diff --git a/chaincfg/config.go b/chaincfg/config.go new file mode 100644 index 00000000..88fadbda --- /dev/null +++ b/chaincfg/config.go @@ -0,0 +1,15 @@ +package chaincfg + +import sdk "github.com/cosmos/cosmos-sdk/types" + +const ( + AppName = "0gchain" + EnvPrefix = "0GCHAIN" +) + +func SetSDKConfig() *sdk.Config { + config := sdk.GetConfig() + setBech32Prefixes(config) + setBip44CoinType(config) + return config +} diff --git a/chaincfg/denoms.go b/chaincfg/denoms.go new file mode 100644 index 00000000..d119a2a9 --- /dev/null +++ b/chaincfg/denoms.go @@ -0,0 +1,28 @@ +package chaincfg + +import ( + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +const ( + // DisplayDenom defines the denomination displayed to users in client applications. + DisplayDenom = "a0gi" + // BaseDenom defines to the default denomination used in 0g-chain + BaseDenom = "neuron" + + BaseDenomUnit = 18 + + ConversionMultiplier = 1e18 +) + +// RegisterDenoms registers the base and display denominations to the SDK. +func RegisterDenoms() { + if err := sdk.RegisterDenom(DisplayDenom, math.LegacyOneDec()); err != nil { + panic(err) + } + + if err := sdk.RegisterDenom(BaseDenom, math.LegacyNewDecWithPrec(1, BaseDenomUnit)); err != nil { + panic(err) + } +} diff --git a/chaincfg/homedir.go b/chaincfg/homedir.go new file mode 100644 index 00000000..2a4cb933 --- /dev/null +++ b/chaincfg/homedir.go @@ -0,0 +1,25 @@ +package chaincfg + +import ( + stdlog "log" + "os" + "path/filepath" +) + +const ( + HomeDirName = ".0gchain" +) + +var ( + // DefaultNodeHome default home directories for the application daemon + DefaultNodeHome string +) + +func init() { + userHomeDir, err := os.UserHomeDir() + if err != nil { + stdlog.Printf("Failed to get home dir %v", err) + } + + DefaultNodeHome = filepath.Join(userHomeDir, HomeDirName) +} diff --git a/chaincfg/prefix.go b/chaincfg/prefix.go new file mode 100644 index 00000000..b45c8f6c --- /dev/null +++ b/chaincfg/prefix.go @@ -0,0 +1,44 @@ +package chaincfg + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +const ( + // Bech32Prefix defines the Bech32 prefix used for EthAccounts + Bech32Prefix = "0g" + + // PrefixAccount is the prefix for account keys + PrefixAccount = "acc" + // PrefixValidator is the prefix for validator keys + PrefixValidator = "val" + // PrefixConsensus is the prefix for consensus keys + PrefixConsensus = "cons" + // PrefixPublic is the prefix for public keys + PrefixPublic = "pub" + // PrefixOperator is the prefix for operator keys + PrefixOperator = "oper" + + // PrefixAddress is the prefix for addresses + PrefixAddress = "addr" + + // Bech32PrefixAccAddr defines the Bech32 prefix of an account's address + Bech32PrefixAccAddr = Bech32Prefix + // Bech32PrefixAccPub defines the Bech32 prefix of an account's public key + Bech32PrefixAccPub = Bech32Prefix + PrefixPublic + // Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address + Bech32PrefixValAddr = Bech32Prefix + PrefixValidator + PrefixOperator + // Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key + Bech32PrefixValPub = Bech32Prefix + PrefixValidator + PrefixOperator + PrefixPublic + // Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address + Bech32PrefixConsAddr = Bech32Prefix + PrefixValidator + PrefixConsensus + // Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key + Bech32PrefixConsPub = Bech32Prefix + PrefixValidator + PrefixConsensus + PrefixPublic +) + +// setBech32Prefixes sets the global prefixes to be used when serializing addresses and public keys to Bech32 strings. +func setBech32Prefixes(config *sdk.Config) { + config.SetBech32PrefixForAccount(Bech32PrefixAccAddr, Bech32PrefixAccPub) + config.SetBech32PrefixForValidator(Bech32PrefixValAddr, Bech32PrefixValPub) + config.SetBech32PrefixForConsensusNode(Bech32PrefixConsAddr, Bech32PrefixConsPub) +} diff --git a/cli_test/cli_test.go b/cli_test/cli_test.go index 8d16f50c..c5c504fd 100644 --- a/cli_test/cli_test.go +++ b/cli_test/cli_test.go @@ -62,36 +62,36 @@ func TestKvCLIKeysAddRecover(t *testing.T) { exitSuccess, _, _ = f.KeysAddRecover("test-recover", "dentist task convince chimney quality leave banana trade firm crawl eternal easily") require.True(t, exitSuccess) - require.Equal(t, "kava1rsjxn2e4dfl3a2qzuzzjvvgjmmate383g9q4cz", f.KeyAddress("test-recover").String()) + require.Equal(t, "0g1rsjxn2e4dfl3a2qzuzzjvvgjmmate383g9q4cz", f.KeyAddress("test-recover").String()) // test old bip44 coin type exitSuccess, _, _ = f.KeysAddRecover("test-recover-legacy", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", "--legacy-hd-path") require.True(t, exitSuccess) - require.Equal(t, "kava1qcfdf69js922qrdr4yaww3ax7gjml6pd39p8lj", f.KeyAddress("test-recover-legacy").String()) + require.Equal(t, "0g1qcfdf69js922qrdr4yaww3ax7gjml6pd39p8lj", f.KeyAddress("test-recover-legacy").String()) // Cleanup testing directories f.Cleanup() } -func TestKavaCLIKeysAddRecoverHDPath(t *testing.T) { +func TestZgChainCLIKeysAddRecoverHDPath(t *testing.T) { t.Parallel() f := InitFixtures(t) f.KeysAddRecoverHDPath("test-recoverHD1", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 0, 0) - require.Equal(t, "kava1rsjxn2e4dfl3a2qzuzzjvvgjmmate383g9q4cz", f.KeyAddress("test-recoverHD1").String()) + require.Equal(t, "0g1rsjxn2e4dfl3a2qzuzzjvvgjmmate383g9q4cz", f.KeyAddress("test-recoverHD1").String()) f.KeysAddRecoverHDPath("test-recoverH2", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 1, 5) - require.Equal(t, "kava1qpj6nstqn0n5gzcsaezspuhulje6msjq5t8cq5", f.KeyAddress("test-recoverH2").String()) + require.Equal(t, "0g1qpj6nstqn0n5gzcsaezspuhulje6msjq5t8cq5", f.KeyAddress("test-recoverH2").String()) f.KeysAddRecoverHDPath("test-recoverH3", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 1, 17) - require.Equal(t, "kava1vayfpstgapt7dmv7074kc3ll8xpf0rlzvh4k08", f.KeyAddress("test-recoverH3").String()) + require.Equal(t, "0g1vayfpstgapt7dmv7074kc3ll8xpf0rlzvh4k08", f.KeyAddress("test-recoverH3").String()) f.KeysAddRecoverHDPath("test-recoverH4", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 2, 17) - require.Equal(t, "kava1xvsfnksmhr887skcfrm4pe3va54tkmrtw7wyer", f.KeyAddress("test-recoverH4").String()) + require.Equal(t, "0g1xvsfnksmhr887skcfrm4pe3va54tkmrtw7wyer", f.KeyAddress("test-recoverH4").String()) // test old bip44 coin type f.KeysAddRecoverHDPath("test-recoverH5", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 2, 17, "--legacy-hd-path") - require.Equal(t, "kava1v9plmhvyhgxk3th9ydacm7j4z357s3nhhmy0tv", f.KeyAddress("test-recoverH5").String()) + require.Equal(t, "0g1v9plmhvyhgxk3th9ydacm7j4z357s3nhhmy0tv", f.KeyAddress("test-recoverH5").String()) exitSuccess, _, _ := f.KeysAddRecover("test-recover-fail", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", "--legacy-hd-path --hd-path 44'/459'/0'/0/0") require.False(t, exitSuccess) @@ -99,11 +99,11 @@ func TestKavaCLIKeysAddRecoverHDPath(t *testing.T) { // test -hd-path flag exitSuccess, _, _ = f.KeysAddRecover("test-recoverH6", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", "--hd-path 44'/459'/0'/0/0") require.True(t, exitSuccess) - require.Equal(t, "kava1rsjxn2e4dfl3a2qzuzzjvvgjmmate383g9q4cz", f.KeyAddress("test-recoverH6").String()) + require.Equal(t, "0g1rsjxn2e4dfl3a2qzuzzjvvgjmmate383g9q4cz", f.KeyAddress("test-recoverH6").String()) exitSuccess, _, _ = f.KeysAddRecover("test-recoverH7", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", "--hd-path 44'/459'/2'/0/17") require.True(t, exitSuccess) - require.Equal(t, "kava1xvsfnksmhr887skcfrm4pe3va54tkmrtw7wyer", f.KeyAddress("test-recoverH7").String()) + require.Equal(t, "0g1xvsfnksmhr887skcfrm4pe3va54tkmrtw7wyer", f.KeyAddress("test-recoverH7").String()) // Cleanup testing directories f.Cleanup() diff --git a/cli_test/test_helpers.go b/cli_test/test_helpers.go index 161217f6..be1046f8 100644 --- a/cli_test/test_helpers.go +++ b/cli_test/test_helpers.go @@ -28,7 +28,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/kava-labs/kava/app" + "github.com/0glabs/0g-chain/app" ) const ( @@ -92,7 +92,7 @@ type Fixtures struct { // NewFixtures creates a new instance of Fixtures with many vars set func NewFixtures(t *testing.T) *Fixtures { - tmpDir, err := ioutil.TempDir("", "kava_integration_"+t.Name()+"_") + tmpDir, err := ioutil.TempDir("", "0gchain_integration_"+t.Name()+"_") require.NoError(t, err) servAddr, port, err := server.FreeTCPAddr() @@ -201,9 +201,9 @@ func (f *Fixtures) Flags() string { } //___________________________________________________________________________________ -// kavad +// 0gchaind -// UnsafeResetAll is kavad unsafe-reset-all +// UnsafeResetAll is 0gchaind unsafe-reset-all func (f *Fixtures) UnsafeResetAll(flags ...string) { cmd := fmt.Sprintf("%s --home=%s unsafe-reset-all", f.KvdBinary, f.KvdHome) executeWrite(f.T, addFlags(cmd, flags)) @@ -211,7 +211,7 @@ func (f *Fixtures) UnsafeResetAll(flags ...string) { require.NoError(f.T, err) } -// KvInit is kavad init +// KvInit is 0gchaind init // NOTE: KvInit sets the ChainID for the Fixtures instance func (f *Fixtures) KvInit(moniker string, flags ...string) { cmd := fmt.Sprintf("%s init -o --home=%s %s", f.KvdBinary, f.KvdHome, moniker) @@ -229,25 +229,25 @@ func (f *Fixtures) KvInit(moniker string, flags ...string) { f.ChainID = chainID } -// AddGenesisAccount is kavad add-genesis-account +// AddGenesisAccount is 0gchaind add-genesis-account func (f *Fixtures) AddGenesisAccount(address sdk.AccAddress, coins sdk.Coins, flags ...string) { cmd := fmt.Sprintf("%s add-genesis-account %s %s --home=%s --keyring-backend=test", f.KvdBinary, address, coins, f.KvdHome) executeWriteCheckErr(f.T, addFlags(cmd, flags)) } -// GenTx is kavad gentx +// GenTx is 0gchaind gentx func (f *Fixtures) GenTx(name string, flags ...string) { cmd := fmt.Sprintf("%s gentx --name=%s --home=%s --home-client=%s --keyring-backend=test", f.KvdBinary, name, f.KvdHome, f.KvcliHome) executeWriteCheckErr(f.T, addFlags(cmd, flags)) } -// CollectGenTxs is kavad collect-gentxs +// CollectGenTxs is 0gchaind collect-gentxs func (f *Fixtures) CollectGenTxs(flags ...string) { cmd := fmt.Sprintf("%s collect-gentxs --home=%s", f.KvdBinary, f.KvdHome) executeWriteCheckErr(f.T, addFlags(cmd, flags)) } -// GDStart runs kavad start with the appropriate flags and returns a process +// GDStart runs 0gchaind start with the appropriate flags and returns a process func (f *Fixtures) GDStart(flags ...string) *tests.Process { cmd := fmt.Sprintf("%s start --home=%s --rpc.laddr=%v --p2p.laddr=%v --pruning=everything", f.KvdBinary, f.KvdHome, f.RPCAddr, f.P2PAddr) proc := tests.GoExecuteTWithStdout(f.T, addFlags(cmd, flags)) @@ -256,7 +256,7 @@ func (f *Fixtures) GDStart(flags ...string) *tests.Process { return proc } -// GDTendermint returns the results of kavad tendermint [query] +// GDTendermint returns the results of 0gchaind tendermint [query] func (f *Fixtures) GDTendermint(query string) string { cmd := fmt.Sprintf("%s tendermint %s --home=%s", f.KvdBinary, query, f.KvdHome) success, stdout, stderr := executeWriteRetStdStreams(f.T, cmd) @@ -265,7 +265,7 @@ func (f *Fixtures) GDTendermint(query string) string { return strings.TrimSpace(stdout) } -// ValidateGenesis runs kavad validate-genesis +// ValidateGenesis runs 0gchaind validate-genesis func (f *Fixtures) ValidateGenesis() { cmd := fmt.Sprintf("%s validate-genesis --home=%s", f.KvdBinary, f.KvdHome) executeWriteCheckErr(f.T, cmd) diff --git a/client/docs/legacy-swagger.yml b/client/docs/legacy-swagger.yml index 8e00be70..f83387f1 100644 --- a/client/docs/legacy-swagger.yml +++ b/client/docs/legacy-swagger.yml @@ -2,14 +2,14 @@ swagger: "2.0" info: version: "3.0" - title: Kava Light Client RPC + title: 0g-chain Light Client RPC description: A REST interface for state queries, transaction generation and broadcasting. tags: - name: Vesting description: Validator vesting module APIs schemes: - https -host: api.data.kava.io +host: api.data.0g-chain.io securityDefinitions: kms: type: basic @@ -17,14 +17,14 @@ paths: /vesting/circulatingsupply: get: deprecated: true - summary: Get the current circulating supply of KAVA + summary: Get the current circulating supply of 0g-chain tags: - Vesting produces: - application/json responses: 200: - description: KAVA circulating supply + description: 0g-chain circulating supply schema: properties: height: @@ -38,14 +38,14 @@ paths: /vesting/totalsupply: get: deprecated: true - summary: Get the total supply of KAVA + summary: Get the total supply of 0g-chain tags: - Vesting produces: - application/json responses: 200: - description: KAVA total supply + description: 0g-chain total supply schema: properties: height: diff --git a/client/grpc/README.md b/client/grpc/README.md index e9c1bdd1..c571a7f2 100644 --- a/client/grpc/README.md +++ b/client/grpc/README.md @@ -16,7 +16,7 @@ The Kava gRPC client is a tool for making gRPC queries on a Kava chain. package main import ( - kavaGrpc "github.com/kava-labs/kava/client/grpc" + kavaGrpc "github.com/0glabs/0g-chain/client/grpc" ) grpcUrl := "https://grpc.kava.io:443" client, err := kavaGrpc.NewClient(grpcUrl) @@ -46,7 +46,7 @@ Example: Query Kava module `x/evmutil` for params ```go import ( - evmutiltypes "github.com/kava-labs/kava/x/evmutil/types" + evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types" ) rsp, err := client.Query.Evmutil.Params( diff --git a/client/grpc/client.go b/client/grpc/client.go index 5cb309f1..81a9b666 100644 --- a/client/grpc/client.go +++ b/client/grpc/client.go @@ -3,33 +3,33 @@ package grpc import ( "errors" - "github.com/kava-labs/kava/client/grpc/query" - "github.com/kava-labs/kava/client/grpc/util" + "github.com/0glabs/0g-chain/client/grpc/query" + "github.com/0glabs/0g-chain/client/grpc/util" ) -// KavaGrpcClient enables the usage of kava grpc query clients and query utils -type KavaGrpcClient struct { - config KavaGrpcClientConfig +// ZgChainGrpcClient enables the usage of 0gChain grpc query clients and query utils +type ZgChainGrpcClient struct { + config ZgChainGrpcClientConfig - // Query clients for cosmos and kava modules + // Query clients for cosmos and 0gChain modules Query *query.QueryClient // Utils for common queries (ie fetch an unpacked BaseAccount) *util.Util } -// KavaGrpcClientConfig is a configuration struct for a KavaGrpcClient -type KavaGrpcClientConfig struct { +// ZgChainGrpcClientConfig is a configuration struct for a ZgChainGrpcClient +type ZgChainGrpcClientConfig struct { // note: add future config options here } -// NewClient creates a new KavaGrpcClient via a grpc url -func NewClient(grpcUrl string) (*KavaGrpcClient, error) { +// NewClient creates a new ZgChainGrpcClient via a grpc url +func NewClient(grpcUrl string) (*ZgChainGrpcClient, error) { return NewClientWithConfig(grpcUrl, NewDefaultConfig()) } -// NewClientWithConfig creates a new KavaGrpcClient via a grpc url and config -func NewClientWithConfig(grpcUrl string, config KavaGrpcClientConfig) (*KavaGrpcClient, error) { +// NewClientWithConfig creates a new ZgChainGrpcClient via a grpc url and config +func NewClientWithConfig(grpcUrl string, config ZgChainGrpcClientConfig) (*ZgChainGrpcClient, error) { if grpcUrl == "" { return nil, errors.New("grpc url cannot be empty") } @@ -37,7 +37,7 @@ func NewClientWithConfig(grpcUrl string, config KavaGrpcClientConfig) (*KavaGrpc if error != nil { return nil, error } - client := &KavaGrpcClient{ + client := &ZgChainGrpcClient{ Query: query, Util: util.NewUtil(query), config: config, @@ -45,6 +45,6 @@ func NewClientWithConfig(grpcUrl string, config KavaGrpcClientConfig) (*KavaGrpc return client, nil } -func NewDefaultConfig() KavaGrpcClientConfig { - return KavaGrpcClientConfig{} +func NewDefaultConfig() ZgChainGrpcClientConfig { + return ZgChainGrpcClientConfig{} } diff --git a/client/grpc/client_test.go b/client/grpc/client_test.go index 82b8ae5d..116558d2 100644 --- a/client/grpc/client_test.go +++ b/client/grpc/client_test.go @@ -3,7 +3,7 @@ package grpc_test import ( "testing" - "github.com/kava-labs/kava/client/grpc" + "github.com/0glabs/0g-chain/client/grpc" "github.com/stretchr/testify/require" ) diff --git a/client/grpc/query/doc.go b/client/grpc/query/doc.go index 465e8c79..57b3f316 100644 --- a/client/grpc/query/doc.go +++ b/client/grpc/query/doc.go @@ -1,7 +1,7 @@ /* -The query package includes Cosmos and Kava gRPC query clients. +The query package includes Cosmos and 0gChain gRPC query clients. To ensure that the `QueryClient` stays updated, add new module query clients -to the `QueryClient` whenever new modules with grpc queries are added to the Kava app. +to the `QueryClient` whenever new modules with grpc queries are added to the 0gChain app. */ package query diff --git a/client/grpc/query/query.go b/client/grpc/query/query.go index 8466c5d6..ddbba8bb 100644 --- a/client/grpc/query/query.go +++ b/client/grpc/query/query.go @@ -24,24 +24,12 @@ import ( evmtypes "github.com/evmos/ethermint/x/evm/types" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" - auctiontypes "github.com/kava-labs/kava/x/auction/types" - bep3types "github.com/kava-labs/kava/x/bep3/types" - cdptypes "github.com/kava-labs/kava/x/cdp/types" - committeetypes "github.com/kava-labs/kava/x/committee/types" - communitytypes "github.com/kava-labs/kava/x/community/types" - earntypes "github.com/kava-labs/kava/x/earn/types" - evmutiltypes "github.com/kava-labs/kava/x/evmutil/types" - hardtypes "github.com/kava-labs/kava/x/hard/types" - incentivetypes "github.com/kava-labs/kava/x/incentive/types" - issuancetypes "github.com/kava-labs/kava/x/issuance/types" - kavadisttypes "github.com/kava-labs/kava/x/kavadist/types" - liquidtypes "github.com/kava-labs/kava/x/liquid/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" - savingstypes "github.com/kava-labs/kava/x/savings/types" - swaptypes "github.com/kava-labs/kava/x/swap/types" + committeetypes "github.com/0glabs/0g-chain/x/committee/v1/types" + dastypes "github.com/0glabs/0g-chain/x/das/v1/types" + evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types" ) -// QueryClient is a wrapper with all Cosmos and Kava grpc query clients +// QueryClient is a wrapper with all Cosmos and 0gChain grpc query clients type QueryClient struct { // cosmos-sdk query clients @@ -68,23 +56,11 @@ type QueryClient struct { IbcClient ibcclienttypes.QueryClient IbcTransfer ibctransfertypes.QueryClient - // kava module query clients + // 0g-chain module query clients - Auction auctiontypes.QueryClient - Bep3 bep3types.QueryClient - Cdp cdptypes.QueryClient Committee committeetypes.QueryClient - Community communitytypes.QueryClient - Earn earntypes.QueryClient + Das dastypes.QueryClient Evmutil evmutiltypes.QueryClient - Hard hardtypes.QueryClient - Incentive incentivetypes.QueryClient - Issuance issuancetypes.QueryClient - Kavadist kavadisttypes.QueryClient - Liquid liquidtypes.QueryClient - Pricefeed pricefeedtypes.QueryClient - Savings savingstypes.QueryClient - Swap swaptypes.QueryClient } // NewQueryClient creates a new QueryClient and initializes all the module query clients @@ -115,21 +91,9 @@ func NewQueryClient(grpcEndpoint string) (*QueryClient, error) { IbcClient: ibcclienttypes.NewQueryClient(conn), IbcTransfer: ibctransfertypes.NewQueryClient(conn), - Auction: auctiontypes.NewQueryClient(conn), - Bep3: bep3types.NewQueryClient(conn), - Cdp: cdptypes.NewQueryClient(conn), Committee: committeetypes.NewQueryClient(conn), - Community: communitytypes.NewQueryClient(conn), - Earn: earntypes.NewQueryClient(conn), + Das: dastypes.NewQueryClient(conn), Evmutil: evmutiltypes.NewQueryClient(conn), - Hard: hardtypes.NewQueryClient(conn), - Incentive: incentivetypes.NewQueryClient(conn), - Issuance: issuancetypes.NewQueryClient(conn), - Kavadist: kavadisttypes.NewQueryClient(conn), - Liquid: liquidtypes.NewQueryClient(conn), - Pricefeed: pricefeedtypes.NewQueryClient(conn), - Savings: savingstypes.NewQueryClient(conn), - Swap: swaptypes.NewQueryClient(conn), } return client, nil } diff --git a/client/grpc/query/query_test.go b/client/grpc/query/query_test.go index 86ed9dbc..298ca24c 100644 --- a/client/grpc/query/query_test.go +++ b/client/grpc/query/query_test.go @@ -3,7 +3,7 @@ package query_test import ( "testing" - "github.com/kava-labs/kava/client/grpc/query" + "github.com/0glabs/0g-chain/client/grpc/query" "github.com/stretchr/testify/require" ) @@ -54,21 +54,9 @@ func TestNewQueryClient_ValidClient(t *testing.T) { require.NotNil(t, client.IbcClient) require.NotNil(t, client.IbcTransfer) - // validate kava clients - require.NotNil(t, client.Auction) - require.NotNil(t, client.Bep3) - require.NotNil(t, client.Cdp) - require.NotNil(t, client.Committee) - require.NotNil(t, client.Community) - require.NotNil(t, client.Earn) + // validate 0gChain clients require.NotNil(t, client.Evmutil) - require.NotNil(t, client.Hard) - require.NotNil(t, client.Incentive) - require.NotNil(t, client.Issuance) - require.NotNil(t, client.Kavadist) - require.NotNil(t, client.Liquid) - require.NotNil(t, client.Pricefeed) - require.NotNil(t, client.Savings) - require.NotNil(t, client.Swap) + require.NotNil(t, client.Committee) + require.NotNil(t, client.Das) }) } diff --git a/client/grpc/util/doc.go b/client/grpc/util/doc.go index 2c2acdba..fbc55566 100644 --- a/client/grpc/util/doc.go +++ b/client/grpc/util/doc.go @@ -1,5 +1,5 @@ /* -The util package contains utility functions for the Kava gRPC client. +The util package contains utility functions for the 0gChain gRPC client. For example, `account.go` includes account-related query helpers. In this file, utilities such as `client.Util.BaseAccount(addr)` is exposed to diff --git a/client/grpc/util/util.go b/client/grpc/util/util.go index 0c9c5744..bdb12d68 100644 --- a/client/grpc/util/util.go +++ b/client/grpc/util/util.go @@ -7,12 +7,12 @@ import ( grpctypes "github.com/cosmos/cosmos-sdk/types/grpc" "google.golang.org/grpc/metadata" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/app/params" - query "github.com/kava-labs/kava/client/grpc/query" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/app/params" + query "github.com/0glabs/0g-chain/client/grpc/query" ) -// Util contains utility functions for the Kava gRPC client +// Util contains utility functions for the 0gChain gRPC client type Util struct { query *query.QueryClient encodingConfig params.EncodingConfig diff --git a/client/rest/rest_test.go b/client/rest/rest_test.go index 6de35a45..2e5efde2 100644 --- a/client/rest/rest_test.go +++ b/client/rest/rest_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/require" simappparams "cosmossdk.io/simapp/params" + "github.com/0glabs/0g-chain/client/rest" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" @@ -20,7 +21,6 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/client/rest" ) func TestBaseReq_Sanitize(t *testing.T) { diff --git a/cmd/kava/cmd/app.go b/cmd/0gchaind/app.go similarity index 96% rename from cmd/kava/cmd/app.go rename to cmd/0gchaind/app.go index b4bf2c80..d24743fb 100644 --- a/cmd/kava/cmd/app.go +++ b/cmd/0gchaind/app.go @@ -1,4 +1,4 @@ -package cmd +package main import ( "errors" @@ -23,9 +23,8 @@ import ( "github.com/spf13/cast" "github.com/spf13/cobra" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/app/params" - metricstypes "github.com/kava-labs/kava/x/metrics/types" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/app/params" ) const ( @@ -34,7 +33,7 @@ const ( flagSkipLoadLatest = "skip-load-latest" ) -// appCreator holds functions used by the sdk server to control the kava app. +// appCreator holds functions used by the sdk server to control the 0g-chain app. // The methods implement types in cosmos-sdk/server/types type appCreator struct { encodingConfig params.EncodingConfig @@ -118,7 +117,7 @@ func (ac appCreator) newApp( MempoolAuthAddresses: mempoolAuthAddresses, EVMTrace: cast.ToString(appOpts.Get(ethermintflags.EVMTracer)), EVMMaxGasWanted: cast.ToUint64(appOpts.Get(ethermintflags.EVMMaxTxGasWanted)), - TelemetryOptions: metricstypes.TelemetryOptionsFromAppOpts(appOpts), + // TelemetryOptions: metricstypes.TelemetryOptionsFromAppOpts(appOpts), }, baseapp.SetPruning(pruningOpts), baseapp.SetMinGasPrices(strings.Replace(cast.ToString(appOpts.Get(server.FlagMinGasPrices)), ";", ",", -1)), diff --git a/cmd/kava/cmd/assert-invariants.go b/cmd/0gchaind/assert-invariants.go similarity index 96% rename from cmd/kava/cmd/assert-invariants.go rename to cmd/0gchaind/assert-invariants.go index de4ef717..6a83442e 100644 --- a/cmd/kava/cmd/assert-invariants.go +++ b/cmd/0gchaind/assert-invariants.go @@ -1,4 +1,4 @@ -package cmd +package main import ( "encoding/json" @@ -9,8 +9,8 @@ import ( genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" "github.com/spf13/cobra" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/app/params" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/app/params" ) func AssertInvariantsCmd(config params.EncodingConfig) *cobra.Command { diff --git a/cmd/kava/cmd/genaccounts.go b/cmd/0gchaind/genaccounts.go similarity index 99% rename from cmd/kava/cmd/genaccounts.go rename to cmd/0gchaind/genaccounts.go index 5a5d157f..ef5e920e 100644 --- a/cmd/kava/cmd/genaccounts.go +++ b/cmd/0gchaind/genaccounts.go @@ -1,5 +1,5 @@ // Sourced from https://github.com/evmos/ethermint/blob/main/cmd/ethermintd/genaccounts.go -package cmd +package main import ( "bufio" diff --git a/cmd/kava/cmd/keys.go b/cmd/0gchaind/keys.go similarity index 99% rename from cmd/kava/cmd/keys.go rename to cmd/0gchaind/keys.go index 9d8587c0..3ec6ee0a 100644 --- a/cmd/kava/cmd/keys.go +++ b/cmd/0gchaind/keys.go @@ -1,4 +1,4 @@ -package cmd +package main import ( "bufio" diff --git a/cmd/kava/main.go b/cmd/0gchaind/main.go similarity index 52% rename from cmd/kava/main.go rename to cmd/0gchaind/main.go index 155b5a42..5a1c4cfe 100644 --- a/cmd/kava/main.go +++ b/cmd/0gchaind/main.go @@ -6,14 +6,16 @@ import ( "github.com/cosmos/cosmos-sdk/server" svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/cmd/kava/cmd" + "github.com/0glabs/0g-chain/chaincfg" ) func main() { - rootCmd := cmd.NewRootCmd() + chaincfg.SetSDKConfig().Seal() + chaincfg.RegisterDenoms() - if err := svrcmd.Execute(rootCmd, cmd.EnvPrefix, app.DefaultNodeHome); err != nil { + rootCmd := NewRootCmd() + + if err := svrcmd.Execute(rootCmd, chaincfg.EnvPrefix, chaincfg.DefaultNodeHome); err != nil { switch e := err.(type) { case server.ErrorCode: os.Exit(e.Code) diff --git a/cmd/kava/cmd/query.go b/cmd/0gchaind/query.go similarity index 95% rename from cmd/kava/cmd/query.go rename to cmd/0gchaind/query.go index 8bf5cec9..e8021e99 100644 --- a/cmd/kava/cmd/query.go +++ b/cmd/0gchaind/query.go @@ -1,4 +1,4 @@ -package cmd +package main import ( "github.com/cosmos/cosmos-sdk/client" @@ -7,7 +7,7 @@ import ( authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/spf13/cobra" - "github.com/kava-labs/kava/app" + "github.com/0glabs/0g-chain/app" ) // newQueryCmd creates all the commands for querying blockchain state. diff --git a/cmd/kava/cmd/root.go b/cmd/0gchaind/root.go similarity index 81% rename from cmd/kava/cmd/root.go rename to cmd/0gchaind/root.go index 6b9242e7..575b2d45 100644 --- a/cmd/kava/cmd/root.go +++ b/cmd/0gchaind/root.go @@ -1,4 +1,4 @@ -package cmd +package main import ( "fmt" @@ -23,21 +23,16 @@ import ( servercfg "github.com/evmos/ethermint/server/config" "github.com/spf13/cobra" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/app/params" - "github.com/kava-labs/kava/cmd/kava/cmd/rocksdb" - "github.com/kava-labs/kava/cmd/kava/opendb" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/app/params" + "github.com/0glabs/0g-chain/chaincfg" + "github.com/0glabs/0g-chain/cmd/opendb" + "github.com/0glabs/0g-chain/cmd/rocksdb" ) -// EnvPrefix is the prefix environment variables must have to configure the app. -const EnvPrefix = "KAVA" - -// NewRootCmd creates a new root command for the kava blockchain. +// NewRootCmd creates a new root command for the 0g-chain blockchain. func NewRootCmd() *cobra.Command { - app.SetSDKConfig().Seal() - encodingConfig := app.MakeEncodingConfig() - initClientCtx := client.Context{}. WithCodec(encodingConfig.Marshaler). WithInterfaceRegistry(encodingConfig.InterfaceRegistry). @@ -46,13 +41,12 @@ func NewRootCmd() *cobra.Command { WithInput(os.Stdin). WithAccountRetriever(types.AccountRetriever{}). WithBroadcastMode(flags.FlagBroadcastMode). - WithHomeDir(app.DefaultNodeHome). + WithHomeDir(chaincfg.DefaultNodeHome). WithKeyringOptions(hd.EthSecp256k1Option()). - WithViper(EnvPrefix) - + WithViper(chaincfg.EnvPrefix) rootCmd := &cobra.Command{ - Use: "kava", - Short: "Daemon and CLI for the Kava blockchain.", + Use: chaincfg.AppName, + Short: "Daemon and CLI for the 0g-chain blockchain.", PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { cmd.SetOut(cmd.OutOrStdout()) cmd.SetErr(cmd.ErrOrStderr()) @@ -71,7 +65,7 @@ func NewRootCmd() *cobra.Command { return err } - customAppTemplate, customAppConfig := servercfg.AppConfig("ukava") + customAppTemplate, customAppConfig := servercfg.AppConfig(chaincfg.BaseDenom) return server.InterceptConfigsPreRunHandler( cmd, @@ -82,12 +76,12 @@ func NewRootCmd() *cobra.Command { }, } - addSubCmds(rootCmd, encodingConfig, app.DefaultNodeHome) + addSubCmds(rootCmd, encodingConfig, chaincfg.DefaultNodeHome) return rootCmd } -// addSubCmds registers all the sub commands used by kava. +// addSubCmds registers all the sub commands used by 0g-chain. func addSubCmds(rootCmd *cobra.Command, encodingConfig params.EncodingConfig, defaultNodeHome string) { gentxModule, ok := app.ModuleBasics[genutiltypes.ModuleName].(genutil.AppModuleBasic) if !ok { @@ -116,7 +110,7 @@ func addSubCmds(rootCmd *cobra.Command, encodingConfig params.EncodingConfig, de opts := ethermintserver.StartOptions{ AppCreator: ac.newApp, - DefaultNodeHome: app.DefaultNodeHome, + DefaultNodeHome: chaincfg.DefaultNodeHome, DBOpener: opendb.OpenDB, } // ethermintserver adds additional flags to start the JSON-RPC server for evm support @@ -131,7 +125,7 @@ func addSubCmds(rootCmd *cobra.Command, encodingConfig params.EncodingConfig, de rootCmd.AddCommand( newQueryCmd(), newTxCmd(), - keyCommands(app.DefaultNodeHome), + keyCommands(chaincfg.DefaultNodeHome), rocksdb.RocksDBCmd, newShardCmd(opts), ) diff --git a/cmd/kava/cmd/shard.go b/cmd/0gchaind/shard.go similarity index 95% rename from cmd/kava/cmd/shard.go rename to cmd/0gchaind/shard.go index 7a44589b..e25ff3d7 100644 --- a/cmd/kava/cmd/shard.go +++ b/cmd/0gchaind/shard.go @@ -1,10 +1,10 @@ -package cmd +package main import ( "fmt" "strings" - "github.com/kava-labs/kava/app" + "github.com/0glabs/0g-chain/app" "github.com/spf13/cobra" dbm "github.com/cometbft/cometbft-db" @@ -39,7 +39,7 @@ func newShardCmd(opts ethermintserver.StartOptions) *cobra.Command { cmd := &cobra.Command{ Use: "shard --home --start --end [--only-app-state] [--only-cometbft-state] [--force-app-version ]", Short: "Strip all blocks from the database outside of a given range", - Long: `shard opens a local kava home directory's databases and removes all blocks outside a range defined by --start and --end. The range is inclusive of the end block. + Long: `shard opens a local 0g-chainhome directory's databases and removes all blocks outside a range defined by --start and --end. The range is inclusive of the end block. It works by first rolling back the latest state to the block before the end block, and then by pruning all state before the start block. @@ -54,14 +54,14 @@ Similarly, the --only-cometbft-state flag skips pruning app state. This can be u The shard command only flags the iavl tree nodes for deletion. Actual removal from the databases will be performed when each database is compacted. WARNING: this is a destructive action.`, - Example: `Create a 1M block data shard (keeps blocks kava 1,000,000 to 2,000,000) -$ kava shard --home path/to/.kava --start 1000000 --end 2000000 + Example: `Create a 1M block data shard (keeps blocks a0gi 1,000,000 to 2,000,000) +$ 0gchaind shard --home path/to/.0gchain --start 1000000 --end 2000000 Prune all blocks up to 5,000,000: -$ kava shard --home path/to/.kava --start 5000000 --end -1 +$ 0gchaind shard --home path/to/.0gchain --start 5000000 --end -1 Prune first 1M blocks _without_ affecting blockstore or cometBFT state: -$ kava shard --home path/to/.kava --start 1000000 --end -1 --only-app-state`, +$ 0gchaind shard --home path/to/.0gchain --start 1000000 --end -1 --only-app-state`, RunE: func(cmd *cobra.Command, args []string) error { ////////////////////////// // parse & validate flags diff --git a/cmd/kava/cmd/status.go b/cmd/0gchaind/status.go similarity index 99% rename from cmd/kava/cmd/status.go rename to cmd/0gchaind/status.go index bc5165a0..8c15dc0f 100644 --- a/cmd/kava/cmd/status.go +++ b/cmd/0gchaind/status.go @@ -1,4 +1,4 @@ -package cmd +package main import ( "context" diff --git a/cmd/kava/cmd/tx.go b/cmd/0gchaind/tx.go similarity index 95% rename from cmd/kava/cmd/tx.go rename to cmd/0gchaind/tx.go index 25d1c5ac..167e4b01 100644 --- a/cmd/kava/cmd/tx.go +++ b/cmd/0gchaind/tx.go @@ -1,4 +1,4 @@ -package cmd +package main import ( "github.com/cosmos/cosmos-sdk/client" @@ -6,7 +6,7 @@ import ( authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/spf13/cobra" - "github.com/kava-labs/kava/app" + "github.com/0glabs/0g-chain/app" ) // newTxCmd creates all commands for submitting blockchain transactions. diff --git a/cmd/kava/opendb/metrics.go b/cmd/opendb/metrics.go similarity index 100% rename from cmd/kava/opendb/metrics.go rename to cmd/opendb/metrics.go diff --git a/cmd/kava/opendb/opendb.go b/cmd/opendb/opendb.go similarity index 100% rename from cmd/kava/opendb/opendb.go rename to cmd/opendb/opendb.go diff --git a/cmd/kava/opendb/opendb_rocksdb.go b/cmd/opendb/opendb_rocksdb.go similarity index 99% rename from cmd/kava/opendb/opendb_rocksdb.go rename to cmd/opendb/opendb_rocksdb.go index d4c8f956..94155451 100644 --- a/cmd/kava/opendb/opendb_rocksdb.go +++ b/cmd/opendb/opendb_rocksdb.go @@ -1,7 +1,7 @@ //go:build rocksdb // +build rocksdb -// Copyright 2023 Kava Labs, Inc. +// Copyright 2024 0glabs Labs, Inc. // Copyright 2023 Cronos Labs, Inc. // // Derived from https://github.com/crypto-org-chain/cronos@496ce7e diff --git a/cmd/kava/opendb/opendb_rocksdb_test.go b/cmd/opendb/opendb_rocksdb_test.go similarity index 100% rename from cmd/kava/opendb/opendb_rocksdb_test.go rename to cmd/opendb/opendb_rocksdb_test.go diff --git a/cmd/kava/opendb/props_loader.go b/cmd/opendb/props_loader.go similarity index 100% rename from cmd/kava/opendb/props_loader.go rename to cmd/opendb/props_loader.go diff --git a/cmd/kava/opendb/props_loader_test.go b/cmd/opendb/props_loader_test.go similarity index 100% rename from cmd/kava/opendb/props_loader_test.go rename to cmd/opendb/props_loader_test.go diff --git a/cmd/kava/opendb/stat_parser.go b/cmd/opendb/stat_parser.go similarity index 100% rename from cmd/kava/opendb/stat_parser.go rename to cmd/opendb/stat_parser.go diff --git a/cmd/kava/opendb/stat_parser_test.go b/cmd/opendb/stat_parser_test.go similarity index 100% rename from cmd/kava/opendb/stat_parser_test.go rename to cmd/opendb/stat_parser_test.go diff --git a/cmd/kava/opendb/stats_loader.go b/cmd/opendb/stats_loader.go similarity index 100% rename from cmd/kava/opendb/stats_loader.go rename to cmd/opendb/stats_loader.go diff --git a/cmd/kava/opendb/stats_loader_test.go b/cmd/opendb/stats_loader_test.go similarity index 100% rename from cmd/kava/opendb/stats_loader_test.go rename to cmd/opendb/stats_loader_test.go diff --git a/cmd/kava/cmd/rocksdb/compact.go b/cmd/rocksdb/compact.go similarity index 99% rename from cmd/kava/cmd/rocksdb/compact.go rename to cmd/rocksdb/compact.go index 4adcbfe8..dc3721e1 100644 --- a/cmd/kava/cmd/rocksdb/compact.go +++ b/cmd/rocksdb/compact.go @@ -14,9 +14,9 @@ import ( "syscall" "time" + "github.com/0glabs/0g-chain/cmd/opendb" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" - "github.com/kava-labs/kava/cmd/kava/opendb" "github.com/linxGnu/grocksdb" "github.com/spf13/cobra" "golang.org/x/exp/slices" diff --git a/cmd/kava/cmd/rocksdb/rocksdb.go b/cmd/rocksdb/rocksdb.go similarity index 100% rename from cmd/kava/cmd/rocksdb/rocksdb.go rename to cmd/rocksdb/rocksdb.go diff --git a/cmd/kava/cmd/rocksdb/rocksdb_dummy.go b/cmd/rocksdb/rocksdb_dummy.go similarity index 100% rename from cmd/kava/cmd/rocksdb/rocksdb_dummy.go rename to cmd/rocksdb/rocksdb_dummy.go diff --git a/contracts/contracts/ERC20KavaWrappedCosmosCoin.sol b/contracts/contracts/ERC20KavaWrappedCosmosCoin.sol index bd637525..17142309 100644 --- a/contracts/contracts/ERC20KavaWrappedCosmosCoin.sol +++ b/contracts/contracts/ERC20KavaWrappedCosmosCoin.sol @@ -4,11 +4,11 @@ pragma solidity ^0.8.18; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; -/// @title An ERC20 token contract owned and deployed by the evmutil module of Kava. +/// @title An ERC20 token contract owned and deployed by the evmutil module of 0g-chain. /// Tokens are backed one-for-one by cosmos-sdk coins held in the module account. -/// @author Kava Labs, LLC -/// @custom:security-contact security@kava.io -contract ERC20KavaWrappedCosmosCoin is ERC20, Ownable { +/// @author 0g Labs, LLC +/// @custom:security-contact security@0g.ai +contract ERC200gChainWrappedCosmosCoin is ERC20, Ownable { /// @notice The decimals places of the token. For display purposes only. uint8 private immutable _decimals; diff --git a/contracts/hardhat.config.ts b/contracts/hardhat.config.ts index 64d944f4..c4b73edc 100644 --- a/contracts/hardhat.config.ts +++ b/contracts/hardhat.config.ts @@ -5,7 +5,7 @@ const config: HardhatUserConfig = { solidity: { version: "0.8.18", settings: { - // istanbul upgrade occurred before the london hardfork, so is compatible with kava's evm + // istanbul upgrade occurred before the london hardfork, so is compatible with 0g-chain's evm evmVersion: "istanbul", // optimize build for deployment to mainnet! optimizer: { @@ -16,21 +16,21 @@ const config: HardhatUserConfig = { }, networks: { // kvtool's local network - kava: { + chain: { url: "http://127.0.0.1:8545", accounts: [ - // kava keys unsafe-export-eth-key whale2 + // 0g-chain keys unsafe-export-eth-key whale2 "AA50F4C6C15190D9E18BF8B14FC09BFBA0E7306331A4F232D10A77C2879E7966", ], }, protonet: { - url: "https://evm.app.protonet.us-east.production.kava.io:443", + url: "https://evm.app.protonet.us-east.production.0g-chain.io:443", accounts: [ "247069F0BC3A5914CB2FD41E4133BBDAA6DBED9F47A01B9F110B5602C6E4CDD9", ], }, internal_testnet: { - url: "https://evm.data.internal.testnet.us-east.production.kava.io:443", + url: "https://evm.data.internal.testnet.us-east.production.0g-chain.io:443", accounts: [ "247069F0BC3A5914CB2FD41E4133BBDAA6DBED9F47A01B9F110B5602C6E4CDD9", ], diff --git a/contracts/package-lock.json b/contracts/package-lock.json index 479261bc..001655ca 100644 --- a/contracts/package-lock.json +++ b/contracts/package-lock.json @@ -1,11 +1,11 @@ { - "name": "kava-contracts", + "name": "0g-chain-contracts", "version": "0.0.1", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "kava-contracts", + "name": "0g-chain-contracts", "version": "0.0.1", "devDependencies": { "@nomicfoundation/hardhat-toolbox": "^2.0.2", diff --git a/contracts/package.json b/contracts/package.json index b28c0d3a..a04b21ab 100644 --- a/contracts/package.json +++ b/contracts/package.json @@ -1,9 +1,9 @@ { - "name": "kava-contracts", + "name": "0g-chain-contracts", "version": "0.0.1", - "author": "Kava Labs", + "author": "0g Labs", "private": true, - "description": "Solidity contracts for Kava Blockchain", + "description": "Solidity contracts for 0g Blockchain", "engines": { "node": ">=18.0.0" }, @@ -12,7 +12,7 @@ "clean": "hardhat clean", "compile": "hardhat compile", "coverage": "hardhat coverage", - "ethermint-json": "jq '{ abi: .abi | tostring, bin: .bytecode | ltrimstr(\"0x\")}' artifacts/contracts/ERC20KavaWrappedCosmosCoin.sol/ERC20KavaWrappedCosmosCoin.json > ../x/evmutil/types/ethermint_json/ERC20KavaWrappedCosmosCoin.json", + "ethermint-json": "jq '{ abi: .abi | tostring, bin: .bytecode | ltrimstr(\"0x\")}' artifacts/contracts/ERC200gChainWrappedCosmosCoin.sol/ERC200gChainWrappedCosmosCoin.json > ../x/evmutil/types/ethermint_json/ERC200gChainWrappedCosmosCoin.json", "gen-ts-types": "hardhat typechain", "lint": "eslint '**/*.{js,ts}'", "lint-fix": "eslint '**/*.{js,ts}' --fix", diff --git a/contracts/scripts/deploy.ts b/contracts/scripts/deploy.ts index 2d190264..291c756e 100644 --- a/contracts/scripts/deploy.ts +++ b/contracts/scripts/deploy.ts @@ -1,14 +1,14 @@ import { ethers } from "hardhat"; async function main() { - const tokenName = "Kava-wrapped ATOM"; + const tokenName = "0g-chain-wrapped ATOM"; const tokenSymbol = "kATOM"; const tokenDecimals = 6; - const ERC20KavaWrappedCosmosCoin = await ethers.getContractFactory( - "ERC20KavaWrappedCosmosCoin" + const ERC200gChainWrappedCosmosCoin = await ethers.getContractFactory( + "ERC200gChainWrappedCosmosCoin" ); - const token = await ERC20KavaWrappedCosmosCoin.deploy( + const token = await ERC200gChainWrappedCosmosCoin.deploy( tokenName, tokenSymbol, tokenDecimals diff --git a/contracts/test/ERC20KavaWrappedCosmosCoin.test.ts b/contracts/test/ERC20KavaWrappedCosmosCoin.test.ts index 9da8c458..e5cb74a4 100644 --- a/contracts/test/ERC20KavaWrappedCosmosCoin.test.ts +++ b/contracts/test/ERC20KavaWrappedCosmosCoin.test.ts @@ -2,21 +2,21 @@ import { expect } from "chai"; import { Signer } from "ethers"; import { ethers } from "hardhat"; import { - ERC20KavaWrappedCosmosCoin, - ERC20KavaWrappedCosmosCoin__factory as ERC20KavaWrappedCosmosCoinFactory, + ERC200gChainWrappedCosmosCoin, + ERC200gChainWrappedCosmosCoin__factory as ERC200gChainWrappedCosmosCoinFactory, } from "../typechain-types"; const decimals = 6n; -describe("ERC20KavaWrappedCosmosCoin", function () { - let erc20: ERC20KavaWrappedCosmosCoin; - let erc20Factory: ERC20KavaWrappedCosmosCoinFactory; +describe("ERC200gChainWrappedCosmosCoin", function () { + let erc20: ERC200gChainWrappedCosmosCoin; + let erc20Factory: ERC200gChainWrappedCosmosCoinFactory; let owner: Signer; let sender: Signer; beforeEach(async function () { erc20Factory = await ethers.getContractFactory( - "ERC20KavaWrappedCosmosCoin" + "ERC200gChainWrappedCosmosCoin" ); erc20 = await erc20Factory.deploy("Wrapped ATOM", "ATOM", decimals); [owner, sender] = await ethers.getSigners(); diff --git a/crypto/vrf/algorithm.go b/crypto/vrf/algorithm.go new file mode 100644 index 00000000..bc344e44 --- /dev/null +++ b/crypto/vrf/algorithm.go @@ -0,0 +1,58 @@ +package vrf + +import ( + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" +) + +var ( + // SupportedAlgorithms defines the list of signing algorithms used on Evmos: + // - eth_secp256k1 (Ethereum) + // - secp256k1 (Tendermint) + SupportedAlgorithms = keyring.SigningAlgoList{VrfAlgo} + // SupportedAlgorithmsLedger defines the list of signing algorithms used on Evmos for the Ledger device: + // - eth_secp256k1 (Ethereum) + // - secp256k1 (Tendermint) + SupportedAlgorithmsLedger = keyring.SigningAlgoList{VrfAlgo} +) + +func VrfOption() keyring.Option { + return func(options *keyring.Options) { + options.SupportedAlgos = SupportedAlgorithms + options.SupportedAlgosLedger = SupportedAlgorithmsLedger + } +} + +const ( + VrfType = hd.PubKeyType(KeyType) +) + +var ( + _ keyring.SignatureAlgo = VrfAlgo + VrfAlgo = vrfAlgo{} +) + +type vrfAlgo struct{} + +func (s vrfAlgo) Name() hd.PubKeyType { + return VrfType +} + +func (s vrfAlgo) Derive() hd.DeriveFn { + return func(mnemonic, bip39Passphrase, path string) ([]byte, error) { + key, err := GenerateKey() + if err != nil { + return nil, err + } + + return key.Bytes(), nil + } +} + +func (s vrfAlgo) Generate() hd.GenerateFn { + return func(bz []byte) cryptotypes.PrivKey { + key, _ := GenerateKey() + return key + } +} diff --git a/crypto/vrf/keys.pb.go b/crypto/vrf/keys.pb.go new file mode 100644 index 00000000..e67dc52b --- /dev/null +++ b/crypto/vrf/keys.pb.go @@ -0,0 +1,496 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: crypto/vrf/keys.proto + +package vrf + +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 + +// PubKey defines a type alias for an vrf.PublicKey that implements +// Vrf's PubKey interface. It represents the 32-byte compressed public +// key format. +type PubKey struct { + // key is the public key in byte form + Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` +} + +func (m *PubKey) Reset() { *m = PubKey{} } +func (*PubKey) ProtoMessage() {} +func (*PubKey) Descriptor() ([]byte, []int) { + return fileDescriptor_eae59d1af27f5957, []int{0} +} +func (m *PubKey) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PubKey) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PubKey.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 *PubKey) XXX_Merge(src proto.Message) { + xxx_messageInfo_PubKey.Merge(m, src) +} +func (m *PubKey) XXX_Size() int { + return m.Size() +} +func (m *PubKey) XXX_DiscardUnknown() { + xxx_messageInfo_PubKey.DiscardUnknown(m) +} + +var xxx_messageInfo_PubKey proto.InternalMessageInfo + +func (m *PubKey) GetKey() []byte { + if m != nil { + return m.Key + } + return nil +} + +// PrivKey defines a type alias for an vrf.PrivateKey that implements +// Vrf's PrivateKey interface. +type PrivKey struct { + // key is the private key in byte form + Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` +} + +func (m *PrivKey) Reset() { *m = PrivKey{} } +func (m *PrivKey) String() string { return proto.CompactTextString(m) } +func (*PrivKey) ProtoMessage() {} +func (*PrivKey) Descriptor() ([]byte, []int) { + return fileDescriptor_eae59d1af27f5957, []int{1} +} +func (m *PrivKey) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PrivKey) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PrivKey.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 *PrivKey) XXX_Merge(src proto.Message) { + xxx_messageInfo_PrivKey.Merge(m, src) +} +func (m *PrivKey) XXX_Size() int { + return m.Size() +} +func (m *PrivKey) XXX_DiscardUnknown() { + xxx_messageInfo_PrivKey.DiscardUnknown(m) +} + +var xxx_messageInfo_PrivKey proto.InternalMessageInfo + +func (m *PrivKey) GetKey() []byte { + if m != nil { + return m.Key + } + return nil +} + +func init() { + proto.RegisterType((*PubKey)(nil), "crypto.vrf.PubKey") + proto.RegisterType((*PrivKey)(nil), "crypto.vrf.PrivKey") +} + +func init() { proto.RegisterFile("crypto/vrf/keys.proto", fileDescriptor_eae59d1af27f5957) } + +var fileDescriptor_eae59d1af27f5957 = []byte{ + // 174 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4d, 0x2e, 0xaa, 0x2c, + 0x28, 0xc9, 0xd7, 0x2f, 0x2b, 0x4a, 0xd3, 0xcf, 0x4e, 0xad, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, + 0xc9, 0x17, 0xe2, 0x82, 0x08, 0xeb, 0x95, 0x15, 0xa5, 0x49, 0x89, 0xa4, 0xe7, 0xa7, 0xe7, 0x83, + 0x85, 0xf5, 0x41, 0x2c, 0x88, 0x0a, 0x25, 0x05, 0x2e, 0xb6, 0x80, 0xd2, 0x24, 0xef, 0xd4, 0x4a, + 0x21, 0x01, 0x2e, 0xe6, 0xec, 0xd4, 0x4a, 0x09, 0x46, 0x05, 0x46, 0x0d, 0x9e, 0x20, 0x10, 0xd3, + 0x8a, 0x65, 0xc6, 0x02, 0x79, 0x06, 0x25, 0x69, 0x2e, 0xf6, 0x80, 0xa2, 0xcc, 0x32, 0xac, 0x4a, + 0x9c, 0xec, 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, + 0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0x4a, 0x35, 0x3d, 0xb3, + 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0xdf, 0x20, 0x3d, 0x27, 0x31, 0xa9, 0x58, 0xdf, + 0x20, 0x5d, 0x37, 0x39, 0x23, 0x31, 0x33, 0x4f, 0x1f, 0xe1, 0xd8, 0x24, 0x36, 0xb0, 0x33, 0x8c, + 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xdb, 0xb8, 0x32, 0x07, 0xc1, 0x00, 0x00, 0x00, +} + +func (m *PubKey) 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 *PubKey) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PubKey) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Key) > 0 { + i -= len(m.Key) + copy(dAtA[i:], m.Key) + i = encodeVarintKeys(dAtA, i, uint64(len(m.Key))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *PrivKey) 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 *PrivKey) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PrivKey) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Key) > 0 { + i -= len(m.Key) + copy(dAtA[i:], m.Key) + i = encodeVarintKeys(dAtA, i, uint64(len(m.Key))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintKeys(dAtA []byte, offset int, v uint64) int { + offset -= sovKeys(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *PubKey) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Key) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *PrivKey) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Key) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func sovKeys(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozKeys(x uint64) (n int) { + return sovKeys(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *PubKey) 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 ErrIntOverflowKeys + } + 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: PubKey: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PubKey: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthKeys + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...) + if m.Key == nil { + m.Key = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PrivKey) 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 ErrIntOverflowKeys + } + 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: PrivKey: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PrivKey: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthKeys + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...) + if m.Key == nil { + m.Key = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipKeys(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, ErrIntOverflowKeys + } + 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, ErrIntOverflowKeys + } + 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, ErrIntOverflowKeys + } + 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, ErrInvalidLengthKeys + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupKeys + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthKeys + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthKeys = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowKeys = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupKeys = fmt.Errorf("proto: unexpected end of group") +) diff --git a/crypto/vrf/vrf.go b/crypto/vrf/vrf.go new file mode 100644 index 00000000..a3586cb2 --- /dev/null +++ b/crypto/vrf/vrf.go @@ -0,0 +1,194 @@ +package vrf + +import ( + "bytes" + "crypto/subtle" + "fmt" + + errorsmod "cosmossdk.io/errors" + tmcrypto "github.com/cometbft/cometbft/crypto" + vrfalgo "github.com/coniks-sys/coniks-go/crypto/vrf" + "github.com/cosmos/cosmos-sdk/codec" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + errortypes "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/ethereum/go-ethereum/common" +) + +const ( + // PrivKeySize defines the size of the PrivKey bytes + PrivKeySize = 64 + // PubKeySize defines the size of the PubKey bytes + PubKeySize = 32 + // KeyType is the string constant for the vrf algorithm + KeyType = "vrf" +) + +// Amino encoding names +const ( + // PrivKeyName defines the amino encoding name for the vrf private key + PrivKeyName = "vrf/PrivKey" + // PubKeyName defines the amino encoding name for the vrf public key + PubKeyName = "vrf/PubKey" +) + +// ---------------------------------------------------------------------------- +// vrf Private Key + +var ( + _ cryptotypes.PrivKey = &PrivKey{} + _ codec.AminoMarshaler = &PrivKey{} +) + +// GenerateKey generates a new random private key. It returns an error upon +// failure. +func GenerateKey() (*PrivKey, error) { + priv, err := vrfalgo.GenerateKey(nil) + if err != nil { + return nil, err + } + + return &PrivKey{ + Key: priv, + }, nil +} + +func (privKey PrivKey) getVrfPrivateKey() vrfalgo.PrivateKey { + return vrfalgo.PrivateKey(privKey.Key) +} + +// Bytes returns the byte representation of the Private Key. +func (privKey PrivKey) Bytes() []byte { + bz := make([]byte, len(privKey.Key)) + copy(bz, privKey.Key) + + return bz +} + +// PubKey returns the private key's public key. If the privkey is not valid +// it returns a nil value. +func (privKey PrivKey) PubKey() cryptotypes.PubKey { + pk, _ := vrfalgo.PrivateKey(privKey.Key).Public() + + return &PubKey{ + Key: pk, + } +} + +// Equals returns true if two private keys are equal and false otherwise. +func (privKey PrivKey) Equals(other cryptotypes.LedgerPrivKey) bool { + return privKey.Type() == other.Type() && subtle.ConstantTimeCompare(privKey.Bytes(), other.Bytes()) == 1 +} + +// Type returns vrf +func (privKey PrivKey) Type() string { + return KeyType +} + +// Compute generates the vrf value for the byte slice m using the +// underlying private key sk. +func (privKey PrivKey) Sign(digestBz []byte) ([]byte, error) { + sk := privKey.getVrfPrivateKey() + + return sk.Compute(digestBz), nil +} + +// MarshalAmino overrides Amino binary marshaling. +func (privKey PrivKey) MarshalAmino() ([]byte, error) { + return privKey.Key, nil +} + +// UnmarshalAmino overrides Amino binary marshaling. +func (privKey *PrivKey) UnmarshalAmino(bz []byte) error { + if len(bz) != PrivKeySize { + return fmt.Errorf("invalid privkey size, expected %d got %d", PrivKeySize, len(bz)) + } + privKey.Key = bz + + return nil +} + +// MarshalAminoJSON overrides Amino JSON marshaling. +func (privKey PrivKey) MarshalAminoJSON() ([]byte, error) { + // When we marshal to Amino JSON, we don't marshal the "key" field itself, + // just its contents (i.e. the key bytes). + return privKey.MarshalAmino() +} + +// UnmarshalAminoJSON overrides Amino JSON marshaling. +func (privKey *PrivKey) UnmarshalAminoJSON(bz []byte) error { + return privKey.UnmarshalAmino(bz) +} + +// ---------------------------------------------------------------------------- +// vrf Public Key + +var ( + _ cryptotypes.PubKey = &PubKey{} + _ codec.AminoMarshaler = &PubKey{} +) + +// func (pubKey PubKey) getVrfPublicKey() vrfalgo.PublicKey { +// return vrfalgo.PublicKey(pubKey.Key) +// } + +// Address returns the address of the ECDSA public key. +// The function will return an empty address if the public key is invalid. +func (pubKey PubKey) Address() tmcrypto.Address { + return tmcrypto.Address(common.BytesToAddress(pubKey.Key).Bytes()) +} + +// Bytes returns the raw bytes of the ECDSA public key. +func (pubKey PubKey) Bytes() []byte { + bz := make([]byte, len(pubKey.Key)) + copy(bz, pubKey.Key) + + return bz +} + +// String implements the fmt.Stringer interface. +func (pubKey PubKey) String() string { + return fmt.Sprintf("vrf{%X}", pubKey.Key) +} + +// Type returns vrf +func (pubKey PubKey) Type() string { + return KeyType +} + +// Equals returns true if the pubkey type is the same and their bytes are deeply equal. +func (pubKey PubKey) Equals(other cryptotypes.PubKey) bool { + return pubKey.Type() == other.Type() && bytes.Equal(pubKey.Bytes(), other.Bytes()) +} + +// Verify returns true iff vrf=Compute(m) for the sk that +// corresponds to pk. +func (pubKey PubKey) VerifySignature(msg, sig []byte) bool { + panic("not implement") +} + +// MarshalAmino overrides Amino binary marshaling. +func (pubKey PubKey) MarshalAmino() ([]byte, error) { + return pubKey.Key, nil +} + +// UnmarshalAmino overrides Amino binary marshaling. +func (pubKey *PubKey) UnmarshalAmino(bz []byte) error { + if len(bz) != PubKeySize { + return errorsmod.Wrapf(errortypes.ErrInvalidPubKey, "invalid pubkey size, expected %d, got %d", PubKeySize, len(bz)) + } + pubKey.Key = bz + + return nil +} + +// MarshalAminoJSON overrides Amino JSON marshaling. +func (pubKey PubKey) MarshalAminoJSON() ([]byte, error) { + // When we marshal to Amino JSON, we don't marshal the "key" field itself, + // just its contents (i.e. the key bytes). + return pubKey.MarshalAmino() +} + +// UnmarshalAminoJSON overrides Amino JSON marshaling. +func (pubKey *PubKey) UnmarshalAminoJSON(bz []byte) error { + return pubKey.UnmarshalAmino(bz) +} diff --git a/crypto/vrf/vrf_test.go b/crypto/vrf/vrf_test.go new file mode 100644 index 00000000..f5696182 --- /dev/null +++ b/crypto/vrf/vrf_test.go @@ -0,0 +1,96 @@ +package vrf + +import ( + "testing" + + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + + "encoding/base64" + + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestPrivKey(t *testing.T) { + // validate type and equality + privKey, err := GenerateKey() + require.NoError(t, err) + require.Implements(t, (*cryptotypes.PrivKey)(nil), privKey) + + // validate inequality + privKey2, err := GenerateKey() + require.NoError(t, err) + require.False(t, privKey.Equals(privKey2)) +} + +func TestPrivKey_PubKey(t *testing.T) { + privKey, err := GenerateKey() + require.NoError(t, err) + + // validate type and equality + pubKey := &PubKey{ + Key: privKey.PubKey().Bytes(), + } + require.Implements(t, (*cryptotypes.PubKey)(nil), pubKey) + + // validate inequality + privKey2, err := GenerateKey() + require.NoError(t, err) + require.False(t, pubKey.Equals(privKey2.PubKey())) +} + +func TestMarshalAmino(t *testing.T) { + aminoCdc := codec.NewLegacyAmino() + privKey, err := GenerateKey() + require.NoError(t, err) + + pubKey := privKey.PubKey().(*PubKey) + + testCases := []struct { + desc string + msg codec.AminoMarshaler + typ interface{} + expBinary []byte + expJSON string + }{ + { + "vrf private key", + privKey, + &PrivKey{}, + append([]byte{64}, privKey.Bytes()...), // Length-prefixed. + "\"" + base64.StdEncoding.EncodeToString(privKey.Bytes()) + "\"", + }, + { + "vrf public key", + pubKey, + &PubKey{}, + append([]byte{32}, pubKey.Bytes()...), // Length-prefixed. + "\"" + base64.StdEncoding.EncodeToString(pubKey.Bytes()) + "\"", + }, + } + + for _, tc := range testCases { + t.Run(tc.desc, func(t *testing.T) { + // Do a round trip of encoding/decoding binary. + bz, err := aminoCdc.Marshal(tc.msg) + require.NoError(t, err) + require.Equal(t, tc.expBinary, bz) + + err = aminoCdc.Unmarshal(bz, tc.typ) + require.NoError(t, err) + + require.Equal(t, tc.msg, tc.typ) + + // Do a round trip of encoding/decoding JSON. + bz, err = aminoCdc.MarshalJSON(tc.msg) + require.NoError(t, err) + require.Equal(t, tc.expJSON, string(bz)) + + err = aminoCdc.UnmarshalJSON(bz, tc.typ) + require.NoError(t, err) + + require.Equal(t, tc.msg, tc.typ) + }) + } +} diff --git a/docker-compose.yml b/docker-compose.yml index 62ebd1ec..82e7afcc 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -3,7 +3,7 @@ version: '3' services: kvdnode0: container_name: kvdnode0 - image: "kava/kavanode" + image: "0glabs/0g-chain-node" ports: - "26656-26657:26656-26657" environment: @@ -17,7 +17,7 @@ services: kvdnode1: container_name: kvdnode1 - image: "kava/kavanode" + image: "0glabs/0g-chain-node" ports: - "26659-26660:26656-26657" environment: @@ -31,7 +31,7 @@ services: kvdnode2: container_name: kvdnode2 - image: "kava/kavanode" + image: "0glabs/0g-chain-node" environment: - ID=2 - LOG=${LOG:-kvd.log} @@ -45,7 +45,7 @@ services: kvdnode3: container_name: kvdnode3 - image: "kava/kavanode" + image: "0glabs/0g-chain-node" environment: - ID=3 - LOG=${LOG:-kvd.log} diff --git a/go.mod b/go.mod index 4e300659..d315df3a 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module github.com/kava-labs/kava +module github.com/0glabs/0g-chain go 1.21 @@ -9,6 +9,7 @@ require ( github.com/cenkalti/backoff/v4 v4.1.3 github.com/cometbft/cometbft v0.37.4 github.com/cometbft/cometbft-db v0.9.1 + github.com/coniks-sys/coniks-go v0.0.0-20180722014011-11acf4819b71 github.com/cosmos/cosmos-proto v1.0.0-beta.4 github.com/cosmos/cosmos-sdk v0.47.10 github.com/cosmos/go-bip39 v1.0.0 @@ -18,7 +19,6 @@ require ( github.com/ethereum/go-ethereum v1.10.26 github.com/evmos/ethermint v0.21.0 github.com/go-kit/kit v0.12.0 - github.com/gogo/protobuf v1.3.2 github.com/golang/protobuf v1.5.3 github.com/gorilla/mux v1.8.0 github.com/grpc-ecosystem/grpc-gateway v1.16.0 @@ -111,6 +111,7 @@ require ( github.com/go-stack/stack v1.8.1 // indirect github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect github.com/gogo/googleapis v1.4.1 // indirect + github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/glog v1.1.2 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/mock v1.6.0 // indirect @@ -183,7 +184,6 @@ require ( github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/status-im/keycard-go v0.2.0 // indirect - github.com/stretchr/objx v0.5.0 // indirect github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect github.com/tendermint/go-amino v0.16.0 // indirect github.com/tidwall/btree v1.6.0 // indirect diff --git a/go.sum b/go.sum index 33f558d2..05106bfb 100644 --- a/go.sum +++ b/go.sum @@ -396,6 +396,8 @@ github.com/coinbase/rosetta-sdk-go v0.7.9 h1:lqllBjMnazTjIqYrOGv8h8jxjg9+hJazIGZ github.com/coinbase/rosetta-sdk-go v0.7.9/go.mod h1:0/knutI7XGVqXmmH4OQD8OckFrbQ8yMsUZTG7FXCR2M= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= github.com/confio/ics23/go v0.9.0/go.mod h1:4LPZ2NYqnYIVRklaozjNR1FScgDJ2s5Xrp+e/mYVRak= +github.com/coniks-sys/coniks-go v0.0.0-20180722014011-11acf4819b71 h1:MFLTqgfJclmtaQ1SRUrWwmDX/1UBok3XWUethkJ2swQ= +github.com/coniks-sys/coniks-go v0.0.0-20180722014011-11acf4819b71/go.mod h1:TrHYHH4Wze7v7Hkwu1MH1W+mCPQKM+gs+PicdEV14o8= github.com/consensys/bavard v0.1.8-0.20210406032232-f3452dc9b572/go.mod h1:Bpd0/3mZuaj6Sj+PqrmIquiOKy397AKGThQPaGzNXAQ= github.com/consensys/bavard v0.1.8-0.20210915155054-088da2f7f54a/go.mod h1:9ItSMtA/dXMAiL7BG6bqW2m3NdSEObYWoH223nGHukI= github.com/consensys/gnark-crypto v0.4.1-0.20210426202927-39ac3d4b3f1f/go.mod h1:815PAHg3wvysy0SyIqanF8gZ0Y1wjk/hrDHD/iT88+Q= diff --git a/helper/da/client/client.go b/helper/da/client/client.go new file mode 100644 index 00000000..533c9e9c --- /dev/null +++ b/helper/da/client/client.go @@ -0,0 +1,61 @@ +package client + +import ( + "context" + "time" + + "github.com/0glabs/0g-evmos/helper/da/light" + + "github.com/pkg/errors" +) + +type DaLightRpcClient interface { + Sample(ctx context.Context, streamId, headerHash []byte, blobIdx, times uint32) (bool, error) + Destroy() + GetInstanceCount() int +} + +type daLightClient struct { + maxInstance int + pool ConnectionPool +} + +func NewDaLightClient(address string, instanceLimit int) DaLightRpcClient { + return &daLightClient{ + maxInstance: instanceLimit, + pool: NewConnectionPool(address, instanceLimit, 10*time.Minute), + } +} + +func (c *daLightClient) Sample(ctx context.Context, streamId, headerHash []byte, blobIdx, times uint32) (bool, error) { + connection, err := c.pool.GetConnection() + if err != nil { + return false, errors.Wrap(err, "failed to connect to da light server") + } + defer c.pool.ReleaseConnection(connection) + + req := &light.SampleRequest{ + StreamId: streamId, + BatchHeaderHash: headerHash, + BlobIndex: blobIdx, + Times: times, + } + client := light.NewLightClient(connection) + reply, err := client.Sample(ctx, req) + if err != nil { + return false, errors.Wrap(err, "failed to sample from da light server") + } + + return reply.Success, nil +} + +func (c *daLightClient) Destroy() { + if c.pool != nil { + c.pool.Close() + c.pool = nil + } +} + +func (c *daLightClient) GetInstanceCount() int { + return c.maxInstance +} diff --git a/helper/da/client/pool.go b/helper/da/client/pool.go new file mode 100644 index 00000000..887704a0 --- /dev/null +++ b/helper/da/client/pool.go @@ -0,0 +1,101 @@ +package client + +import ( + "errors" + "sync" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/backoff" + "google.golang.org/grpc/credentials/insecure" +) + +type ConnectionPool interface { + GetConnection() (*grpc.ClientConn, error) + ReleaseConnection(*grpc.ClientConn) + Close() +} + +type connectionPoolImpl struct { + address string + maxSize int + timeout time.Duration + param grpc.ConnectParams + + mu sync.Mutex + pool []*grpc.ClientConn +} + +func NewConnectionPool(address string, maxSize int, timeout time.Duration) ConnectionPool { + return &connectionPoolImpl{ + address: address, + maxSize: maxSize, + timeout: timeout, + param: grpc.ConnectParams{ + Backoff: backoff.Config{ + BaseDelay: 1.0 * time.Second, + Multiplier: 1.5, + Jitter: 0.2, + MaxDelay: 30 * time.Second, + }, + MinConnectTimeout: 30 * time.Second, + }, + pool: make([]*grpc.ClientConn, 0, maxSize), + } +} + +func (p *connectionPoolImpl) GetConnection() (*grpc.ClientConn, error) { + p.mu.Lock() + defer p.mu.Unlock() + + if p.pool == nil { + return nil, errors.New("connection pool is closed") + } + + // Check if there's any available connection in the pool + if len(p.pool) > 0 { + conn := p.pool[0] + p.pool = p.pool[1:] + return conn, nil + } + + // If the pool is empty, create a new connection + conn, err := grpc.Dial(p.address, grpc.WithBlock(), + grpc.WithConnectParams(p.param), + grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + return nil, err + } + return conn, nil +} + +func (p *connectionPoolImpl) ReleaseConnection(conn *grpc.ClientConn) { + p.mu.Lock() + defer p.mu.Unlock() + + if p.pool != nil { + // If the pool is full, close the connection + if len(p.pool) >= p.maxSize { + conn.Close() + return + } + + // Add the connection back to the pool + p.pool = append(p.pool, conn) + } else { + conn.Close() + } +} + +func (p *connectionPoolImpl) Close() { + p.mu.Lock() + defer p.mu.Unlock() + + if p.pool != nil { + for _, conn := range p.pool { + conn.Close() + } + + p.pool = nil + } +} diff --git a/helper/da/go.mod b/helper/da/go.mod new file mode 100644 index 00000000..b0e11e7e --- /dev/null +++ b/helper/da/go.mod @@ -0,0 +1,26 @@ +module github.com/0glabs/0g-evmos/helper/da + +go 1.20 + +require ( + github.com/json-iterator/go v1.1.12 + github.com/lesismal/nbio v1.5.4 + github.com/pkg/errors v0.9.1 + github.com/rs/zerolog v1.32.0 + google.golang.org/grpc v1.63.2 + google.golang.org/protobuf v1.33.0 +) + +require ( + github.com/lesismal/llib v1.1.13 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.19 // indirect + github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/stretchr/testify v1.8.4 // indirect + golang.org/x/crypto v0.19.0 // indirect + golang.org/x/net v0.21.0 // indirect + golang.org/x/sys v0.17.0 // indirect + golang.org/x/text v0.14.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de // indirect +) diff --git a/helper/da/go.sum b/helper/da/go.sum new file mode 100644 index 00000000..cc3cf3ca --- /dev/null +++ b/helper/da/go.sum @@ -0,0 +1,60 @@ +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/lesismal/llib v1.1.13 h1:+w1+t0PykXpj2dXQck0+p6vdC9/mnbEXHgUy/HXDGfE= +github.com/lesismal/llib v1.1.13/go.mod h1:70tFXXe7P1FZ02AU9l8LgSOK7d7sRrpnkUr3rd3gKSg= +github.com/lesismal/nbio v1.5.4 h1:fZ6FOVZOBm7nFuudYsq+WyHJuM2UNuPdlvF/1LVa6lo= +github.com/lesismal/nbio v1.5.4/go.mod h1:mvfYBAA1jmrafXf2XvkM28jWkMTfA5jGks+HKDBMmOc= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.32.0 h1:keLypqrlIjaFsbmJOBdB/qvyF8KEtCWHwobLp5l/mQ0= +github.com/rs/zerolog v1.32.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +golang.org/x/crypto v0.0.0-20210513122933-cd7d49e622d5/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= +golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de h1:cZGRis4/ot9uVm639a+rHCUaG0JJHEsdyzSQTMX+suY= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de/go.mod h1:H4O17MA/PE9BsGx3w+a+W2VOLLD1Qf7oJneAoU6WktY= +google.golang.org/grpc v1.63.2 h1:MUeiw1B2maTVZthpU5xvASfTh3LDbxHd6IJ6QQVU+xM= +google.golang.org/grpc v1.63.2/go.mod h1:WAX/8DgncnokcFUldAxq7GeB5DXHDbMF+lLvDomNkRA= +google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= +google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/helper/da/light/light.pb.go b/helper/da/light/light.pb.go new file mode 100644 index 00000000..60c987f2 --- /dev/null +++ b/helper/da/light/light.pb.go @@ -0,0 +1,397 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.28.1 +// protoc v4.25.3 +// source: light/light.proto + +package light + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// SampleRequest contains the blob to sample (by batch and blob index) and required sample times +type SampleRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + StreamId []byte `protobuf:"bytes,1,opt,name=stream_id,json=streamId,proto3" json:"stream_id,omitempty"` + BatchHeaderHash []byte `protobuf:"bytes,2,opt,name=batch_header_hash,json=batchHeaderHash,proto3" json:"batch_header_hash,omitempty"` + BlobIndex uint32 `protobuf:"varint,3,opt,name=blob_index,json=blobIndex,proto3" json:"blob_index,omitempty"` + Times uint32 `protobuf:"varint,4,opt,name=times,proto3" json:"times,omitempty"` +} + +func (x *SampleRequest) Reset() { + *x = SampleRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_light_light_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SampleRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SampleRequest) ProtoMessage() {} + +func (x *SampleRequest) ProtoReflect() protoreflect.Message { + mi := &file_light_light_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SampleRequest.ProtoReflect.Descriptor instead. +func (*SampleRequest) Descriptor() ([]byte, []int) { + return file_light_light_proto_rawDescGZIP(), []int{0} +} + +func (x *SampleRequest) GetStreamId() []byte { + if x != nil { + return x.StreamId + } + return nil +} + +func (x *SampleRequest) GetBatchHeaderHash() []byte { + if x != nil { + return x.BatchHeaderHash + } + return nil +} + +func (x *SampleRequest) GetBlobIndex() uint32 { + if x != nil { + return x.BlobIndex + } + return 0 +} + +func (x *SampleRequest) GetTimes() uint32 { + if x != nil { + return x.Times + } + return 0 +} + +// SampleReply contains the sample result +type SampleReply struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` +} + +func (x *SampleReply) Reset() { + *x = SampleReply{} + if protoimpl.UnsafeEnabled { + mi := &file_light_light_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SampleReply) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SampleReply) ProtoMessage() {} + +func (x *SampleReply) ProtoReflect() protoreflect.Message { + mi := &file_light_light_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SampleReply.ProtoReflect.Descriptor instead. +func (*SampleReply) Descriptor() ([]byte, []int) { + return file_light_light_proto_rawDescGZIP(), []int{1} +} + +func (x *SampleReply) GetSuccess() bool { + if x != nil { + return x.Success + } + return false +} + +type RetrieveRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + BatchHeaderHash []byte `protobuf:"bytes,1,opt,name=batch_header_hash,json=batchHeaderHash,proto3" json:"batch_header_hash,omitempty"` + BlobIndex uint32 `protobuf:"varint,2,opt,name=blob_index,json=blobIndex,proto3" json:"blob_index,omitempty"` +} + +func (x *RetrieveRequest) Reset() { + *x = RetrieveRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_light_light_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *RetrieveRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RetrieveRequest) ProtoMessage() {} + +func (x *RetrieveRequest) ProtoReflect() protoreflect.Message { + mi := &file_light_light_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RetrieveRequest.ProtoReflect.Descriptor instead. +func (*RetrieveRequest) Descriptor() ([]byte, []int) { + return file_light_light_proto_rawDescGZIP(), []int{2} +} + +func (x *RetrieveRequest) GetBatchHeaderHash() []byte { + if x != nil { + return x.BatchHeaderHash + } + return nil +} + +func (x *RetrieveRequest) GetBlobIndex() uint32 { + if x != nil { + return x.BlobIndex + } + return 0 +} + +type RetrieveReply struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Status bool `protobuf:"varint,1,opt,name=status,proto3" json:"status,omitempty"` + Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` +} + +func (x *RetrieveReply) Reset() { + *x = RetrieveReply{} + if protoimpl.UnsafeEnabled { + mi := &file_light_light_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *RetrieveReply) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RetrieveReply) ProtoMessage() {} + +func (x *RetrieveReply) ProtoReflect() protoreflect.Message { + mi := &file_light_light_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RetrieveReply.ProtoReflect.Descriptor instead. +func (*RetrieveReply) Descriptor() ([]byte, []int) { + return file_light_light_proto_rawDescGZIP(), []int{3} +} + +func (x *RetrieveReply) GetStatus() bool { + if x != nil { + return x.Status + } + return false +} + +func (x *RetrieveReply) GetData() []byte { + if x != nil { + return x.Data + } + return nil +} + +var File_light_light_proto protoreflect.FileDescriptor + +var file_light_light_proto_rawDesc = []byte{ + 0x0a, 0x11, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2f, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x12, 0x05, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x22, 0x8d, 0x01, 0x0a, 0x0d, 0x53, + 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, + 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, + 0x08, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x49, 0x64, 0x12, 0x2a, 0x0a, 0x11, 0x62, 0x61, 0x74, + 0x63, 0x68, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x48, 0x65, 0x61, 0x64, 0x65, + 0x72, 0x48, 0x61, 0x73, 0x68, 0x12, 0x1d, 0x0a, 0x0a, 0x62, 0x6c, 0x6f, 0x62, 0x5f, 0x69, 0x6e, + 0x64, 0x65, 0x78, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x62, 0x6c, 0x6f, 0x62, 0x49, + 0x6e, 0x64, 0x65, 0x78, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x18, 0x04, 0x20, + 0x01, 0x28, 0x0d, 0x52, 0x05, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x22, 0x27, 0x0a, 0x0b, 0x53, 0x61, + 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x75, 0x63, + 0x63, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x73, 0x75, 0x63, 0x63, + 0x65, 0x73, 0x73, 0x22, 0x5c, 0x0a, 0x0f, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x2a, 0x0a, 0x11, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, + 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x0c, 0x52, 0x0f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x48, 0x61, + 0x73, 0x68, 0x12, 0x1d, 0x0a, 0x0a, 0x62, 0x6c, 0x6f, 0x62, 0x5f, 0x69, 0x6e, 0x64, 0x65, 0x78, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x62, 0x6c, 0x6f, 0x62, 0x49, 0x6e, 0x64, 0x65, + 0x78, 0x22, 0x3b, 0x0a, 0x0d, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x52, 0x65, 0x70, + 0x6c, 0x79, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x08, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, + 0x74, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x32, 0x79, + 0x0a, 0x05, 0x4c, 0x69, 0x67, 0x68, 0x74, 0x12, 0x34, 0x0a, 0x06, 0x53, 0x61, 0x6d, 0x70, 0x6c, + 0x65, 0x12, 0x14, 0x2e, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2e, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x12, 0x2e, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2e, + 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x00, 0x12, 0x3a, 0x0a, + 0x08, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x12, 0x16, 0x2e, 0x6c, 0x69, 0x67, 0x68, + 0x74, 0x2e, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x1a, 0x14, 0x2e, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2e, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, + 0x76, 0x65, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x00, 0x42, 0x30, 0x5a, 0x2e, 0x67, 0x69, 0x74, + 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x30, 0x67, 0x6c, 0x61, 0x62, 0x73, 0x2f, 0x30, + 0x67, 0x2d, 0x64, 0x61, 0x74, 0x61, 0x2d, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x2f, 0x72, 0x75, 0x6e, + 0x2f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x33, +} + +var ( + file_light_light_proto_rawDescOnce sync.Once + file_light_light_proto_rawDescData = file_light_light_proto_rawDesc +) + +func file_light_light_proto_rawDescGZIP() []byte { + file_light_light_proto_rawDescOnce.Do(func() { + file_light_light_proto_rawDescData = protoimpl.X.CompressGZIP(file_light_light_proto_rawDescData) + }) + return file_light_light_proto_rawDescData +} + +var file_light_light_proto_msgTypes = make([]protoimpl.MessageInfo, 4) +var file_light_light_proto_goTypes = []interface{}{ + (*SampleRequest)(nil), // 0: light.SampleRequest + (*SampleReply)(nil), // 1: light.SampleReply + (*RetrieveRequest)(nil), // 2: light.RetrieveRequest + (*RetrieveReply)(nil), // 3: light.RetrieveReply +} +var file_light_light_proto_depIdxs = []int32{ + 0, // 0: light.Light.Sample:input_type -> light.SampleRequest + 2, // 1: light.Light.Retrieve:input_type -> light.RetrieveRequest + 1, // 2: light.Light.Sample:output_type -> light.SampleReply + 3, // 3: light.Light.Retrieve:output_type -> light.RetrieveReply + 2, // [2:4] is the sub-list for method output_type + 0, // [0:2] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_light_light_proto_init() } +func file_light_light_proto_init() { + if File_light_light_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_light_light_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SampleRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_light_light_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SampleReply); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_light_light_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*RetrieveRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_light_light_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*RetrieveReply); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_light_light_proto_rawDesc, + NumEnums: 0, + NumMessages: 4, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_light_light_proto_goTypes, + DependencyIndexes: file_light_light_proto_depIdxs, + MessageInfos: file_light_light_proto_msgTypes, + }.Build() + File_light_light_proto = out.File + file_light_light_proto_rawDesc = nil + file_light_light_proto_goTypes = nil + file_light_light_proto_depIdxs = nil +} diff --git a/helper/da/light/light_grpc.pb.go b/helper/da/light/light_grpc.pb.go new file mode 100644 index 00000000..0586c987 --- /dev/null +++ b/helper/da/light/light_grpc.pb.go @@ -0,0 +1,141 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.2.0 +// - protoc v4.25.3 +// source: light/light.proto + +package light + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.32.0 or later. +const _ = grpc.SupportPackageIsVersion7 + +// LightClient is the client API for Light service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type LightClient interface { + Sample(ctx context.Context, in *SampleRequest, opts ...grpc.CallOption) (*SampleReply, error) + Retrieve(ctx context.Context, in *RetrieveRequest, opts ...grpc.CallOption) (*RetrieveReply, error) +} + +type lightClient struct { + cc grpc.ClientConnInterface +} + +func NewLightClient(cc grpc.ClientConnInterface) LightClient { + return &lightClient{cc} +} + +func (c *lightClient) Sample(ctx context.Context, in *SampleRequest, opts ...grpc.CallOption) (*SampleReply, error) { + out := new(SampleReply) + err := c.cc.Invoke(ctx, "/light.Light/Sample", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *lightClient) Retrieve(ctx context.Context, in *RetrieveRequest, opts ...grpc.CallOption) (*RetrieveReply, error) { + out := new(RetrieveReply) + err := c.cc.Invoke(ctx, "/light.Light/Retrieve", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// LightServer is the server API for Light service. +// All implementations must embed UnimplementedLightServer +// for forward compatibility +type LightServer interface { + Sample(context.Context, *SampleRequest) (*SampleReply, error) + Retrieve(context.Context, *RetrieveRequest) (*RetrieveReply, error) + mustEmbedUnimplementedLightServer() +} + +// UnimplementedLightServer must be embedded to have forward compatible implementations. +type UnimplementedLightServer struct { +} + +func (UnimplementedLightServer) Sample(context.Context, *SampleRequest) (*SampleReply, error) { + return nil, status.Errorf(codes.Unimplemented, "method Sample not implemented") +} +func (UnimplementedLightServer) Retrieve(context.Context, *RetrieveRequest) (*RetrieveReply, error) { + return nil, status.Errorf(codes.Unimplemented, "method Retrieve not implemented") +} +func (UnimplementedLightServer) mustEmbedUnimplementedLightServer() {} + +// UnsafeLightServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to LightServer will +// result in compilation errors. +type UnsafeLightServer interface { + mustEmbedUnimplementedLightServer() +} + +func RegisterLightServer(s grpc.ServiceRegistrar, srv LightServer) { + s.RegisterService(&Light_ServiceDesc, srv) +} + +func _Light_Sample_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SampleRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(LightServer).Sample(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/light.Light/Sample", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(LightServer).Sample(ctx, req.(*SampleRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Light_Retrieve_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RetrieveRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(LightServer).Retrieve(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/light.Light/Retrieve", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(LightServer).Retrieve(ctx, req.(*RetrieveRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// Light_ServiceDesc is the grpc.ServiceDesc for Light service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var Light_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "light.Light", + HandlerType: (*LightServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Sample", + Handler: _Light_Sample_Handler, + }, + { + MethodName: "Retrieve", + Handler: _Light_Retrieve_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "light/light.proto", +} diff --git a/helper/da/main.go b/helper/da/main.go new file mode 100644 index 00000000..001737a8 --- /dev/null +++ b/helper/da/main.go @@ -0,0 +1,89 @@ +package main + +import ( + "context" + "flag" + "fmt" + "io" + "log" + "net/url" + "os" + "os/signal" + "time" + + "github.com/0glabs/0g-evmos/helper/da/service" + "github.com/0glabs/0g-evmos/helper/da/types" + + "github.com/lesismal/nbio/nbhttp" + "github.com/lesismal/nbio/nbhttp/websocket" +) + +const ( + subscribeMsg = "{\"jsonrpc\":\"2.0\",\"method\":\"subscribe\",\"id\":1,\"params\":{\"query\":\"tm.event='Tx'\"}}" +) + +var ( + rpcAddress = flag.String("rpc-address", "34.214.2.28:32001", "address of da-light rpc server") + wsAddress = flag.String("ws-address", "127.0.0.1:26657", "address of emvos ws server") + relativePath = flag.String("relative-path", "", "relative path of evmosd") + account = flag.String("account", "", "account to run evmosd cli") + keyring = flag.String("keyring", "", "keyring to run evmosd cli") + homePath = flag.String("home", "", "home path of evmosd node") +) + +func newUpgrader() *websocket.Upgrader { + u := websocket.NewUpgrader() + u.OnMessage(func(c *websocket.Conn, messageType websocket.MessageType, data []byte) { + log.Println("onEcho:", string(data)) + ctx := context.WithValue(context.Background(), types.DA_RPC_ADDRESS, *rpcAddress) + ctx = context.WithValue(ctx, types.NODE_CLI_RELATIVE_PATH, *relativePath) + ctx = context.WithValue(ctx, types.NODE_CLI_EXEC_ACCOUNT, *account) + ctx = context.WithValue(ctx, types.NODE_CLI_EXEC_KEYRING, *keyring) + ctx = context.WithValue(ctx, types.NODE_HOME_PATH, *homePath) + go func() { service.OnMessage(ctx, c, messageType, data) }() + }) + + u.OnClose(func(c *websocket.Conn, err error) { + fmt.Println("OnClose:", c.RemoteAddr().String(), err) + service.OnClose() + }) + + return u +} + +func main() { + flag.Parse() + engine := nbhttp.NewEngine(nbhttp.Config{}) + err := engine.Start() + if err != nil { + fmt.Printf("nbio.Start failed: %v\n", err) + return + } + + go func() { + u := url.URL{Scheme: "ws", Host: *wsAddress, Path: "/websocket"} + dialer := &websocket.Dialer{ + Engine: engine, + Upgrader: newUpgrader(), + DialTimeout: time.Second * 3, + } + c, res, err := dialer.Dial(u.String(), nil) + if err != nil { + if res != nil && res.Body != nil { + bReason, _ := io.ReadAll(res.Body) + fmt.Printf("dial failed: %v, reason: %v\n", err, string(bReason)) + } else { + fmt.Printf("dial failed: %v\n", err) + } + return + } + c.WriteMessage(websocket.TextMessage, []byte(subscribeMsg)) + }() + + interrupt := make(chan os.Signal, 1) + signal.Notify(interrupt, os.Interrupt) + <-interrupt + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + engine.Shutdown(ctx) +} diff --git a/helper/da/proto/light.proto b/helper/da/proto/light.proto new file mode 100644 index 00000000..f816b54f --- /dev/null +++ b/helper/da/proto/light.proto @@ -0,0 +1,33 @@ +syntax = "proto3"; + +package light; + +option go_package = "proto/light"; + +service Light { + rpc Sample(SampleRequest) returns (SampleReply) {} + rpc Retrieve(RetrieveRequest) returns (RetrieveReply) {} +} + +// SampleRequest contains the blob to sample (by batch and blob index) and required sample times +message SampleRequest { + bytes stream_id = 1; + bytes batch_header_hash = 2; + uint32 blob_index = 3; + uint32 times = 4; +} + +// SampleReply contains the sample result +message SampleReply { + bool success = 1; +} + +message RetrieveRequest { + bytes batch_header_hash = 1; + uint32 blob_index = 2; +} + +message RetrieveReply { + bool status = 1; + bytes data = 2; +} \ No newline at end of file diff --git a/helper/da/service/handler.go b/helper/da/service/handler.go new file mode 100644 index 00000000..e7f5d19f --- /dev/null +++ b/helper/da/service/handler.go @@ -0,0 +1,186 @@ +package service + +import ( + "context" + "encoding/hex" + "os" + "os/exec" + "strconv" + "strings" + + "github.com/0glabs/0g-evmos/helper/da/client" + "github.com/0glabs/0g-evmos/helper/da/types" + "github.com/0glabs/0g-evmos/helper/da/utils/sizedw8grp" + + jsoniter "github.com/json-iterator/go" + "github.com/lesismal/nbio/nbhttp/websocket" + "github.com/pkg/errors" + "github.com/rs/zerolog/log" +) + +const ( + defaultClientInstance = 10 +) + +var rpcClient client.DaLightRpcClient + +func OnMessage(ctx context.Context, c *websocket.Conn, messageType websocket.MessageType, data []byte) { + if messageType == websocket.TextMessage { + rawMsg := unwrapJsonRpc(data) + if verifyQuery(rawMsg) { + eventStr := jsoniter.Get(rawMsg, "events").ToString() + events := map[string][]string{} + if err := jsoniter.UnmarshalFromString(eventStr, &events); err == nil { + dasRequestMap := make(map[string]string, 4) + for key, val := range events { + if strings.HasPrefix(key, "das_request.") { + dasRequestMap[strings.ReplaceAll(key, "das_request.", "")] = val[0] + } + } + if len(dasRequestMap) == 4 { + rid, _ := strconv.ParseUint(dasRequestMap["request_id"], 10, 64) + numBlobs, _ := strconv.ParseUint(dasRequestMap["num_blobs"], 10, 64) + req := types.DASRequest{ + RequestId: rid, + StreamId: dasRequestMap["stream_id"], + BatchHeaderHash: dasRequestMap["batch_header_hash"], + NumBlobs: numBlobs, + } + err := handleDasRequest(ctx, req) + + if err != nil { + log.Err(err).Msgf("failed to handle das request: %v, %v", req, err) + } else { + log.Info().Msgf("successfully handled das request: %v", req) + } + } + } + } + } else { + // TODO: handle other message + } +} + +func OnClose() { + if rpcClient != nil { + rpcClient.Destroy() + rpcClient = nil + } +} + +func unwrapJsonRpc(data []byte) []byte { + result := jsoniter.Get(data, "result") + if 0 < len(result.Keys()) { + return []byte(result.ToString()) + } + return []byte{} +} + +func verifyQuery(data []byte) bool { + if len(data) > 0 { + return jsoniter.Get(data, "query").ToString() == "tm.event='Tx'" + } + return false +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} + +func handleDasRequest(ctx context.Context, request types.DASRequest) error { + if rpcClient == nil { + addrVal := ctx.Value(types.DA_RPC_ADDRESS) + if addrVal == nil { + return errors.New("da light service address not found in context") + } + + limit := ctx.Value(types.INSTANCE_LIMIT) + if limit == nil { + limit = defaultClientInstance + } + + rpcClient = client.NewDaLightClient(addrVal.(string), limit.(int)) + } + + streamID, err := hex.DecodeString(request.StreamId) + if err != nil { + return err + } + + batchHeaderHash, err := hex.DecodeString(request.BatchHeaderHash) + if err != nil { + return err + } + + result := make(chan bool, request.NumBlobs) + taskCnt := min(rpcClient.GetInstanceCount(), int(request.NumBlobs)) + wg := sizedw8grp.New(taskCnt) + + for i := uint64(0); i < request.NumBlobs; i++ { + wg.Add() + go func(idx uint64) { + defer wg.Done() + ret, err := rpcClient.Sample(ctx, streamID, batchHeaderHash, uint32(idx), 1) + if err != nil { + log.Err(err).Msgf("failed to sample data availability with blob index %d", idx) + result <- false + } else { + log.Info().Msgf("sample result for blob index %d: %v", idx, ret) + result <- ret + } + }(i) + } + wg.Wait() + close(result) + + finalResult := true + for val := range result { + if !val { + finalResult = false + break + } + } + + return runEvmosdCliReportDasResult(ctx, request.RequestId, finalResult) +} + +func runEvmosdCliReportDasResult(ctx context.Context, requestId uint64, result bool) error { + relativePath := ctx.Value(types.NODE_CLI_RELATIVE_PATH) + if relativePath == nil { + return errors.New("relativePath not found in context") + } + + account := ctx.Value(types.NODE_CLI_EXEC_ACCOUNT) + if account == nil { + return errors.New("account not found in context") + } + + args := []string{ + "tx", + "das", + "report-das-result", + strconv.FormatUint(requestId, 10), + strconv.FormatBool(result), + "--from", account.(string), + "--gas-prices", "767812500aevmos", // TODO: use args to set gas prices + } + + homePath := ctx.Value(types.NODE_HOME_PATH) + if homePath != nil { + args = append(args, "--home", homePath.(string)) + } + + keyring := ctx.Value(types.NODE_CLI_EXEC_KEYRING) + if keyring != nil { + args = append(args, "--keyring-backend", keyring.(string)) + } + + cmdStr := relativePath.(string) + "evmosd" + cmd := exec.Command(cmdStr, append(args, "-y")...) + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + return cmd.Run() +} diff --git a/helper/da/types/dasreq.go b/helper/da/types/dasreq.go new file mode 100644 index 00000000..1c3b92e3 --- /dev/null +++ b/helper/da/types/dasreq.go @@ -0,0 +1,8 @@ +package types + +type DASRequest struct { + RequestId uint64 `json:"request_id"` + StreamId string `json:"stream_id"` + BatchHeaderHash string `json:"batch_header_hash"` + NumBlobs uint64 `json:"num_blobs"` +} diff --git a/helper/da/types/keys.go b/helper/da/types/keys.go new file mode 100644 index 00000000..e824f793 --- /dev/null +++ b/helper/da/types/keys.go @@ -0,0 +1,10 @@ +package types + +const ( + DA_RPC_ADDRESS = "rpc_address" + INSTANCE_LIMIT = "instance_limit" + NODE_CLI_RELATIVE_PATH = "relative_path" + NODE_CLI_EXEC_ACCOUNT = "node_exec_account" + NODE_CLI_EXEC_KEYRING = "node_exec_keyring" + NODE_HOME_PATH = "home_path" +) diff --git a/helper/da/utils/sizedw8grp/sizedw8grp.go b/helper/da/utils/sizedw8grp/sizedw8grp.go new file mode 100644 index 00000000..ac7348e6 --- /dev/null +++ b/helper/da/utils/sizedw8grp/sizedw8grp.go @@ -0,0 +1,51 @@ +package sizedw8grp + +import ( + "context" + "math" + "sync" +) + +type SizedWaitGroup struct { + Size int + + current chan struct{} + wg sync.WaitGroup +} + +func New(limit int) SizedWaitGroup { + size := math.MaxInt32 + if limit > 0 { + size = limit + } + return SizedWaitGroup{ + Size: size, + + current: make(chan struct{}, size), + wg: sync.WaitGroup{}, + } +} + +func (s *SizedWaitGroup) Add() { + _ = s.AddWithContext(context.Background()) +} + +func (s *SizedWaitGroup) AddWithContext(ctx context.Context) error { + select { + case <-ctx.Done(): + return ctx.Err() + case s.current <- struct{}{}: + break + } + s.wg.Add(1) + return nil +} + +func (s *SizedWaitGroup) Done() { + <-s.current + s.wg.Done() +} + +func (s *SizedWaitGroup) Wait() { + s.wg.Wait() +} diff --git a/localtestnet.sh b/localtestnet.sh index 90985775..94a751f5 100755 --- a/localtestnet.sh +++ b/localtestnet.sh @@ -20,11 +20,11 @@ relayerMnemonic="never reject sniff east arctic funny twin feed upper series sta # 0xa2F728F997f62F47D4262a70947F6c36885dF9fa # kava15tmj37vh7ch504px9fcfglmvx6y9m70646ev8t -DATA=~/.kava +DATA=~/.0gchain # remove any old state and config rm -rf $DATA -BINARY=kava +BINARY=0gchaind # Create new data directory, overwriting any that alread existed chainID="zgchain_8888-1" @@ -49,37 +49,37 @@ $BINARY config keyring-backend test # Create validator keys and add account to genesis validatorKeyName="validator" printf "$validatorMnemonic\n" | $BINARY keys add $validatorKeyName --recover -$BINARY add-genesis-account $validatorKeyName 2000000000ukava +$BINARY add-genesis-account $validatorKeyName 2000000000000000000000neuron # Create faucet keys and add account to genesis faucetKeyName="faucet" printf "$faucetMnemonic\n" | $BINARY keys add $faucetKeyName --recover -$BINARY add-genesis-account $faucetKeyName 1000000000ukava +$BINARY add-genesis-account $faucetKeyName 1000000000000000000000neuron evmFaucetKeyName="evm-faucet" printf "$evmFaucetMnemonic\n" | $BINARY keys add $evmFaucetKeyName --eth --recover -$BINARY add-genesis-account $evmFaucetKeyName 1000000000ukava +$BINARY add-genesis-account $evmFaucetKeyName 1000000000000000000000neuron userKeyName="user" printf "$userMnemonic\n" | $BINARY keys add $userKeyName --eth --recover -$BINARY add-genesis-account $userKeyName 1000000000ukava,1000000000usdx +$BINARY add-genesis-account $userKeyName 1000000000000000000000neuron,1000000000usdx relayerKeyName="relayer" printf "$relayerMnemonic\n" | $BINARY keys add $relayerKeyName --eth --recover -$BINARY add-genesis-account $relayerKeyName 1000000000ukava +$BINARY add-genesis-account $relayerKeyName 1000000000000000000000neuron -storageContractAcc="kava1l0j9dqdvd3fatfqywhm4y6avrln4jracrfy9hk" -$BINARY add-genesis-account $storageContractAcc 1000000000ukava +storageContractAcc="0g1vsjpjgw8p5f4x0nwp8ernl9lkszewcqqss7r5d" +$BINARY add-genesis-account $storageContractAcc 1000000000000000000000neuron # Create a delegation tx for the validator and add to genesis -$BINARY gentx $validatorKeyName 1000000000ukava --keyring-backend test --chain-id $chainID +$BINARY gentx $validatorKeyName 1000000000000000000000neuron --keyring-backend test --chain-id $chainID $BINARY collect-gentxs # Replace stake with ukava -sed -in-place='' 's/stake/ukava/g' $DATA/config/genesis.json +sed -in-place='' 's/stake/neuron/g' $DATA/config/genesis.json -# Replace the default evm denom of aphoton with ukava -sed -in-place='' 's/aphoton/akava/g' $DATA/config/genesis.json +# Replace the default evm denom of aphoton with neuron +sed -in-place='' 's/aphoton/neuron/g' $DATA/config/genesis.json GENESIS=$DATA/config/genesis.json TMP_GENESIS=$DATA/config/tmp_genesis.json @@ -101,17 +101,17 @@ cat $GENESIS | jq '.app_state.evm.params.chain_config.shanghai_block = null' >$T cat $GENESIS | jq '.app_state.evm.params.chain_config.cancun_block = null' >$TMP_GENESIS && mv $TMP_GENESIS $GENESIS # Add earn vault -cat $GENESIS | jq '.app_state.earn.params.allowed_vaults = [ - { - denom: "usdx", - strategies: ["STRATEGY_TYPE_HARD"], - }, - { - denom: "bkava", - strategies: ["STRATEGY_TYPE_SAVINGS"], - }]' >$TMP_GENESIS && mv $TMP_GENESIS $GENESIS +# cat $GENESIS | jq '.app_state.earn.params.allowed_vaults = [ +# { +# denom: "usdx", +# strategies: ["STRATEGY_TYPE_HARD"], +# }, +# { +# denom: "bkava", +# strategies: ["STRATEGY_TYPE_SAVINGS"], +# }]' >$TMP_GENESIS && mv $TMP_GENESIS $GENESIS -cat $GENESIS | jq '.app_state.savings.params.supported_denoms = ["bkava-kavavaloper1ffv7nhd3z6sych2qpqkk03ec6hzkmufyz4scd0"]' >$TMP_GENESIS && mv $TMP_GENESIS $GENESIS +# cat $GENESIS | jq '.app_state.savings.params.supported_denoms = ["bkava-kavavaloper1ffv7nhd3z6sych2qpqkk03ec6hzkmufyz4scd0"]' >$TMP_GENESIS && mv $TMP_GENESIS $GENESIS $BINARY config broadcast-mode sync diff --git a/migrate/doc.go b/migrate/doc.go index ca17d49e..45be79ff 100644 --- a/migrate/doc.go +++ b/migrate/doc.go @@ -11,8 +11,8 @@ There are two types of migration: Genesis migration starts a whole new blockchain (with new chain-id) for the new software version. In-Place upgrade keeps the blockchain (and chain-id) the same for the new software version. -We only support migrations between mainnet kava releases. -We only support migrations from the previous mainnet kava version to the current. We don't support migrating between two old versions, use the old software version for this. +We only support migrations between mainnet 0g-chain releases. +We only support migrations from the previous mainnet 0g-chain version to the current. We don't support migrating between two old versions, use the old software version for this. We only support migrations from old to new versions, not the other way around. Genesis Migration @@ -22,7 +22,7 @@ The process is: - marshal it to json (using current codec) On each release we can delete the previous releases migration and old GenesisState type. -eg kava-3 migrates `auth.GenesisState` from kava-2 to `auth.GenesisState` from kava-3, -but for kava-4 we don't need to keep around kava-2's `auth.GenesisState` type. +eg 0g-chain-3 migrates `auth.GenesisState` from 0g-chain-2 to `auth.GenesisState` from 0g-chain-3, +but for 0g-chain-4 we don't need to keep around 0g-chain-2's `auth.GenesisState` type. */ package migrate diff --git a/migrate/utils/periodic_vesting_reset_test.go b/migrate/utils/periodic_vesting_reset_test.go index ad6bbf1b..55c75b1a 100644 --- a/migrate/utils/periodic_vesting_reset_test.go +++ b/migrate/utils/periodic_vesting_reset_test.go @@ -5,6 +5,7 @@ import ( "time" sdkmath "cosmossdk.io/math" + "github.com/0glabs/0g-chain/chaincfg" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -41,7 +42,7 @@ func TestResetPeriodVestingAccount_NoVestingPeriods(t *testing.T) { } func TestResetPeriodVestingAccount_SingleVestingPeriod_Vested(t *testing.T) { - balance := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))) + balance := sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))) vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past periods := vestingtypes.Periods{ @@ -64,7 +65,7 @@ func TestResetPeriodVestingAccount_SingleVestingPeriod_Vested(t *testing.T) { } func TestResetPeriodVestingAccount_SingleVestingPeriod_Vesting(t *testing.T) { - balance := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))) + balance := sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))) vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past periods := vestingtypes.Periods{ @@ -97,7 +98,7 @@ func TestResetPeriodVestingAccount_SingleVestingPeriod_Vesting(t *testing.T) { } func TestResetPeriodVestingAccount_SingleVestingPeriod_ExactStartTime(t *testing.T) { - balance := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))) + balance := sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))) vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past periods := vestingtypes.Periods{ @@ -125,25 +126,25 @@ func TestResetPeriodVestingAccount_SingleVestingPeriod_ExactStartTime(t *testing } func TestResetPeriodVestingAccount_MultiplePeriods(t *testing.T) { - balance := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(4e6))) + balance := sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(4e6))) vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past periods := vestingtypes.Periods{ vestingtypes.Period{ Length: 15 * 24 * 60 * 60, // -15 days - vested - Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), + Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))), }, vestingtypes.Period{ Length: 15 * 24 * 60 * 60, // 0 days - exact on the start time - Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), + Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))), }, vestingtypes.Period{ Length: 15 * 24 * 60 * 60, // +15 days - vesting - Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), + Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))), }, vestingtypes.Period{ Length: 15 * 24 * 60 * 60, // +30 days - vesting - Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), + Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))), }, } @@ -159,36 +160,36 @@ func TestResetPeriodVestingAccount_MultiplePeriods(t *testing.T) { expectedPeriods := []vestingtypes.Period{ { Length: 15 * 24 * 60 * 60, // 15 days - Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), + Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))), }, { Length: 15 * 24 * 60 * 60, // 15 days - Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), + Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))), }, } - assert.Equal(t, sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(2e6))), vacc.OriginalVesting, "expected original vesting to be updated") + assert.Equal(t, sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(2e6))), vacc.OriginalVesting, "expected original vesting to be updated") assert.Equal(t, newVestingStartTime.Unix(), vacc.StartTime, "expected vesting start time to be updated") assert.Equal(t, expectedEndtime, vacc.EndTime, "expected vesting end time end at last period") assert.Equal(t, expectedPeriods, vacc.VestingPeriods, "expected vesting periods to be updated") } func TestResetPeriodVestingAccount_DelegatedVesting_GreaterThanVesting(t *testing.T) { - balance := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(3e6))) + balance := sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(3e6))) vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past periods := vestingtypes.Periods{ vestingtypes.Period{ Length: 15 * 24 * 60 * 60, // -15 days - vested - Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), + Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))), }, vestingtypes.Period{ Length: 15 * 24 * 60 * 60, // 0 days - exact on the start time - Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), + Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))), }, vestingtypes.Period{ Length: 15 * 24 * 60 * 60, // +15 days - vesting - Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), + Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))), }, } @@ -198,35 +199,35 @@ func TestResetPeriodVestingAccount_DelegatedVesting_GreaterThanVesting(t *testin newVestingStartTime := vestingStartTime.Add(30 * 24 * time.Hour) ResetPeriodicVestingAccount(vacc, newVestingStartTime) - assert.Equal(t, sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(2e6))), vacc.DelegatedFree, "expected delegated free to be updated") - assert.Equal(t, sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), vacc.DelegatedVesting, "expected delegated vesting to be updated") + assert.Equal(t, sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(2e6))), vacc.DelegatedFree, "expected delegated free to be updated") + assert.Equal(t, sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))), vacc.DelegatedVesting, "expected delegated vesting to be updated") } func TestResetPeriodVestingAccount_DelegatedVesting_LessThanVested(t *testing.T) { - balance := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(3e6))) + balance := sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(3e6))) vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past periods := vestingtypes.Periods{ vestingtypes.Period{ Length: 15 * 24 * 60 * 60, // -15 days - vested - Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), + Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))), }, vestingtypes.Period{ Length: 15 * 24 * 60 * 60, // 0 days - exact on the start time - Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), + Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))), }, vestingtypes.Period{ Length: 15 * 24 * 60 * 60, // +15 days - vesting - Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), + Amount: sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))), }, } vacc := createVestingAccount(balance, vestingStartTime, periods) - vacc.TrackDelegation(vestingStartTime, balance, sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6)))) + vacc.TrackDelegation(vestingStartTime, balance, sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6)))) newVestingStartTime := vestingStartTime.Add(30 * 24 * time.Hour) ResetPeriodicVestingAccount(vacc, newVestingStartTime) assert.Equal(t, sdk.Coins(nil), vacc.DelegatedFree, "expected delegrated free to be unmodified") - assert.Equal(t, sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), vacc.DelegatedVesting, "expected delegated vesting to be unmodified") + assert.Equal(t, sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(1e6))), vacc.DelegatedVesting, "expected delegated vesting to be unmodified") } diff --git a/networks/local/Makefile b/networks/local/Makefile index 7ab650be..51796d03 100644 --- a/networks/local/Makefile +++ b/networks/local/Makefile @@ -1,4 +1,4 @@ all: - docker build --tag kava/kavanode kavanode + docker build --tag 0glabs/0g-chain-node 0g-chain-node .PHONY: all diff --git a/proto/crypto/vrf/keys.proto b/proto/crypto/vrf/keys.proto new file mode 100644 index 00000000..4526cdf4 --- /dev/null +++ b/proto/crypto/vrf/keys.proto @@ -0,0 +1,25 @@ +// Copyright Tharsis Labs Ltd.(Evmos) +// SPDX-License-Identifier:ENCL-1.0(https://github.com/evmos/evmos/blob/main/LICENSE) +syntax = "proto3"; +package crypto.vrf; + +import "gogoproto/gogo.proto"; + +option go_package = "github.com/0glabs/0g-chain/crypto/vrf"; + +// PubKey defines a type alias for an vrf.PublicKey that implements +// Vrf's PubKey interface. It represents the 32-byte compressed public +// key format. +message PubKey { + option (gogoproto.goproto_stringer) = false; + + // key is the public key in byte form + bytes key = 1; +} + +// PrivKey defines a type alias for an vrf.PrivateKey that implements +// Vrf's PrivateKey interface. +message PrivKey { + // key is the private key in byte form + bytes key = 1; +} diff --git a/proto/kava/auction/v1beta1/auction.proto b/proto/kava/auction/v1beta1/auction.proto deleted file mode 100644 index a5e8c7d8..00000000 --- a/proto/kava/auction/v1beta1/auction.proto +++ /dev/null @@ -1,98 +0,0 @@ -syntax = "proto3"; -package kava.auction.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; - -option go_package = "github.com/kava-labs/kava/x/auction/types"; -option (gogoproto.goproto_getters_all) = false; - -// BaseAuction defines common attributes of all auctions -message BaseAuction { - option (cosmos_proto.implements_interface) = "Auction"; - - uint64 id = 1 [(gogoproto.customname) = "ID"]; - - string initiator = 2; - - cosmos.base.v1beta1.Coin lot = 3 [(gogoproto.nullable) = false]; - - bytes bidder = 4 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - - cosmos.base.v1beta1.Coin bid = 5 [(gogoproto.nullable) = false]; - - bool has_received_bids = 6; - - google.protobuf.Timestamp end_time = 7 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; - - google.protobuf.Timestamp max_end_time = 8 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; -} - -// SurplusAuction is a forward auction that burns what it receives from bids. -// It is normally used to sell off excess pegged asset acquired by the CDP system. -message SurplusAuction { - option (cosmos_proto.implements_interface) = "Auction"; - - BaseAuction base_auction = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; -} - -// DebtAuction is a reverse auction that mints what it pays out. -// It is normally used to acquire pegged asset to cover the CDP system's debts that were not covered by selling -// collateral. -message DebtAuction { - option (cosmos_proto.implements_interface) = "Auction"; - - BaseAuction base_auction = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; - - cosmos.base.v1beta1.Coin corresponding_debt = 2 [(gogoproto.nullable) = false]; -} - -// CollateralAuction is a two phase auction. -// Initially, in forward auction phase, bids can be placed up to a max bid. -// Then it switches to a reverse auction phase, where the initial amount up for auction is bid down. -// Unsold Lot is sent to LotReturns, being divided among the addresses by weight. -// Collateral auctions are normally used to sell off collateral seized from CDPs. -message CollateralAuction { - option (cosmos_proto.implements_interface) = "Auction"; - - BaseAuction base_auction = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; - - cosmos.base.v1beta1.Coin corresponding_debt = 2 [(gogoproto.nullable) = false]; - - cosmos.base.v1beta1.Coin max_bid = 3 [(gogoproto.nullable) = false]; - - WeightedAddresses lot_returns = 4 [(gogoproto.nullable) = false]; -} - -// WeightedAddresses is a type for storing some addresses and associated weights. -message WeightedAddresses { - repeated bytes addresses = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - - repeated bytes weights = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/auction/v1beta1/genesis.proto b/proto/kava/auction/v1beta1/genesis.proto deleted file mode 100644 index ca6ca799..00000000 --- a/proto/kava/auction/v1beta1/genesis.proto +++ /dev/null @@ -1,55 +0,0 @@ -syntax = "proto3"; -package kava.auction.v1beta1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/any.proto"; -import "google/protobuf/duration.proto"; - -option go_package = "github.com/kava-labs/kava/x/auction/types"; -option (gogoproto.goproto_getters_all) = false; - -// GenesisState defines the auction module's genesis state. -message GenesisState { - uint64 next_auction_id = 1; - - Params params = 2 [(gogoproto.nullable) = false]; - - // Genesis auctions - repeated google.protobuf.Any auctions = 3 [(cosmos_proto.accepts_interface) = "GenesisAuction"]; -} - -// Params defines the parameters for the issuance module. -message Params { - reserved 2; - reserved "bid_duration"; - - google.protobuf.Duration max_auction_duration = 1 [ - (gogoproto.nullable) = false, - (gogoproto.stdduration) = true - ]; - - google.protobuf.Duration forward_bid_duration = 6 [ - (gogoproto.nullable) = false, - (gogoproto.stdduration) = true - ]; - google.protobuf.Duration reverse_bid_duration = 7 [ - (gogoproto.nullable) = false, - (gogoproto.stdduration) = true - ]; - - bytes increment_surplus = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - bytes increment_debt = 4 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - bytes increment_collateral = 5 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/auction/v1beta1/query.proto b/proto/kava/auction/v1beta1/query.proto deleted file mode 100644 index 5c93ffa0..00000000 --- a/proto/kava/auction/v1beta1/query.proto +++ /dev/null @@ -1,84 +0,0 @@ -syntax = "proto3"; -package kava.auction.v1beta1; - -import "cosmos/base/query/v1beta1/pagination.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "google/protobuf/any.proto"; -import "kava/auction/v1beta1/genesis.proto"; - -option go_package = "github.com/kava-labs/kava/x/auction/types"; - -// Query defines the gRPC querier service for auction module -service Query { - // Params queries all parameters of the auction module. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/auction/v1beta1/params"; - } - - // Auction queries an individual Auction by auction ID - rpc Auction(QueryAuctionRequest) returns (QueryAuctionResponse) { - option (google.api.http).get = "/kava/auction/v1beta1/auctions/{auction_id}"; - } - - // Auctions queries auctions filtered by asset denom, owner address, phase, and auction type - rpc Auctions(QueryAuctionsRequest) returns (QueryAuctionsResponse) { - option (google.api.http).get = "/kava/auction/v1beta1/auctions"; - } - - // NextAuctionID queries the next auction ID - rpc NextAuctionID(QueryNextAuctionIDRequest) returns (QueryNextAuctionIDResponse) { - option (google.api.http).get = "/kava/auction/v1beta1/next-auction-id"; - } -} - -// QueryParamsRequest defines the request type for querying x/auction parameters. -message QueryParamsRequest {} - -// QueryParamsResponse defines the response type for querying x/auction parameters. -message QueryParamsResponse { - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryAuctionRequest is the request type for the Query/Auction RPC method. -message QueryAuctionRequest { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - uint64 auction_id = 1; -} - -// QueryAuctionResponse is the response type for the Query/Auction RPC method. -message QueryAuctionResponse { - google.protobuf.Any auction = 1; -} - -// QueryAuctionsRequest is the request type for the Query/Auctions RPC method. -message QueryAuctionsRequest { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string type = 1; - string owner = 2; - string denom = 3; - string phase = 4; - - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 5; -} - -// QueryAuctionsResponse is the response type for the Query/Auctions RPC method. -message QueryAuctionsResponse { - repeated google.protobuf.Any auctions = 1; - - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryNextAuctionIDRequest defines the request type for querying x/auction next auction ID. -message QueryNextAuctionIDRequest {} - -// QueryNextAuctionIDResponse defines the response type for querying x/auction next auction ID. -message QueryNextAuctionIDResponse { - uint64 id = 1; -} diff --git a/proto/kava/auction/v1beta1/tx.proto b/proto/kava/auction/v1beta1/tx.proto deleted file mode 100644 index f6675392..00000000 --- a/proto/kava/auction/v1beta1/tx.proto +++ /dev/null @@ -1,28 +0,0 @@ -syntax = "proto3"; -package kava.auction.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/auction/types"; - -// Msg defines the auction Msg service. -service Msg { - // PlaceBid message type used by bidders to place bids on auctions - rpc PlaceBid(MsgPlaceBid) returns (MsgPlaceBidResponse); -} - -// MsgPlaceBid represents a message used by bidders to place bids on auctions -message MsgPlaceBid { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - uint64 auction_id = 1; - - string bidder = 2; - - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// MsgPlaceBidResponse defines the Msg/PlaceBid response type. -message MsgPlaceBidResponse {} diff --git a/proto/kava/bep3/v1beta1/.tx.proto.swp b/proto/kava/bep3/v1beta1/.tx.proto.swp deleted file mode 100644 index 338957ff..00000000 Binary files a/proto/kava/bep3/v1beta1/.tx.proto.swp and /dev/null differ diff --git a/proto/kava/bep3/v1beta1/bep3.proto b/proto/kava/bep3/v1beta1/bep3.proto deleted file mode 100644 index 9b6825c0..00000000 --- a/proto/kava/bep3/v1beta1/bep3.proto +++ /dev/null @@ -1,160 +0,0 @@ -syntax = "proto3"; -package kava.bep3.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/duration.proto"; - -option go_package = "github.com/kava-labs/kava/x/bep3/types"; - -// Params defines the parameters for the bep3 module. -message Params { - // asset_params define the parameters for each bep3 asset - repeated AssetParam asset_params = 1 [ - (gogoproto.castrepeated) = "AssetParams", - (gogoproto.nullable) = false - ]; -} - -// AssetParam defines parameters for each bep3 asset. -message AssetParam { - // denom represents the denominatin for this asset - string denom = 1; - // coin_id represents the registered coin type to use (https://github.com/satoshilabs/slips/blob/master/slip-0044.md) - int64 coin_id = 2 [(gogoproto.customname) = "CoinID"]; - // supply_limit defines the maximum supply allowed for the asset - a total or time based rate limit - SupplyLimit supply_limit = 3 [(gogoproto.nullable) = false]; - // active specifies if the asset is live or paused - bool active = 4; - // deputy_address the kava address of the deputy - bytes deputy_address = 5 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - // fixed_fee defines the fee for incoming swaps - string fixed_fee = 6 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - // min_swap_amount defines the minimum amount able to be swapped in a single message - string min_swap_amount = 7 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - // max_swap_amount defines the maximum amount able to be swapped in a single message - string max_swap_amount = 8 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - // min_block_lock defined the minimum blocks to lock - uint64 min_block_lock = 9; - // min_block_lock defined the maximum blocks to lock - uint64 max_block_lock = 10; -} - -// SupplyLimit define the absolute and time-based limits for an assets's supply. -message SupplyLimit { - // limit defines the total supply allowed - string limit = 1 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - // time_limited enables or disables time based supply limiting - bool time_limited = 2; - // time_period specifies the duration that time_based_limit is evalulated - google.protobuf.Duration time_period = 3 [ - (gogoproto.nullable) = false, - (gogoproto.stdduration) = true - ]; - // time_based_limit defines the maximum supply that can be swapped within time_period - string time_based_limit = 4 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} - -// SwapStatus is the status of an AtomicSwap -enum SwapStatus { - option (gogoproto.goproto_enum_prefix) = false; - - // SWAP_STATUS_UNSPECIFIED represents an unspecified status - SWAP_STATUS_UNSPECIFIED = 0; - // SWAP_STATUS_OPEN represents an open swap - SWAP_STATUS_OPEN = 1; - // SWAP_STATUS_COMPLETED represents a completed swap - SWAP_STATUS_COMPLETED = 2; - // SWAP_STATUS_EXPIRED represents an expired swap - SWAP_STATUS_EXPIRED = 3; -} - -// SwapDirection is the direction of an AtomicSwap -enum SwapDirection { - option (gogoproto.goproto_enum_prefix) = false; - - // SWAP_DIRECTION_UNSPECIFIED represents unspecified or invalid swap direcation - SWAP_DIRECTION_UNSPECIFIED = 0; - // SWAP_DIRECTION_INCOMING represents is incoming swap (to the kava chain) - SWAP_DIRECTION_INCOMING = 1; - // SWAP_DIRECTION_OUTGOING represents an outgoing swap (from the kava chain) - SWAP_DIRECTION_OUTGOING = 2; -} - -// AtomicSwap defines an atomic swap between chains for the pricefeed module. -message AtomicSwap { - // amount represents the amount being swapped - repeated cosmos.base.v1beta1.Coin amount = 1 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; - // random_number_hash represents the hash of the random number - bytes random_number_hash = 2 [(gogoproto.casttype) = "github.com/cometbft/cometbft/libs/bytes.HexBytes"]; - // expire_height represents the height when the swap expires - uint64 expire_height = 3; - // timestamp represents the timestamp of the swap - int64 timestamp = 4; - // sender is the kava chain sender of the swap - bytes sender = 5 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - // recipient is the kava chain recipient of the swap - bytes recipient = 6 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - // sender_other_chain is the sender on the other chain - string sender_other_chain = 7; - // recipient_other_chain is the recipient on the other chain - string recipient_other_chain = 8; - // closed_block is the block when the swap is closed - int64 closed_block = 9; - // status represents the current status of the swap - SwapStatus status = 10; - // cross_chain identifies whether the atomic swap is cross chain - bool cross_chain = 11; - // direction identifies if the swap is incoming or outgoing - SwapDirection direction = 12; -} - -// AssetSupply defines information about an asset's supply. -message AssetSupply { - // incoming_supply represents the incoming supply of an asset - cosmos.base.v1beta1.Coin incoming_supply = 1 [(gogoproto.nullable) = false]; - // outgoing_supply represents the outgoing supply of an asset - cosmos.base.v1beta1.Coin outgoing_supply = 2 [(gogoproto.nullable) = false]; - // current_supply represents the current on-chain supply of an asset - cosmos.base.v1beta1.Coin current_supply = 3 [(gogoproto.nullable) = false]; - // time_limited_current_supply represents the time limited current supply of an asset - cosmos.base.v1beta1.Coin time_limited_current_supply = 4 [(gogoproto.nullable) = false]; - // time_elapsed represents the time elapsed - google.protobuf.Duration time_elapsed = 5 [ - (gogoproto.nullable) = false, - (gogoproto.stdduration) = true - ]; -} diff --git a/proto/kava/bep3/v1beta1/genesis.proto b/proto/kava/bep3/v1beta1/genesis.proto deleted file mode 100644 index 1e353ea6..00000000 --- a/proto/kava/bep3/v1beta1/genesis.proto +++ /dev/null @@ -1,32 +0,0 @@ -syntax = "proto3"; -package kava.bep3.v1beta1; - -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; -import "kava/bep3/v1beta1/bep3.proto"; - -option go_package = "github.com/kava-labs/kava/x/bep3/types"; - -// GenesisState defines the pricefeed module's genesis state. -message GenesisState { - // params defines all the parameters of the module. - Params params = 1 [(gogoproto.nullable) = false]; - - // atomic_swaps represents the state of stored atomic swaps - repeated AtomicSwap atomic_swaps = 2 [ - (gogoproto.castrepeated) = "AtomicSwaps", - (gogoproto.nullable) = false - ]; - - // supplies represents the supply information of each atomic swap - repeated AssetSupply supplies = 3 [ - (gogoproto.castrepeated) = "AssetSupplies", - (gogoproto.nullable) = false - ]; - - // previous_block_time represents the time of the previous block - google.protobuf.Timestamp previous_block_time = 4 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/bep3/v1beta1/query.proto b/proto/kava/bep3/v1beta1/query.proto deleted file mode 100644 index dc851580..00000000 --- a/proto/kava/bep3/v1beta1/query.proto +++ /dev/null @@ -1,165 +0,0 @@ -syntax = "proto3"; -package kava.bep3.v1beta1; - -import "cosmos/base/query/v1beta1/pagination.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "google/protobuf/duration.proto"; -import "kava/bep3/v1beta1/bep3.proto"; - -option go_package = "github.com/kava-labs/kava/x/bep3/types"; - -// Query defines the gRPC querier service for bep3 module -service Query { - // Params queries module params - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/bep3/v1beta1/params"; - } - - // AssetSupply queries info about an asset's supply - rpc AssetSupply(QueryAssetSupplyRequest) returns (QueryAssetSupplyResponse) { - option (google.api.http).get = "/kava/bep3/v1beta1/assetsupply/{denom}"; - } - - // AssetSupplies queries a list of asset supplies - rpc AssetSupplies(QueryAssetSuppliesRequest) returns (QueryAssetSuppliesResponse) { - option (google.api.http).get = "/kava/bep3/v1beta1/assetsupplies"; - } - - // AtomicSwap queries info about an atomic swap - rpc AtomicSwap(QueryAtomicSwapRequest) returns (QueryAtomicSwapResponse) { - option (google.api.http).get = "/kava/bep3/v1beta1/atomicswap/{swap_id}"; - } - - // AtomicSwaps queries a list of atomic swaps - rpc AtomicSwaps(QueryAtomicSwapsRequest) returns (QueryAtomicSwapsResponse) { - option (google.api.http).get = "/kava/bep3/v1beta1/atomicswaps"; - } -} - -// QueryParamsRequest defines the request type for querying x/bep3 parameters. -message QueryParamsRequest {} - -// QueryParamsResponse defines the response type for querying x/bep3 parameters. -message QueryParamsResponse { - // params represents the parameters of the module - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryAssetSupplyRequest is the request type for the Query/AssetSupply RPC method. -message QueryAssetSupplyRequest { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - // denom filters the asset response for the specified denom - string denom = 1; -} - -// AssetSupplyResponse defines information about an asset's supply. -message AssetSupplyResponse { - // incoming_supply represents the incoming supply of an asset - cosmos.base.v1beta1.Coin incoming_supply = 1 [(gogoproto.nullable) = false]; - // outgoing_supply represents the outgoing supply of an asset - cosmos.base.v1beta1.Coin outgoing_supply = 2 [(gogoproto.nullable) = false]; - // current_supply represents the current on-chain supply of an asset - cosmos.base.v1beta1.Coin current_supply = 3 [(gogoproto.nullable) = false]; - // time_limited_current_supply represents the time limited current supply of an asset - cosmos.base.v1beta1.Coin time_limited_current_supply = 4 [(gogoproto.nullable) = false]; - // time_elapsed represents the time elapsed - google.protobuf.Duration time_elapsed = 5 [ - (gogoproto.nullable) = false, - (gogoproto.stdduration) = true - ]; -} - -// QueryAssetSupplyResponse is the response type for the Query/AssetSupply RPC method. -message QueryAssetSupplyResponse { - // asset_supply represents the supply of the asset - AssetSupplyResponse asset_supply = 1 [(gogoproto.nullable) = false]; -} - -// QueryAssetSuppliesRequest is the request type for the Query/AssetSupplies RPC method. -message QueryAssetSuppliesRequest { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; -} - -// QueryAssetSuppliesResponse is the response type for the Query/AssetSupplies RPC method. -message QueryAssetSuppliesResponse { - // asset_supplies represents the supplies of returned assets - repeated AssetSupplyResponse asset_supplies = 1 [(gogoproto.nullable) = false]; -} - -// QueryAtomicSwapRequest is the request type for the Query/AtomicSwap RPC method. -message QueryAtomicSwapRequest { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - // swap_id represents the id of the swap to query - string swap_id = 1; -} - -// QueryAtomicSwapResponse is the response type for the Query/AtomicSwap RPC method. -message QueryAtomicSwapResponse { - AtomicSwapResponse atomic_swap = 2 [(gogoproto.nullable) = false]; -} - -// AtomicSwapResponse represents the returned atomic swap properties -message AtomicSwapResponse { - // id represents the id of the atomic swap - string id = 1; - // amount represents the amount being swapped - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; - // random_number_hash represents the hash of the random number - string random_number_hash = 3; - // expire_height represents the height when the swap expires - uint64 expire_height = 4; - // timestamp represents the timestamp of the swap - int64 timestamp = 5; - // sender is the kava chain sender of the swap - string sender = 6 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // recipient is the kava chain recipient of the swap - string recipient = 7 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // sender_other_chain is the sender on the other chain - string sender_other_chain = 8; - // recipient_other_chain is the recipient on the other chain - string recipient_other_chain = 9; - // closed_block is the block when the swap is closed - int64 closed_block = 10; - // status represents the current status of the swap - SwapStatus status = 11; - // cross_chain identifies whether the atomic swap is cross chain - bool cross_chain = 12; - // direction identifies if the swap is incoming or outgoing - SwapDirection direction = 13; -} - -// QueryAtomicSwapsRequest is the request type for the Query/AtomicSwaps RPC method. -message QueryAtomicSwapsRequest { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - // involve filters by address - string involve = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // expiration filters by expiration block height - uint64 expiration = 2; - // status filters by swap status - SwapStatus status = 3; - // direction fitlers by swap direction - SwapDirection direction = 4; - - cosmos.base.query.v1beta1.PageRequest pagination = 5; -} - -// QueryAtomicSwapsResponse is the response type for the Query/AtomicSwaps RPC method. -message QueryAtomicSwapsResponse { - // atomic_swap represents the returned atomic swaps for the request - repeated AtomicSwapResponse atomic_swaps = 1 [(gogoproto.nullable) = false]; - - cosmos.base.query.v1beta1.PageResponse pagination = 3; -} diff --git a/proto/kava/bep3/v1beta1/tx.proto b/proto/kava/bep3/v1beta1/tx.proto deleted file mode 100644 index 1ff090b9..00000000 --- a/proto/kava/bep3/v1beta1/tx.proto +++ /dev/null @@ -1,69 +0,0 @@ -syntax = "proto3"; -package kava.bep3.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/bep3/types"; - -// Msg defines the bep3 Msg service. -service Msg { - // CreateAtomicSwap defines a method for creating an atomic swap - rpc CreateAtomicSwap(MsgCreateAtomicSwap) returns (MsgCreateAtomicSwapResponse); - - // ClaimAtomicSwap defines a method for claiming an atomic swap - rpc ClaimAtomicSwap(MsgClaimAtomicSwap) returns (MsgClaimAtomicSwapResponse); - - // RefundAtomicSwap defines a method for refunding an atomic swap - rpc RefundAtomicSwap(MsgRefundAtomicSwap) returns (MsgRefundAtomicSwapResponse); -} - -// MsgCreateAtomicSwap defines the Msg/CreateAtomicSwap request type. -message MsgCreateAtomicSwap { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string from = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string to = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string recipient_other_chain = 3; - string sender_other_chain = 4; - string random_number_hash = 5; - int64 timestamp = 6; - repeated cosmos.base.v1beta1.Coin amount = 7 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; - uint64 height_span = 8; -} - -// MsgCreateAtomicSwapResponse defines the Msg/CreateAtomicSwap response type. -message MsgCreateAtomicSwapResponse {} - -// MsgClaimAtomicSwap defines the Msg/ClaimAtomicSwap request type. -message MsgClaimAtomicSwap { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string from = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string swap_id = 2 [(gogoproto.customname) = "SwapID"]; - string random_number = 3; -} - -// MsgClaimAtomicSwapResponse defines the Msg/ClaimAtomicSwap response type. -message MsgClaimAtomicSwapResponse {} - -// MsgRefundAtomicSwap defines the Msg/RefundAtomicSwap request type. -message MsgRefundAtomicSwap { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string from = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string swap_id = 2 [(gogoproto.customname) = "SwapID"]; -} - -// MsgRefundAtomicSwapResponse defines the Msg/RefundAtomicSwap response type. -message MsgRefundAtomicSwapResponse {} diff --git a/proto/kava/cdp/v1beta1/cdp.proto b/proto/kava/cdp/v1beta1/cdp.proto deleted file mode 100644 index 1ee21001..00000000 --- a/proto/kava/cdp/v1beta1/cdp.proto +++ /dev/null @@ -1,59 +0,0 @@ -syntax = "proto3"; -package kava.cdp.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; - -option go_package = "github.com/kava-labs/kava/x/cdp/types"; -option (gogoproto.goproto_getters_all) = false; - -// CDP defines the state of a single collateralized debt position. -message CDP { - uint64 id = 1 [(gogoproto.customname) = "ID"]; - bytes owner = 2 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - string type = 3; - cosmos.base.v1beta1.Coin collateral = 4 [(gogoproto.nullable) = false]; - cosmos.base.v1beta1.Coin principal = 5 [(gogoproto.nullable) = false]; - cosmos.base.v1beta1.Coin accumulated_fees = 6 [(gogoproto.nullable) = false]; - google.protobuf.Timestamp fees_updated = 7 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - string interest_factor = 8 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// Deposit defines an amount of coins deposited by an account to a cdp -message Deposit { - uint64 cdp_id = 1 [(gogoproto.customname) = "CdpID"]; - string depositor = 2 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// TotalPrincipal defines the total principal of a given collateral type -message TotalPrincipal { - string collateral_type = 1; - cosmos.base.v1beta1.Coin amount = 2 [(gogoproto.nullable) = false]; -} - -// TotalCollateral defines the total collateral of a given collateral type -message TotalCollateral { - string collateral_type = 1; - cosmos.base.v1beta1.Coin amount = 2 [(gogoproto.nullable) = false]; -} - -// OwnerCDPIndex defines the cdp ids for a single cdp owner -message OwnerCDPIndex { - repeated uint64 cdp_ids = 1 [(gogoproto.customname) = "CdpIDs"]; -} diff --git a/proto/kava/cdp/v1beta1/genesis.proto b/proto/kava/cdp/v1beta1/genesis.proto deleted file mode 100644 index a993bbae..00000000 --- a/proto/kava/cdp/v1beta1/genesis.proto +++ /dev/null @@ -1,155 +0,0 @@ -syntax = "proto3"; -package kava.cdp.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; -import "kava/cdp/v1beta1/cdp.proto"; - -option go_package = "github.com/kava-labs/kava/x/cdp/types"; - -// GenesisState defines the cdp module's genesis state. -message GenesisState { - // params defines all the parameters of the module. - Params params = 1 [(gogoproto.nullable) = false]; - - repeated CDP cdps = 2 [ - (gogoproto.customname) = "CDPs", - (gogoproto.castrepeated) = "CDPs", - (gogoproto.nullable) = false - ]; - repeated Deposit deposits = 3 [ - (gogoproto.castrepeated) = "Deposits", - (gogoproto.nullable) = false - ]; - uint64 starting_cdp_id = 4 [(gogoproto.customname) = "StartingCdpID"]; - string debt_denom = 5; - string gov_denom = 6; - repeated GenesisAccumulationTime previous_accumulation_times = 7 [ - (gogoproto.castrepeated) = "GenesisAccumulationTimes", - (gogoproto.nullable) = false - ]; - repeated GenesisTotalPrincipal total_principals = 8 [ - (gogoproto.castrepeated) = "GenesisTotalPrincipals", - (gogoproto.nullable) = false - ]; -} - -// Params defines the parameters for the cdp module. -message Params { - repeated CollateralParam collateral_params = 1 [ - (gogoproto.castrepeated) = "CollateralParams", - (gogoproto.nullable) = false - ]; - DebtParam debt_param = 2 [(gogoproto.nullable) = false]; - - cosmos.base.v1beta1.Coin global_debt_limit = 3 [(gogoproto.nullable) = false]; - string surplus_auction_threshold = 4 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - string surplus_auction_lot = 5 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - string debt_auction_threshold = 6 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - string debt_auction_lot = 7 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - bool circuit_breaker = 8; - - int64 liquidation_block_interval = 9; -} - -// DebtParam defines governance params for debt assets -message DebtParam { - string denom = 1; - string reference_asset = 2; - string conversion_factor = 3 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - string debt_floor = 4 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} - -// CollateralParam defines governance parameters for each collateral type within the cdp module -message CollateralParam { - string denom = 1; - string type = 2; - string liquidation_ratio = 3 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - cosmos.base.v1beta1.Coin debt_limit = 4 [(gogoproto.nullable) = false]; - string stability_fee = 5 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string auction_size = 6 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - string liquidation_penalty = 7 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string spot_market_id = 8 [(gogoproto.customname) = "SpotMarketID"]; - string liquidation_market_id = 9 [(gogoproto.customname) = "LiquidationMarketID"]; - string keeper_reward_percentage = 10 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string check_collateralization_index_count = 11 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - string conversion_factor = 12 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} - -// GenesisAccumulationTime defines the previous distribution time and its corresponding denom -message GenesisAccumulationTime { - string collateral_type = 1; - google.protobuf.Timestamp previous_accumulation_time = 2 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - string interest_factor = 3 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// GenesisTotalPrincipal defines the total principal and its corresponding collateral type -message GenesisTotalPrincipal { - string collateral_type = 1; - string total_principal = 2 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/cdp/v1beta1/query.proto b/proto/kava/cdp/v1beta1/query.proto deleted file mode 100644 index ec27b840..00000000 --- a/proto/kava/cdp/v1beta1/query.proto +++ /dev/null @@ -1,160 +0,0 @@ -syntax = "proto3"; -package kava.cdp.v1beta1; - -import "cosmos/auth/v1beta1/auth.proto"; -import "cosmos/base/query/v1beta1/pagination.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "google/protobuf/timestamp.proto"; -import "kava/cdp/v1beta1/cdp.proto"; -import "kava/cdp/v1beta1/genesis.proto"; - -option go_package = "github.com/kava-labs/kava/x/cdp/types"; - -// Query defines the gRPC querier service for cdp module -service Query { - // Params queries all parameters of the cdp module. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/cdp/v1beta1/params"; - } - - // Accounts queries the CDP module accounts. - rpc Accounts(QueryAccountsRequest) returns (QueryAccountsResponse) { - option (google.api.http).get = "/kava/cdp/v1beta1/accounts"; - } - - // TotalPrincipal queries the total principal of a given collateral type. - rpc TotalPrincipal(QueryTotalPrincipalRequest) returns (QueryTotalPrincipalResponse) { - option (google.api.http).get = "/kava/cdp/v1beta1/totalPrincipal"; - } - - // TotalCollateral queries the total collateral of a given collateral type. - rpc TotalCollateral(QueryTotalCollateralRequest) returns (QueryTotalCollateralResponse) { - option (google.api.http).get = "/kava/cdp/v1beta1/totalCollateral"; - } - - // Cdps queries all active CDPs. - rpc Cdps(QueryCdpsRequest) returns (QueryCdpsResponse) { - option (google.api.http).get = "/kava/cdp/v1beta1/cdps"; - } - - // Cdp queries a CDP with the input owner address and collateral type. - rpc Cdp(QueryCdpRequest) returns (QueryCdpResponse) { - option (google.api.http).get = "/kava/cdp/v1beta1/cdps/{owner}/{collateral_type}"; - } - - // Deposits queries deposits associated with the CDP owned by an address for a collateral type. - rpc Deposits(QueryDepositsRequest) returns (QueryDepositsResponse) { - option (google.api.http).get = "/kava/cdp/v1beta1/cdps/deposits/{owner}/{collateral_type}"; - } -} - -// QueryParamsRequest defines the request type for the Query/Params RPC method. -message QueryParamsRequest {} - -// QueryParamsResponse defines the response type for the Query/Params RPC method. -message QueryParamsResponse { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryAccountsRequest defines the request type for the Query/Accounts RPC method. -message QueryAccountsRequest {} - -// QueryAccountsResponse defines the response type for the Query/Accounts RPC method. -message QueryAccountsResponse { - repeated cosmos.auth.v1beta1.ModuleAccount accounts = 1 [(gogoproto.nullable) = false]; -} - -// QueryCdpRequest defines the request type for the Query/Cdp RPC method. -message QueryCdpRequest { - string collateral_type = 1; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; -} - -// QueryCdpResponse defines the response type for the Query/Cdp RPC method. -message QueryCdpResponse { - CDPResponse cdp = 1 [(gogoproto.nullable) = false]; -} - -// QueryCdpsRequest is the params for a filtered CDP query, the request type for the Query/Cdps RPC method. -message QueryCdpsRequest { - string collateral_type = 1; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - uint64 id = 3 [(gogoproto.customname) = "ID"]; - // sdk.Dec as a string - string ratio = 4; - - cosmos.base.query.v1beta1.PageRequest pagination = 5; -} - -// QueryCdpsResponse defines the response type for the Query/Cdps RPC method. -message QueryCdpsResponse { - repeated CDPResponse cdps = 1 [ - (gogoproto.castrepeated) = "CDPResponses", - (gogoproto.nullable) = false - ]; - - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryDepositsRequest defines the request type for the Query/Deposits RPC method. -message QueryDepositsRequest { - string collateral_type = 1; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; -} - -// QueryDepositsResponse defines the response type for the Query/Deposits RPC method. -message QueryDepositsResponse { - repeated Deposit deposits = 1 [ - (gogoproto.castrepeated) = "Deposits", - (gogoproto.nullable) = false - ]; -} - -// QueryTotalPrincipalRequest defines the request type for the Query/TotalPrincipal RPC method. -message QueryTotalPrincipalRequest { - string collateral_type = 1; -} - -// QueryTotalPrincipalResponse defines the response type for the Query/TotalPrincipal RPC method. -message QueryTotalPrincipalResponse { - repeated TotalPrincipal total_principal = 1 [ - (gogoproto.castrepeated) = "TotalPrincipals", - (gogoproto.nullable) = false - ]; -} - -// QueryTotalCollateralRequest defines the request type for the Query/TotalCollateral RPC method. -message QueryTotalCollateralRequest { - string collateral_type = 1; -} - -// QueryTotalCollateralResponse defines the response type for the Query/TotalCollateral RPC method. -message QueryTotalCollateralResponse { - repeated TotalCollateral total_collateral = 1 [ - (gogoproto.castrepeated) = "TotalCollaterals", - (gogoproto.nullable) = false - ]; -} - -// CDPResponse defines the state of a single collateralized debt position. -message CDPResponse { - uint64 id = 1 [(gogoproto.customname) = "ID"]; - string owner = 2; - string type = 3; - cosmos.base.v1beta1.Coin collateral = 4 [(gogoproto.nullable) = false]; - cosmos.base.v1beta1.Coin principal = 5 [(gogoproto.nullable) = false]; - cosmos.base.v1beta1.Coin accumulated_fees = 6 [(gogoproto.nullable) = false]; - google.protobuf.Timestamp fees_updated = 7 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - string interest_factor = 8; - cosmos.base.v1beta1.Coin collateral_value = 9 [(gogoproto.nullable) = false]; - string collateralization_ratio = 10; -} diff --git a/proto/kava/cdp/v1beta1/tx.proto b/proto/kava/cdp/v1beta1/tx.proto deleted file mode 100644 index 29c00688..00000000 --- a/proto/kava/cdp/v1beta1/tx.proto +++ /dev/null @@ -1,91 +0,0 @@ -syntax = "proto3"; -package kava.cdp.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/cdp/types"; - -// Msg defines the cdp Msg service. -service Msg { - // CreateCDP defines a method to create a new CDP. - rpc CreateCDP(MsgCreateCDP) returns (MsgCreateCDPResponse); - // Deposit defines a method to deposit to a CDP. - rpc Deposit(MsgDeposit) returns (MsgDepositResponse); - // Withdraw defines a method to withdraw collateral from a CDP. - rpc Withdraw(MsgWithdraw) returns (MsgWithdrawResponse); - // DrawDebt defines a method to draw debt from a CDP. - rpc DrawDebt(MsgDrawDebt) returns (MsgDrawDebtResponse); - // RepayDebt defines a method to repay debt from a CDP. - rpc RepayDebt(MsgRepayDebt) returns (MsgRepayDebtResponse); - // Liquidate defines a method to attempt to liquidate a CDP whos - // collateralization ratio is under its liquidation ratio. - rpc Liquidate(MsgLiquidate) returns (MsgLiquidateResponse); -} - -// MsgCreateCDP defines a message to create a new CDP. -message MsgCreateCDP { - string sender = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - cosmos.base.v1beta1.Coin collateral = 2 [(gogoproto.nullable) = false]; - cosmos.base.v1beta1.Coin principal = 3 [(gogoproto.nullable) = false]; - string collateral_type = 4; -} - -// MsgCreateCDPResponse defines the Msg/CreateCDP response type. -message MsgCreateCDPResponse { - uint64 cdp_id = 1 [(gogoproto.customname) = "CdpID"]; -} - -// MsgDeposit defines a message to deposit to a CDP. -message MsgDeposit { - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - cosmos.base.v1beta1.Coin collateral = 3 [(gogoproto.nullable) = false]; - string collateral_type = 4; -} - -// MsgDepositResponse defines the Msg/Deposit response type. -message MsgDepositResponse {} - -// MsgWithdraw defines a message to withdraw collateral from a CDP. -message MsgWithdraw { - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - cosmos.base.v1beta1.Coin collateral = 3 [(gogoproto.nullable) = false]; - string collateral_type = 4; -} - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -message MsgWithdrawResponse {} - -// MsgDrawDebt defines a message to draw debt from a CDP. -message MsgDrawDebt { - string sender = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string collateral_type = 2; - cosmos.base.v1beta1.Coin principal = 3 [(gogoproto.nullable) = false]; -} - -// MsgDrawDebtResponse defines the Msg/DrawDebt response type. -message MsgDrawDebtResponse {} - -// MsgRepayDebt defines a message to repay debt from a CDP. -message MsgRepayDebt { - string sender = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string collateral_type = 2; - cosmos.base.v1beta1.Coin payment = 3 [(gogoproto.nullable) = false]; -} - -// MsgRepayDebtResponse defines the Msg/RepayDebt response type. -message MsgRepayDebtResponse {} - -// MsgLiquidate defines a message to attempt to liquidate a CDP whos -// collateralization ratio is under its liquidation ratio. -message MsgLiquidate { - string keeper = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string borrower = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string collateral_type = 3; -} - -// MsgLiquidateResponse defines the Msg/Liquidate response type. -message MsgLiquidateResponse {} diff --git a/proto/kava/committee/v1beta1/committee.proto b/proto/kava/committee/v1beta1/committee.proto deleted file mode 100644 index b0ab001b..00000000 --- a/proto/kava/committee/v1beta1/committee.proto +++ /dev/null @@ -1,70 +0,0 @@ -syntax = "proto3"; -package kava.committee.v1beta1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/any.proto"; -import "google/protobuf/duration.proto"; - -option go_package = "github.com/kava-labs/kava/x/committee/types"; -option (gogoproto.goproto_getters_all) = false; - -// BaseCommittee is a common type shared by all Committees -message BaseCommittee { - option (cosmos_proto.implements_interface) = "Committee"; - option (gogoproto.goproto_stringer) = false; - - uint64 id = 1 [(gogoproto.customname) = "ID"]; - string description = 2; - repeated bytes members = 3 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - repeated google.protobuf.Any permissions = 4 [(cosmos_proto.accepts_interface) = "Permission"]; - - // Smallest percentage that must vote for a proposal to pass - string vote_threshold = 5 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The length of time a proposal remains active for. Proposals will close earlier if they get enough votes. - google.protobuf.Duration proposal_duration = 6 [ - (gogoproto.nullable) = false, - (gogoproto.stdduration) = true - ]; - TallyOption tally_option = 7; -} - -// MemberCommittee is an alias of BaseCommittee -message MemberCommittee { - option (cosmos_proto.implements_interface) = "Committee"; - option (gogoproto.goproto_stringer) = false; - - BaseCommittee base_committee = 1 [(gogoproto.embed) = true]; -} - -// TokenCommittee supports voting on proposals by token holders -message TokenCommittee { - option (cosmos_proto.implements_interface) = "Committee"; - option (gogoproto.goproto_stringer) = false; - - BaseCommittee base_committee = 1 [(gogoproto.embed) = true]; - string quorum = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string tally_denom = 3; -} - -// TallyOption enumerates the valid types of a tally. -enum TallyOption { - option (gogoproto.goproto_enum_prefix) = false; - - // TALLY_OPTION_UNSPECIFIED defines a null tally option. - TALLY_OPTION_UNSPECIFIED = 0; - // Votes are tallied each block and the proposal passes as soon as the vote threshold is reached - TALLY_OPTION_FIRST_PAST_THE_POST = 1; - // Votes are tallied exactly once, when the deadline time is reached - TALLY_OPTION_DEADLINE = 2; -} diff --git a/proto/kava/committee/v1beta1/genesis.proto b/proto/kava/committee/v1beta1/genesis.proto deleted file mode 100644 index 4c973352..00000000 --- a/proto/kava/committee/v1beta1/genesis.proto +++ /dev/null @@ -1,62 +0,0 @@ -syntax = "proto3"; -package kava.committee.v1beta1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/any.proto"; -import "google/protobuf/timestamp.proto"; - -option go_package = "github.com/kava-labs/kava/x/committee/types"; - -// GenesisState defines the committee module's genesis state. -message GenesisState { - option (gogoproto.goproto_getters) = false; - - uint64 next_proposal_id = 1 [(gogoproto.customname) = "NextProposalID"]; - repeated google.protobuf.Any committees = 2 [(cosmos_proto.accepts_interface) = "Committee"]; - repeated Proposal proposals = 3 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "Proposals" - ]; - repeated Vote votes = 4 [(gogoproto.nullable) = false]; -} - -// Proposal is an internal record of a governance proposal submitted to a committee. -message Proposal { - option (gogoproto.goproto_getters) = false; - option (gogoproto.goproto_stringer) = false; - - google.protobuf.Any content = 1 [(cosmos_proto.accepts_interface) = "cosmos.gov.v1beta1.Content"]; - uint64 id = 2 [(gogoproto.customname) = "ID"]; - uint64 committee_id = 3 [(gogoproto.customname) = "CommitteeID"]; - google.protobuf.Timestamp deadline = 4 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; -} - -// Vote is an internal record of a single governance vote. -message Vote { - option (gogoproto.goproto_getters) = false; - - uint64 proposal_id = 1 [(gogoproto.customname) = "ProposalID"]; - bytes voter = 2 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - VoteType vote_type = 3; -} - -// VoteType enumerates the valid types of a vote. -enum VoteType { - option (gogoproto.goproto_enum_prefix) = false; - - // VOTE_TYPE_UNSPECIFIED defines a no-op vote option. - VOTE_TYPE_UNSPECIFIED = 0; - // VOTE_TYPE_YES defines a yes vote option. - VOTE_TYPE_YES = 1; - // VOTE_TYPE_NO defines a no vote option. - VOTE_TYPE_NO = 2; - // VOTE_TYPE_ABSTAIN defines an abstain vote option. - VOTE_TYPE_ABSTAIN = 3; -} diff --git a/proto/kava/committee/v1beta1/permissions.proto b/proto/kava/committee/v1beta1/permissions.proto deleted file mode 100644 index 997f21af..00000000 --- a/proto/kava/committee/v1beta1/permissions.proto +++ /dev/null @@ -1,72 +0,0 @@ -syntax = "proto3"; -package kava.committee.v1beta1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/committee/types"; - -// GodPermission allows any governance proposal. It is used mainly for testing. -message GodPermission { - option (cosmos_proto.implements_interface) = "Permission"; -} - -// SoftwareUpgradePermission permission type for software upgrade proposals -message SoftwareUpgradePermission { - option (cosmos_proto.implements_interface) = "Permission"; -} - -// TextPermission allows any text governance proposal. -message TextPermission { - option (cosmos_proto.implements_interface) = "Permission"; -} - -// CommunityCDPRepayDebtPermission allows submission of CommunityCDPRepayDebtProposal -message CommunityCDPRepayDebtPermission { - option (cosmos_proto.implements_interface) = "Permission"; -} - -// CommunityCDPWithdrawCollateralPermission allows submission of CommunityCDPWithdrawCollateralProposal -message CommunityCDPWithdrawCollateralPermission { - option (cosmos_proto.implements_interface) = "Permission"; -} - -// CommunityPoolLendWithdrawPermission allows submission of CommunityPoolLendWithdrawProposal -message CommunityPoolLendWithdrawPermission { - option (cosmos_proto.implements_interface) = "Permission"; -} - -// ParamsChangePermission allows any parameter or sub parameter change proposal. -message ParamsChangePermission { - option (cosmos_proto.implements_interface) = "Permission"; - repeated AllowedParamsChange allowed_params_changes = 1 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "AllowedParamsChanges" - ]; -} - -// AllowedParamsChange contains data on the allowed parameter changes for subspace, key, and sub params requirements. -message AllowedParamsChange { - string subspace = 1; - string key = 2; - - // Requirements for when the subparam value is a single record. This contains list of allowed attribute keys that can - // be changed on the subparam record. - repeated string single_subparam_allowed_attrs = 3; - - // Requirements for when the subparam value is a list of records. The requirements contains requirements for each - // record in the list. - repeated SubparamRequirement multi_subparams_requirements = 4 [(gogoproto.nullable) = false]; -} - -// SubparamRequirement contains requirements for a single record in a subparam value list -message SubparamRequirement { - // The required attr key of the param record. - string key = 1; - - // The required param value for the param record key. The key and value is used to match to the target param record. - string val = 2; - - // The sub param attrs that are allowed to be changed. - repeated string allowed_subparam_attr_changes = 3; -} diff --git a/proto/kava/committee/v1beta1/proposal.proto b/proto/kava/committee/v1beta1/proposal.proto deleted file mode 100644 index 22b61dce..00000000 --- a/proto/kava/committee/v1beta1/proposal.proto +++ /dev/null @@ -1,27 +0,0 @@ -syntax = "proto3"; -package kava.committee.v1beta1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/any.proto"; - -option go_package = "github.com/kava-labs/kava/x/committee/types"; -option (gogoproto.goproto_getters_all) = false; - -// CommitteeChangeProposal is a gov proposal for creating a new committee or modifying an existing one. -message CommitteeChangeProposal { - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - string title = 1; - string description = 2; - google.protobuf.Any new_committee = 3 [(cosmos_proto.accepts_interface) = "Committee"]; -} - -// CommitteeDeleteProposal is a gov proposal for removing a committee. -message CommitteeDeleteProposal { - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - string title = 1; - string description = 2; - uint64 committee_id = 3 [(gogoproto.customname) = "CommitteeID"]; -} diff --git a/proto/kava/committee/v1beta1/query.proto b/proto/kava/committee/v1beta1/query.proto deleted file mode 100644 index d99ff7ef..00000000 --- a/proto/kava/committee/v1beta1/query.proto +++ /dev/null @@ -1,181 +0,0 @@ -syntax = "proto3"; -package kava.committee.v1beta1; - -import "cosmos/base/query/v1beta1/pagination.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "google/protobuf/any.proto"; -import "google/protobuf/timestamp.proto"; -import "kava/committee/v1beta1/genesis.proto"; - -option go_package = "github.com/kava-labs/kava/x/committee/types"; -option (gogoproto.goproto_getters_all) = false; - -// Query defines the gRPC querier service for committee module -service Query { - // Committees queries all committess of the committee module. - rpc Committees(QueryCommitteesRequest) returns (QueryCommitteesResponse) { - option (google.api.http).get = "/kava/committee/v1beta1/committees"; - } - // Committee queries a committee based on committee ID. - rpc Committee(QueryCommitteeRequest) returns (QueryCommitteeResponse) { - option (google.api.http).get = "/kava/committee/v1beta1/committees/{committee_id}"; - } - // Proposals queries proposals based on committee ID. - rpc Proposals(QueryProposalsRequest) returns (QueryProposalsResponse) { - option (google.api.http).get = "/kava/committee/v1beta1/proposals"; - } - // Deposits queries a proposal based on proposal ID. - rpc Proposal(QueryProposalRequest) returns (QueryProposalResponse) { - option (google.api.http).get = "/kava/committee/v1beta1/proposals/{proposal_id}"; - } - // NextProposalID queries the next proposal ID of the committee module. - rpc NextProposalID(QueryNextProposalIDRequest) returns (QueryNextProposalIDResponse) { - option (google.api.http).get = "/kava/committee/v1beta1/next-proposal-id"; - } - // Votes queries all votes for a single proposal ID. - rpc Votes(QueryVotesRequest) returns (QueryVotesResponse) { - option (google.api.http).get = "/kava/committee/v1beta1/proposals/{proposal_id}/votes"; - } - // Vote queries the vote of a single voter for a single proposal ID. - rpc Vote(QueryVoteRequest) returns (QueryVoteResponse) { - option (google.api.http).get = "/kava/committee/v1beta1/proposals/{proposal_id}/votes/{voter}"; - } - // Tally queries the tally of a single proposal ID. - rpc Tally(QueryTallyRequest) returns (QueryTallyResponse) { - option (google.api.http).get = "/kava/committee/v1beta1/proposals/{proposal_id}/tally"; - } - // RawParams queries the raw params data of any subspace and key. - rpc RawParams(QueryRawParamsRequest) returns (QueryRawParamsResponse) { - option (google.api.http).get = "/kava/committee/v1beta1/raw-params"; - } -} - -// QueryCommitteesRequest defines the request type for querying x/committee committees. -message QueryCommitteesRequest {} - -// QueryCommitteesResponse defines the response type for querying x/committee committees. -message QueryCommitteesResponse { - repeated google.protobuf.Any committees = 1 [(cosmos_proto.accepts_interface) = "Committee"]; -} - -// QueryCommitteeRequest defines the request type for querying x/committee committee. -message QueryCommitteeRequest { - uint64 committee_id = 1; -} - -// QueryCommitteeResponse defines the response type for querying x/committee committee. -message QueryCommitteeResponse { - google.protobuf.Any committee = 1 [(cosmos_proto.accepts_interface) = "Committee"]; -} - -// QueryProposalsRequest defines the request type for querying x/committee proposals. -message QueryProposalsRequest { - uint64 committee_id = 1; -} - -// QueryProposalsResponse defines the response type for querying x/committee proposals. -message QueryProposalsResponse { - repeated QueryProposalResponse proposals = 1 [(gogoproto.nullable) = false]; -} - -// QueryProposalRequest defines the request type for querying x/committee proposal. -message QueryProposalRequest { - uint64 proposal_id = 1; -} - -// QueryProposalResponse defines the response type for querying x/committee proposal. -message QueryProposalResponse { - google.protobuf.Any pub_proposal = 1 [ - (cosmos_proto.accepts_interface) = "cosmos.gov.v1beta1.Content", - (gogoproto.customname) = "PubProposal" - ]; - uint64 id = 2 [(gogoproto.customname) = "ID"]; - uint64 committee_id = 3 [(gogoproto.customname) = "CommitteeID"]; - google.protobuf.Timestamp deadline = 4 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; -} - -// QueryNextProposalIDRequest defines the request type for querying x/committee NextProposalID. -message QueryNextProposalIDRequest {} - -// QueryNextProposalIDRequest defines the response type for querying x/committee NextProposalID. -message QueryNextProposalIDResponse { - uint64 next_proposal_id = 1 [(gogoproto.customname) = "NextProposalID"]; -} - -// QueryVotesRequest defines the request type for querying x/committee votes. -message QueryVotesRequest { - uint64 proposal_id = 1; - cosmos.base.query.v1beta1.PageRequest pagination = 2; -} - -// QueryVotesResponse defines the response type for querying x/committee votes. -message QueryVotesResponse { - // votes defined the queried votes. - repeated QueryVoteResponse votes = 1 [(gogoproto.nullable) = false]; - - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryVoteRequest defines the request type for querying x/committee vote. -message QueryVoteRequest { - uint64 proposal_id = 1; - string voter = 2; -} - -// QueryVoteResponse defines the response type for querying x/committee vote. -message QueryVoteResponse { - uint64 proposal_id = 1 [(gogoproto.customname) = "ProposalID"]; - string voter = 2; - VoteType vote_type = 3; -} - -// QueryTallyRequest defines the request type for querying x/committee tally. -message QueryTallyRequest { - uint64 proposal_id = 1; -} - -// QueryTallyResponse defines the response type for querying x/committee tally. -message QueryTallyResponse { - uint64 proposal_id = 1 [(gogoproto.customname) = "ProposalID"]; - string yes_votes = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string no_votes = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string current_votes = 4 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string possible_votes = 5 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string vote_threshold = 6 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string quorum = 7 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// QueryRawParamsRequest defines the request type for querying x/committee raw params. -message QueryRawParamsRequest { - string subspace = 1; - string key = 2; -} - -// QueryRawParamsResponse defines the response type for querying x/committee raw params. -message QueryRawParamsResponse { - string raw_data = 1; -} diff --git a/proto/kava/committee/v1beta1/tx.proto b/proto/kava/committee/v1beta1/tx.proto deleted file mode 100644 index c3a32021..00000000 --- a/proto/kava/committee/v1beta1/tx.proto +++ /dev/null @@ -1,40 +0,0 @@ -syntax = "proto3"; -package kava.committee.v1beta1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/any.proto"; -import "kava/committee/v1beta1/genesis.proto"; - -option go_package = "github.com/kava-labs/kava/x/committee/types"; -option (gogoproto.goproto_getters_all) = false; - -// Msg defines the committee Msg service -service Msg { - // SubmitProposal defines a method for submitting a committee proposal - rpc SubmitProposal(MsgSubmitProposal) returns (MsgSubmitProposalResponse); - // Vote defines a method for voting on a proposal - rpc Vote(MsgVote) returns (MsgVoteResponse); -} - -// MsgSubmitProposal is used by committee members to create a new proposal that they can vote on. -message MsgSubmitProposal { - google.protobuf.Any pub_proposal = 1 [(cosmos_proto.accepts_interface) = "cosmos.gov.v1beta1.Content"]; - string proposer = 2; - uint64 committee_id = 3 [(gogoproto.customname) = "CommitteeID"]; -} - -// MsgSubmitProposalResponse defines the SubmitProposal response type -message MsgSubmitProposalResponse { - uint64 proposal_id = 1 [(gogoproto.customname) = "ProposalID"]; -} - -// MsgVote is submitted by committee members to vote on proposals. -message MsgVote { - uint64 proposal_id = 1 [(gogoproto.customname) = "ProposalID"]; - string voter = 2; - VoteType vote_type = 3; -} - -// MsgVoteResponse defines the Vote response type -message MsgVoteResponse {} diff --git a/proto/kava/community/v1beta1/genesis.proto b/proto/kava/community/v1beta1/genesis.proto deleted file mode 100644 index f7f6549d..00000000 --- a/proto/kava/community/v1beta1/genesis.proto +++ /dev/null @@ -1,18 +0,0 @@ -syntax = "proto3"; -package kava.community.v1beta1; - -import "gogoproto/gogo.proto"; -import "kava/community/v1beta1/params.proto"; -import "kava/community/v1beta1/staking.proto"; - -option go_package = "github.com/kava-labs/kava/x/community/types"; - -// GenesisState defines the community module's genesis state. -message GenesisState { - // params defines all the parameters related to commmunity - Params params = 1 [(gogoproto.nullable) = false]; - - // StakingRewardsState stores the internal staking reward data required to - // track staking rewards across blocks - StakingRewardsState staking_rewards_state = 2 [(gogoproto.nullable) = false]; -} diff --git a/proto/kava/community/v1beta1/params.proto b/proto/kava/community/v1beta1/params.proto deleted file mode 100644 index 53c3c118..00000000 --- a/proto/kava/community/v1beta1/params.proto +++ /dev/null @@ -1,35 +0,0 @@ -syntax = "proto3"; -package kava.community.v1beta1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; - -option go_package = "github.com/kava-labs/kava/x/community/types"; - -// Params defines the parameters of the community module. -message Params { - option (gogoproto.equal) = true; - - // upgrade_time_disable_inflation is the time at which to disable mint and kavadist module inflation. - // If set to 0, inflation will be disabled from block 1. - google.protobuf.Timestamp upgrade_time_disable_inflation = 1 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - - // staking_rewards_per_second is the amount paid out to delegators each block from the community account - string staking_rewards_per_second = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", - (gogoproto.nullable) = false - ]; - - // upgrade_time_set_staking_rewards_per_second is the initial staking_rewards_per_second to set - // and use when the disable inflation time is reached - string upgrade_time_set_staking_rewards_per_second = 3 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/community/v1beta1/proposal.proto b/proto/kava/community/v1beta1/proposal.proto deleted file mode 100644 index 0f6cb637..00000000 --- a/proto/kava/community/v1beta1/proposal.proto +++ /dev/null @@ -1,57 +0,0 @@ -syntax = "proto3"; -package kava.community.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/community/types"; - -// CommunityPoolLendDepositProposal deposits from the community pool into lend -message CommunityPoolLendDepositProposal { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - repeated cosmos.base.v1beta1.Coin amount = 3 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// CommunityPoolLendWithdrawProposal withdraws a lend position back to the community pool -message CommunityPoolLendWithdrawProposal { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - repeated cosmos.base.v1beta1.Coin amount = 3 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// CommunityCDPRepayDebtProposal repays a cdp debt position owned by the community module -// This proposal exists primarily to allow committees to repay community module cdp debts. -message CommunityCDPRepayDebtProposal { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - string collateral_type = 3; - cosmos.base.v1beta1.Coin payment = 4 [(gogoproto.nullable) = false]; -} - -// CommunityCDPWithdrawCollateralProposal withdraws cdp collateral owned by the community module -// This proposal exists primarily to allow committees to withdraw community module cdp collateral. -message CommunityCDPWithdrawCollateralProposal { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - string collateral_type = 3; - cosmos.base.v1beta1.Coin collateral = 4 [(gogoproto.nullable) = false]; -} diff --git a/proto/kava/community/v1beta1/query.proto b/proto/kava/community/v1beta1/query.proto deleted file mode 100644 index b21bb059..00000000 --- a/proto/kava/community/v1beta1/query.proto +++ /dev/null @@ -1,81 +0,0 @@ -syntax = "proto3"; -package kava.community.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "kava/community/v1beta1/params.proto"; - -option go_package = "github.com/kava-labs/kava/x/community/types"; - -// Query defines the gRPC querier service for x/community. -service Query { - // Params queires the module params. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/community/v1beta1/params"; - } - - // Balance queries the balance of all coins of x/community module. - rpc Balance(QueryBalanceRequest) returns (QueryBalanceResponse) { - option (google.api.http).get = "/kava/community/v1beta1/balance"; - } - - // TotalBalance queries the balance of all coins, including x/distribution, - // x/community, and supplied balances. - rpc TotalBalance(QueryTotalBalanceRequest) returns (QueryTotalBalanceResponse) { - option (google.api.http).get = "/kava/community/v1beta1/total_balance"; - } - - // AnnualizedRewards calculates and returns the current annualized reward percentages, - // like staking rewards, for the chain. - rpc AnnualizedRewards(QueryAnnualizedRewardsRequest) returns (QueryAnnualizedRewardsResponse) { - option (google.api.http).get = "/kava/community/v1beta1/annualized_rewards"; - } -} - -// QueryParams defines the request type for querying x/community params. -message QueryParamsRequest {} - -// QueryParamsResponse defines the response type for querying x/community params. -message QueryParamsResponse { - // params represents the community module parameters - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryBalanceRequest defines the request type for querying x/community balance. -message QueryBalanceRequest {} - -// QueryBalanceResponse defines the response type for querying x/community balance. -message QueryBalanceResponse { - repeated cosmos.base.v1beta1.Coin coins = 1 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// QueryTotalBalanceRequest defines the request type for querying total community pool balance. -message QueryTotalBalanceRequest {} - -// QueryTotalBalanceResponse defines the response type for querying total -// community pool balance. This matches the x/distribution CommunityPool query response. -message QueryTotalBalanceResponse { - // pool defines community pool's coins. - repeated cosmos.base.v1beta1.DecCoin pool = 1 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.DecCoins", - (gogoproto.nullable) = false - ]; -} - -// QueryAnnualizedRewardsRequest defines the request type for querying the annualized rewards. -message QueryAnnualizedRewardsRequest {} - -// QueryAnnualizedRewardsResponse defines the response type for querying the annualized rewards. -message QueryAnnualizedRewardsResponse { - // staking_rewards is the calculated annualized staking rewards percentage rate - string staking_rewards = 1 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/community/v1beta1/staking.proto b/proto/kava/community/v1beta1/staking.proto deleted file mode 100644 index e49fe58f..00000000 --- a/proto/kava/community/v1beta1/staking.proto +++ /dev/null @@ -1,26 +0,0 @@ -syntax = "proto3"; -package kava.community.v1beta1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; - -option go_package = "github.com/kava-labs/kava/x/community/types"; - -// StakingRewardsState represents the state of staking reward accumulation between blocks. -message StakingRewardsState { - // last_accumulation_time represents the last block time which rewards where calculated and distributed. - // This may be zero to signal accumulation should start on the next interval. - google.protobuf.Timestamp last_accumulation_time = 1 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - - // accumulated_truncation_error represents the sum of previous errors due to truncation on payout - // This value will always be on the interval [0, 1). - string last_truncation_error = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/community/v1beta1/tx.proto b/proto/kava/community/v1beta1/tx.proto deleted file mode 100644 index 6a7f523b..00000000 --- a/proto/kava/community/v1beta1/tx.proto +++ /dev/null @@ -1,47 +0,0 @@ -syntax = "proto3"; -package kava.community.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "kava/community/v1beta1/params.proto"; - -option go_package = "github.com/kava-labs/kava/x/community/types"; -option (gogoproto.equal_all) = true; - -// Msg defines the community Msg service. -service Msg { - // FundCommunityPool defines a method to allow an account to directly fund the community module account. - rpc FundCommunityPool(MsgFundCommunityPool) returns (MsgFundCommunityPoolResponse); - - // UpdateParams defines a method to allow an account to update the community module parameters. - rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse); -} - -// MsgFundCommunityPool allows an account to directly fund the community module account. -message MsgFundCommunityPool { - option (gogoproto.goproto_getters) = false; - - repeated cosmos.base.v1beta1.Coin amount = 1 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; - string depositor = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; -} - -// MsgFundCommunityPoolResponse defines the Msg/FundCommunityPool response type. -message MsgFundCommunityPoolResponse {} - -// MsgUpdateParams allows an account to update the community module parameters. -message MsgUpdateParams { - option (gogoproto.goproto_getters) = false; - - // authority is the address that controls the module (defaults to x/gov unless overwritten). - string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - // params defines the x/community parameters to update. - Params params = 2 [(gogoproto.nullable) = false]; -} - -// MsgUpdateParamsResponse defines the Msg/UpdateParams response type. -message MsgUpdateParamsResponse {} diff --git a/proto/kava/earn/v1beta1/genesis.proto b/proto/kava/earn/v1beta1/genesis.proto deleted file mode 100644 index 38b73bb4..00000000 --- a/proto/kava/earn/v1beta1/genesis.proto +++ /dev/null @@ -1,24 +0,0 @@ -syntax = "proto3"; -package kava.earn.v1beta1; - -import "gogoproto/gogo.proto"; -import "kava/earn/v1beta1/params.proto"; -import "kava/earn/v1beta1/vault.proto"; - -option go_package = "github.com/kava-labs/kava/x/earn/types"; - -// GenesisState defines the earn module's genesis state. -message GenesisState { - // params defines all the parameters related to earn - Params params = 1 [(gogoproto.nullable) = false]; - // vault_records defines the available vaults - repeated VaultRecord vault_records = 2 [ - (gogoproto.castrepeated) = "VaultRecords", - (gogoproto.nullable) = false - ]; - // share_records defines the owned shares of each vault - repeated VaultShareRecord vault_share_records = 3 [ - (gogoproto.castrepeated) = "VaultShareRecords", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/earn/v1beta1/params.proto b/proto/kava/earn/v1beta1/params.proto deleted file mode 100644 index ba430839..00000000 --- a/proto/kava/earn/v1beta1/params.proto +++ /dev/null @@ -1,15 +0,0 @@ -syntax = "proto3"; -package kava.earn.v1beta1; - -import "gogoproto/gogo.proto"; -import "kava/earn/v1beta1/vault.proto"; - -option go_package = "github.com/kava-labs/kava/x/earn/types"; - -// Params defines the parameters of the earn module. -message Params { - repeated AllowedVault allowed_vaults = 1 [ - (gogoproto.castrepeated) = "AllowedVaults", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/earn/v1beta1/proposal.proto b/proto/kava/earn/v1beta1/proposal.proto deleted file mode 100644 index 18b6af17..00000000 --- a/proto/kava/earn/v1beta1/proposal.proto +++ /dev/null @@ -1,55 +0,0 @@ -syntax = "proto3"; -package kava.earn.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/earn/types"; - -// CommunityPoolDepositProposal deposits from the community pool into an earn vault -message CommunityPoolDepositProposal { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// CommunityPoolDepositProposalJSON defines a CommunityPoolDepositProposal with a deposit -message CommunityPoolDepositProposalJSON { - option (gogoproto.goproto_stringer) = true; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; - repeated cosmos.base.v1beta1.Coin deposit = 4 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// CommunityPoolWithdrawProposal withdraws from an earn vault back to community pool -message CommunityPoolWithdrawProposal { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// CommunityPoolWithdrawProposalJSON defines a CommunityPoolWithdrawProposal with a deposit -message CommunityPoolWithdrawProposalJSON { - option (gogoproto.goproto_stringer) = true; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; - repeated cosmos.base.v1beta1.Coin deposit = 4 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} diff --git a/proto/kava/earn/v1beta1/query.proto b/proto/kava/earn/v1beta1/query.proto deleted file mode 100644 index 8d788d85..00000000 --- a/proto/kava/earn/v1beta1/query.proto +++ /dev/null @@ -1,160 +0,0 @@ -syntax = "proto3"; -package kava.earn.v1beta1; - -import "cosmos/base/query/v1beta1/pagination.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "kava/earn/v1beta1/params.proto"; -import "kava/earn/v1beta1/strategy.proto"; -import "kava/earn/v1beta1/vault.proto"; - -option go_package = "github.com/kava-labs/kava/x/earn/types"; -option (gogoproto.goproto_getters_all) = false; - -// Query defines the gRPC querier service for earn module -service Query { - // Params queries all parameters of the earn module. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/earn/v1beta1/params"; - } - - // Vaults queries all vaults - rpc Vaults(QueryVaultsRequest) returns (QueryVaultsResponse) { - option (google.api.http).get = "/kava/earn/v1beta1/vaults"; - } - - // Vault queries a single vault based on the vault denom - rpc Vault(QueryVaultRequest) returns (QueryVaultResponse) { - option (google.api.http).get = "/kava/earn/v1beta1/vaults/{denom=**}"; - } - - // Deposits queries deposit details based on depositor address and vault - rpc Deposits(QueryDepositsRequest) returns (QueryDepositsResponse) { - option (google.api.http).get = "/kava/earn/v1beta1/deposits"; - } - - // TotalSupply returns the total sum of all coins currently locked into the earn module. - rpc TotalSupply(QueryTotalSupplyRequest) returns (QueryTotalSupplyResponse) { - option (google.api.http).get = "/kava/earn/v1beta1/total_supply"; - } -} - -// QueryParamsRequest defines the request type for querying x/earn parameters. -message QueryParamsRequest {} - -// QueryParamsResponse defines the response type for querying x/earn parameters. -message QueryParamsResponse { - // params represents the earn module parameters - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryVaultsRequest is the request type for the Query/Vaults RPC method. -message QueryVaultsRequest {} - -// QueryVaultsResponse is the response type for the Query/Vaults RPC method. -message QueryVaultsResponse { - // vaults represents the earn module vaults - repeated VaultResponse vaults = 1 [(gogoproto.nullable) = false]; -} - -// QueryVaultRequest is the request type for the Query/Vault RPC method. -message QueryVaultRequest { - // vault filters vault by denom - string denom = 1; -} - -// QueryVaultResponse is the response type for the Query/Vault RPC method. -message QueryVaultResponse { - // vault represents the queried earn module vault - VaultResponse vault = 1 [(gogoproto.nullable) = false]; -} - -// VaultResponse is the response type for a vault. -message VaultResponse { - // denom represents the denom of the vault - string denom = 1; - - // VaultStrategy is the strategy used for this vault. - repeated StrategyType strategies = 2 [(gogoproto.castrepeated) = "StrategyTypes"]; - - // IsPrivateVault is true if the vault only allows depositors contained in - // AllowedDepositors. - bool is_private_vault = 3; - - // AllowedDepositors is a list of addresses that are allowed to deposit to - // this vault if IsPrivateVault is true. Addresses not contained in this list - // are not allowed to deposit into this vault. If IsPrivateVault is false, - // this should be empty and ignored. - repeated string allowed_depositors = 4 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - // TotalShares is the total amount of shares issued to depositors. - string total_shares = 5; - - // TotalValue is the total value of denom coins supplied to the vault if the - // vault were to be liquidated. - string total_value = 6 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} - -// QueryDepositsRequest is the request type for the Query/Deposits RPC method. -message QueryDepositsRequest { - // depositor optionally filters deposits by depositor - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - // denom optionally filters deposits by vault denom - string denom = 2; - - // respond with vault value in ukava for bkava vaults - bool value_in_staked_tokens = 3; - - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 4; -} - -// QueryDepositsResponse is the response type for the Query/Deposits RPC method. -message QueryDepositsResponse { - // deposits returns the deposits matching the requested parameters - repeated DepositResponse deposits = 1 [(gogoproto.nullable) = false]; - - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// DepositResponse defines a deposit query response type. -message DepositResponse { - // depositor represents the owner of the deposit. - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - // Shares represent the issued shares from their corresponding vaults. - repeated VaultShare shares = 2 [ - (gogoproto.castrepeated) = "VaultShares", - (gogoproto.nullable) = false - ]; - - // Value represents the total accumulated value of denom coins supplied to - // vaults. This may be greater than or equal to amount_supplied depending on - // the strategy. - repeated cosmos.base.v1beta1.Coin value = 3 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// QueryTotalSupplyRequest defines the request type for Query/TotalSupply method. -message QueryTotalSupplyRequest {} - -// TotalSupplyResponse defines the response type for the Query/TotalSupply method. -message QueryTotalSupplyResponse { - // Height is the block height at which these totals apply - int64 height = 1; - // Result is a list of coins supplied to earn - repeated cosmos.base.v1beta1.Coin result = 2 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} diff --git a/proto/kava/earn/v1beta1/strategy.proto b/proto/kava/earn/v1beta1/strategy.proto deleted file mode 100644 index cd866339..00000000 --- a/proto/kava/earn/v1beta1/strategy.proto +++ /dev/null @@ -1,20 +0,0 @@ -syntax = "proto3"; -package kava.earn.v1beta1; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/earn/types"; - -// StrategyType is the type of strategy that a vault uses to optimize yields. -enum StrategyType { - option (gogoproto.goproto_enum_prefix) = false; - - // STRATEGY_TYPE_UNSPECIFIED represents an unspecified or invalid strategy type. - STRATEGY_TYPE_UNSPECIFIED = 0; - // STRATEGY_TYPE_HARD represents the strategy that deposits assets in the Hard - // module. - STRATEGY_TYPE_HARD = 1; - // STRATEGY_TYPE_SAVINGS represents the strategy that deposits assets in the - // Savings module. - STRATEGY_TYPE_SAVINGS = 2; -} diff --git a/proto/kava/earn/v1beta1/tx.proto b/proto/kava/earn/v1beta1/tx.proto deleted file mode 100644 index 4301a097..00000000 --- a/proto/kava/earn/v1beta1/tx.proto +++ /dev/null @@ -1,57 +0,0 @@ -syntax = "proto3"; -package kava.earn.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "kava/earn/v1beta1/strategy.proto"; -import "kava/earn/v1beta1/vault.proto"; - -option go_package = "github.com/kava-labs/kava/x/earn/types"; - -// Msg defines the earn Msg service. -service Msg { - // Deposit defines a method for depositing assets into a vault - rpc Deposit(MsgDeposit) returns (MsgDepositResponse); - // Withdraw defines a method for withdrawing assets into a vault - rpc Withdraw(MsgWithdraw) returns (MsgWithdrawResponse); -} - -// MsgDeposit represents a message for depositing assedts into a vault -message MsgDeposit { - option (gogoproto.goproto_getters) = false; - - // depositor represents the address to deposit funds from - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // Amount represents the token to deposit. The vault corresponds to the denom - // of the amount coin. - cosmos.base.v1beta1.Coin amount = 2 [(gogoproto.nullable) = false]; - - // Strategy is the vault strategy to use. - StrategyType strategy = 3; -} - -// MsgDepositResponse defines the Msg/Deposit response type. -message MsgDepositResponse { - VaultShare shares = 1 [(gogoproto.nullable) = false]; -} - -// MsgWithdraw represents a message for withdrawing liquidity from a vault -message MsgWithdraw { - option (gogoproto.goproto_getters) = false; - - // from represents the address we are withdrawing for - string from = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - // Amount represents the token to withdraw. The vault corresponds to the denom - // of the amount coin. - cosmos.base.v1beta1.Coin amount = 2 [(gogoproto.nullable) = false]; - - // Strategy is the vault strategy to use. - StrategyType strategy = 3; -} - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -message MsgWithdrawResponse { - VaultShare shares = 1 [(gogoproto.nullable) = false]; -} diff --git a/proto/kava/earn/v1beta1/vault.proto b/proto/kava/earn/v1beta1/vault.proto deleted file mode 100644 index 8b3052d8..00000000 --- a/proto/kava/earn/v1beta1/vault.proto +++ /dev/null @@ -1,63 +0,0 @@ -syntax = "proto3"; -package kava.earn.v1beta1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "kava/earn/v1beta1/strategy.proto"; - -option go_package = "github.com/kava-labs/kava/x/earn/types"; - -// AllowedVault is a vault that is allowed to be created. These can be -// modified via parameter governance. -message AllowedVault { - // Denom is the only supported denomination of the vault for deposits and withdrawals. - string denom = 1; - - // VaultStrategy is the strategy used for this vault. - repeated StrategyType strategies = 2 [(gogoproto.castrepeated) = "StrategyTypes"]; - - // IsPrivateVault is true if the vault only allows depositors contained in - // AllowedDepositors. - bool is_private_vault = 3; - - // AllowedDepositors is a list of addresses that are allowed to deposit to - // this vault if IsPrivateVault is true. Addresses not contained in this list - // are not allowed to deposit into this vault. If IsPrivateVault is false, - // this should be empty and ignored. - repeated bytes allowed_depositors = 4 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; -} - -// VaultRecord is the state of a vault. -message VaultRecord { - // TotalShares is the total distributed number of shares in the vault. - VaultShare total_shares = 1 [(gogoproto.nullable) = false]; -} - -// VaultShareRecord defines the vault shares owned by a depositor. -message VaultShareRecord { - // Depositor represents the owner of the shares - bytes depositor = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - // Shares represent the vault shares owned by the depositor. - repeated VaultShare shares = 2 [ - (gogoproto.castrepeated) = "VaultShares", - (gogoproto.nullable) = false - ]; -} - -// VaultShare defines shares of a vault owned by a depositor. -message VaultShare { - option (gogoproto.goproto_stringer) = false; - - string denom = 1; - string amount = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/hard/v1beta1/genesis.proto b/proto/kava/hard/v1beta1/genesis.proto deleted file mode 100644 index c2520a42..00000000 --- a/proto/kava/hard/v1beta1/genesis.proto +++ /dev/null @@ -1,58 +0,0 @@ -syntax = "proto3"; -package kava.hard.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; -import "kava/hard/v1beta1/hard.proto"; - -option go_package = "github.com/kava-labs/kava/x/hard/types"; - -// GenesisState defines the hard module's genesis state. -message GenesisState { - Params params = 1 [(gogoproto.nullable) = false]; - repeated GenesisAccumulationTime previous_accumulation_times = 2 [ - (gogoproto.castrepeated) = "GenesisAccumulationTimes", - (gogoproto.nullable) = false - ]; - repeated Deposit deposits = 3 [ - (gogoproto.castrepeated) = "Deposits", - (gogoproto.nullable) = false - ]; - repeated Borrow borrows = 4 [ - (gogoproto.castrepeated) = "Borrows", - (gogoproto.nullable) = false - ]; - repeated cosmos.base.v1beta1.Coin total_supplied = 5 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; - repeated cosmos.base.v1beta1.Coin total_borrowed = 6 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; - repeated cosmos.base.v1beta1.Coin total_reserves = 7 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// GenesisAccumulationTime stores the previous distribution time and its corresponding denom. -message GenesisAccumulationTime { - string collateral_type = 1; - google.protobuf.Timestamp previous_accumulation_time = 2 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - string supply_interest_factor = 3 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string borrow_interest_factor = 4 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/hard/v1beta1/hard.proto b/proto/kava/hard/v1beta1/hard.proto deleted file mode 100644 index fafcbde7..00000000 --- a/proto/kava/hard/v1beta1/hard.proto +++ /dev/null @@ -1,146 +0,0 @@ -syntax = "proto3"; -package kava.hard.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/hard/types"; -option (gogoproto.goproto_getters_all) = false; - -// Params defines the parameters for the hard module. -message Params { - repeated MoneyMarket money_markets = 1 [ - (gogoproto.castrepeated) = "MoneyMarkets", - (gogoproto.nullable) = false - ]; - string minimum_borrow_usd_value = 2 [ - (gogoproto.customname) = "MinimumBorrowUSDValue", - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// MoneyMarket is a money market for an individual asset. -message MoneyMarket { - string denom = 1; - BorrowLimit borrow_limit = 2 [(gogoproto.nullable) = false]; - string spot_market_id = 3 [(gogoproto.customname) = "SpotMarketID"]; - string conversion_factor = 4 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - InterestRateModel interest_rate_model = 5 [(gogoproto.nullable) = false]; - string reserve_factor = 6 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string keeper_reward_percentage = 7 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// BorrowLimit enforces restrictions on a money market. -message BorrowLimit { - bool has_max_limit = 1 [(gogoproto.jsontag) = "has_max_limit"]; - string maximum_limit = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string loan_to_value = 3 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// InterestRateModel contains information about an asset's interest rate. -message InterestRateModel { - string base_rate_apy = 1 [ - (gogoproto.customname) = "BaseRateAPY", - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string base_multiplier = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string kink = 3 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string jump_multiplier = 4 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// Deposit defines an amount of coins deposited into a hard module account. -message Deposit { - string depositor = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; - repeated SupplyInterestFactor index = 3 [ - (gogoproto.castrepeated) = "SupplyInterestFactors", - (gogoproto.nullable) = false - ]; -} - -// Borrow defines an amount of coins borrowed from a hard module account. -message Borrow { - string borrower = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; - repeated BorrowInterestFactor index = 3 [ - (gogoproto.castrepeated) = "BorrowInterestFactors", - (gogoproto.nullable) = false - ]; -} - -// SupplyInterestFactor defines an individual borrow interest factor. -message SupplyInterestFactor { - string denom = 1; - string value = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// BorrowInterestFactor defines an individual borrow interest factor. -message BorrowInterestFactor { - string denom = 1; - string value = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// CoinsProto defines a Protobuf wrapper around a Coins slice -message CoinsProto { - repeated cosmos.base.v1beta1.Coin coins = 1 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/hard/v1beta1/query.proto b/proto/kava/hard/v1beta1/query.proto deleted file mode 100644 index 92ef7248..00000000 --- a/proto/kava/hard/v1beta1/query.proto +++ /dev/null @@ -1,281 +0,0 @@ -syntax = "proto3"; -package kava.hard.v1beta1; - -import "cosmos/auth/v1beta1/auth.proto"; -import "cosmos/base/query/v1beta1/pagination.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "kava/hard/v1beta1/hard.proto"; - -option go_package = "github.com/kava-labs/kava/x/hard/types"; - -// Query defines the gRPC querier service for bep3 module. -service Query { - // Params queries module params. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/params"; - } - - // Accounts queries module accounts. - rpc Accounts(QueryAccountsRequest) returns (QueryAccountsResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/accounts"; - } - - // Deposits queries hard deposits. - rpc Deposits(QueryDepositsRequest) returns (QueryDepositsResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/deposits"; - } - - // UnsyncedDeposits queries unsynced deposits. - rpc UnsyncedDeposits(QueryUnsyncedDepositsRequest) returns (QueryUnsyncedDepositsResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/unsynced-deposits"; - } - - // TotalDeposited queries total coins deposited to hard liquidity pools. - rpc TotalDeposited(QueryTotalDepositedRequest) returns (QueryTotalDepositedResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/total-deposited"; - } - - // Borrows queries hard borrows. - rpc Borrows(QueryBorrowsRequest) returns (QueryBorrowsResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/borrows"; - } - - // UnsyncedBorrows queries unsynced borrows. - rpc UnsyncedBorrows(QueryUnsyncedBorrowsRequest) returns (QueryUnsyncedBorrowsResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/unsynced-borrows"; - } - - // TotalBorrowed queries total coins borrowed from hard liquidity pools. - rpc TotalBorrowed(QueryTotalBorrowedRequest) returns (QueryTotalBorrowedResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/total-borrowed"; - } - - // InterestRate queries the hard module interest rates. - rpc InterestRate(QueryInterestRateRequest) returns (QueryInterestRateResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/interest-rate"; - } - - // Reserves queries total hard reserve coins. - rpc Reserves(QueryReservesRequest) returns (QueryReservesResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/reserves"; - } - - // InterestFactors queries hard module interest factors. - rpc InterestFactors(QueryInterestFactorsRequest) returns (QueryInterestFactorsResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/interest-factors"; - } -} - -// QueryParamsRequest is the request type for the Query/Params RPC method. -message QueryParamsRequest {} - -// QueryParamsResponse is the response type for the Query/Params RPC method. -message QueryParamsResponse { - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryAccountsRequest is the request type for the Query/Accounts RPC method. -message QueryAccountsRequest {} - -// QueryAccountsResponse is the response type for the Query/Accounts RPC method. -message QueryAccountsResponse { - repeated cosmos.auth.v1beta1.ModuleAccount accounts = 1 [(gogoproto.nullable) = false]; -} - -// QueryDepositsRequest is the request type for the Query/Deposits RPC method. -message QueryDepositsRequest { - string denom = 1; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - cosmos.base.query.v1beta1.PageRequest pagination = 3; -} - -// QueryDepositsResponse is the response type for the Query/Deposits RPC method. -message QueryDepositsResponse { - repeated DepositResponse deposits = 1 [ - (gogoproto.castrepeated) = "DepositResponses", - (gogoproto.nullable) = false - ]; - - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryUnsyncedDepositsRequest is the request type for the Query/UnsyncedDeposits RPC method. -message QueryUnsyncedDepositsRequest { - string denom = 1; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - cosmos.base.query.v1beta1.PageRequest pagination = 3; -} - -// QueryUnsyncedDepositsResponse is the response type for the Query/UnsyncedDeposits RPC method. -message QueryUnsyncedDepositsResponse { - repeated DepositResponse deposits = 1 [ - (gogoproto.castrepeated) = "DepositResponses", - (gogoproto.nullable) = false - ]; - - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryTotalDepositedRequest is the request type for the Query/TotalDeposited RPC method. -message QueryTotalDepositedRequest { - string denom = 1; -} - -// QueryTotalDepositedResponse is the response type for the Query/TotalDeposited RPC method. -message QueryTotalDepositedResponse { - repeated cosmos.base.v1beta1.Coin supplied_coins = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// QueryBorrowsRequest is the request type for the Query/Borrows RPC method. -message QueryBorrowsRequest { - string denom = 1; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - cosmos.base.query.v1beta1.PageRequest pagination = 3; -} - -// QueryBorrowsResponse is the response type for the Query/Borrows RPC method. -message QueryBorrowsResponse { - repeated BorrowResponse borrows = 1 [ - (gogoproto.castrepeated) = "BorrowResponses", - (gogoproto.nullable) = false - ]; - - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryUnsyncedBorrowsRequest is the request type for the Query/UnsyncedBorrows RPC method. -message QueryUnsyncedBorrowsRequest { - string denom = 1; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - cosmos.base.query.v1beta1.PageRequest pagination = 3; -} - -// QueryUnsyncedBorrowsResponse is the response type for the Query/UnsyncedBorrows RPC method. -message QueryUnsyncedBorrowsResponse { - repeated BorrowResponse borrows = 1 [ - (gogoproto.castrepeated) = "BorrowResponses", - (gogoproto.nullable) = false - ]; - - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryTotalBorrowedRequest is the request type for the Query/TotalBorrowed RPC method. -message QueryTotalBorrowedRequest { - string denom = 1; -} - -// QueryTotalBorrowedResponse is the response type for the Query/TotalBorrowed RPC method. -message QueryTotalBorrowedResponse { - repeated cosmos.base.v1beta1.Coin borrowed_coins = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// QueryInterestRateRequest is the request type for the Query/InterestRate RPC method. -message QueryInterestRateRequest { - string denom = 1; -} - -// QueryInterestRateResponse is the response type for the Query/InterestRate RPC method. -message QueryInterestRateResponse { - repeated MoneyMarketInterestRate interest_rates = 1 [ - (gogoproto.castrepeated) = "MoneyMarketInterestRates", - (gogoproto.nullable) = false - ]; -} - -// QueryReservesRequest is the request type for the Query/Reserves RPC method. -message QueryReservesRequest { - string denom = 1; -} - -// QueryReservesResponse is the response type for the Query/Reserves RPC method. -message QueryReservesResponse { - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// QueryInterestFactorsRequest is the request type for the Query/InterestFactors RPC method. -message QueryInterestFactorsRequest { - string denom = 1; -} - -// QueryInterestFactorsResponse is the response type for the Query/InterestFactors RPC method. -message QueryInterestFactorsResponse { - repeated InterestFactor interest_factors = 1 [ - (gogoproto.castrepeated) = "InterestFactors", - (gogoproto.nullable) = false - ]; -} - -// DepositResponse defines an amount of coins deposited into a hard module account. -message DepositResponse { - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; - repeated SupplyInterestFactorResponse index = 3 [ - (gogoproto.castrepeated) = "SupplyInterestFactorResponses", - (gogoproto.nullable) = false - ]; -} - -// SupplyInterestFactorResponse defines an individual borrow interest factor. -message SupplyInterestFactorResponse { - string denom = 1; - // sdk.Dec as string - string value = 2; -} - -// BorrowResponse defines an amount of coins borrowed from a hard module account. -message BorrowResponse { - string borrower = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; - repeated BorrowInterestFactorResponse index = 3 [ - (gogoproto.castrepeated) = "BorrowInterestFactorResponses", - (gogoproto.nullable) = false - ]; -} - -// BorrowInterestFactorResponse defines an individual borrow interest factor. -message BorrowInterestFactorResponse { - string denom = 1; - // sdk.Dec as string - string value = 2; -} - -// MoneyMarketInterestRate is a unique type returned by interest rate queries -message MoneyMarketInterestRate { - string denom = 1; - // sdk.Dec as String - string supply_interest_rate = 2; - // sdk.Dec as String - string borrow_interest_rate = 3; -} - -// InterestFactor is a unique type returned by interest factor queries -message InterestFactor { - string denom = 1; - // sdk.Dec as String - string borrow_interest_factor = 2; - // sdk.Dec as String - string supply_interest_factor = 3; -} diff --git a/proto/kava/hard/v1beta1/tx.proto b/proto/kava/hard/v1beta1/tx.proto deleted file mode 100644 index 16c40709..00000000 --- a/proto/kava/hard/v1beta1/tx.proto +++ /dev/null @@ -1,80 +0,0 @@ -syntax = "proto3"; -package kava.hard.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/hard/types"; - -// Msg defines the hard Msg service. -service Msg { - // Deposit defines a method for depositing funds to hard liquidity pool. - rpc Deposit(MsgDeposit) returns (MsgDepositResponse); - // Withdraw defines a method for withdrawing funds from hard liquidity pool. - rpc Withdraw(MsgWithdraw) returns (MsgWithdrawResponse); - // Borrow defines a method for borrowing funds from hard liquidity pool. - rpc Borrow(MsgBorrow) returns (MsgBorrowResponse); - // Repay defines a method for repaying funds borrowed from hard liquidity pool. - rpc Repay(MsgRepay) returns (MsgRepayResponse); - // Liquidate defines a method for attempting to liquidate a borrower that is over their loan-to-value. - rpc Liquidate(MsgLiquidate) returns (MsgLiquidateResponse); -} - -// MsgDeposit defines the Msg/Deposit request type. -message MsgDeposit { - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// MsgDepositResponse defines the Msg/Deposit response type. -message MsgDepositResponse {} - -// MsgWithdraw defines the Msg/Withdraw request type. -message MsgWithdraw { - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -message MsgWithdrawResponse {} - -// MsgBorrow defines the Msg/Borrow request type. -message MsgBorrow { - string borrower = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// MsgBorrowResponse defines the Msg/Borrow response type. -message MsgBorrowResponse {} - -// MsgRepay defines the Msg/Repay request type. -message MsgRepay { - string sender = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - repeated cosmos.base.v1beta1.Coin amount = 3 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// MsgRepayResponse defines the Msg/Repay response type. -message MsgRepayResponse {} - -// MsgLiquidate defines the Msg/Liquidate request type. -message MsgLiquidate { - string keeper = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string borrower = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; -} - -// MsgLiquidateResponse defines the Msg/Liquidate response type. -message MsgLiquidateResponse {} diff --git a/proto/kava/incentive/v1beta1/apy.proto b/proto/kava/incentive/v1beta1/apy.proto deleted file mode 100644 index 5b6abf93..00000000 --- a/proto/kava/incentive/v1beta1/apy.proto +++ /dev/null @@ -1,18 +0,0 @@ -syntax = "proto3"; -package kava.incentive.v1beta1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/incentive/types"; - -// Apy contains the calculated APY for a given collateral type at a specific -// instant in time. -message Apy { - string collateral_type = 1; - string apy = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/incentive/v1beta1/claims.proto b/proto/kava/incentive/v1beta1/claims.proto deleted file mode 100644 index f9e54906..00000000 --- a/proto/kava/incentive/v1beta1/claims.proto +++ /dev/null @@ -1,171 +0,0 @@ -syntax = "proto3"; -package kava.incentive.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/incentive/types"; -option (gogoproto.goproto_getters_all) = false; - -// -------------- Base Claim Types, Reward Indexes -------------- - -// BaseClaim is a claim with a single reward coin types -message BaseClaim { - option (cosmos_proto.implements_interface) = "Claim"; - - bytes owner = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - - cosmos.base.v1beta1.Coin reward = 2 [(gogoproto.nullable) = false]; -} - -// BaseMultiClaim is a claim with multiple reward coin types -message BaseMultiClaim { - option (cosmos_proto.implements_interface) = "Claim"; - - bytes owner = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - - repeated cosmos.base.v1beta1.Coin reward = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// RewardIndex stores reward accumulation information -message RewardIndex { - string collateral_type = 1; - - bytes reward_factor = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// RewardIndexesProto defines a Protobuf wrapper around a RewardIndexes slice -message RewardIndexesProto { - repeated RewardIndex reward_indexes = 1 [ - (gogoproto.castrepeated) = "RewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// MultiRewardIndex stores reward accumulation information on multiple reward types -message MultiRewardIndex { - string collateral_type = 1; - - repeated RewardIndex reward_indexes = 2 [ - (gogoproto.castrepeated) = "RewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// MultiRewardIndexesProto defines a Protobuf wrapper around a MultiRewardIndexes slice -message MultiRewardIndexesProto { - repeated MultiRewardIndex multi_reward_indexes = 1 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// -------------- Custom Claim Types -------------- - -// USDXMintingClaim is for USDX minting rewards -message USDXMintingClaim { - option (cosmos_proto.implements_interface) = "Claim"; - - BaseClaim base_claim = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; - - repeated RewardIndex reward_indexes = 2 [ - (gogoproto.castrepeated) = "RewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// HardLiquidityProviderClaim stores the hard liquidity provider rewards that can be claimed by owner -message HardLiquidityProviderClaim { - option (cosmos_proto.implements_interface) = "Claim"; - - BaseMultiClaim base_claim = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; - - repeated MultiRewardIndex supply_reward_indexes = 2 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; - - repeated MultiRewardIndex borrow_reward_indexes = 3 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// DelegatorClaim stores delegation rewards that can be claimed by owner -message DelegatorClaim { - option (cosmos_proto.implements_interface) = "Claim"; - - BaseMultiClaim base_claim = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; - - repeated MultiRewardIndex reward_indexes = 2 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// SwapClaim stores the swap rewards that can be claimed by owner -message SwapClaim { - option (cosmos_proto.implements_interface) = "Claim"; - - BaseMultiClaim base_claim = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; - - repeated MultiRewardIndex reward_indexes = 2 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// SavingsClaim stores the savings rewards that can be claimed by owner -message SavingsClaim { - option (cosmos_proto.implements_interface) = "Claim"; - - BaseMultiClaim base_claim = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; - - repeated MultiRewardIndex reward_indexes = 2 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// EarnClaim stores the earn rewards that can be claimed by owner -message EarnClaim { - option (cosmos_proto.implements_interface) = "Claim"; - - BaseMultiClaim base_claim = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; - - repeated MultiRewardIndex reward_indexes = 2 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/incentive/v1beta1/genesis.proto b/proto/kava/incentive/v1beta1/genesis.proto deleted file mode 100644 index 97348b4c..00000000 --- a/proto/kava/incentive/v1beta1/genesis.proto +++ /dev/null @@ -1,89 +0,0 @@ -syntax = "proto3"; -package kava.incentive.v1beta1; - -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; -import "kava/incentive/v1beta1/claims.proto"; -import "kava/incentive/v1beta1/params.proto"; - -// import "cosmos/base/v1beta1/coin.proto"; -// import "cosmos/base/v1beta1/coins.proto"; - -option go_package = "github.com/kava-labs/kava/x/incentive/types"; -option (gogoproto.goproto_getters_all) = false; - -// AccumulationTime stores the previous reward distribution time and its corresponding collateral type -message AccumulationTime { - string collateral_type = 1; - - google.protobuf.Timestamp previous_accumulation_time = 2 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; -} - -// GenesisRewardState groups together the global state for a particular reward so it can be exported in genesis. -message GenesisRewardState { - repeated AccumulationTime accumulation_times = 1 [ - (gogoproto.castrepeated) = "AccumulationTimes", - (gogoproto.nullable) = false - ]; - - repeated MultiRewardIndex multi_reward_indexes = 2 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// GenesisState is the state that must be provided at genesis. -message GenesisState { - Params params = 1 [(gogoproto.nullable) = false]; - - GenesisRewardState usdx_reward_state = 2 [ - (gogoproto.customname) = "USDXRewardState", - (gogoproto.nullable) = false - ]; - - GenesisRewardState hard_supply_reward_state = 3 [(gogoproto.nullable) = false]; - - GenesisRewardState hard_borrow_reward_state = 4 [(gogoproto.nullable) = false]; - - GenesisRewardState delegator_reward_state = 5 [(gogoproto.nullable) = false]; - - GenesisRewardState swap_reward_state = 6 [(gogoproto.nullable) = false]; - - repeated USDXMintingClaim usdx_minting_claims = 7 [ - (gogoproto.customname) = "USDXMintingClaims", - (gogoproto.castrepeated) = "USDXMintingClaims", - (gogoproto.nullable) = false - ]; - - repeated HardLiquidityProviderClaim hard_liquidity_provider_claims = 8 [ - (gogoproto.castrepeated) = "HardLiquidityProviderClaims", - (gogoproto.nullable) = false - ]; - - repeated DelegatorClaim delegator_claims = 9 [ - (gogoproto.castrepeated) = "DelegatorClaims", - (gogoproto.nullable) = false - ]; - - repeated SwapClaim swap_claims = 10 [ - (gogoproto.castrepeated) = "SwapClaims", - (gogoproto.nullable) = false - ]; - - GenesisRewardState savings_reward_state = 11 [(gogoproto.nullable) = false]; - - repeated SavingsClaim savings_claims = 12 [ - (gogoproto.castrepeated) = "SavingsClaims", - (gogoproto.nullable) = false - ]; - - GenesisRewardState earn_reward_state = 13 [(gogoproto.nullable) = false]; - - repeated EarnClaim earn_claims = 14 [ - (gogoproto.castrepeated) = "EarnClaims", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/incentive/v1beta1/params.proto b/proto/kava/incentive/v1beta1/params.proto deleted file mode 100644 index 7571f9a3..00000000 --- a/proto/kava/incentive/v1beta1/params.proto +++ /dev/null @@ -1,121 +0,0 @@ -syntax = "proto3"; -package kava.incentive.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; - -option go_package = "github.com/kava-labs/kava/x/incentive/types"; -option (gogoproto.goproto_getters_all) = false; - -// RewardPeriod stores the state of an ongoing reward -message RewardPeriod { - bool active = 1; - - string collateral_type = 2; - - google.protobuf.Timestamp start = 3 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; - - google.protobuf.Timestamp end = 4 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; - - cosmos.base.v1beta1.Coin rewards_per_second = 5 [(gogoproto.nullable) = false]; -} - -// MultiRewardPeriod supports multiple reward types -message MultiRewardPeriod { - bool active = 1; - - string collateral_type = 2; - - google.protobuf.Timestamp start = 3 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; - - google.protobuf.Timestamp end = 4 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; - - repeated cosmos.base.v1beta1.Coin rewards_per_second = 5 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// Multiplier amount the claim rewards get increased by, along with how long the claim rewards are locked -message Multiplier { - string name = 1; - - int64 months_lockup = 2; - - bytes factor = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// MultipliersPerDenom is a map of denoms to a set of multipliers -message MultipliersPerDenom { - string denom = 1; - - repeated Multiplier multipliers = 2 [ - (gogoproto.castrepeated) = "Multipliers", - (gogoproto.nullable) = false - ]; -} - -// Params -message Params { - repeated RewardPeriod usdx_minting_reward_periods = 1 [ - (gogoproto.customname) = "USDXMintingRewardPeriods", - (gogoproto.castrepeated) = "RewardPeriods", - (gogoproto.nullable) = false - ]; - - repeated MultiRewardPeriod hard_supply_reward_periods = 2 [ - (gogoproto.castrepeated) = "MultiRewardPeriods", - (gogoproto.nullable) = false - ]; - - repeated MultiRewardPeriod hard_borrow_reward_periods = 3 [ - (gogoproto.castrepeated) = "MultiRewardPeriods", - (gogoproto.nullable) = false - ]; - - repeated MultiRewardPeriod delegator_reward_periods = 4 [ - (gogoproto.castrepeated) = "MultiRewardPeriods", - (gogoproto.nullable) = false - ]; - - repeated MultiRewardPeriod swap_reward_periods = 5 [ - (gogoproto.castrepeated) = "MultiRewardPeriods", - (gogoproto.nullable) = false - ]; - - repeated MultipliersPerDenom claim_multipliers = 6 [ - (gogoproto.castrepeated) = "MultipliersPerDenoms", - (gogoproto.nullable) = false - ]; - - google.protobuf.Timestamp claim_end = 7 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; - - repeated MultiRewardPeriod savings_reward_periods = 8 [ - (gogoproto.castrepeated) = "MultiRewardPeriods", - (gogoproto.nullable) = false - ]; - - repeated MultiRewardPeriod earn_reward_periods = 9 [ - (gogoproto.castrepeated) = "MultiRewardPeriods", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/incentive/v1beta1/query.proto b/proto/kava/incentive/v1beta1/query.proto deleted file mode 100644 index f814d66c..00000000 --- a/proto/kava/incentive/v1beta1/query.proto +++ /dev/null @@ -1,130 +0,0 @@ -syntax = "proto3"; -package kava.incentive.v1beta1; - -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "kava/incentive/v1beta1/apy.proto"; -import "kava/incentive/v1beta1/claims.proto"; -import "kava/incentive/v1beta1/params.proto"; - -option go_package = "github.com/kava-labs/kava/x/incentive/types"; - -// Query defines the gRPC querier service for incentive module. -service Query { - // Params queries module params. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/incentive/v1beta1/params"; - } - - // Rewards queries reward information for a given user. - rpc Rewards(QueryRewardsRequest) returns (QueryRewardsResponse) { - option (google.api.http).get = "/kava/incentive/v1beta1/rewards"; - } - - // Rewards queries the reward factors. - rpc RewardFactors(QueryRewardFactorsRequest) returns (QueryRewardFactorsResponse) { - option (google.api.http).get = "/kava/incentive/v1beta1/reward_factors"; - } - - // Apy queries incentive reward apy for a reward. - rpc Apy(QueryApyRequest) returns (QueryApyResponse) { - option (google.api.http).get = "/kava/incentive/v1beta1/apy"; - } -} - -// QueryParamsRequest is the request type for the Query/Params RPC method. -message QueryParamsRequest {} - -// QueryParamsResponse is the response type for the Query/Params RPC method. -message QueryParamsResponse { - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryRewardsRequest is the request type for the Query/Rewards RPC method. -message QueryRewardsRequest { - // owner is the address of the user to query rewards for. - string owner = 1; - // reward_type is the type of reward to query rewards for, e.g. hard, earn, - // swap. - string reward_type = 2; - // unsynchronized is a flag to query rewards that are not simulated for reward - // synchronized for the current block. - bool unsynchronized = 3; -} - -// QueryRewardsResponse is the response type for the Query/Rewards RPC method. -message QueryRewardsResponse { - repeated USDXMintingClaim usdx_minting_claims = 1 [ - (gogoproto.customname) = "USDXMintingClaims", - (gogoproto.castrepeated) = "USDXMintingClaims", - (gogoproto.nullable) = false - ]; - - repeated HardLiquidityProviderClaim hard_liquidity_provider_claims = 2 [ - (gogoproto.castrepeated) = "HardLiquidityProviderClaims", - (gogoproto.nullable) = false - ]; - - repeated DelegatorClaim delegator_claims = 3 [ - (gogoproto.castrepeated) = "DelegatorClaims", - (gogoproto.nullable) = false - ]; - - repeated SwapClaim swap_claims = 4 [ - (gogoproto.castrepeated) = "SwapClaims", - (gogoproto.nullable) = false - ]; - - repeated SavingsClaim savings_claims = 5 [ - (gogoproto.castrepeated) = "SavingsClaims", - (gogoproto.nullable) = false - ]; - - repeated EarnClaim earn_claims = 6 [ - (gogoproto.castrepeated) = "EarnClaims", - (gogoproto.nullable) = false - ]; -} - -// QueryRewardFactorsRequest is the request type for the Query/RewardFactors RPC method. -message QueryRewardFactorsRequest {} - -// QueryRewardFactorsResponse is the response type for the Query/RewardFactors RPC method. -message QueryRewardFactorsResponse { - repeated RewardIndex usdx_minting_reward_factors = 1 [ - (gogoproto.castrepeated) = "RewardIndexes", - (gogoproto.nullable) = false - ]; - repeated MultiRewardIndex hard_supply_reward_factors = 2 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; - repeated MultiRewardIndex hard_borrow_reward_factors = 3 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; - repeated MultiRewardIndex delegator_reward_factors = 4 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; - repeated MultiRewardIndex swap_reward_factors = 5 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; - repeated MultiRewardIndex savings_reward_factors = 6 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; - repeated MultiRewardIndex earn_reward_factors = 7 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// QueryApysRequest is the request type for the Query/Apys RPC method. -message QueryApyRequest {} - -// QueryApysResponse is the response type for the Query/Apys RPC method. -message QueryApyResponse { - repeated Apy earn = 1 [(gogoproto.nullable) = false]; -} diff --git a/proto/kava/incentive/v1beta1/tx.proto b/proto/kava/incentive/v1beta1/tx.proto deleted file mode 100644 index 0f03da4e..00000000 --- a/proto/kava/incentive/v1beta1/tx.proto +++ /dev/null @@ -1,124 +0,0 @@ -syntax = "proto3"; -package kava.incentive.v1beta1; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/incentive/types"; - -// Msg defines the incentive Msg service. -service Msg { - // ClaimUSDXMintingReward is a message type used to claim USDX minting rewards - rpc ClaimUSDXMintingReward(MsgClaimUSDXMintingReward) returns (MsgClaimUSDXMintingRewardResponse); - - // ClaimHardReward is a message type used to claim Hard liquidity provider rewards - rpc ClaimHardReward(MsgClaimHardReward) returns (MsgClaimHardRewardResponse); - - // ClaimDelegatorReward is a message type used to claim delegator rewards - rpc ClaimDelegatorReward(MsgClaimDelegatorReward) returns (MsgClaimDelegatorRewardResponse); - - // ClaimSwapReward is a message type used to claim swap rewards - rpc ClaimSwapReward(MsgClaimSwapReward) returns (MsgClaimSwapRewardResponse); - - // ClaimSavingsReward is a message type used to claim savings rewards - rpc ClaimSavingsReward(MsgClaimSavingsReward) returns (MsgClaimSavingsRewardResponse); - - // ClaimEarnReward is a message type used to claim earn rewards - rpc ClaimEarnReward(MsgClaimEarnReward) returns (MsgClaimEarnRewardResponse); -} - -// Selection is a pair of denom and multiplier name. It holds the choice of multiplier a user makes when they claim a -// denom. -message Selection { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string denom = 1; - string multiplier_name = 2; -} - -// MsgClaimUSDXMintingReward message type used to claim USDX minting rewards -message MsgClaimUSDXMintingReward { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string sender = 1; - string multiplier_name = 2; -} - -// MsgClaimUSDXMintingRewardResponse defines the Msg/ClaimUSDXMintingReward response type. -message MsgClaimUSDXMintingRewardResponse {} - -// MsgClaimHardReward message type used to claim Hard liquidity provider rewards -message MsgClaimHardReward { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string sender = 1; - repeated Selection denoms_to_claim = 2 [ - (gogoproto.castrepeated) = "Selections", - (gogoproto.nullable) = false - ]; -} - -// MsgClaimHardRewardResponse defines the Msg/ClaimHardReward response type. -message MsgClaimHardRewardResponse {} - -// MsgClaimDelegatorReward message type used to claim delegator rewards -message MsgClaimDelegatorReward { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string sender = 1; - repeated Selection denoms_to_claim = 2 [ - (gogoproto.castrepeated) = "Selections", - (gogoproto.nullable) = false - ]; -} - -// MsgClaimDelegatorRewardResponse defines the Msg/ClaimDelegatorReward response type. -message MsgClaimDelegatorRewardResponse {} - -// MsgClaimSwapReward message type used to claim delegator rewards -message MsgClaimSwapReward { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string sender = 1; - repeated Selection denoms_to_claim = 2 [ - (gogoproto.castrepeated) = "Selections", - (gogoproto.nullable) = false - ]; -} - -// MsgClaimSwapRewardResponse defines the Msg/ClaimSwapReward response type. -message MsgClaimSwapRewardResponse {} - -// MsgClaimSavingsReward message type used to claim savings rewards -message MsgClaimSavingsReward { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string sender = 1; - repeated Selection denoms_to_claim = 2 [ - (gogoproto.castrepeated) = "Selections", - (gogoproto.nullable) = false - ]; -} - -// MsgClaimSavingsRewardResponse defines the Msg/ClaimSavingsReward response type. -message MsgClaimSavingsRewardResponse {} - -// MsgClaimEarnReward message type used to claim earn rewards -message MsgClaimEarnReward { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string sender = 1; - repeated Selection denoms_to_claim = 2 [ - (gogoproto.castrepeated) = "Selections", - (gogoproto.nullable) = false - ]; -} - -// MsgClaimEarnRewardResponse defines the Msg/ClaimEarnReward response type. -message MsgClaimEarnRewardResponse {} diff --git a/proto/kava/issuance/v1beta1/genesis.proto b/proto/kava/issuance/v1beta1/genesis.proto deleted file mode 100644 index 4f791de2..00000000 --- a/proto/kava/issuance/v1beta1/genesis.proto +++ /dev/null @@ -1,64 +0,0 @@ -syntax = "proto3"; -package kava.issuance.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/duration.proto"; - -option go_package = "github.com/kava-labs/kava/x/issuance/types"; - -// GenesisState defines the issuance module's genesis state. -message GenesisState { - // params defines all the parameters of the module. - Params params = 1 [(gogoproto.nullable) = false]; - - repeated AssetSupply supplies = 2 [(gogoproto.nullable) = false]; -} - -// Params defines the parameters for the issuance module. -message Params { - option (gogoproto.goproto_stringer) = false; - - repeated Asset assets = 1 [(gogoproto.nullable) = false]; -} - -// Asset type for assets in the issuance module -message Asset { - option (gogoproto.goproto_stringer) = false; - - string owner = 1; - string denom = 2; - repeated string blocked_addresses = 3; - bool paused = 4; - bool blockable = 5; - RateLimit rate_limit = 6 [(gogoproto.nullable) = false]; -} - -// RateLimit parameters for rate-limiting the supply of an issued asset -message RateLimit { - bool active = 1; - - bytes limit = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false, - (gogoproto.jsontag) = "limit,omitempty" - ]; - - google.protobuf.Duration time_period = 3 [ - (gogoproto.nullable) = false, - (gogoproto.stdduration) = true - ]; -} - -// AssetSupply contains information about an asset's rate-limited supply (the -// total supply of the asset is tracked in the top-level supply module) -message AssetSupply { - option (gogoproto.goproto_stringer) = false; - - cosmos.base.v1beta1.Coin current_supply = 1 [(gogoproto.nullable) = false]; - - google.protobuf.Duration time_elapsed = 2 [ - (gogoproto.nullable) = false, - (gogoproto.stdduration) = true - ]; -} diff --git a/proto/kava/issuance/v1beta1/query.proto b/proto/kava/issuance/v1beta1/query.proto deleted file mode 100644 index 91bb912d..00000000 --- a/proto/kava/issuance/v1beta1/query.proto +++ /dev/null @@ -1,24 +0,0 @@ -syntax = "proto3"; -package kava.issuance.v1beta1; - -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "kava/issuance/v1beta1/genesis.proto"; - -option go_package = "github.com/kava-labs/kava/x/issuance/types"; - -// Query defines the gRPC querier service for issuance module -service Query { - // Params queries all parameters of the issuance module. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/issuance/v1beta1/params"; - } -} - -// QueryParamsRequest defines the request type for querying x/issuance parameters. -message QueryParamsRequest {} - -// QueryParamsResponse defines the response type for querying x/issuance parameters. -message QueryParamsResponse { - Params params = 1 [(gogoproto.nullable) = false]; -} diff --git a/proto/kava/issuance/v1beta1/tx.proto b/proto/kava/issuance/v1beta1/tx.proto deleted file mode 100644 index 3f3833a9..00000000 --- a/proto/kava/issuance/v1beta1/tx.proto +++ /dev/null @@ -1,89 +0,0 @@ -syntax = "proto3"; -package kava.issuance.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/issuance/types"; - -// Msg defines the issuance Msg service. -service Msg { - // IssueTokens message type used by the issuer to issue new tokens - rpc IssueTokens(MsgIssueTokens) returns (MsgIssueTokensResponse); - - // RedeemTokens message type used by the issuer to redeem (burn) tokens - rpc RedeemTokens(MsgRedeemTokens) returns (MsgRedeemTokensResponse); - - // BlockAddress message type used by the issuer to block an address from holding or transferring tokens - rpc BlockAddress(MsgBlockAddress) returns (MsgBlockAddressResponse); - - // UnblockAddress message type used by the issuer to unblock an address from holding or transferring tokens - rpc UnblockAddress(MsgUnblockAddress) returns (MsgUnblockAddressResponse); - - // SetPauseStatus message type used to pause or unpause status - rpc SetPauseStatus(MsgSetPauseStatus) returns (MsgSetPauseStatusResponse); -} - -// MsgIssueTokens represents a message used by the issuer to issue new tokens -message MsgIssueTokens { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string sender = 1; - cosmos.base.v1beta1.Coin tokens = 2 [(gogoproto.nullable) = false]; - string receiver = 3; -} - -// MsgIssueTokensResponse defines the Msg/IssueTokens response type. -message MsgIssueTokensResponse {} - -// MsgRedeemTokens represents a message used by the issuer to redeem (burn) tokens -message MsgRedeemTokens { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string sender = 1; - cosmos.base.v1beta1.Coin tokens = 2 [(gogoproto.nullable) = false]; -} - -// MsgRedeemTokensResponse defines the Msg/RedeemTokens response type. -message MsgRedeemTokensResponse {} - -// MsgBlockAddress represents a message used by the issuer to block an address from holding or transferring tokens -message MsgBlockAddress { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string sender = 1; - string denom = 2; - string blocked_address = 3; -} - -// MsgBlockAddressResponse defines the Msg/BlockAddress response type. -message MsgBlockAddressResponse {} - -// MsgUnblockAddress message type used by the issuer to unblock an address from holding or transferring tokens -message MsgUnblockAddress { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string sender = 1; - string denom = 2; - string blocked_address = 3; -} - -// MsgUnblockAddressResponse defines the Msg/UnblockAddress response type. -message MsgUnblockAddressResponse {} - -// MsgSetPauseStatus message type used by the issuer to pause or unpause status -message MsgSetPauseStatus { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string sender = 1; - string denom = 2; - bool status = 3; -} - -// MsgSetPauseStatusResponse defines the Msg/SetPauseStatus response type. -message MsgSetPauseStatusResponse {} diff --git a/proto/kava/kavadist/v1beta1/genesis.proto b/proto/kava/kavadist/v1beta1/genesis.proto deleted file mode 100644 index eee5de66..00000000 --- a/proto/kava/kavadist/v1beta1/genesis.proto +++ /dev/null @@ -1,18 +0,0 @@ -syntax = "proto3"; -package kava.kavadist.v1beta1; - -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; -import "kava/kavadist/v1beta1/params.proto"; - -option go_package = "github.com/kava-labs/kava/x/kavadist/types"; - -// GenesisState defines the kavadist module's genesis state. -message GenesisState { - Params params = 1 [(gogoproto.nullable) = false]; - - google.protobuf.Timestamp previous_block_time = 2 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/kavadist/v1beta1/params.proto b/proto/kava/kavadist/v1beta1/params.proto deleted file mode 100644 index 5c90b718..00000000 --- a/proto/kava/kavadist/v1beta1/params.proto +++ /dev/null @@ -1,83 +0,0 @@ -syntax = "proto3"; -package kava.kavadist.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; - -option go_package = "github.com/kava-labs/kava/x/kavadist/types"; -option (gogoproto.goproto_getters_all) = false; -option (gogoproto.goproto_stringer_all) = false; - -// Params governance parameters for kavadist module -message Params { - bool active = 1; - repeated Period periods = 3 [(gogoproto.nullable) = false]; - InfrastructureParams infrastructure_params = 4 [(gogoproto.nullable) = false]; -} - -// InfrastructureParams define the parameters for infrastructure rewards. -message InfrastructureParams { - repeated Period infrastructure_periods = 1 [ - (gogoproto.castrepeated) = "Periods", - (gogoproto.nullable) = false - ]; - repeated CoreReward core_rewards = 2 [ - (gogoproto.castrepeated) = "CoreRewards", - (gogoproto.nullable) = false - ]; - repeated PartnerReward partner_rewards = 3 [ - (gogoproto.castrepeated) = "PartnerRewards", - (gogoproto.nullable) = false - ]; - option (gogoproto.goproto_stringer) = true; -} - -// CoreReward defines the reward weights for core infrastructure providers. -message CoreReward { - bytes address = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - string weight = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - option (gogoproto.goproto_stringer) = true; -} - -// PartnerRewards defines the reward schedule for partner infrastructure providers. -message PartnerReward { - bytes address = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - cosmos.base.v1beta1.Coin rewards_per_second = 2 [(gogoproto.nullable) = false]; - option (gogoproto.goproto_stringer) = true; -} - -// Period stores the specified start and end dates, and the inflation, expressed as a decimal -// representing the yearly APR of KAVA tokens that will be minted during that period -message Period { - option (gogoproto.equal) = true; - - // example "2020-03-01T15:20:00Z" - google.protobuf.Timestamp start = 1 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - - // example "2020-06-01T15:20:00Z" - google.protobuf.Timestamp end = 2 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - - // example "1.000000003022265980" - 10% inflation - bytes inflation = 3 [ - (gogoproto.nullable) = false, - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec" - ]; -} diff --git a/proto/kava/kavadist/v1beta1/proposal.proto b/proto/kava/kavadist/v1beta1/proposal.proto deleted file mode 100644 index 2ec8fbe7..00000000 --- a/proto/kava/kavadist/v1beta1/proposal.proto +++ /dev/null @@ -1,44 +0,0 @@ -syntax = "proto3"; -package kava.kavadist.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/kavadist/types"; - -// CommunityPoolMultiSpendProposal spends from the community pool by sending to one or more -// addresses -message CommunityPoolMultiSpendProposal { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - repeated MultiSpendRecipient recipient_list = 3 [(gogoproto.nullable) = false]; -} - -// CommunityPoolMultiSpendProposalJSON defines a CommunityPoolMultiSpendProposal with a deposit -message CommunityPoolMultiSpendProposalJSON { - option (gogoproto.goproto_stringer) = true; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - repeated MultiSpendRecipient recipient_list = 3 [(gogoproto.nullable) = false]; - repeated cosmos.base.v1beta1.Coin deposit = 4 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// MultiSpendRecipient defines a recipient and the amount of coins they are receiving -message MultiSpendRecipient { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - string address = 1; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} diff --git a/proto/kava/kavadist/v1beta1/query.proto b/proto/kava/kavadist/v1beta1/query.proto deleted file mode 100644 index 65838587..00000000 --- a/proto/kava/kavadist/v1beta1/query.proto +++ /dev/null @@ -1,41 +0,0 @@ -syntax = "proto3"; -package kava.kavadist.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "kava/kavadist/v1beta1/params.proto"; - -option go_package = "github.com/kava-labs/kava/x/kavadist/types"; - -// Query defines the gRPC querier service. -service Query { - // Params queries the parameters of x/kavadist module. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/kavadist/v1beta1/parameters"; - } - - // Balance queries the balance of all coins of x/kavadist module. - rpc Balance(QueryBalanceRequest) returns (QueryBalanceResponse) { - option (google.api.http).get = "/kava/kavadist/v1beta1/balance"; - } -} - -// QueryParamsRequest defines the request type for querying x/kavadist parameters. -message QueryParamsRequest {} - -// QueryParamsResponse defines the response type for querying x/kavadist parameters. -message QueryParamsResponse { - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryBalanceRequest defines the request type for querying x/kavadist balance. -message QueryBalanceRequest {} - -// QueryBalanceResponse defines the response type for querying x/kavadist balance. -message QueryBalanceResponse { - repeated cosmos.base.v1beta1.Coin coins = 1 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} diff --git a/proto/kava/liquid/v1beta1/query.proto b/proto/kava/liquid/v1beta1/query.proto deleted file mode 100644 index e528dd35..00000000 --- a/proto/kava/liquid/v1beta1/query.proto +++ /dev/null @@ -1,52 +0,0 @@ -syntax = "proto3"; -package kava.liquid.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; - -option go_package = "github.com/kava-labs/kava/x/liquid/types"; -option (gogoproto.goproto_getters_all) = false; - -// Query defines the gRPC querier service for liquid module -service Query { - // DelegatedBalance returns an account's vesting and vested coins currently delegated to validators. - // It ignores coins in unbonding delegations. - rpc DelegatedBalance(QueryDelegatedBalanceRequest) returns (QueryDelegatedBalanceResponse) { - option (google.api.http).get = "/kava/liquid/v1beta1/delegated_balance/{delegator}"; - } - - // TotalSupply returns the total sum of all coins currently locked into the liquid module. - rpc TotalSupply(QueryTotalSupplyRequest) returns (QueryTotalSupplyResponse) { - option (google.api.http).get = "/kava/liquid/v1beta1/total_supply"; - } -} - -// QueryDelegatedBalanceRequest defines the request type for Query/DelegatedBalance method. -message QueryDelegatedBalanceRequest { - // delegator is the address of the account to query - string delegator = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; -} - -// DelegatedBalanceResponse defines the response type for the Query/DelegatedBalance method. -message QueryDelegatedBalanceResponse { - // vested is the amount of all delegated coins that have vested (ie not locked) - cosmos.base.v1beta1.Coin vested = 1 [(gogoproto.nullable) = false]; - // vesting is the amount of all delegated coins that are still vesting (ie locked) - cosmos.base.v1beta1.Coin vesting = 2 [(gogoproto.nullable) = false]; -} - -// QueryTotalSupplyRequest defines the request type for Query/TotalSupply method. -message QueryTotalSupplyRequest {} - -// TotalSupplyResponse defines the response type for the Query/TotalSupply method. -message QueryTotalSupplyResponse { - // Height is the block height at which these totals apply - int64 height = 1; - // Result is a list of coins supplied to liquid - repeated cosmos.base.v1beta1.Coin result = 2 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} diff --git a/proto/kava/liquid/v1beta1/tx.proto b/proto/kava/liquid/v1beta1/tx.proto deleted file mode 100644 index 077e2b0b..00000000 --- a/proto/kava/liquid/v1beta1/tx.proto +++ /dev/null @@ -1,53 +0,0 @@ -syntax = "proto3"; -package kava.liquid.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/liquid/types"; - -// Msg defines the liquid Msg service. -service Msg { - // MintDerivative defines a method for converting a delegation into staking deriviatives. - rpc MintDerivative(MsgMintDerivative) returns (MsgMintDerivativeResponse); - - // BurnDerivative defines a method for converting staking deriviatives into a delegation. - rpc BurnDerivative(MsgBurnDerivative) returns (MsgBurnDerivativeResponse); -} - -// MsgMintDerivative defines the Msg/MintDerivative request type. -message MsgMintDerivative { - // sender is the owner of the delegation to be converted - string sender = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // validator is the validator of the delegation to be converted - string validator = 2; - // amount is the quantity of staked assets to be converted - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// MsgMintDerivativeResponse defines the Msg/MintDerivative response type. -message MsgMintDerivativeResponse { - // received is the amount of staking derivative minted and sent to the sender - cosmos.base.v1beta1.Coin received = 1 [(gogoproto.nullable) = false]; -} - -// MsgBurnDerivative defines the Msg/BurnDerivative request type. -message MsgBurnDerivative { - // sender is the owner of the derivatives to be converted - string sender = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // validator is the validator of the derivatives to be converted - string validator = 2; - // amount is the quantity of derivatives to be converted - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// MsgBurnDerivativeResponse defines the Msg/BurnDerivative response type. -message MsgBurnDerivativeResponse { - // received is the number of delegation shares sent to the sender - string received = 1 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/pricefeed/v1beta1/genesis.proto b/proto/kava/pricefeed/v1beta1/genesis.proto deleted file mode 100644 index 84e263e8..00000000 --- a/proto/kava/pricefeed/v1beta1/genesis.proto +++ /dev/null @@ -1,20 +0,0 @@ -syntax = "proto3"; -package kava.pricefeed.v1beta1; - -import "gogoproto/gogo.proto"; -import "kava/pricefeed/v1beta1/store.proto"; - -option go_package = "github.com/kava-labs/kava/x/pricefeed/types"; -option (gogoproto.equal_all) = true; -option (gogoproto.verbose_equal_all) = true; - -// GenesisState defines the pricefeed module's genesis state. -message GenesisState { - // params defines all the parameters of the module. - Params params = 1 [(gogoproto.nullable) = false]; - - repeated PostedPrice posted_prices = 2 [ - (gogoproto.castrepeated) = "PostedPrices", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/pricefeed/v1beta1/query.proto b/proto/kava/pricefeed/v1beta1/query.proto deleted file mode 100644 index eecc9bc8..00000000 --- a/proto/kava/pricefeed/v1beta1/query.proto +++ /dev/null @@ -1,163 +0,0 @@ -syntax = "proto3"; -package kava.pricefeed.v1beta1; - -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "google/protobuf/timestamp.proto"; -import "kava/pricefeed/v1beta1/store.proto"; - -option go_package = "github.com/kava-labs/kava/x/pricefeed/types"; -option (gogoproto.equal_all) = true; -option (gogoproto.verbose_equal_all) = true; - -// Query defines the gRPC querier service for pricefeed module -service Query { - // Params queries all parameters of the pricefeed module. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/pricefeed/v1beta1/params"; - } - - // Price queries price details based on a market - rpc Price(QueryPriceRequest) returns (QueryPriceResponse) { - option (google.api.http).get = "/kava/pricefeed/v1beta1/prices/{market_id}"; - } - - // Prices queries all prices - rpc Prices(QueryPricesRequest) returns (QueryPricesResponse) { - option (google.api.http).get = "/kava/pricefeed/v1beta1/prices"; - } - - // RawPrices queries all raw prices based on a market - rpc RawPrices(QueryRawPricesRequest) returns (QueryRawPricesResponse) { - option (google.api.http).get = "/kava/pricefeed/v1beta1/rawprices/{market_id}"; - } - - // Oracles queries all oracles based on a market - rpc Oracles(QueryOraclesRequest) returns (QueryOraclesResponse) { - option (google.api.http).get = "/kava/pricefeed/v1beta1/oracles/{market_id}"; - } - - // Markets queries all markets - rpc Markets(QueryMarketsRequest) returns (QueryMarketsResponse) { - option (google.api.http).get = "/kava/pricefeed/v1beta1/markets"; - } -} - -// QueryParamsRequest defines the request type for querying x/pricefeed -// parameters. -message QueryParamsRequest {} - -// QueryParamsResponse defines the response type for querying x/pricefeed -// parameters. -message QueryParamsResponse { - option (gogoproto.goproto_getters) = false; - - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryPriceRequest is the request type for the Query/PriceRequest RPC method. -message QueryPriceRequest { - option (gogoproto.goproto_getters) = false; - - string market_id = 1; -} - -// QueryPriceResponse is the response type for the Query/Prices RPC method. -message QueryPriceResponse { - option (gogoproto.goproto_getters) = false; - - CurrentPriceResponse price = 1 [(gogoproto.nullable) = false]; -} - -// QueryPricesRequest is the request type for the Query/Prices RPC method. -message QueryPricesRequest {} - -// QueryPricesResponse is the response type for the Query/Prices RPC method. -message QueryPricesResponse { - option (gogoproto.goproto_getters) = false; - - repeated CurrentPriceResponse prices = 1 [ - (gogoproto.castrepeated) = "CurrentPriceResponses", - (gogoproto.nullable) = false - ]; -} - -// QueryRawPricesRequest is the request type for the Query/RawPrices RPC method. -message QueryRawPricesRequest { - option (gogoproto.goproto_getters) = false; - - string market_id = 1; -} - -// QueryRawPricesResponse is the response type for the Query/RawPrices RPC -// method. -message QueryRawPricesResponse { - option (gogoproto.goproto_getters) = false; - - repeated PostedPriceResponse raw_prices = 1 [ - (gogoproto.castrepeated) = "PostedPriceResponses", - (gogoproto.nullable) = false - ]; -} - -// QueryOraclesRequest is the request type for the Query/Oracles RPC method. -message QueryOraclesRequest { - option (gogoproto.goproto_getters) = false; - - string market_id = 1; -} - -// QueryOraclesResponse is the response type for the Query/Oracles RPC method. -message QueryOraclesResponse { - option (gogoproto.goproto_getters) = false; - - // List of oracle addresses - repeated string oracles = 1; -} - -// QueryMarketsRequest is the request type for the Query/Markets RPC method. -message QueryMarketsRequest {} - -// QueryMarketsResponse is the response type for the Query/Markets RPC method. -message QueryMarketsResponse { - option (gogoproto.goproto_getters) = false; - - // List of markets - repeated MarketResponse markets = 1 [ - (gogoproto.castrepeated) = "MarketResponses", - (gogoproto.nullable) = false - ]; -} - -// PostedPriceResponse defines a price for market posted by a specific oracle. -message PostedPriceResponse { - string market_id = 1 [(gogoproto.customname) = "MarketID"]; - string oracle_address = 2; - string price = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - google.protobuf.Timestamp expiry = 4 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; -} - -// CurrentPriceResponse defines a current price for a particular market in the pricefeed -// module. -message CurrentPriceResponse { - string market_id = 1 [(gogoproto.customname) = "MarketID"]; - string price = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// MarketResponse defines an asset in the pricefeed. -message MarketResponse { - string market_id = 1 [(gogoproto.customname) = "MarketID"]; - string base_asset = 2; - string quote_asset = 3; - repeated string oracles = 4; - bool active = 5; -} diff --git a/proto/kava/pricefeed/v1beta1/store.proto b/proto/kava/pricefeed/v1beta1/store.proto deleted file mode 100644 index ebe04337..00000000 --- a/proto/kava/pricefeed/v1beta1/store.proto +++ /dev/null @@ -1,57 +0,0 @@ -syntax = "proto3"; -package kava.pricefeed.v1beta1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; - -option go_package = "github.com/kava-labs/kava/x/pricefeed/types"; -option (gogoproto.equal_all) = true; -option (gogoproto.verbose_equal_all) = true; - -// Params defines the parameters for the pricefeed module. -message Params { - repeated Market markets = 1 [ - (gogoproto.castrepeated) = "Markets", - (gogoproto.nullable) = false - ]; -} - -// Market defines an asset in the pricefeed. -message Market { - string market_id = 1 [(gogoproto.customname) = "MarketID"]; - string base_asset = 2; - string quote_asset = 3; - repeated bytes oracles = 4 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - bool active = 5; -} - -// PostedPrice defines a price for market posted by a specific oracle. -message PostedPrice { - string market_id = 1 [(gogoproto.customname) = "MarketID"]; - bytes oracle_address = 2 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - string price = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - google.protobuf.Timestamp expiry = 4 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; -} - -// CurrentPrice defines a current price for a particular market in the pricefeed -// module. -message CurrentPrice { - string market_id = 1 [(gogoproto.customname) = "MarketID"]; - string price = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/pricefeed/v1beta1/tx.proto b/proto/kava/pricefeed/v1beta1/tx.proto deleted file mode 100644 index 66da318a..00000000 --- a/proto/kava/pricefeed/v1beta1/tx.proto +++ /dev/null @@ -1,35 +0,0 @@ -syntax = "proto3"; -package kava.pricefeed.v1beta1; - -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; - -option go_package = "github.com/kava-labs/kava/x/pricefeed/types"; -option (gogoproto.equal_all) = true; -option (gogoproto.verbose_equal_all) = true; - -// Msg defines the pricefeed Msg service. -service Msg { - // PostPrice defines a method for creating a new post price - rpc PostPrice(MsgPostPrice) returns (MsgPostPriceResponse); -} - -// MsgPostPrice represents a method for creating a new post price -message MsgPostPrice { - option (gogoproto.goproto_getters) = false; - - // address of client - string from = 1; - string market_id = 2 [(gogoproto.customname) = "MarketID"]; - string price = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - google.protobuf.Timestamp expiry = 4 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; -} - -// MsgPostPriceResponse defines the Msg/PostPrice response type. -message MsgPostPriceResponse {} diff --git a/proto/kava/router/v1beta1/tx.proto b/proto/kava/router/v1beta1/tx.proto deleted file mode 100644 index da387f7d..00000000 --- a/proto/kava/router/v1beta1/tx.proto +++ /dev/null @@ -1,80 +0,0 @@ -syntax = "proto3"; -package kava.router.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/router/types"; -option (gogoproto.goproto_getters_all) = false; - -// Msg defines the router Msg service. -service Msg { - // MintDeposit converts a delegation into staking derivatives and deposits it all into an earn vault. - rpc MintDeposit(MsgMintDeposit) returns (MsgMintDepositResponse); - - // DelegateMintDeposit delegates tokens to a validator, then converts them into staking derivatives, - // then deposits to an earn vault. - rpc DelegateMintDeposit(MsgDelegateMintDeposit) returns (MsgDelegateMintDepositResponse); - - // WithdrawBurn removes staking derivatives from an earn vault and converts them back to a staking delegation. - rpc WithdrawBurn(MsgWithdrawBurn) returns (MsgWithdrawBurnResponse); - - // WithdrawBurnUndelegate removes staking derivatives from an earn vault, converts them to a staking delegation, - // then undelegates them from their validator. - rpc WithdrawBurnUndelegate(MsgWithdrawBurnUndelegate) returns (MsgWithdrawBurnUndelegateResponse); -} - -// MsgMintDeposit converts a delegation into staking derivatives and deposits it all into an earn vault. -message MsgMintDeposit { - // depositor represents the owner of the delegation to convert - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // validator is the validator for the depositor's delegation - string validator = 2; - // amount is the delegation balance to convert - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// MsgMintDepositResponse defines the Msg/MsgMintDeposit response type. -message MsgMintDepositResponse {} - -// MsgDelegateMintDeposit delegates tokens to a validator, then converts them into staking derivatives, -// then deposits to an earn vault. -message MsgDelegateMintDeposit { - // depositor represents the owner of the tokens to delegate - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // validator is the address of the validator to delegate to - string validator = 2; - // amount is the tokens to delegate - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// MsgDelegateMintDepositResponse defines the Msg/MsgDelegateMintDeposit response type. -message MsgDelegateMintDepositResponse {} - -// MsgWithdrawBurn removes staking derivatives from an earn vault and converts them back to a staking delegation. -message MsgWithdrawBurn { - // from is the owner of the earn vault to withdraw from - string from = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // validator is the address to select the derivative denom to withdraw - string validator = 2; - // amount is the staked token equivalent to withdraw - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// MsgWithdrawBurnResponse defines the Msg/MsgWithdrawBurn response type. -message MsgWithdrawBurnResponse {} - -// MsgWithdrawBurnUndelegate removes staking derivatives from an earn vault, converts them to a staking delegation, -// then undelegates them from their validator. -message MsgWithdrawBurnUndelegate { - // from is the owner of the earn vault to withdraw from - string from = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // validator is the address to select the derivative denom to withdraw - string validator = 2; - // amount is the staked token equivalent to withdraw - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// MsgWithdrawBurnUndelegateResponse defines the Msg/MsgWithdrawBurnUndelegate response type. -message MsgWithdrawBurnUndelegateResponse {} diff --git a/proto/kava/savings/v1beta1/genesis.proto b/proto/kava/savings/v1beta1/genesis.proto deleted file mode 100644 index 26164add..00000000 --- a/proto/kava/savings/v1beta1/genesis.proto +++ /dev/null @@ -1,18 +0,0 @@ -syntax = "proto3"; -package kava.savings.v1beta1; - -import "gogoproto/gogo.proto"; -import "kava/savings/v1beta1/store.proto"; - -option go_package = "github.com/kava-labs/kava/x/savings/types"; - -// GenesisState defines the savings module's genesis state. -message GenesisState { - // params defines all the parameters of the module. - Params params = 1 [(gogoproto.nullable) = false]; - - repeated Deposit deposits = 2 [ - (gogoproto.castrepeated) = "Deposits", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/savings/v1beta1/query.proto b/proto/kava/savings/v1beta1/query.proto deleted file mode 100644 index fa3aff55..00000000 --- a/proto/kava/savings/v1beta1/query.proto +++ /dev/null @@ -1,75 +0,0 @@ -syntax = "proto3"; -package kava.savings.v1beta1; - -import "cosmos/base/query/v1beta1/pagination.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "kava/savings/v1beta1/store.proto"; - -option go_package = "github.com/kava-labs/kava/x/savings/types"; - -// Query defines the gRPC querier service for savings module -service Query { - // Params queries all parameters of the savings module. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/savings/v1beta1/params"; - } - - // Deposits queries savings deposits. - rpc Deposits(QueryDepositsRequest) returns (QueryDepositsResponse) { - option (google.api.http).get = "/kava/savings/v1beta1/deposits"; - } - - // TotalSupply returns the total sum of all coins currently locked into the savings module. - rpc TotalSupply(QueryTotalSupplyRequest) returns (QueryTotalSupplyResponse) { - option (google.api.http).get = "/kava/savings/v1beta1/total_supply"; - } -} - -// QueryParamsRequest defines the request type for querying x/savings -// parameters. -message QueryParamsRequest {} - -// QueryParamsResponse defines the response type for querying x/savings -// parameters. -message QueryParamsResponse { - option (gogoproto.goproto_getters) = false; - - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryDepositsRequest defines the request type for querying x/savings -// deposits. -message QueryDepositsRequest { - string denom = 1; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - cosmos.base.query.v1beta1.PageRequest pagination = 3; -} - -// QueryDepositsResponse defines the response type for querying x/savings -// deposits. -message QueryDepositsResponse { - repeated Deposit deposits = 1 [ - (gogoproto.castrepeated) = "Deposits", - (gogoproto.nullable) = false - ]; - - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryTotalSupplyRequest defines the request type for Query/TotalSupply method. -message QueryTotalSupplyRequest {} - -// TotalSupplyResponse defines the response type for the Query/TotalSupply method. -message QueryTotalSupplyResponse { - // Height is the block height at which these totals apply - int64 height = 1; - // Result is a list of coins supplied to savings - repeated cosmos.base.v1beta1.Coin result = 2 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} diff --git a/proto/kava/savings/v1beta1/store.proto b/proto/kava/savings/v1beta1/store.proto deleted file mode 100644 index 7beeee10..00000000 --- a/proto/kava/savings/v1beta1/store.proto +++ /dev/null @@ -1,27 +0,0 @@ -syntax = "proto3"; -package kava.savings.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/savings/types"; -option (gogoproto.goproto_getters_all) = false; - -// Params defines the parameters for the savings module. -message Params { - repeated string supported_denoms = 1; -} - -// Deposit defines an amount of coins deposited into a savings module account. -message Deposit { - string depositor = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/savings/v1beta1/tx.proto b/proto/kava/savings/v1beta1/tx.proto deleted file mode 100644 index 35ab38dc..00000000 --- a/proto/kava/savings/v1beta1/tx.proto +++ /dev/null @@ -1,41 +0,0 @@ -syntax = "proto3"; -package kava.savings.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/savings/types"; - -// Msg defines the savings Msg service. -service Msg { - // Deposit defines a method for depositing funds to the savings module account - rpc Deposit(MsgDeposit) returns (MsgDepositResponse); - - // Withdraw defines a method for withdrawing funds to the savings module account - rpc Withdraw(MsgWithdraw) returns (MsgWithdrawResponse); -} - -// MsgDeposit defines the Msg/Deposit request type. -message MsgDeposit { - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// MsgDepositResponse defines the Msg/Deposit response type. -message MsgDepositResponse {} - -// MsgWithdraw defines the Msg/Withdraw request type. -message MsgWithdraw { - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -message MsgWithdrawResponse {} diff --git a/proto/kava/swap/v1beta1/genesis.proto b/proto/kava/swap/v1beta1/genesis.proto deleted file mode 100644 index dfdb5cb9..00000000 --- a/proto/kava/swap/v1beta1/genesis.proto +++ /dev/null @@ -1,23 +0,0 @@ -syntax = "proto3"; -package kava.swap.v1beta1; - -import "gogoproto/gogo.proto"; -import "kava/swap/v1beta1/swap.proto"; - -option go_package = "github.com/kava-labs/kava/x/swap/types"; - -// GenesisState defines the swap module's genesis state. -message GenesisState { - // params defines all the parameters related to swap - Params params = 1 [(gogoproto.nullable) = false]; - // pool_records defines the available pools - repeated PoolRecord pool_records = 2 [ - (gogoproto.castrepeated) = "PoolRecords", - (gogoproto.nullable) = false - ]; - // share_records defines the owned shares of each pool - repeated ShareRecord share_records = 3 [ - (gogoproto.castrepeated) = "ShareRecords", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/swap/v1beta1/query.proto b/proto/kava/swap/v1beta1/query.proto deleted file mode 100644 index 63a0f8fb..00000000 --- a/proto/kava/swap/v1beta1/query.proto +++ /dev/null @@ -1,118 +0,0 @@ -syntax = "proto3"; -package kava.swap.v1beta1; - -import "cosmos/base/query/v1beta1/pagination.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "kava/swap/v1beta1/swap.proto"; - -option go_package = "github.com/kava-labs/kava/x/swap/types"; - -// Query defines the gRPC querier service for swap module -service Query { - // Params queries all parameters of the swap module. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/swap/v1beta1/params"; - } - // Pools queries pools based on pool ID - rpc Pools(QueryPoolsRequest) returns (QueryPoolsResponse) { - option (google.api.http).get = "/kava/swap/v1beta1/pools"; - } - // Deposits queries deposit details based on owner address and pool - rpc Deposits(QueryDepositsRequest) returns (QueryDepositsResponse) { - option (google.api.http).get = "/kava/swap/v1beta1/deposits"; - } -} - -// QueryParamsRequest defines the request type for querying x/swap parameters. -message QueryParamsRequest { - option (gogoproto.goproto_getters) = false; -} - -// QueryParamsResponse defines the response type for querying x/swap parameters. -message QueryParamsResponse { - option (gogoproto.goproto_getters) = false; - - // params represents the swap module parameters - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryPoolsRequest is the request type for the Query/Pools RPC method. -message QueryPoolsRequest { - // pool_id filters pools by id - string pool_id = 1; - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 2; -} - -// QueryPoolsResponse is the response type for the Query/Pools RPC method. -message QueryPoolsResponse { - // pools represents returned pools - repeated PoolResponse pools = 1 [(gogoproto.nullable) = false]; - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// Pool represents the state of a single pool -message PoolResponse { - option (gogoproto.goproto_getters) = false; - - // name represents the name of the pool - string name = 1; - // coins represents the total reserves of the pool - repeated cosmos.base.v1beta1.Coin coins = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; - // total_shares represents the total shares of the pool - string total_shares = 3 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} - -// QueryDepositsRequest is the request type for the Query/Deposits RPC method. -message QueryDepositsRequest { - option (gogoproto.goproto_getters) = false; - - // owner optionally filters deposits by owner - string owner = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // pool_id optionally fitlers deposits by pool id - string pool_id = 2; - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 3; -} - -// QueryDepositsResponse is the response type for the Query/Deposits RPC method. -message QueryDepositsResponse { - option (gogoproto.goproto_getters) = false; - - // deposits returns the deposits matching the requested parameters - repeated DepositResponse deposits = 1 [(gogoproto.nullable) = false]; - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// DepositResponse defines a single deposit query response type. -message DepositResponse { - option (gogoproto.goproto_getters) = false; - - // depositor represents the owner of the deposit - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // pool_id represents the pool the deposit is for - string pool_id = 2; - // shares_owned presents the shares owned by the depositor for the pool - string shares_owned = 3 [ - (cosmos_proto.scalar) = "cosmos.AddressString", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - // shares_value represents the coin value of the shares_owned - repeated cosmos.base.v1beta1.Coin shares_value = 4 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/swap/v1beta1/swap.proto b/proto/kava/swap/v1beta1/swap.proto deleted file mode 100644 index 4e295d8e..00000000 --- a/proto/kava/swap/v1beta1/swap.proto +++ /dev/null @@ -1,69 +0,0 @@ -syntax = "proto3"; -package kava.swap.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/swap/types"; - -// Params defines the parameters for the swap module. -message Params { - option (gogoproto.goproto_stringer) = false; // false here because we define Stringer method in params.go - - // allowed_pools defines that pools that are allowed to be created - repeated AllowedPool allowed_pools = 1 [ - (gogoproto.castrepeated) = "AllowedPools", - (gogoproto.nullable) = false - ]; - // swap_fee defines the swap fee for all pools - string swap_fee = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// AllowedPool defines a pool that is allowed to be created -message AllowedPool { - option (gogoproto.goproto_stringer) = false; // false here because we define Stringer method in params.go - - // token_a represents the a token allowed - string token_a = 1; - // token_b represents the b token allowed - string token_b = 2; -} - -// PoolRecord represents the state of a liquidity pool -// and is used to store the state of a denominated pool -message PoolRecord { - // pool_id represents the unique id of the pool - string pool_id = 1 [(gogoproto.customname) = "PoolID"]; - // reserves_a is the a token coin reserves - cosmos.base.v1beta1.Coin reserves_a = 2 [(gogoproto.nullable) = false]; - // reserves_b is the a token coin reserves - cosmos.base.v1beta1.Coin reserves_b = 3 [(gogoproto.nullable) = false]; - // total_shares is the total distrubuted shares of the pool - string total_shares = 4 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} - -// ShareRecord stores the shares owned for a depositor and pool -message ShareRecord { - // depositor represents the owner of the shares - bytes depositor = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - // pool_id represents the pool the shares belong to - string pool_id = 2 [(gogoproto.customname) = "PoolID"]; - // shares_owned represents the number of shares owned by depsoitor for the pool_id - string shares_owned = 3 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/swap/v1beta1/tx.proto b/proto/kava/swap/v1beta1/tx.proto deleted file mode 100644 index 7980b66c..00000000 --- a/proto/kava/swap/v1beta1/tx.proto +++ /dev/null @@ -1,114 +0,0 @@ -syntax = "proto3"; -package kava.swap.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/kava-labs/kava/x/swap/types"; - -// Msg defines the swap Msg service. -service Msg { - // Deposit defines a method for depositing liquidity into a pool - rpc Deposit(MsgDeposit) returns (MsgDepositResponse); - // Withdraw defines a method for withdrawing liquidity into a pool - rpc Withdraw(MsgWithdraw) returns (MsgWithdrawResponse); - // SwapExactForTokens represents a message for trading exact coinA for coinB - rpc SwapExactForTokens(MsgSwapExactForTokens) returns (MsgSwapExactForTokensResponse); - // SwapForExactTokens represents a message for trading coinA for an exact coinB - rpc SwapForExactTokens(MsgSwapForExactTokens) returns (MsgSwapForExactTokensResponse); -} - -// MsgDeposit represents a message for depositing liquidity into a pool -message MsgDeposit { - option (gogoproto.goproto_getters) = false; - - // depositor represents the address to deposit funds from - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // token_a represents one token of deposit pair - cosmos.base.v1beta1.Coin token_a = 2 [(gogoproto.nullable) = false]; - // token_b represents one token of deposit pair - cosmos.base.v1beta1.Coin token_b = 3 [(gogoproto.nullable) = false]; - // slippage represents the max decimal percentage price change - string slippage = 4 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - // deadline represents the unix timestamp to complete the deposit by - int64 deadline = 5; -} - -// MsgDepositResponse defines the Msg/Deposit response type. -message MsgDepositResponse {} - -// MsgWithdraw represents a message for withdrawing liquidity from a pool -message MsgWithdraw { - option (gogoproto.goproto_getters) = false; - - // from represents the address we are withdrawing for - string from = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // shares represents the amount of shares to withdraw - string shares = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - // min_token_a represents the minimum a token to withdraw - cosmos.base.v1beta1.Coin min_token_a = 3 [(gogoproto.nullable) = false]; - // min_token_a represents the minimum a token to withdraw - cosmos.base.v1beta1.Coin min_token_b = 4 [(gogoproto.nullable) = false]; - // deadline represents the unix timestamp to complete the withdraw by - int64 deadline = 5; -} - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -message MsgWithdrawResponse {} - -// MsgSwapExactForTokens represents a message for trading exact coinA for coinB -message MsgSwapExactForTokens { - option (gogoproto.goproto_getters) = false; - - // represents the address swaping the tokens - string requester = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // exact_token_a represents the exact amount to swap for token_b - cosmos.base.v1beta1.Coin exact_token_a = 2 [(gogoproto.nullable) = false]; - // token_b represents the desired token_b to swap for - cosmos.base.v1beta1.Coin token_b = 3 [(gogoproto.nullable) = false]; - // slippage represents the maximum change in token_b allowed - string slippage = 4 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - // deadline represents the unix timestamp to complete the swap by - int64 deadline = 5; -} - -// MsgSwapExactForTokensResponse defines the Msg/SwapExactForTokens response -// type. -message MsgSwapExactForTokensResponse {} - -// MsgSwapForExactTokens represents a message for trading coinA for an exact -// coinB -message MsgSwapForExactTokens { - option (gogoproto.goproto_getters) = false; - - // represents the address swaping the tokens - string requester = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // token_a represents the desired token_a to swap for - cosmos.base.v1beta1.Coin token_a = 2 [(gogoproto.nullable) = false]; - // exact_token_b represents the exact token b amount to swap for token a - cosmos.base.v1beta1.Coin exact_token_b = 3 [(gogoproto.nullable) = false]; - // slippage represents the maximum change in token_a allowed - string slippage = 4 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - // deadline represents the unix timestamp to complete the swap by - int64 deadline = 5; -} - -// MsgSwapForExactTokensResponse defines the Msg/SwapForExactTokensResponse -// response type. -message MsgSwapForExactTokensResponse {} diff --git a/proto/zgc/committee/v1/genesis.proto b/proto/zgc/committee/v1/genesis.proto new file mode 100644 index 00000000..167944b6 --- /dev/null +++ b/proto/zgc/committee/v1/genesis.proto @@ -0,0 +1,52 @@ +syntax = "proto3"; +package zgc.committee.v1; + +import "cosmos_proto/cosmos.proto"; +import "gogoproto/gogo.proto"; +import "google/protobuf/any.proto"; +import "google/protobuf/timestamp.proto"; + +option go_package = "github.com/0glabs/0g-chain/x/committee/v1/types"; + +message Params { + uint64 committee_size = 1; +} + +// GenesisState defines the committee module's genesis state. +message GenesisState { + option (gogoproto.goproto_getters) = false; + + Params params = 1 [(gogoproto.nullable) = false]; + uint64 voting_start_height = 2; + uint64 voting_period = 3; + uint64 current_committee_id = 4 [(gogoproto.customname) = "CurrentCommitteeID"]; + repeated Committee committees = 5 [(gogoproto.nullable) = false]; +} + +message Committee { + uint64 id = 1 [(gogoproto.customname) = "ID"]; + uint64 voting_start_height = 2; + uint64 start_height = 3; + uint64 end_height = 4; + repeated Vote votes = 5 [(gogoproto.nullable) = false]; + repeated bytes members = 6 [ + (cosmos_proto.scalar) = "cosmos.AddressBytes", + (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.ValAddress" + ]; +} + +message Vote { + option (gogoproto.goproto_getters) = false; + + uint64 committee_id = 1 [(gogoproto.customname) = "CommitteeID"]; + bytes voter = 2 [ + (cosmos_proto.scalar) = "cosmos.AddressBytes", + (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.ValAddress" + ]; + repeated Ballot ballots = 3; +} + +message Ballot { + uint64 id = 1 [(gogoproto.customname) = "ID"]; + bytes content = 2; +} diff --git a/proto/zgc/committee/v1/query.proto b/proto/zgc/committee/v1/query.proto new file mode 100644 index 00000000..b644ea07 --- /dev/null +++ b/proto/zgc/committee/v1/query.proto @@ -0,0 +1,34 @@ +syntax = "proto3"; +package zgc.committee.v1; + +import "cosmos_proto/cosmos.proto"; +import "gogoproto/gogo.proto"; +import "google/api/annotations.proto"; +import "google/protobuf/any.proto"; +import "google/protobuf/timestamp.proto"; +import "zgc/committee/v1/genesis.proto"; + +option go_package = "github.com/0glabs/0g-chain/x/committee/v1/types"; +option (gogoproto.goproto_getters_all) = false; + +// Query defines the gRPC querier service for committee module +service Query { + rpc CurrentCommitteeID(QueryCurrentCommitteeIDRequest) returns (QueryCurrentCommitteeIDResponse) { + option (google.api.http).get = "/0gchain/committee/v1/current-committee-id"; + } + rpc RegisteredVoters(QueryRegisteredVotersRequest) returns (QueryRegisteredVotersResponse) { + option (google.api.http).get = "/0gchain/committee/v1/registered-voters"; + } +} + +message QueryCurrentCommitteeIDRequest {} + +message QueryCurrentCommitteeIDResponse { + uint64 current_committee_id = 1 [(gogoproto.customname) = "CurrentCommitteeID"]; +} + +message QueryRegisteredVotersRequest {} + +message QueryRegisteredVotersResponse { + repeated string voters = 1; +} diff --git a/proto/zgc/committee/v1/tx.proto b/proto/zgc/committee/v1/tx.proto new file mode 100644 index 00000000..6f36028b --- /dev/null +++ b/proto/zgc/committee/v1/tx.proto @@ -0,0 +1,31 @@ +syntax = "proto3"; +package zgc.committee.v1; + +import "cosmos_proto/cosmos.proto"; +import "gogoproto/gogo.proto"; +import "google/protobuf/any.proto"; +import "zgc/committee/v1/genesis.proto"; + +option go_package = "github.com/0glabs/0g-chain/x/committee/v1/types"; +option (gogoproto.goproto_getters_all) = false; + +// Msg defines the committee Msg service +service Msg { + rpc Register(MsgRegister) returns (MsgRegisterResponse); + rpc Vote(MsgVote) returns (MsgVoteResponse); +} + +message MsgRegister { + string voter = 1; + bytes key = 2; +} + +message MsgRegisterResponse {} + +message MsgVote { + uint64 committee_id = 1 [(gogoproto.customname) = "CommitteeID"]; + string voter = 2; + repeated Ballot ballots = 3; +} + +message MsgVoteResponse {} diff --git a/proto/zgc/das/v1/genesis.proto b/proto/zgc/das/v1/genesis.proto new file mode 100644 index 00000000..9aae1faa --- /dev/null +++ b/proto/zgc/das/v1/genesis.proto @@ -0,0 +1,37 @@ +syntax = "proto3"; +package zgc.das.v1; + +import "cosmos_proto/cosmos.proto"; +import "gogoproto/gogo.proto"; +import "google/protobuf/any.proto"; +import "google/protobuf/timestamp.proto"; + +option go_package = "github.com/0glabs/0g-chain/x/das/v1/types"; + +message Params {} + +// GenesisState defines the das module's genesis state. +message GenesisState { + option (gogoproto.goproto_getters) = false; + + Params params = 1 [(gogoproto.nullable) = false]; + uint64 next_request_id = 2 [(gogoproto.customname) = "NextRequestID"]; + repeated DASRequest requests = 3 [(gogoproto.nullable) = false]; + repeated DASResponse responses = 4 [(gogoproto.nullable) = false]; +} + +message DASRequest { + uint64 id = 1 [(gogoproto.customname) = "ID"]; + bytes stream_id = 2 [(gogoproto.customname) = "StreamID"]; + bytes batch_header_hash = 3; + uint32 num_blobs = 4; +} + +message DASResponse { + uint64 id = 1 [(gogoproto.customname) = "ID"]; + bytes sampler = 2 [ + (cosmos_proto.scalar) = "cosmos.AddressBytes", + (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.ValAddress" + ]; + repeated bool results = 3; +} diff --git a/proto/zgc/das/v1/query.proto b/proto/zgc/das/v1/query.proto new file mode 100644 index 00000000..371c50e8 --- /dev/null +++ b/proto/zgc/das/v1/query.proto @@ -0,0 +1,24 @@ +syntax = "proto3"; +package zgc.das.v1; + +import "cosmos_proto/cosmos.proto"; +import "gogoproto/gogo.proto"; +import "google/api/annotations.proto"; +import "google/protobuf/any.proto"; +import "google/protobuf/timestamp.proto"; + +option go_package = "github.com/0glabs/0g-chain/x/das/v1/types"; +option (gogoproto.goproto_getters_all) = false; + +// Query defines the gRPC querier service for the das module +service Query { + rpc NextRequestID(QueryNextRequestIDRequest) returns (QueryNextRequestIDResponse) { + option (google.api.http).get = "/0gchain/das/v1/next-request-id"; + } +} + +message QueryNextRequestIDRequest {} + +message QueryNextRequestIDResponse { + uint64 next_request_id = 1 [(gogoproto.customname) = "NextRequestID"]; +} diff --git a/proto/zgc/das/v1/tx.proto b/proto/zgc/das/v1/tx.proto new file mode 100644 index 00000000..482c4679 --- /dev/null +++ b/proto/zgc/das/v1/tx.proto @@ -0,0 +1,35 @@ +syntax = "proto3"; +package zgc.das.v1; + +import "cosmos_proto/cosmos.proto"; +import "gogoproto/gogo.proto"; +import "google/protobuf/any.proto"; +import "zgc/das/v1/genesis.proto"; + +option go_package = "github.com/0glabs/0g-chain/x/das/v1/types"; +option (gogoproto.goproto_getters_all) = false; + +// Msg defines the das Msg service +service Msg { + rpc RequestDAS(MsgRequestDAS) returns (MsgRequestDASResponse); + rpc ReportDASResult(MsgReportDASResult) returns (MsgReportDASResultResponse); +} + +message MsgRequestDAS { + string requester = 1 [(gogoproto.moretags) = "Requester"]; + string stream_id = 2 [(gogoproto.customname) = "StreamID"]; + string batch_header_hash = 3; + uint32 num_blobs = 4; +} + +message MsgRequestDASResponse { + uint64 request_id = 1 [(gogoproto.customname) = "RequestID"]; +} + +message MsgReportDASResult { + uint64 request_id = 1 [(gogoproto.customname) = "RequestID"]; + string sampler = 2; + repeated bool results = 3; +} + +message MsgReportDASResultResponse {} diff --git a/proto/kava/evmutil/v1beta1/conversion_pair.proto b/proto/zgc/evmutil/v1beta1/conversion_pair.proto similarity index 75% rename from proto/kava/evmutil/v1beta1/conversion_pair.proto rename to proto/zgc/evmutil/v1beta1/conversion_pair.proto index 678690fd..b47c9157 100644 --- a/proto/kava/evmutil/v1beta1/conversion_pair.proto +++ b/proto/zgc/evmutil/v1beta1/conversion_pair.proto @@ -1,20 +1,20 @@ syntax = "proto3"; -package kava.evmutil.v1beta1; +package zgc.evmutil.v1beta1; import "gogoproto/gogo.proto"; -option go_package = "github.com/kava-labs/kava/x/evmutil/types"; +option go_package = "github.com/0glabs/0g-chain/x/evmutil/types"; option (gogoproto.equal_all) = true; option (gogoproto.verbose_equal_all) = true; -// ConversionPair defines a Kava ERC20 address and corresponding denom that is +// ConversionPair defines a 0g-chain ERC20 address and corresponding denom that is // allowed to be converted between ERC20 and sdk.Coin message ConversionPair { option (gogoproto.goproto_getters) = false; - // ERC20 address of the token on the Kava EVM - bytes kava_erc20_address = 1 [ - (gogoproto.customname) = "KavaERC20Address", + // ERC20 address of the token on the 0g-chain EVM + bytes zgchain_erc20_address = 1 [ + (gogoproto.customname) = "ZgchainERC20Address", (gogoproto.casttype) = "HexBytes" ]; diff --git a/proto/kava/evmutil/v1beta1/genesis.proto b/proto/zgc/evmutil/v1beta1/genesis.proto similarity index 85% rename from proto/kava/evmutil/v1beta1/genesis.proto rename to proto/zgc/evmutil/v1beta1/genesis.proto index fa0f6722..75f0c3f6 100644 --- a/proto/kava/evmutil/v1beta1/genesis.proto +++ b/proto/zgc/evmutil/v1beta1/genesis.proto @@ -1,11 +1,11 @@ syntax = "proto3"; -package kava.evmutil.v1beta1; +package zgc.evmutil.v1beta1; import "cosmos_proto/cosmos.proto"; import "gogoproto/gogo.proto"; -import "kava/evmutil/v1beta1/conversion_pair.proto"; +import "zgc/evmutil/v1beta1/conversion_pair.proto"; -option go_package = "github.com/kava-labs/kava/x/evmutil/types"; +option go_package = "github.com/0glabs/0g-chain/x/evmutil/types"; option (gogoproto.equal_all) = true; option (gogoproto.verbose_equal_all) = true; @@ -28,7 +28,7 @@ message Account { (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" ]; - // balance indicates the amount of akava owned by the address. + // balance indicates the amount of neuron owned by the address. string balance = 2 [ (cosmos_proto.scalar) = "cosmos.Int", (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", @@ -39,7 +39,7 @@ message Account { // Params defines the evmutil module params message Params { // enabled_conversion_pairs defines the list of conversion pairs allowed to be - // converted between Kava ERC20 and sdk.Coin + // converted between 0g-chain ERC20 and sdk.Coin repeated ConversionPair enabled_conversion_pairs = 4 [ (gogoproto.nullable) = false, (gogoproto.castrepeated) = "ConversionPairs" diff --git a/proto/kava/evmutil/v1beta1/query.proto b/proto/zgc/evmutil/v1beta1/query.proto similarity index 87% rename from proto/kava/evmutil/v1beta1/query.proto rename to proto/zgc/evmutil/v1beta1/query.proto index 960bac48..5c40abb8 100644 --- a/proto/kava/evmutil/v1beta1/query.proto +++ b/proto/zgc/evmutil/v1beta1/query.proto @@ -1,23 +1,23 @@ syntax = "proto3"; -package kava.evmutil.v1beta1; +package zgc.evmutil.v1beta1; import "cosmos/base/query/v1beta1/pagination.proto"; import "gogoproto/gogo.proto"; import "google/api/annotations.proto"; -import "kava/evmutil/v1beta1/genesis.proto"; +import "zgc/evmutil/v1beta1/genesis.proto"; -option go_package = "github.com/kava-labs/kava/x/evmutil/types"; +option go_package = "github.com/0glabs/0g-chain/x/evmutil/types"; // Query defines the gRPC querier service for evmutil module service Query { // Params queries all parameters of the evmutil module. rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/evmutil/v1beta1/params"; + option (google.api.http).get = "/0g-chain/evmutil/v1beta1/params"; } // DeployedCosmosCoinContracts queries a list cosmos coin denom and their deployed erc20 address rpc DeployedCosmosCoinContracts(QueryDeployedCosmosCoinContractsRequest) returns (QueryDeployedCosmosCoinContractsResponse) { - option (google.api.http).get = "/kava/evmutil/v1beta1/deployed_cosmos_coin_contracts"; + option (google.api.http).get = "/0g-chain/evmutil/v1beta1/deployed_cosmos_coin_contracts"; } } diff --git a/proto/kava/evmutil/v1beta1/tx.proto b/proto/zgc/evmutil/v1beta1/tx.proto similarity index 77% rename from proto/kava/evmutil/v1beta1/tx.proto rename to proto/zgc/evmutil/v1beta1/tx.proto index 93c43f15..8a5d64fa 100644 --- a/proto/kava/evmutil/v1beta1/tx.proto +++ b/proto/zgc/evmutil/v1beta1/tx.proto @@ -1,20 +1,20 @@ syntax = "proto3"; -package kava.evmutil.v1beta1; +package zgc.evmutil.v1beta1; import "cosmos/base/v1beta1/coin.proto"; import "cosmos_proto/cosmos.proto"; import "gogoproto/gogo.proto"; -option go_package = "github.com/kava-labs/kava/x/evmutil/types"; +option go_package = "github.com/0glabs/0g-chain/x/evmutil/types"; option (gogoproto.equal_all) = true; option (gogoproto.verbose_equal_all) = true; // Msg defines the evmutil Msg service. service Msg { - // ConvertCoinToERC20 defines a method for converting sdk.Coin to Kava ERC20. + // ConvertCoinToERC20 defines a method for converting sdk.Coin to 0g-chain ERC20. rpc ConvertCoinToERC20(MsgConvertCoinToERC20) returns (MsgConvertCoinToERC20Response); - // ConvertERC20ToCoin defines a method for converting Kava ERC20 to sdk.Coin. + // ConvertERC20ToCoin defines a method for converting 0g-chain ERC20 to sdk.Coin. rpc ConvertERC20ToCoin(MsgConvertERC20ToCoin) returns (MsgConvertERC20ToCoinResponse); // ConvertCosmosCoinToERC20 defines a method for converting a cosmos sdk.Coin to an ERC20. @@ -24,11 +24,11 @@ service Msg { rpc ConvertCosmosCoinFromERC20(MsgConvertCosmosCoinFromERC20) returns (MsgConvertCosmosCoinFromERC20Response); } -// MsgConvertCoinToERC20 defines a conversion from sdk.Coin to Kava ERC20 for EVM-native assets. +// MsgConvertCoinToERC20 defines a conversion from sdk.Coin to 0g-chain ERC20 for EVM-native assets. message MsgConvertCoinToERC20 { - // Kava bech32 address initiating the conversion. + // 0g-chain bech32 address initiating the conversion. string initiator = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // EVM 0x hex address that will receive the converted Kava ERC20 tokens. + // EVM 0x hex address that will receive the converted 0g-chain ERC20 tokens. string receiver = 2; // Amount is the sdk.Coin amount to convert. cosmos.base.v1beta1.Coin amount = 3; @@ -37,14 +37,14 @@ message MsgConvertCoinToERC20 { // MsgConvertCoinToERC20Response defines the response value from Msg/ConvertCoinToERC20. message MsgConvertCoinToERC20Response {} -// MsgConvertERC20ToCoin defines a conversion from Kava ERC20 to sdk.Coin for EVM-native assets. +// MsgConvertERC20ToCoin defines a conversion from 0g-chain ERC20 to sdk.Coin for EVM-native assets. message MsgConvertERC20ToCoin { // EVM 0x hex address initiating the conversion. string initiator = 1; - // Kava bech32 address that will receive the converted sdk.Coin. + // 0g-chain bech32 address that will receive the converted sdk.Coin. string receiver = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; // EVM 0x hex address of the ERC20 contract. - string kava_erc20_address = 3 [(gogoproto.customname) = "KavaERC20Address"]; + string zgchain_erc20_address = 3 [(gogoproto.customname) = "ZgchainERC20Address"]; // ERC20 token amount to convert. string amount = 4 [ (cosmos_proto.scalar) = "cosmos.Int", @@ -59,7 +59,7 @@ message MsgConvertERC20ToCoinResponse {} // MsgConvertCosmosCoinToERC20 defines a conversion from cosmos sdk.Coin to ERC20 for cosmos-native assets. message MsgConvertCosmosCoinToERC20 { - // Kava bech32 address initiating the conversion. + // 0g-chain bech32 address initiating the conversion. string initiator = 1; // EVM hex address that will receive the ERC20 tokens. string receiver = 2; @@ -74,7 +74,7 @@ message MsgConvertCosmosCoinToERC20Response {} message MsgConvertCosmosCoinFromERC20 { // EVM hex address initiating the conversion. string initiator = 1; - // Kava bech32 address that will receive the cosmos coins. + // 0g-chain bech32 address that will receive the cosmos coins. string receiver = 2; // Amount is the amount to convert, expressed as a Cosmos coin. cosmos.base.v1beta1.Coin amount = 3; diff --git a/proto/kava/validatorvesting/v1beta1/query.proto b/proto/zgc/validatorvesting/v1beta1/query.proto similarity index 83% rename from proto/kava/validatorvesting/v1beta1/query.proto rename to proto/zgc/validatorvesting/v1beta1/query.proto index 406c0713..53311fc1 100644 --- a/proto/kava/validatorvesting/v1beta1/query.proto +++ b/proto/zgc/validatorvesting/v1beta1/query.proto @@ -1,48 +1,48 @@ syntax = "proto3"; -package kava.validatorvesting.v1beta1; +package zgc.validatorvesting.v1beta1; import "cosmos_proto/cosmos.proto"; import "gogoproto/gogo.proto"; import "google/api/annotations.proto"; -option go_package = "github.com/kava-labs/kava/x/validator-vesting/types"; +option go_package = "github.com/0glabs/0g-chain/x/validator-vesting/types"; option (gogoproto.goproto_getters_all) = false; // Query defines the gRPC querier service for validator-vesting module service Query { - // CirculatingSupply returns the total amount of kava tokens in circulation + // CirculatingSupply returns the total amount of 0g-chain tokens in circulation rpc CirculatingSupply(QueryCirculatingSupplyRequest) returns (QueryCirculatingSupplyResponse) { - option (google.api.http).get = "/kava/validator-vesting/v1beta1/circulating_supply"; + option (google.api.http).get = "/0g-chain/validator-vesting/v1beta1/circulating_supply"; } - // TotalSupply returns the total amount of kava tokens + // TotalSupply returns the total amount of 0g-chain tokens rpc TotalSupply(QueryTotalSupplyRequest) returns (QueryTotalSupplyResponse) { - option (google.api.http).get = "/kava/validator-vesting/v1beta1/total_supply"; + option (google.api.http).get = "/0g-chain/validator-vesting/v1beta1/total_supply"; } // CirculatingSupplyHARD returns the total amount of hard tokens in circulation rpc CirculatingSupplyHARD(QueryCirculatingSupplyHARDRequest) returns (QueryCirculatingSupplyHARDResponse) { - option (google.api.http).get = "/kava/validator-vesting/v1beta1/circulating_supply_hard"; + option (google.api.http).get = "/0g-chain/validator-vesting/v1beta1/circulating_supply_hard"; } // CirculatingSupplyUSDX returns the total amount of usdx tokens in circulation rpc CirculatingSupplyUSDX(QueryCirculatingSupplyUSDXRequest) returns (QueryCirculatingSupplyUSDXResponse) { - option (google.api.http).get = "/kava/validator-vesting/v1beta1/circulating_supply_usdx"; + option (google.api.http).get = "/0g-chain/validator-vesting/v1beta1/circulating_supply_usdx"; } // CirculatingSupplySWP returns the total amount of swp tokens in circulation rpc CirculatingSupplySWP(QueryCirculatingSupplySWPRequest) returns (QueryCirculatingSupplySWPResponse) { - option (google.api.http).get = "/kava/validator-vesting/v1beta1/circulating_supply_swp"; + option (google.api.http).get = "/0g-chain/validator-vesting/v1beta1/circulating_supply_swp"; } // TotalSupplyHARD returns the total amount of hard tokens rpc TotalSupplyHARD(QueryTotalSupplyHARDRequest) returns (QueryTotalSupplyHARDResponse) { - option (google.api.http).get = "/kava/validator-vesting/v1beta1/total_supply_hard"; + option (google.api.http).get = "/0g-chain/validator-vesting/v1beta1/total_supply_hard"; } // TotalSupplyUSDX returns the total amount of usdx tokens rpc TotalSupplyUSDX(QueryTotalSupplyUSDXRequest) returns (QueryTotalSupplyUSDXResponse) { - option (google.api.http).get = "/kava/validator-vesting/v1beta1/total_supply_usdx"; + option (google.api.http).get = "/0g-chain/validator-vesting/v1beta1/total_supply_usdx"; } } diff --git a/tests/e2e/e2e_community_update_params_test.go b/tests/e2e/e2e_community_update_params_test.go index 59fe0ccb..28b9521a 100644 --- a/tests/e2e/e2e_community_update_params_test.go +++ b/tests/e2e/e2e_community_update_params_test.go @@ -1,186 +1,177 @@ package e2e_test import ( - "context" "encoding/hex" - "time" - sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - - "github.com/kava-labs/kava/tests/e2e/testutil" - "github.com/kava-labs/kava/tests/util" - communitytypes "github.com/kava-labs/kava/x/community/types" + // communitytypes "github.com/0glabs/0g-chain/x/community/types" ) -func (suite *IntegrationTestSuite) TestCommunityUpdateParams_NonAuthority() { - // ARRANGE - // setup kava account - funds := ukava(1e5) // .1 KAVA - kavaAcc := suite.Kava.NewFundedAccount("community-non-authority", sdk.NewCoins(funds)) +// func (suite *IntegrationTestSuite) TestCommunityUpdateParams_NonAuthority() { +// // ARRANGE +// // setup 0g account +// funds := a0gi(1e5) // .1 A0GI +// zgChainAcc := suite.ZgChain.NewFundedAccount("community-non-authority", sdk.NewCoins(funds)) - gasLimit := int64(2e5) - fee := ukava(200) +// gasLimit := int64(2e5) +// fee := a0gi(200) - msg := communitytypes.NewMsgUpdateParams( - kavaAcc.SdkAddress, - communitytypes.DefaultParams(), - ) +// msg := communitytypes.NewMsgUpdateParams( +// zgChainAcc.SdkAddress, +// communitytypes.DefaultParams(), +// ) - // ACT - req := util.KavaMsgRequest{ - Msgs: []sdk.Msg{&msg}, - GasLimit: uint64(gasLimit), - FeeAmount: sdk.NewCoins(fee), - Memo: "this is a failure!", - } - res := kavaAcc.SignAndBroadcastKavaTx(req) +// // ACT +// req := util.ZgChainMsgRequest{ +// Msgs: []sdk.Msg{&msg}, +// GasLimit: uint64(gasLimit), +// FeeAmount: sdk.NewCoins(fee), +// Memo: "this is a failure!", +// } +// res := zgChainAcc.SignAndBroadcastZgChainTx(req) - // ASSERT - _, err := util.WaitForSdkTxCommit(suite.Kava.Grpc.Query.Tx, res.Result.TxHash, 6*time.Second) - suite.Require().Error(err) - suite.Require().ErrorContains( - err, - govtypes.ErrInvalidSigner.Error(), - "should return with authority check error", - ) -} +// // ASSERT +// _, err := util.WaitForSdkTxCommit(suite.ZgChain.Grpc.Query.Tx, res.Result.TxHash, 6*time.Second) +// suite.Require().Error(err) +// suite.Require().ErrorContains( +// err, +// govtypes.ErrInvalidSigner.Error(), +// "should return with authority check error", +// ) +// } -func (suite *IntegrationTestSuite) TestCommunityUpdateParams_Authority() { - // ARRANGE - govParamsRes, err := suite.Kava.Grpc.Query.Gov.Params(context.Background(), &govv1.QueryParamsRequest{ - ParamsType: govv1.ParamDeposit, - }) - suite.NoError(err) +// func (suite *IntegrationTestSuite) TestCommunityUpdateParams_Authority() { +// // ARRANGE +// govParamsRes, err := suite.ZgChain.Grpc.Query.Gov.Params(context.Background(), &govv1.QueryParamsRequest{ +// ParamsType: govv1.ParamDeposit, +// }) +// suite.NoError(err) - // Check initial params - communityParamsResInitial, err := suite.Kava.Grpc.Query.Community.Params( - context.Background(), - &communitytypes.QueryParamsRequest{}, - ) - suite.Require().NoError(err) +// // Check initial params +// communityParamsResInitial, err := suite.ZgChain.Grpc.Query.Community.Params( +// context.Background(), +// &communitytypes.QueryParamsRequest{}, +// ) +// suite.Require().NoError(err) - // setup kava account - // .1 KAVA + min deposit amount for proposal - funds := sdk.NewCoins(ukava(1e5)).Add(govParamsRes.DepositParams.MinDeposit...) - kavaAcc := suite.Kava.NewFundedAccount("community-update-params", funds) +// // setup 0g account +// // .1 A0GI + min deposit amount for proposal +// funds := sdk.NewCoins(a0gi(1e5)).Add(govParamsRes.DepositParams.MinDeposit...) +// zgChainAcc := suite.ZgChain.NewFundedAccount("community-update-params", funds) - gasLimit := int64(2e5) - fee := ukava(200) +// gasLimit := int64(2e5) +// fee := a0gi(200) - // Wait until switchover actually happens - When testing without the upgrade - // handler that sets a relative switchover time, the switchover time in - // genesis should be set in the past so it runs immediately. - suite.Require().Eventually( - func() bool { - params, err := suite.Kava.Grpc.Query.Community.Params( - context.Background(), - &communitytypes.QueryParamsRequest{}, - ) - suite.Require().NoError(err) +// // Wait until switchover actually happens - When testing without the upgrade +// // handler that sets a relative switchover time, the switchover time in +// // genesis should be set in the past so it runs immediately. +// suite.Require().Eventually( +// func() bool { +// params, err := suite.ZgChain.Grpc.Query.Community.Params( +// context.Background(), +// &communitytypes.QueryParamsRequest{}, +// ) +// suite.Require().NoError(err) - return params.Params.UpgradeTimeDisableInflation.Equal(time.Time{}) - }, - 20*time.Second, - 1*time.Second, - "switchover should happen", - ) +// return params.Params.UpgradeTimeDisableInflation.Equal(time.Time{}) +// }, +// 20*time.Second, +// 1*time.Second, +// "switchover should happen", +// ) - // Add 1 to the staking rewards per second - newStakingRewardsPerSecond := communityParamsResInitial.Params. - StakingRewardsPerSecond. - Add(sdkmath.LegacyNewDec(1)) +// // Add 1 to the staking rewards per second +// newStakingRewardsPerSecond := communityParamsResInitial.Params. +// StakingRewardsPerSecond. +// Add(sdkmath.LegacyNewDec(1)) - // 1. Proposal - // Only modify stakingRewardsPerSecond, as to not re-run the switchover and - // to not influence other tests - updateParamsMsg := communitytypes.NewMsgUpdateParams( - authtypes.NewModuleAddress(govtypes.ModuleName), // authority - communitytypes.NewParams( - time.Time{}, // after switchover, is empty - newStakingRewardsPerSecond, // only modify stakingRewardsPerSecond - communityParamsResInitial.Params.UpgradeTimeSetStakingRewardsPerSecond, - ), - ) +// // 1. Proposal +// // Only modify stakingRewardsPerSecond, as to not re-run the switchover and +// // to not influence other tests +// updateParamsMsg := communitytypes.NewMsgUpdateParams( +// authtypes.NewModuleAddress(govtypes.ModuleName), // authority +// communitytypes.NewParams( +// time.Time{}, // after switchover, is empty +// newStakingRewardsPerSecond, // only modify stakingRewardsPerSecond +// communityParamsResInitial.Params.UpgradeTimeSetStakingRewardsPerSecond, +// ), +// ) - // Make sure we're actually changing the params - suite.NotEqual( - updateParamsMsg.Params, - communityParamsResInitial.Params, - "new params should be different from existing", - ) +// // Make sure we're actually changing the params +// suite.NotEqual( +// updateParamsMsg.Params, +// communityParamsResInitial.Params, +// "new params should be different from existing", +// ) - proposalMsg, err := govv1.NewMsgSubmitProposal( - []sdk.Msg{&updateParamsMsg}, - govParamsRes.Params.MinDeposit, - kavaAcc.SdkAddress.String(), - "community-update-params", - "title", - "summary", - ) - suite.NoError(err) +// proposalMsg, err := govv1.NewMsgSubmitProposal( +// []sdk.Msg{&updateParamsMsg}, +// govParamsRes.Params.MinDeposit, +// zgChainAcc.SdkAddress.String(), +// "community-update-params", +// "title", +// "summary", +// ) +// suite.NoError(err) - req := util.KavaMsgRequest{ - Msgs: []sdk.Msg{proposalMsg}, - GasLimit: uint64(gasLimit), - FeeAmount: sdk.NewCoins(fee), - Memo: "this is a proposal please accept me", - } - res := kavaAcc.SignAndBroadcastKavaTx(req) - suite.Require().NoError(res.Err) +// req := util.ZgChainMsgRequest{ +// Msgs: []sdk.Msg{proposalMsg}, +// GasLimit: uint64(gasLimit), +// FeeAmount: sdk.NewCoins(fee), +// Memo: "this is a proposal please accept me", +// } +// res := zgChainAcc.SignAndBroadcastZgChainTx(req) +// suite.Require().NoError(res.Err) - // Wait for proposal to be submitted - txRes, err := util.WaitForSdkTxCommit(suite.Kava.Grpc.Query.Tx, res.Result.TxHash, 6*time.Second) - suite.Require().NoError(err) +// // Wait for proposal to be submitted +// txRes, err := util.WaitForSdkTxCommit(suite.ZgChain.Grpc.Query.Tx, res.Result.TxHash, 6*time.Second) +// suite.Require().NoError(err) - // Parse tx response to get proposal id - var govRes govv1.MsgSubmitProposalResponse - suite.decodeTxMsgResponse(txRes, &govRes) +// // Parse tx response to get proposal id +// var govRes govv1.MsgSubmitProposalResponse +// suite.decodeTxMsgResponse(txRes, &govRes) - // 2. Vote for proposal from whale account - whale := suite.Kava.GetAccount(testutil.FundedAccountName) - voteMsg := govv1.NewMsgVote( - whale.SdkAddress, - govRes.ProposalId, - govv1.OptionYes, - "", - ) +// // 2. Vote for proposal from whale account +// whale := suite.ZgChain.GetAccount(testutil.FundedAccountName) +// voteMsg := govv1.NewMsgVote( +// whale.SdkAddress, +// govRes.ProposalId, +// govv1.OptionYes, +// "", +// ) - voteReq := util.KavaMsgRequest{ - Msgs: []sdk.Msg{voteMsg}, - GasLimit: uint64(gasLimit), - FeeAmount: sdk.NewCoins(fee), - Memo: "voting", - } - voteRes := whale.SignAndBroadcastKavaTx(voteReq) - suite.Require().NoError(voteRes.Err) +// voteReq := util.ZgChainMsgRequest{ +// Msgs: []sdk.Msg{voteMsg}, +// GasLimit: uint64(gasLimit), +// FeeAmount: sdk.NewCoins(fee), +// Memo: "voting", +// } +// voteRes := whale.SignAndBroadcastZgChainTx(voteReq) +// suite.Require().NoError(voteRes.Err) - _, err = util.WaitForSdkTxCommit(suite.Kava.Grpc.Query.Tx, voteRes.Result.TxHash, 6*time.Second) - suite.Require().NoError(err) +// _, err = util.WaitForSdkTxCommit(suite.ZgChain.Grpc.Query.Tx, voteRes.Result.TxHash, 6*time.Second) +// suite.Require().NoError(err) - // 3. Wait until proposal passes - suite.Require().Eventually(func() bool { - proposalRes, err := suite.Kava.Grpc.Query.Gov.Proposal(context.Background(), &govv1.QueryProposalRequest{ - ProposalId: govRes.ProposalId, - }) - suite.NoError(err) +// // 3. Wait until proposal passes +// suite.Require().Eventually(func() bool { +// proposalRes, err := suite.ZgChain.Grpc.Query.Gov.Proposal(context.Background(), &govv1.QueryProposalRequest{ +// ProposalId: govRes.ProposalId, +// }) +// suite.NoError(err) - return proposalRes.Proposal.Status == govv1.StatusPassed - }, 60*time.Second, 1*time.Second) +// return proposalRes.Proposal.Status == govv1.StatusPassed +// }, 60*time.Second, 1*time.Second) - // Check parameters are updated - communityParamsRes, err := suite.Kava.Grpc.Query.Community.Params( - context.Background(), - &communitytypes.QueryParamsRequest{}, - ) - suite.Require().NoError(err) +// // Check parameters are updated +// communityParamsRes, err := suite.ZgChain.Grpc.Query.Community.Params( +// context.Background(), +// &communitytypes.QueryParamsRequest{}, +// ) +// suite.Require().NoError(err) - suite.Equal(updateParamsMsg.Params, communityParamsRes.Params) -} +// suite.Equal(updateParamsMsg.Params, communityParamsRes.Params) +// } func (suite *IntegrationTestSuite) decodeTxMsgResponse(txRes *sdk.TxResponse, ptr codec.ProtoMarshaler) { // convert txRes.Data hex string to bytes @@ -189,10 +180,10 @@ func (suite *IntegrationTestSuite) decodeTxMsgResponse(txRes *sdk.TxResponse, pt // Unmarshal data to TxMsgData var txMsgData sdk.TxMsgData - suite.Kava.EncodingConfig.Marshaler.MustUnmarshal(txResBytes, &txMsgData) + suite.ZgChain.EncodingConfig.Marshaler.MustUnmarshal(txResBytes, &txMsgData) suite.T().Logf("txData.MsgResponses: %v", txMsgData.MsgResponses) // Parse MsgResponse - suite.Kava.EncodingConfig.Marshaler.MustUnmarshal(txMsgData.MsgResponses[0].Value, ptr) + suite.ZgChain.EncodingConfig.Marshaler.MustUnmarshal(txMsgData.MsgResponses[0].Value, ptr) suite.Require().NoError(err) } diff --git a/tests/e2e/e2e_convert_cosmos_coins_test.go b/tests/e2e/e2e_convert_cosmos_coins_test.go index aca92140..4f81910f 100644 --- a/tests/e2e/e2e_convert_cosmos_coins_test.go +++ b/tests/e2e/e2e_convert_cosmos_coins_test.go @@ -12,9 +12,9 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/kava-labs/kava/tests/e2e/testutil" - "github.com/kava-labs/kava/tests/util" - evmutiltypes "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/tests/e2e/testutil" + "github.com/0glabs/0g-chain/tests/util" + evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types" ) const initialCosmosCoinConversionDenomFunds = int64(1e4) @@ -24,24 +24,24 @@ func setupConvertToCoinTest( ) (denom string, initialFunds sdk.Coins, user *testutil.SigningAccount) { // we expect a denom to be registered to the allowed denoms param // and for the funded account to have a balance for that denom - params, err := suite.Kava.Grpc.Query.Evmutil.Params( + params, err := suite.ZgChain.Grpc.Query.Evmutil.Params( context.Background(), &evmutiltypes.QueryParamsRequest{}, ) suite.NoError(err) suite.GreaterOrEqual( len(params.Params.AllowedCosmosDenoms), 1, - "kava chain expected to have at least one AllowedCosmosDenom for ERC20 conversion", + "0g-chain expected to have at least one AllowedCosmosDenom for ERC20 conversion", ) tokenInfo := params.Params.AllowedCosmosDenoms[0] denom = tokenInfo.CosmosDenom initialFunds = sdk.NewCoins( - sdk.NewInt64Coin(suite.Kava.StakingDenom, 1e5), // gas money + sdk.NewInt64Coin(suite.ZgChain.StakingDenom, 1e5), // gas money sdk.NewInt64Coin(denom, initialCosmosCoinConversionDenomFunds), // conversion-enabled cosmos coin ) - user = suite.Kava.NewFundedAccount(accountName, initialFunds) + user = suite.ZgChain.NewFundedAccount(accountName, initialFunds) return denom, initialFunds, user } @@ -63,20 +63,20 @@ func (suite *IntegrationTestSuite) setupAccountWithCosmosCoinERC20Balance( user.EvmAddress.Hex(), convertAmount, ) - tx := util.KavaMsgRequest{ + tx := util.ZgChainMsgRequest{ Msgs: []sdk.Msg{&msg}, GasLimit: 4e5, - FeeAmount: sdk.NewCoins(ukava(400)), + FeeAmount: sdk.NewCoins(a0gi(big.NewInt(400))), Data: "converting sdk coin to erc20", } - res := user.SignAndBroadcastKavaTx(tx) + res := user.SignAndBroadcastZgChainTx(tx) suite.NoError(res.Err) // adjust sdk balance sdkBalance = sdkBalance.Sub(convertAmount) // query for the deployed contract - deployedContracts, err := suite.Kava.Grpc.Query.Evmutil.DeployedCosmosCoinContracts( + deployedContracts, err := suite.ZgChain.Grpc.Query.Evmutil.DeployedCosmosCoinContracts( context.Background(), &evmutiltypes.QueryDeployedCosmosCoinContractsRequest{CosmosDenoms: []string{denom}}, ) @@ -92,7 +92,7 @@ func (suite *IntegrationTestSuite) TestConvertCosmosCoinsToFromERC20() { denom, initialFunds, user := setupConvertToCoinTest(suite, "cosmo-coin-converter") convertAmount := int64(5e3) - initialModuleBalance := suite.Kava.GetModuleBalances(evmutiltypes.ModuleName).AmountOf(denom) + initialModuleBalance := suite.ZgChain.GetModuleBalances(evmutiltypes.ModuleName).AmountOf(denom) /////////////////////////////// // CONVERT COSMOS COIN -> ERC20 @@ -102,17 +102,17 @@ func (suite *IntegrationTestSuite) TestConvertCosmosCoinsToFromERC20() { user.EvmAddress.Hex(), sdk.NewInt64Coin(denom, convertAmount), ) - tx := util.KavaMsgRequest{ + tx := util.ZgChainMsgRequest{ Msgs: []sdk.Msg{&convertToErc20Msg}, GasLimit: 2e6, - FeeAmount: sdk.NewCoins(ukava(2000)), + FeeAmount: sdk.NewCoins(a0gi(big.NewInt(2000))), Data: "converting sdk coin to erc20", } - res := user.SignAndBroadcastKavaTx(tx) + res := user.SignAndBroadcastZgChainTx(tx) suite.NoError(res.Err) // query for the deployed contract - deployedContracts, err := suite.Kava.Grpc.Query.Evmutil.DeployedCosmosCoinContracts( + deployedContracts, err := suite.ZgChain.Grpc.Query.Evmutil.DeployedCosmosCoinContracts( context.Background(), &evmutiltypes.QueryDeployedCosmosCoinContractsRequest{CosmosDenoms: []string{denom}}, ) @@ -122,17 +122,17 @@ func (suite *IntegrationTestSuite) TestConvertCosmosCoinsToFromERC20() { contractAddress := deployedContracts.DeployedCosmosCoinContracts[0].Address // check erc20 balance - erc20Balance := suite.Kava.GetErc20Balance(contractAddress.Address, user.EvmAddress) + erc20Balance := suite.ZgChain.GetErc20Balance(contractAddress.Address, user.EvmAddress) suite.BigIntsEqual(big.NewInt(convertAmount), erc20Balance, "unexpected erc20 balance post-convert") // check cosmos coin is deducted from account expectedFunds := initialFunds.AmountOf(denom).SubRaw(convertAmount) - balance := suite.Kava.QuerySdkForBalances(user.SdkAddress).AmountOf(denom) + balance := suite.ZgChain.QuerySdkForBalances(user.SdkAddress).AmountOf(denom) suite.Equal(expectedFunds, balance) // check that module account has sdk coins expectedModuleBalance := initialModuleBalance.AddRaw(convertAmount) - actualModuleBalance := suite.Kava.GetModuleBalances(evmutiltypes.ModuleName).AmountOf(denom) + actualModuleBalance := suite.ZgChain.GetModuleBalances(evmutiltypes.ModuleName).AmountOf(denom) suite.Equal(expectedModuleBalance, actualModuleBalance) /////////////////////////////// @@ -144,26 +144,26 @@ func (suite *IntegrationTestSuite) TestConvertCosmosCoinsToFromERC20() { sdk.NewInt64Coin(denom, convertAmount), ) - tx = util.KavaMsgRequest{ + tx = util.ZgChainMsgRequest{ Msgs: []sdk.Msg{&convertFromErc20Msg}, GasLimit: 2e5, - FeeAmount: sdk.NewCoins(ukava(200)), + FeeAmount: sdk.NewCoins(a0gi(big.NewInt(200))), Data: "converting erc20 to cosmos coin", } - res = user.SignAndBroadcastKavaTx(tx) + res = user.SignAndBroadcastZgChainTx(tx) suite.NoError(res.Err) // check erc20 balance - erc20Balance = suite.Kava.GetErc20Balance(contractAddress.Address, user.EvmAddress) + erc20Balance = suite.ZgChain.GetErc20Balance(contractAddress.Address, user.EvmAddress) suite.BigIntsEqual(big.NewInt(0), erc20Balance, "expected all erc20 to be converted back") // check cosmos coin is added back to account expectedFunds = initialFunds.AmountOf(denom) - balance = suite.Kava.QuerySdkForBalances(user.SdkAddress).AmountOf(denom) + balance = suite.ZgChain.QuerySdkForBalances(user.SdkAddress).AmountOf(denom) suite.Equal(expectedFunds, balance) // check that module account has sdk coins deducted - actualModuleBalance = suite.Kava.GetModuleBalances(evmutiltypes.ModuleName).AmountOf(denom) + actualModuleBalance = suite.ZgChain.GetModuleBalances(evmutiltypes.ModuleName).AmountOf(denom) suite.Equal(initialModuleBalance, actualModuleBalance) } @@ -172,7 +172,7 @@ func (suite *IntegrationTestSuite) TestEIP712ConvertCosmosCoinsToFromERC20() { denom, initialFunds, user := setupConvertToCoinTest(suite, "cosmo-coin-converter-eip712") convertAmount := int64(5e3) - initialModuleBalance := suite.Kava.GetModuleBalances(evmutiltypes.ModuleName).AmountOf(denom) + initialModuleBalance := suite.ZgChain.GetModuleBalances(evmutiltypes.ModuleName).AmountOf(denom) /////////////////////////////// // CONVERT COSMOS COIN -> ERC20 @@ -184,28 +184,28 @@ func (suite *IntegrationTestSuite) TestEIP712ConvertCosmosCoinsToFromERC20() { ) tx := suite.NewEip712TxBuilder( user, - suite.Kava, + suite.ZgChain, 2e6, - sdk.NewCoins(ukava(1e4)), + sdk.NewCoins(a0gi(big.NewInt(1e4))), []sdk.Msg{&convertToErc20Msg}, "this is a memo", ).GetTx() - txBytes, err := suite.Kava.EncodingConfig.TxConfig.TxEncoder()(tx) + txBytes, err := suite.ZgChain.EncodingConfig.TxConfig.TxEncoder()(tx) suite.NoError(err) // submit the eip712 message to the chain. - res, err := suite.Kava.Grpc.Query.Tx.BroadcastTx(context.Background(), &txtypes.BroadcastTxRequest{ + res, err := suite.ZgChain.Grpc.Query.Tx.BroadcastTx(context.Background(), &txtypes.BroadcastTxRequest{ TxBytes: txBytes, Mode: txtypes.BroadcastMode_BROADCAST_MODE_SYNC, }) suite.NoError(err) suite.Equal(sdkerrors.SuccessABCICode, res.TxResponse.Code) - _, err = util.WaitForSdkTxCommit(suite.Kava.Grpc.Query.Tx, res.TxResponse.TxHash, 12*time.Second) + _, err = util.WaitForSdkTxCommit(suite.ZgChain.Grpc.Query.Tx, res.TxResponse.TxHash, 12*time.Second) suite.Require().NoError(err) // query for the deployed contract - deployedContracts, err := suite.Kava.Grpc.Query.Evmutil.DeployedCosmosCoinContracts( + deployedContracts, err := suite.ZgChain.Grpc.Query.Evmutil.DeployedCosmosCoinContracts( context.Background(), &evmutiltypes.QueryDeployedCosmosCoinContractsRequest{CosmosDenoms: []string{denom}}, ) @@ -215,17 +215,17 @@ func (suite *IntegrationTestSuite) TestEIP712ConvertCosmosCoinsToFromERC20() { contractAddress := deployedContracts.DeployedCosmosCoinContracts[0].Address // check erc20 balance - erc20Balance := suite.Kava.GetErc20Balance(contractAddress.Address, user.EvmAddress) + erc20Balance := suite.ZgChain.GetErc20Balance(contractAddress.Address, user.EvmAddress) suite.BigIntsEqual(big.NewInt(convertAmount), erc20Balance, "unexpected erc20 balance post-convert") // check cosmos coin is deducted from account expectedFunds := initialFunds.AmountOf(denom).SubRaw(convertAmount) - balance := suite.Kava.QuerySdkForBalances(user.SdkAddress).AmountOf(denom) + balance := suite.ZgChain.QuerySdkForBalances(user.SdkAddress).AmountOf(denom) suite.Equal(expectedFunds, balance) // check that module account has sdk coins expectedModuleBalance := initialModuleBalance.AddRaw(convertAmount) - actualModuleBalance := suite.Kava.GetModuleBalances(evmutiltypes.ModuleName).AmountOf(denom) + actualModuleBalance := suite.ZgChain.GetModuleBalances(evmutiltypes.ModuleName).AmountOf(denom) suite.Equal(expectedModuleBalance, actualModuleBalance) /////////////////////////////// @@ -238,37 +238,37 @@ func (suite *IntegrationTestSuite) TestEIP712ConvertCosmosCoinsToFromERC20() { ) tx = suite.NewEip712TxBuilder( user, - suite.Kava, + suite.ZgChain, 2e5, - sdk.NewCoins(ukava(200)), + sdk.NewCoins(a0gi(big.NewInt(200))), []sdk.Msg{&convertFromErc20Msg}, "", ).GetTx() - txBytes, err = suite.Kava.EncodingConfig.TxConfig.TxEncoder()(tx) + txBytes, err = suite.ZgChain.EncodingConfig.TxConfig.TxEncoder()(tx) suite.NoError(err) // submit the eip712 message to the chain - res, err = suite.Kava.Grpc.Query.Tx.BroadcastTx(context.Background(), &txtypes.BroadcastTxRequest{ + res, err = suite.ZgChain.Grpc.Query.Tx.BroadcastTx(context.Background(), &txtypes.BroadcastTxRequest{ TxBytes: txBytes, Mode: txtypes.BroadcastMode_BROADCAST_MODE_SYNC, }) suite.NoError(err) suite.Equal(sdkerrors.SuccessABCICode, res.TxResponse.Code) - _, err = util.WaitForSdkTxCommit(suite.Kava.Grpc.Query.Tx, res.TxResponse.TxHash, 6*time.Second) + _, err = util.WaitForSdkTxCommit(suite.ZgChain.Grpc.Query.Tx, res.TxResponse.TxHash, 6*time.Second) suite.NoError(err) // check erc20 balance - erc20Balance = suite.Kava.GetErc20Balance(contractAddress.Address, user.EvmAddress) + erc20Balance = suite.ZgChain.GetErc20Balance(contractAddress.Address, user.EvmAddress) suite.BigIntsEqual(big.NewInt(0), erc20Balance, "expected all erc20 to be converted back") // check cosmos coin is added back to account expectedFunds = initialFunds.AmountOf(denom) - balance = suite.Kava.QuerySdkForBalances(user.SdkAddress).AmountOf(denom) + balance = suite.ZgChain.QuerySdkForBalances(user.SdkAddress).AmountOf(denom) suite.Equal(expectedFunds, balance) // check that module account has sdk coins deducted - actualModuleBalance = suite.Kava.GetModuleBalances(evmutiltypes.ModuleName).AmountOf(denom) + actualModuleBalance = suite.ZgChain.GetModuleBalances(evmutiltypes.ModuleName).AmountOf(denom) suite.Equal(initialModuleBalance, actualModuleBalance) } @@ -334,8 +334,8 @@ func (suite *IntegrationTestSuite) TestConvertCosmosCoins_ERC20Magic() { "cosmo-coin-converter-complex-alice", initialAliceAmount, ) - gasMoney := sdk.NewCoins(ukava(1e5)) - bob := suite.Kava.NewFundedAccount("cosmo-coin-converter-complex-bob", gasMoney) + gasMoney := sdk.NewCoins(a0gi(big.NewInt(1e5))) + bob := suite.ZgChain.NewFundedAccount("cosmo-coin-converter-complex-bob", gasMoney) amount := big.NewInt(1e3) // test assumes this is half of alice's balance. // bob can't move alice's funds @@ -400,10 +400,10 @@ func (suite *IntegrationTestSuite) TestConvertCosmosCoins_ERC20Magic() { suite.Require().NoError(res.Err) // alice should have amount deducted - erc20Balance := suite.Kava.GetErc20Balance(contractAddress.Address, alice.EvmAddress) + erc20Balance := suite.ZgChain.GetErc20Balance(contractAddress.Address, alice.EvmAddress) suite.BigIntsEqual(big.NewInt(initialAliceAmount-amount.Int64()), erc20Balance, "alice has unexpected erc20 balance") // bob should have amount added - erc20Balance = suite.Kava.GetErc20Balance(contractAddress.Address, bob.EvmAddress) + erc20Balance = suite.ZgChain.GetErc20Balance(contractAddress.Address, bob.EvmAddress) suite.BigIntsEqual(amount, erc20Balance, "bob has unexpected erc20 balance") // convert bob's new funds back to an sdk.Coin @@ -412,24 +412,24 @@ func (suite *IntegrationTestSuite) TestConvertCosmosCoins_ERC20Magic() { bob.SdkAddress.String(), sdk.NewInt64Coin(denom, amount.Int64()), ) - convertTx := util.KavaMsgRequest{ + convertTx := util.ZgChainMsgRequest{ Msgs: []sdk.Msg{&convertMsg}, GasLimit: 2e5, - FeeAmount: sdk.NewCoins(ukava(200)), + FeeAmount: sdk.NewCoins(a0gi(big.NewInt(200))), Data: "bob converts his new erc20 to an sdk.Coin", } - convertRes := bob.SignAndBroadcastKavaTx(convertTx) + convertRes := bob.SignAndBroadcastZgChainTx(convertTx) suite.NoError(convertRes.Err) // bob should have no more erc20 balance - erc20Balance = suite.Kava.GetErc20Balance(contractAddress.Address, bob.EvmAddress) + erc20Balance = suite.ZgChain.GetErc20Balance(contractAddress.Address, bob.EvmAddress) suite.BigIntsEqual(big.NewInt(0), erc20Balance, "expected no erc20 balance for bob") // bob should have sdk balance - balance := suite.Kava.QuerySdkForBalances(bob.SdkAddress).AmountOf(denom) + balance := suite.ZgChain.QuerySdkForBalances(bob.SdkAddress).AmountOf(denom) suite.Equal(sdk.NewIntFromBigInt(amount), balance) // alice should have the remaining balance - erc20Balance = suite.Kava.GetErc20Balance(contractAddress.Address, alice.EvmAddress) + erc20Balance = suite.ZgChain.GetErc20Balance(contractAddress.Address, alice.EvmAddress) suite.BigIntsEqual(amount, erc20Balance, "expected alice to have half initial funds remaining") // convert alice's remaining balance back to sdk coins @@ -438,6 +438,6 @@ func (suite *IntegrationTestSuite) TestConvertCosmosCoins_ERC20Magic() { alice.SdkAddress.String(), sdk.NewInt64Coin(denom, amount.Int64()), ) - convertRes = alice.SignAndBroadcastKavaTx(convertTx) + convertRes = alice.SignAndBroadcastZgChainTx(convertTx) suite.NoError(convertRes.Err) } diff --git a/tests/e2e/e2e_evm_contracts_test.go b/tests/e2e/e2e_evm_contracts_test.go index 404891a1..43d3f3db 100644 --- a/tests/e2e/e2e_evm_contracts_test.go +++ b/tests/e2e/e2e_evm_contracts_test.go @@ -10,22 +10,24 @@ import ( txtypes "github.com/cosmos/cosmos-sdk/types/tx" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/kava-labs/kava/app" - cdptypes "github.com/kava-labs/kava/x/cdp/types" - evmutiltypes "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/chaincfg" - "github.com/kava-labs/kava/tests/e2e/contracts/greeter" - "github.com/kava-labs/kava/tests/util" + // cdptypes "github.com/0glabs/0g-chain/x/cdp/types" + // evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types" + + "github.com/0glabs/0g-chain/tests/e2e/contracts/greeter" + "github.com/0glabs/0g-chain/tests/util" ) func (suite *IntegrationTestSuite) TestEthCallToGreeterContract() { // this test manipulates state of the Greeter contract which means other tests shouldn't use it. // setup funded account to interact with contract - user := suite.Kava.NewFundedAccount("greeter-contract-user", sdk.NewCoins(ukava(1e6))) + user := suite.ZgChain.NewFundedAccount("greeter-contract-user", sdk.NewCoins(a0gi(big.NewInt(1e6)))) - greeterAddr := suite.Kava.ContractAddrs["greeter"] - contract, err := greeter.NewGreeter(greeterAddr, suite.Kava.EvmClient) + greeterAddr := suite.ZgChain.ContractAddrs["greeter"] + contract, err := greeter.NewGreeter(greeterAddr, suite.ZgChain.EvmClient) suite.NoError(err) beforeGreeting, err := contract.Greet(nil) @@ -35,7 +37,7 @@ func (suite *IntegrationTestSuite) TestEthCallToGreeterContract() { tx, err := contract.SetGreeting(user.EvmAuth, updatedGreeting) suite.NoError(err) - _, err = util.WaitForEvmTxReceipt(suite.Kava.EvmClient, tx.Hash(), 10*time.Second) + _, err = util.WaitForEvmTxReceipt(suite.ZgChain.EvmClient, tx.Hash(), 10*time.Second) suite.NoError(err) afterGreeting, err := contract.Greet(nil) @@ -50,14 +52,14 @@ func (suite *IntegrationTestSuite) TestEthCallToErc20() { amount := big.NewInt(1) // make unauthenticated eth_call query to check balance - beforeBalance := suite.Kava.GetErc20Balance(suite.DeployedErc20.Address, randoReceiver) + beforeBalance := suite.ZgChain.GetErc20Balance(suite.DeployedErc20.Address, randoReceiver) // make authenticate eth_call to transfer tokens - res := suite.FundKavaErc20Balance(randoReceiver, amount) + res := suite.FundZgChainErc20Balance(randoReceiver, amount) suite.NoError(res.Err) // make another unauthenticated eth_call query to check new balance - afterBalance := suite.Kava.GetErc20Balance(suite.DeployedErc20.Address, randoReceiver) + afterBalance := suite.ZgChain.GetErc20Balance(suite.DeployedErc20.Address, randoReceiver) suite.BigIntsEqual(big.NewInt(0), beforeBalance, "expected before balance to be zero") suite.BigIntsEqual(amount, afterBalance, "unexpected post-transfer balance") @@ -65,42 +67,42 @@ func (suite *IntegrationTestSuite) TestEthCallToErc20() { func (suite *IntegrationTestSuite) TestEip712BasicMessageAuthorization() { // create new funded account - sender := suite.Kava.NewFundedAccount("eip712-msgSend", sdk.NewCoins(ukava(2e4))) + sender := suite.ZgChain.NewFundedAccount("eip712-msgSend", sdk.NewCoins(a0gi(big.NewInt(2e4)))) receiver := app.RandomAddress() - // setup message for sending some kava to random receiver + // setup message for sending some a0gi to random receiver msgs := []sdk.Msg{ - banktypes.NewMsgSend(sender.SdkAddress, receiver, sdk.NewCoins(ukava(1e3))), + banktypes.NewMsgSend(sender.SdkAddress, receiver, sdk.NewCoins(a0gi(big.NewInt(1e3)))), } // create tx tx := suite.NewEip712TxBuilder( sender, - suite.Kava, + suite.ZgChain, 1e6, - sdk.NewCoins(ukava(1e4)), + sdk.NewCoins(a0gi(big.NewInt(1e4))), msgs, "this is a memo", ).GetTx() - txBytes, err := suite.Kava.EncodingConfig.TxConfig.TxEncoder()(tx) + txBytes, err := suite.ZgChain.EncodingConfig.TxConfig.TxEncoder()(tx) suite.NoError(err) // broadcast tx - res, err := suite.Kava.Grpc.Query.Tx.BroadcastTx(context.Background(), &txtypes.BroadcastTxRequest{ + res, err := suite.ZgChain.Grpc.Query.Tx.BroadcastTx(context.Background(), &txtypes.BroadcastTxRequest{ TxBytes: txBytes, Mode: txtypes.BroadcastMode_BROADCAST_MODE_SYNC, }) suite.NoError(err) suite.Equal(sdkerrors.SuccessABCICode, res.TxResponse.Code) - _, err = util.WaitForSdkTxCommit(suite.Kava.Grpc.Query.Tx, res.TxResponse.TxHash, 6*time.Second) + _, err = util.WaitForSdkTxCommit(suite.ZgChain.Grpc.Query.Tx, res.TxResponse.TxHash, 6*time.Second) suite.NoError(err) - // check that the message was processed & the kava is transferred. - balRes, err := suite.Kava.Grpc.Query.Bank.Balance(context.Background(), &banktypes.QueryBalanceRequest{ + // check that the message was processed & the a0gi is transferred. + balRes, err := suite.ZgChain.Grpc.Query.Bank.Balance(context.Background(), &banktypes.QueryBalanceRequest{ Address: receiver.String(), - Denom: "ukava", + Denom: chaincfg.DisplayDenom, }) suite.NoError(err) suite.Equal(sdk.NewInt(1e3), balRes.Balance.Amount) @@ -108,95 +110,95 @@ func (suite *IntegrationTestSuite) TestEip712BasicMessageAuthorization() { // Note that this test works because the deployed erc20 is configured in evmutil & cdp params. // This test matches the webapp's "USDT Earn" workflow -func (suite *IntegrationTestSuite) TestEip712ConvertToCoinAndDepositToLend() { - // cdp requires minimum of $11 collateral - amount := sdk.NewInt(11e6) // 11 USDT - principal := sdk.NewCoin("usdx", sdk.NewInt(10e6)) - sdkDenom := suite.DeployedErc20.CosmosDenom +// func (suite *IntegrationTestSuite) TestEip712ConvertToCoinAndDepositToLend() { +// // cdp requires minimum of $11 collateral +// amount := sdk.NewInt(11e6) // 11 USDT +// principal := sdk.NewCoin("usdx", sdk.NewInt(10e6)) +// sdkDenom := suite.DeployedErc20.CosmosDenom - // create new funded account - depositor := suite.Kava.NewFundedAccount("eip712-lend-depositor", sdk.NewCoins(ukava(1e5))) - // give them erc20 balance to deposit - fundRes := suite.FundKavaErc20Balance(depositor.EvmAddress, amount.BigInt()) - suite.NoError(fundRes.Err) +// // create new funded account +// depositor := suite.ZgChain.NewFundedAccount("eip712-lend-depositor", sdk.NewCoins(a0gi(big.NewInt(1e5))) +// // give them erc20 balance to deposit +// fundRes := suite.FundZgChainErc20Balance(depositor.EvmAddress, amount.BigInt()) +// suite.NoError(fundRes.Err) - // setup messages for convert to coin & deposit into earn - convertMsg := evmutiltypes.NewMsgConvertERC20ToCoin( - evmutiltypes.NewInternalEVMAddress(depositor.EvmAddress), - depositor.SdkAddress, - evmutiltypes.NewInternalEVMAddress(suite.DeployedErc20.Address), - amount, - ) - depositMsg := cdptypes.NewMsgCreateCDP( - depositor.SdkAddress, - sdk.NewCoin(sdkDenom, amount), - principal, - suite.DeployedErc20.CdpCollateralType, - ) - msgs := []sdk.Msg{ - // convert to coin - &convertMsg, - // deposit into cdp (Mint), take out USDX - &depositMsg, - } +// // setup messages for convert to coin & deposit into earn +// convertMsg := evmutiltypes.NewMsgConvertERC20ToCoin( +// evmutiltypes.NewInternalEVMAddress(depositor.EvmAddress), +// depositor.SdkAddress, +// evmutiltypes.NewInternalEVMAddress(suite.DeployedErc20.Address), +// amount, +// ) +// // depositMsg := cdptypes.NewMsgCreateCDP( +// // depositor.SdkAddress, +// // sdk.NewCoin(sdkDenom, amount), +// // principal, +// // suite.DeployedErc20.CdpCollateralType, +// // ) +// msgs := []sdk.Msg{ +// // convert to coin +// &convertMsg, +// // deposit into cdp (Mint), take out USDX +// // &depositMsg, +// } - // create tx - tx := suite.NewEip712TxBuilder( - depositor, - suite.Kava, - 1e6, - sdk.NewCoins(ukava(1e4)), - msgs, - "doing the USDT Earn workflow! erc20 -> sdk.Coin -> USDX hard deposit", - ).GetTx() +// // create tx +// tx := suite.NewEip712TxBuilder( +// depositor, +// suite.ZgChain, +// 1e6, +// sdk.NewCoins(a0gi(big.NewInt(1e4)), +// msgs, +// "doing the USDT Earn workflow! erc20 -> sdk.Coin -> USDX hard deposit", +// ).GetTx() - txBytes, err := suite.Kava.EncodingConfig.TxConfig.TxEncoder()(tx) - suite.NoError(err) +// txBytes, err := suite.ZgChain.EncodingConfig.TxConfig.TxEncoder()(tx) +// suite.NoError(err) - // broadcast tx - res, err := suite.Kava.Grpc.Query.Tx.BroadcastTx(context.Background(), &txtypes.BroadcastTxRequest{ - TxBytes: txBytes, - Mode: txtypes.BroadcastMode_BROADCAST_MODE_SYNC, - }) - suite.NoError(err) - suite.Equal(sdkerrors.SuccessABCICode, res.TxResponse.Code) +// // broadcast tx +// res, err := suite.ZgChain.Grpc.Query.Tx.BroadcastTx(context.Background(), &txtypes.BroadcastTxRequest{ +// TxBytes: txBytes, +// Mode: txtypes.BroadcastMode_BROADCAST_MODE_SYNC, +// }) +// suite.NoError(err) +// suite.Equal(sdkerrors.SuccessABCICode, res.TxResponse.Code) - _, err = util.WaitForSdkTxCommit(suite.Kava.Grpc.Query.Tx, res.TxResponse.TxHash, 6*time.Second) - suite.Require().NoError(err) +// _, err = util.WaitForSdkTxCommit(suite.ZgChain.Grpc.Query.Tx, res.TxResponse.TxHash, 6*time.Second) +// suite.Require().NoError(err) - // check that depositor no longer has erc20 balance - balance := suite.Kava.GetErc20Balance(suite.DeployedErc20.Address, depositor.EvmAddress) - suite.BigIntsEqual(big.NewInt(0), balance, "expected no erc20 balance") +// // check that depositor no longer has erc20 balance +// balance := suite.ZgChain.GetErc20Balance(suite.DeployedErc20.Address, depositor.EvmAddress) +// suite.BigIntsEqual(big.NewInt(0), balance, "expected no erc20 balance") - // check that account has cdp - cdpRes, err := suite.Kava.Grpc.Query.Cdp.Cdp(context.Background(), &cdptypes.QueryCdpRequest{ - CollateralType: suite.DeployedErc20.CdpCollateralType, - Owner: depositor.SdkAddress.String(), - }) - suite.NoError(err) - suite.True(cdpRes.Cdp.Collateral.Amount.Equal(amount)) - suite.True(cdpRes.Cdp.Principal.Equal(principal)) +// // check that account has cdp +// // cdpRes, err := suite.ZgChain.Grpc.Query.Cdp.Cdp(context.Background(), &cdptypes.QueryCdpRequest{ +// // CollateralType: suite.DeployedErc20.CdpCollateralType, +// // Owner: depositor.SdkAddress.String(), +// // }) +// // suite.NoError(err) +// // suite.True(cdpRes.Cdp.Collateral.Amount.Equal(amount)) +// // suite.True(cdpRes.Cdp.Principal.Equal(principal)) - // withdraw deposit & convert back to erc20 (this allows refund to recover erc20s used in test) - withdraw := cdptypes.NewMsgRepayDebt( - depositor.SdkAddress, - suite.DeployedErc20.CdpCollateralType, - principal, - ) - convertBack := evmutiltypes.NewMsgConvertCoinToERC20( - depositor.SdkAddress.String(), - depositor.EvmAddress.Hex(), - sdk.NewCoin(sdkDenom, amount), - ) - withdrawAndConvertBack := util.KavaMsgRequest{ - Msgs: []sdk.Msg{&withdraw, &convertBack}, - GasLimit: 1e6, - FeeAmount: sdk.NewCoins(ukava(1000)), - Data: "withdrawing from mint & converting back to erc20", - } - lastRes := depositor.SignAndBroadcastKavaTx(withdrawAndConvertBack) - suite.NoError(lastRes.Err) +// // withdraw deposit & convert back to erc20 (this allows refund to recover erc20s used in test) +// // withdraw := cdptypes.NewMsgRepayDebt( +// // depositor.SdkAddress, +// // suite.DeployedErc20.CdpCollateralType, +// // principal, +// // ) +// convertBack := evmutiltypes.NewMsgConvertCoinToERC20( +// depositor.SdkAddress.String(), +// depositor.EvmAddress.Hex(), +// sdk.NewCoin(sdkDenom, amount), +// ) +// withdrawAndConvertBack := util.ZgChainMsgRequest{ +// Msgs: []sdk.Msg{&withdraw, &convertBack}, +// GasLimit: 1e6, +// FeeAmount: sdk.NewCoins(a0gi(big.NewInt(1000)), +// Data: "withdrawing from mint & converting back to erc20", +// } +// lastRes := depositor.SignAndBroadcastZgChainTx(withdrawAndConvertBack) +// suite.NoError(lastRes.Err) - balance = suite.Kava.GetErc20Balance(suite.DeployedErc20.Address, depositor.EvmAddress) - suite.BigIntsEqual(amount.BigInt(), balance, "expected returned erc20 balance") -} +// balance = suite.ZgChain.GetErc20Balance(suite.DeployedErc20.Address, depositor.EvmAddress) +// suite.BigIntsEqual(amount.BigInt(), balance, "expected returned erc20 balance") +// } diff --git a/tests/e2e/e2e_grpc_client_query_test.go b/tests/e2e/e2e_grpc_client_query_test.go index b066c9fa..7f8f9556 100644 --- a/tests/e2e/e2e_grpc_client_query_test.go +++ b/tests/e2e/e2e_grpc_client_query_test.go @@ -2,22 +2,23 @@ package e2e_test import ( "context" + "math/big" sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - evmutiltypes "github.com/kava-labs/kava/x/evmutil/types" + evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types" ) func (suite *IntegrationTestSuite) TestGrpcClientQueryCosmosModule_Balance() { // ARRANGE - // setup kava account - funds := ukava(1e5) // .1 KAVA - kavaAcc := suite.Kava.NewFundedAccount("balance-test", sdk.NewCoins(funds)) + // setup 0g account + funds := a0gi(big.NewInt(1e5)) // .1 A0GI + zgChainAcc := suite.ZgChain.NewFundedAccount("balance-test", sdk.NewCoins(funds)) // ACT - rsp, err := suite.Kava.Grpc.Query.Bank.Balance(context.Background(), &banktypes.QueryBalanceRequest{ - Address: kavaAcc.SdkAddress.String(), + rsp, err := suite.ZgChain.Grpc.Query.Bank.Balance(context.Background(), &banktypes.QueryBalanceRequest{ + Address: zgChainAcc.SdkAddress.String(), Denom: funds.Denom, }) @@ -26,9 +27,9 @@ func (suite *IntegrationTestSuite) TestGrpcClientQueryCosmosModule_Balance() { suite.Require().Equal(funds.Amount, rsp.Balance.Amount) } -func (suite *IntegrationTestSuite) TestGrpcClientQueryKavaModule_EvmParams() { +func (suite *IntegrationTestSuite) TestGrpcClientQueryZgChainModule_EvmParams() { // ACT - rsp, err := suite.Kava.Grpc.Query.Evmutil.Params( + rsp, err := suite.ZgChain.Grpc.Query.Evmutil.Params( context.Background(), &evmutiltypes.QueryParamsRequest{}, ) diff --git a/tests/e2e/e2e_grpc_client_util_test.go b/tests/e2e/e2e_grpc_client_util_test.go index c2b37bda..9050593b 100644 --- a/tests/e2e/e2e_grpc_client_util_test.go +++ b/tests/e2e/e2e_grpc_client_util_test.go @@ -1,20 +1,22 @@ package e2e_test import ( + "math/big" + sdk "github.com/cosmos/cosmos-sdk/types" ) func (suite *IntegrationTestSuite) TestGrpcClientUtil_Account() { // ARRANGE - // setup kava account - kavaAcc := suite.Kava.NewFundedAccount("account-test", sdk.NewCoins(ukava(1e5))) + // setup 0g account + zgChainAcc := suite.ZgChain.NewFundedAccount("account-test", sdk.NewCoins(a0gi(big.NewInt(1e5)))) // ACT - rsp, err := suite.Kava.Grpc.BaseAccount(kavaAcc.SdkAddress.String()) + rsp, err := suite.ZgChain.Grpc.BaseAccount(zgChainAcc.SdkAddress.String()) // ASSERT suite.Require().NoError(err) - suite.Equal(kavaAcc.SdkAddress.String(), rsp.Address) + suite.Equal(zgChainAcc.SdkAddress.String(), rsp.Address) suite.Greater(rsp.AccountNumber, uint64(1)) suite.Equal(uint64(0), rsp.Sequence) } diff --git a/tests/e2e/e2e_min_fees_test.go b/tests/e2e/e2e_min_fees_test.go index 0ff51ce8..032bfdec 100644 --- a/tests/e2e/e2e_min_fees_test.go +++ b/tests/e2e/e2e_min_fees_test.go @@ -12,38 +12,39 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/tests/util" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/chaincfg" + "github.com/0glabs/0g-chain/tests/util" ) func (suite *IntegrationTestSuite) TestEthGasPriceReturnsMinFee() { suite.SkipIfKvtoolDisabled() // read expected min fee from app.toml - minGasPrices, err := getMinFeeFromAppToml(util.KavaHomePath()) - suite.NoError(err) + minGasPrices, err := getMinFeeFromAppToml(util.ZgChainHomePath()) + suite.NoError(err, "failed to read min fee from app.toml") - // evm uses akava, get akava min fee - evmMinGas := minGasPrices.AmountOf("akava").TruncateInt().BigInt() + // evm uses neuron, get neuron min fee + evmMinGas := minGasPrices.AmountOf(chaincfg.BaseDenom).TruncateInt().BigInt() - // returns eth_gasPrice, units in kava - gasPrice, err := suite.Kava.EvmClient.SuggestGasPrice(context.Background()) - suite.NoError(err) + // returns eth_gasPrice, units in a0gi + gasPrice, err := suite.ZgChain.EvmClient.SuggestGasPrice(context.Background()) + suite.NoError(err, "failed to get gas price") - suite.Equal(evmMinGas, gasPrice) + suite.Equal(evmMinGas, gasPrice, "gas price should be equal to min fee") } func (suite *IntegrationTestSuite) TestEvmRespectsMinFee() { suite.SkipIfKvtoolDisabled() // setup sender & receiver - sender := suite.Kava.NewFundedAccount("evm-min-fee-test-sender", sdk.NewCoins(ukava(1e3))) + sender := suite.ZgChain.NewFundedAccount("evm-min-fee-test-sender", sdk.NewCoins(a0gi(big.NewInt(1e3)))) randoReceiver := util.SdkToEvmAddress(app.RandomAddress()) // get min gas price for evm (from app.toml) - minFees, err := getMinFeeFromAppToml(util.KavaHomePath()) + minFees, err := getMinFeeFromAppToml(util.ZgChainHomePath()) suite.NoError(err) - minGasPrice := minFees.AmountOf("akava").TruncateInt() + minGasPrice := minFees.AmountOf(chaincfg.BaseDenom).TruncateInt() // attempt tx with less than min gas price (min fee - 1) tooLowGasPrice := minGasPrice.Sub(sdk.OneInt()).BigInt() @@ -58,12 +59,12 @@ func (suite *IntegrationTestSuite) TestEvmRespectsMinFee() { suite.ErrorContains(res.Err, "insufficient fee") } -func getMinFeeFromAppToml(kavaHome string) (sdk.DecCoins, error) { +func getMinFeeFromAppToml(zgChainHome string) (sdk.DecCoins, error) { // read the expected min gas price from app.toml parsed := struct { MinGasPrices string `toml:"minimum-gas-prices"` }{} - appToml, err := os.ReadFile(filepath.Join(kavaHome, "config", "app.toml")) + appToml, err := os.ReadFile(filepath.Join(zgChainHome, "config", "app.toml")) if err != nil { return nil, err } diff --git a/tests/e2e/e2e_test.go b/tests/e2e/e2e_test.go index 63e63c46..87ab1761 100644 --- a/tests/e2e/e2e_test.go +++ b/tests/e2e/e2e_test.go @@ -18,17 +18,18 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" emtypes "github.com/evmos/ethermint/types" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/tests/e2e/testutil" - "github.com/kava-labs/kava/tests/util" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/chaincfg" + "github.com/0glabs/0g-chain/tests/e2e/testutil" + "github.com/0glabs/0g-chain/tests/util" ) var ( - minEvmGasPrice = big.NewInt(1e10) // akava + minEvmGasPrice = big.NewInt(1e10) // neuron ) -func ukava(amt int64) sdk.Coin { - return sdk.NewCoin("ukava", sdkmath.NewInt(amt)) +func a0gi(amt *big.Int) sdk.Coin { + return sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewIntFromBigInt(amt)) } type IntegrationTestSuite struct { @@ -39,63 +40,63 @@ func TestIntegrationTestSuite(t *testing.T) { suite.Run(t, new(IntegrationTestSuite)) } -// example test that queries kava via SDK and EVM +// example test that queries 0gchain via SDK and EVM func (suite *IntegrationTestSuite) TestChainID() { - expectedEvmNetworkId, err := emtypes.ParseChainID(suite.Kava.ChainID) + expectedEvmNetworkId, err := emtypes.ParseChainID(suite.ZgChain.ChainID) suite.NoError(err) // EVM query - evmNetworkId, err := suite.Kava.EvmClient.NetworkID(context.Background()) + evmNetworkId, err := suite.ZgChain.EvmClient.NetworkID(context.Background()) suite.NoError(err) suite.Equal(expectedEvmNetworkId, evmNetworkId) // SDK query - nodeInfo, err := suite.Kava.Grpc.Query.Tm.GetNodeInfo(context.Background(), &tmservice.GetNodeInfoRequest{}) + nodeInfo, err := suite.ZgChain.Grpc.Query.Tm.GetNodeInfo(context.Background(), &tmservice.GetNodeInfoRequest{}) suite.NoError(err) - suite.Equal(suite.Kava.ChainID, nodeInfo.DefaultNodeInfo.Network) + suite.Equal(suite.ZgChain.ChainID, nodeInfo.DefaultNodeInfo.Network) } // example test that funds a new account & queries its balance func (suite *IntegrationTestSuite) TestFundedAccount() { - funds := ukava(1e3) - acc := suite.Kava.NewFundedAccount("example-acc", sdk.NewCoins(funds)) + funds := a0gi(big.NewInt(1e3)) + acc := suite.ZgChain.NewFundedAccount("example-acc", sdk.NewCoins(funds)) // check that the sdk & evm signers are for the same account suite.Equal(acc.SdkAddress.String(), util.EvmToSdkAddress(acc.EvmAddress).String()) suite.Equal(acc.EvmAddress.Hex(), util.SdkToEvmAddress(acc.SdkAddress).Hex()) // check balance via SDK query - res, err := suite.Kava.Grpc.Query.Bank.Balance(context.Background(), banktypes.NewQueryBalanceRequest( - acc.SdkAddress, "ukava", + res, err := suite.ZgChain.Grpc.Query.Bank.Balance(context.Background(), banktypes.NewQueryBalanceRequest( + acc.SdkAddress, chaincfg.DisplayDenom, )) suite.NoError(err) suite.Equal(funds, *res.Balance) // check balance via EVM query - akavaBal, err := suite.Kava.EvmClient.BalanceAt(context.Background(), acc.EvmAddress, nil) + neuronBal, err := suite.ZgChain.EvmClient.BalanceAt(context.Background(), acc.EvmAddress, nil) suite.NoError(err) - suite.Equal(funds.Amount.MulRaw(1e12).BigInt(), akavaBal) + suite.Equal(funds.Amount.MulRaw(1e12).BigInt(), neuronBal) } // example test that signs & broadcasts an EVM tx func (suite *IntegrationTestSuite) TestTransferOverEVM() { // fund an account that can perform the transfer - initialFunds := ukava(1e6) // 1 KAVA - acc := suite.Kava.NewFundedAccount("evm-test-transfer", sdk.NewCoins(initialFunds)) + initialFunds := a0gi(big.NewInt(1e6)) // 1 A0GI + acc := suite.ZgChain.NewFundedAccount("evm-test-transfer", sdk.NewCoins(initialFunds)) - // get a rando account to send kava to + // get a rando account to send 0gchain to randomAddr := app.RandomAddress() to := util.SdkToEvmAddress(randomAddr) // example fetching of nonce (account sequence) - nonce, err := suite.Kava.EvmClient.PendingNonceAt(context.Background(), acc.EvmAddress) + nonce, err := suite.ZgChain.EvmClient.PendingNonceAt(context.Background(), acc.EvmAddress) suite.NoError(err) suite.Equal(uint64(0), nonce) // sanity check. the account should have no prior txs - // transfer kava over EVM - kavaToTransfer := big.NewInt(1e17) // .1 KAVA; akava has 18 decimals. + // transfer a0gi over EVM + a0giToTransfer := big.NewInt(1e17) // .1 A0GI; neuron has 18 decimals. req := util.EvmTxRequest{ - Tx: ethtypes.NewTransaction(nonce, to, kavaToTransfer, 1e5, minEvmGasPrice, nil), + Tx: ethtypes.NewTransaction(nonce, to, a0giToTransfer, 1e5, minEvmGasPrice, nil), Data: "any ol' data to track this through the system", } res := acc.SignAndBroadcastEvmTx(req) @@ -103,36 +104,36 @@ func (suite *IntegrationTestSuite) TestTransferOverEVM() { suite.Equal(ethtypes.ReceiptStatusSuccessful, res.Receipt.Status) // evm txs refund unused gas. so to know the expected balance we need to know how much gas was used. - ukavaUsedForGas := sdkmath.NewIntFromBigInt(minEvmGasPrice). + a0giUsedForGas := sdkmath.NewIntFromBigInt(minEvmGasPrice). Mul(sdkmath.NewIntFromUint64(res.Receipt.GasUsed)). - QuoRaw(1e12) // convert akava to ukava + QuoRaw(1e12) // convert neuron to a0gi - // expect (9 - gas used) KAVA remaining in account. - balance := suite.Kava.QuerySdkForBalances(acc.SdkAddress) - suite.Equal(sdkmath.NewInt(9e5).Sub(ukavaUsedForGas), balance.AmountOf("ukava")) + // expect (9 - gas used) A0GI remaining in account. + balance := suite.ZgChain.QuerySdkForBalances(acc.SdkAddress) + suite.Equal(sdkmath.NewInt(9e5).Sub(a0giUsedForGas), balance.AmountOf(chaincfg.DisplayDenom)) } -// TestIbcTransfer transfers KAVA from the primary kava chain (suite.Kava) to the ibc chain (suite.Ibc). -// Note that because the IBC chain also runs kava's binary, this tests both the sending & receiving. +// TestIbcTransfer transfers A0GI from the primary 0g-chain (suite.ZgChain) to the ibc chain (suite.Ibc). +// Note that because the IBC chain also runs 0g-chain's binary, this tests both the sending & receiving. func (suite *IntegrationTestSuite) TestIbcTransfer() { suite.SkipIfIbcDisabled() // ARRANGE - // setup kava account - funds := ukava(1e5) // .1 KAVA - kavaAcc := suite.Kava.NewFundedAccount("ibc-transfer-kava-side", sdk.NewCoins(funds)) + // setup 0g-chain account + funds := a0gi(big.NewInt(1e5)) // .1 A0GI + zgChainAcc := suite.ZgChain.NewFundedAccount("ibc-transfer-0g-side", sdk.NewCoins(funds)) // setup ibc account ibcAcc := suite.Ibc.NewFundedAccount("ibc-transfer-ibc-side", sdk.NewCoins()) gasLimit := int64(2e5) - fee := ukava(200) + fee := a0gi(big.NewInt(200)) - fundsToSend := ukava(5e4) // .005 KAVA + fundsToSend := a0gi(big.NewInt(5e4)) // .005 A0GI transferMsg := ibctypes.NewMsgTransfer( testutil.IbcPort, testutil.IbcChannel, fundsToSend, - kavaAcc.SdkAddress.String(), + zgChainAcc.SdkAddress.String(), ibcAcc.SdkAddress.String(), ibcclienttypes.NewHeight(0, 0), // timeout height disabled when 0 uint64(time.Now().Add(30*time.Second).UnixNano()), @@ -142,22 +143,22 @@ func (suite *IntegrationTestSuite) TestIbcTransfer() { expectedSrcBalance := funds.Sub(fundsToSend).Sub(fee) // ACT - // IBC transfer from kava -> ibc - transferTo := util.KavaMsgRequest{ + // IBC transfer from 0g-chain -> ibc + transferTo := util.ZgChainMsgRequest{ Msgs: []sdk.Msg{transferMsg}, GasLimit: uint64(gasLimit), FeeAmount: sdk.NewCoins(fee), - Memo: "sent from Kava!", + Memo: "sent from ZgChain!", } - res := kavaAcc.SignAndBroadcastKavaTx(transferTo) + res := zgChainAcc.SignAndBroadcastZgChainTx(transferTo) // ASSERT suite.NoError(res.Err) - // the balance should be deducted from kava account + // the balance should be deducted from 0g-chain account suite.Eventually(func() bool { - balance := suite.Kava.QuerySdkForBalances(kavaAcc.SdkAddress) - return balance.AmountOf("ukava").Equal(expectedSrcBalance.Amount) + balance := suite.ZgChain.QuerySdkForBalances(zgChainAcc.SdkAddress) + return balance.AmountOf(chaincfg.DisplayDenom).Equal(expectedSrcBalance.Amount) }, 10*time.Second, 1*time.Second) // expect the balance to be transferred to the ibc chain! diff --git a/tests/e2e/e2e_upgrade_handler_test.go b/tests/e2e/e2e_upgrade_handler_test.go index 2a3b4464..d42bae49 100644 --- a/tests/e2e/e2e_upgrade_handler_test.go +++ b/tests/e2e/e2e_upgrade_handler_test.go @@ -13,6 +13,6 @@ func (suite *IntegrationTestSuite) TestUpgradeHandler() { suite.True(true) // Uncomment & use these contexts to compare chain state before & after the upgrade occurs. - // beforeUpgradeCtx := suite.Kava.Grpc.CtxAtHeight(suite.UpgradeHeight - 1) - // afterUpgradeCtx := suite.Kava.Grpc.CtxAtHeight(suite.UpgradeHeight) + // beforeUpgradeCtx := suite.ZgChain.Grpc.CtxAtHeight(suite.UpgradeHeight - 1) + // afterUpgradeCtx := suite.ZgChain.Grpc.CtxAtHeight(suite.UpgradeHeight) } diff --git a/tests/e2e/runner/chain.go b/tests/e2e/runner/chain.go index b11d6179..957636e0 100644 --- a/tests/e2e/runner/chain.go +++ b/tests/e2e/runner/chain.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" + "github.com/0glabs/0g-chain/chaincfg" rpchttpclient "github.com/cometbft/cometbft/rpc/client/http" "github.com/ethereum/go-ethereum/ethclient" ) @@ -67,20 +68,20 @@ func (c *Chains) Register(name string, chain *ChainDetails) error { // the Chain details are all hardcoded because they are currently fixed by kvtool. // someday they may be accepted as configurable parameters. var ( - kvtoolKavaChain = ChainDetails{ + kvtoolZgChainChain = ChainDetails{ RpcUrl: "http://localhost:26657", GrpcUrl: "http://localhost:9090", EvmRpcUrl: "http://localhost:8545", - ChainId: "kavalocalnet_8888-1", - StakingDenom: "ukava", + ChainId: "0gchainlocalnet_8888-1", + StakingDenom: chaincfg.DisplayDenom, } kvtoolIbcChain = ChainDetails{ RpcUrl: "http://localhost:26658", GrpcUrl: "http://localhost:9092", EvmRpcUrl: "http://localhost:8547", - ChainId: "kavalocalnet_8889-2", + ChainId: "0gchainlocalnet_8889-2", StakingDenom: "uatom", } ) diff --git a/tests/e2e/runner/kvtool.go b/tests/e2e/runner/kvtool.go index 087e7527..a7a2e355 100644 --- a/tests/e2e/runner/kvtool.go +++ b/tests/e2e/runner/kvtool.go @@ -8,24 +8,24 @@ import ( ) type KvtoolRunnerConfig struct { - KavaConfigTemplate string + ZgChainConfigTemplate string ImageTag string IncludeIBC bool - EnableAutomatedUpgrade bool - KavaUpgradeName string - KavaUpgradeHeight int64 - KavaUpgradeBaseImageTag string + EnableAutomatedUpgrade bool + ZgChainUpgradeName string + ZgChainUpgradeHeight int64 + ZgChainUpgradeBaseImageTag string SkipShutdown bool } // KvtoolRunner implements a NodeRunner that spins up local chains with kvtool. // It has support for the following: -// - running a Kava node -// - optionally, running an IBC node with a channel opened to the Kava node -// - optionally, start the Kava node on one version and upgrade to another +// - running a ZgChain node +// - optionally, running an IBC node with a channel opened to the ZgChain node +// - optionally, start the ZgChain node on one version and upgrade to another type KvtoolRunner struct { config KvtoolRunnerConfig } @@ -51,8 +51,8 @@ func (k *KvtoolRunner) StartChains() Chains { } // start local test network with kvtool - log.Println("starting kava node") - kvtoolArgs := []string{"testnet", "bootstrap", "--kava.configTemplate", k.config.KavaConfigTemplate} + log.Println("starting 0gchain node") + kvtoolArgs := []string{"testnet", "bootstrap", "--0gchain.configTemplate", k.config.ZgChainConfigTemplate} // include an ibc chain if desired if k.config.IncludeIBC { kvtoolArgs = append(kvtoolArgs, "--ibc") @@ -60,32 +60,32 @@ func (k *KvtoolRunner) StartChains() Chains { // handle automated upgrade functionality, if defined if k.config.EnableAutomatedUpgrade { kvtoolArgs = append(kvtoolArgs, - "--upgrade-name", k.config.KavaUpgradeName, - "--upgrade-height", fmt.Sprint(k.config.KavaUpgradeHeight), - "--upgrade-base-image-tag", k.config.KavaUpgradeBaseImageTag, + "--upgrade-name", k.config.ZgChainUpgradeName, + "--upgrade-height", fmt.Sprint(k.config.ZgChainUpgradeHeight), + "--upgrade-base-image-tag", k.config.ZgChainUpgradeBaseImageTag, ) } // start the chain - startKavaCmd := exec.Command("kvtool", kvtoolArgs...) - startKavaCmd.Env = os.Environ() - startKavaCmd.Env = append(startKavaCmd.Env, fmt.Sprintf("KAVA_TAG=%s", k.config.ImageTag)) - startKavaCmd.Stdout = os.Stdout - startKavaCmd.Stderr = os.Stderr - log.Println(startKavaCmd.String()) - if err := startKavaCmd.Run(); err != nil { - panic(fmt.Sprintf("failed to start kava: %s", err.Error())) + startZgChainCmd := exec.Command("kvtool", kvtoolArgs...) + startZgChainCmd.Env = os.Environ() + startZgChainCmd.Env = append(startZgChainCmd.Env, fmt.Sprintf("0GCHAIN_TAG=%s", k.config.ImageTag)) + startZgChainCmd.Stdout = os.Stdout + startZgChainCmd.Stderr = os.Stderr + log.Println(startZgChainCmd.String()) + if err := startZgChainCmd.Run(); err != nil { + panic(fmt.Sprintf("failed to start 0gchain: %s", err.Error())) } // wait for chain to be live. // if an upgrade is defined, this waits for the upgrade to be completed. - if err := waitForChainStart(kvtoolKavaChain); err != nil { + if err := waitForChainStart(kvtoolZgChainChain); err != nil { k.Shutdown() panic(err) } - log.Println("kava is started!") + log.Println("0gchain is started!") chains := NewChains() - chains.Register("kava", &kvtoolKavaChain) + chains.Register("0gchain", &kvtoolZgChainChain) if k.config.IncludeIBC { chains.Register("ibc", &kvtoolIbcChain) } @@ -101,11 +101,11 @@ func (k *KvtoolRunner) Shutdown() { log.Printf("would shut down but SkipShutdown is true") return } - log.Println("shutting down kava node") - shutdownKavaCmd := exec.Command("kvtool", "testnet", "down") - shutdownKavaCmd.Stdout = os.Stdout - shutdownKavaCmd.Stderr = os.Stderr - if err := shutdownKavaCmd.Run(); err != nil { + log.Println("shutting down 0gchain node") + shutdownZgChainCmd := exec.Command("kvtool", "testnet", "down") + shutdownZgChainCmd.Stdout = os.Stdout + shutdownZgChainCmd.Stderr = os.Stderr + if err := shutdownZgChainCmd.Run(); err != nil { panic(fmt.Sprintf("failed to shutdown kvtool: %s", err.Error())) } } diff --git a/tests/e2e/runner/live.go b/tests/e2e/runner/live.go index ecefd731..018cdf0d 100644 --- a/tests/e2e/runner/live.go +++ b/tests/e2e/runner/live.go @@ -7,15 +7,15 @@ import ( "github.com/cosmos/cosmos-sdk/client/grpc/tmservice" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/kava-labs/kava/client/grpc" + "github.com/0glabs/0g-chain/client/grpc" ) // LiveNodeRunnerConfig implements NodeRunner. // It connects to a running network via the RPC, GRPC, and EVM urls. type LiveNodeRunnerConfig struct { - KavaRpcUrl string - KavaGrpcUrl string - KavaEvmRpcUrl string + ZgChainRpcUrl string + ZgChainGrpcUrl string + ZgChainEvmRpcUrl string UpgradeHeight int64 } @@ -37,41 +37,41 @@ func NewLiveNodeRunner(config LiveNodeRunnerConfig) *LiveNodeRunner { // It initializes connections to the chain based on parameters. // It attempts to ping the necessary endpoints and panics if they cannot be reached. func (r LiveNodeRunner) StartChains() Chains { - fmt.Println("establishing connection to live kava network") + fmt.Println("establishing connection to live 0g-chain network") chains := NewChains() - kavaChain := ChainDetails{ - RpcUrl: r.config.KavaRpcUrl, - GrpcUrl: r.config.KavaGrpcUrl, - EvmRpcUrl: r.config.KavaEvmRpcUrl, + zgChain := ChainDetails{ + RpcUrl: r.config.ZgChainRpcUrl, + GrpcUrl: r.config.ZgChainGrpcUrl, + EvmRpcUrl: r.config.ZgChainEvmRpcUrl, } - if err := waitForChainStart(kavaChain); err != nil { + if err := waitForChainStart(zgChain); err != nil { panic(fmt.Sprintf("failed to ping chain: %s", err)) } // determine chain id - client, err := grpc.NewClient(kavaChain.GrpcUrl) + client, err := grpc.NewClient(zgChain.GrpcUrl) if err != nil { - panic(fmt.Sprintf("failed to create kava grpc client: %s", err)) + panic(fmt.Sprintf("failed to create 0gchain grpc client: %s", err)) } nodeInfo, err := client.Query.Tm.GetNodeInfo(context.Background(), &tmservice.GetNodeInfoRequest{}) if err != nil { - panic(fmt.Sprintf("failed to fetch kava node info: %s", err)) + panic(fmt.Sprintf("failed to fetch 0gchain node info: %s", err)) } - kavaChain.ChainId = nodeInfo.DefaultNodeInfo.Network + zgChain.ChainId = nodeInfo.DefaultNodeInfo.Network // determine staking denom stakingParams, err := client.Query.Staking.Params(context.Background(), &stakingtypes.QueryParamsRequest{}) if err != nil { - panic(fmt.Sprintf("failed to fetch kava staking params: %s", err)) + panic(fmt.Sprintf("failed to fetch 0gchain staking params: %s", err)) } - kavaChain.StakingDenom = stakingParams.Params.BondDenom + zgChain.StakingDenom = stakingParams.Params.BondDenom - chains.Register("kava", &kavaChain) + chains.Register("0gchain", &zgChain) - fmt.Printf("successfully connected to live network %+v\n", kavaChain) + fmt.Printf("successfully connected to live network %+v\n", zgChain) return chains } diff --git a/tests/e2e/runner/main.go b/tests/e2e/runner/main.go index ddb93192..d2c100b1 100644 --- a/tests/e2e/runner/main.go +++ b/tests/e2e/runner/main.go @@ -22,7 +22,7 @@ func waitForChainStart(chainDetails ChainDetails) error { b := backoff.NewExponentialBackOff() b.MaxInterval = 5 * time.Second b.MaxElapsedTime = 30 * time.Second - if err := backoff.Retry(func() error { return pingKava(chainDetails.RpcUrl) }, b); err != nil { + if err := backoff.Retry(func() error { return pingZgChain(chainDetails.RpcUrl) }, b); err != nil { return fmt.Errorf("failed connect to chain: %s", err) } @@ -34,9 +34,9 @@ func waitForChainStart(chainDetails ChainDetails) error { return nil } -func pingKava(rpcUrl string) error { +func pingZgChain(rpcUrl string) error { statusUrl := fmt.Sprintf("%s/status", rpcUrl) - log.Printf("pinging kava chain: %s\n", statusUrl) + log.Printf("pinging 0g-chain: %s\n", statusUrl) res, err := http.Get(statusUrl) if err != nil { return err @@ -45,7 +45,7 @@ func pingKava(rpcUrl string) error { if res.StatusCode >= 400 { return fmt.Errorf("ping to status failed: %d", res.StatusCode) } - log.Println("successfully started Kava!") + log.Println("successfully started ZgChain!") return nil } diff --git a/tests/e2e/testutil/account.go b/tests/e2e/testutil/account.go index 3db20ef5..743a7d31 100644 --- a/tests/e2e/testutil/account.go +++ b/tests/e2e/testutil/account.go @@ -28,8 +28,8 @@ import ( emtests "github.com/evmos/ethermint/tests" emtypes "github.com/evmos/ethermint/types" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/tests/util" + "github.com/0glabs/0g-chain/chaincfg" + "github.com/0glabs/0g-chain/tests/util" ) // SigningAccount wraps details about an account and its private keys. @@ -43,9 +43,9 @@ type SigningAccount struct { evmReqChan chan<- util.EvmTxRequest evmResChan <-chan util.EvmTxResponse - kavaSigner *util.KavaSigner - sdkReqChan chan<- util.KavaMsgRequest - sdkResChan <-chan util.KavaMsgResponse + zgChainSigner *util.ZgChainSigner + sdkReqChan chan<- util.ZgChainMsgRequest + sdkResChan <-chan util.ZgChainMsgResponse EvmAuth *bind.TransactOpts @@ -72,7 +72,7 @@ func (chain *Chain) AddNewSigningAccount(name string, hdPath *hd.BIP44Params, ch chain.t.Fatalf("account with name %s already exists", name) } - // Kava signing account for SDK side + // 0gChain signing account for SDK side privKeyBytes, err := hd.Secp256k1.Derive()(mnemonic, "", hdPath.String()) require.NoErrorf(chain.t, err, "failed to derive private key from mnemonic for %s: %s", name, err) privKey := ðsecp256k1.PrivKey{Key: privKeyBytes} @@ -97,8 +97,8 @@ func (chain *Chain) AddNewSigningAccountFromPrivKey( chain.t.Fatalf("account with name %s already exists", name) } - // Kava signing account for SDK side - kavaSigner := util.NewKavaSigner( + // 0gChain signing account for SDK side + zgChainSigner := util.NewZgChainSigner( chainId, chain.EncodingConfig, chain.Grpc.Query.Auth, @@ -107,11 +107,11 @@ func (chain *Chain) AddNewSigningAccountFromPrivKey( 100, ) - sdkReqChan := make(chan util.KavaMsgRequest) - sdkResChan, err := kavaSigner.Run(sdkReqChan) + sdkReqChan := make(chan util.ZgChainMsgRequest) + sdkResChan, err := zgChainSigner.Run(sdkReqChan) require.NoErrorf(chain.t, err, "failed to start signer for account %s: %s", name, err) - // Kava signing account for EVM side + // 0gChain signing account for EVM side evmChainId, err := emtypes.ParseChainID(chainId) require.NoErrorf(chain.t, err, "unable to parse ethermint-compatible chain id from %s", chainId) ecdsaPrivKey, err := crypto.HexToECDSA(hex.EncodeToString(privKey.Bytes())) @@ -141,21 +141,21 @@ func (chain *Chain) AddNewSigningAccountFromPrivKey( evmReqChan: evmReqChan, evmResChan: evmResChan, - kavaSigner: kavaSigner, - sdkReqChan: sdkReqChan, - sdkResChan: sdkResChan, + zgChainSigner: zgChainSigner, + sdkReqChan: sdkReqChan, + sdkResChan: sdkResChan, EvmAuth: evmSigner.Auth, EvmAddress: evmSigner.Address(), - SdkAddress: kavaSigner.Address(), + SdkAddress: zgChainSigner.Address(), } return chain.accounts[name] } -// SignAndBroadcastKavaTx sends a request to the signer and awaits its response. -func (a *SigningAccount) SignAndBroadcastKavaTx(req util.KavaMsgRequest) util.KavaMsgResponse { +// SignAndBroadcastZgChainTx sends a request to the signer and awaits its response. +func (a *SigningAccount) SignAndBroadcastZgChainTx(req util.ZgChainMsgRequest) util.ZgChainMsgResponse { a.l.Printf("broadcasting sdk tx. has data = %+v\n", req.Data) // send the request to signer a.sdkReqChan <- req @@ -222,7 +222,7 @@ func (chain *Chain) NewFundedAccount(name string, funds sdk.Coins) *SigningAccou acc := chain.AddNewSigningAccount( name, - hd.CreateHDPath(app.Bip44CoinType, 0, 0), + hd.CreateHDPath(chaincfg.Bip44CoinType, 0, 0), chain.ChainID, mnemonic, ) @@ -257,12 +257,12 @@ func (a *SigningAccount) NextNonce() (uint64, error) { } // BankSend is a helper method for sending funds via x/bank's MsgSend -func (a *SigningAccount) BankSend(to sdk.AccAddress, amount sdk.Coins) util.KavaMsgResponse { - return a.SignAndBroadcastKavaTx( - util.KavaMsgRequest{ +func (a *SigningAccount) BankSend(to sdk.AccAddress, amount sdk.Coins) util.ZgChainMsgResponse { + return a.SignAndBroadcastZgChainTx( + util.ZgChainMsgRequest{ Msgs: []sdk.Msg{banktypes.NewMsgSend(a.SdkAddress, to, amount)}, GasLimit: 2e5, // 200,000 gas - FeeAmount: sdk.NewCoins(sdk.NewCoin(a.gasDenom, sdkmath.NewInt(200))), // assume min gas price of .001ukava + FeeAmount: sdk.NewCoins(sdk.NewCoin(a.gasDenom, sdkmath.NewInt(200))), // assume min gas price of .001a0gi Data: fmt.Sprintf("sending %s to %s", amount, to), }, ) diff --git a/tests/e2e/testutil/chain.go b/tests/e2e/testutil/chain.go index c0586070..880cfe7d 100644 --- a/tests/e2e/testutil/chain.go +++ b/tests/e2e/testutil/chain.go @@ -21,11 +21,11 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" - "github.com/kava-labs/kava/app" - kavaparams "github.com/kava-labs/kava/app/params" - "github.com/kava-labs/kava/client/grpc" - "github.com/kava-labs/kava/tests/e2e/runner" - "github.com/kava-labs/kava/tests/util" + "github.com/0glabs/0g-chain/app" + chainparams "github.com/0glabs/0g-chain/app/params" + "github.com/0glabs/0g-chain/client/grpc" + "github.com/0glabs/0g-chain/tests/e2e/runner" + "github.com/0glabs/0g-chain/tests/util" ) // Chain wraps query clients & accounts for a network @@ -41,11 +41,11 @@ type Chain struct { ContractAddrs map[string]common.Address erc20s map[common.Address]struct{} - EncodingConfig kavaparams.EncodingConfig + EncodingConfig chainparams.EncodingConfig TmSignClient tmclient.SignClient - Grpc *grpc.KavaGrpcClient + Grpc *grpc.ZgChainGrpcClient } // NewChain creates the query clients & signing account management for a chain run on a set of ports. @@ -65,7 +65,7 @@ func NewChain(t *testing.T, details *runner.ChainDetails, fundedAccountMnemonic kr, err := keyring.New( sdk.KeyringServiceName(), keyring.BackendTest, - util.KavaHomePath(), + util.ZgChainHomePath(), nil, chain.EncodingConfig.Marshaler, evmhd.EthSecp256k1Option(), @@ -77,7 +77,7 @@ func NewChain(t *testing.T, details *runner.ChainDetails, fundedAccountMnemonic client, err := grpc.NewClient(details.GrpcUrl) if err != nil { - chain.t.Fatalf("failed to create kava grpc client: %s", err) + chain.t.Fatalf("failed to create 0gchain grpc client: %s", err) } chain.Grpc = client diff --git a/tests/e2e/testutil/config.go b/tests/e2e/testutil/config.go index bf78e7ec..23923b53 100644 --- a/tests/e2e/testutil/config.go +++ b/tests/e2e/testutil/config.go @@ -27,7 +27,7 @@ type SuiteConfig struct { IncludeIbcTests bool // The contract address of a deployed ERC-20 token - KavaErc20Address string + ZgchainERC20Address string // When true, the chains will remain running after tests complete (pass or fail) SkipShutdown bool @@ -36,26 +36,26 @@ type SuiteConfig struct { // KvtoolConfig wraps configuration options for running the end-to-end test suite against // a locally running chain. This config must be defined if E2E_RUN_KVTOOL_NETWORKS is true. type KvtoolConfig struct { - // The kava.configTemplate flag to be passed to kvtool, usually "master". + // The 0gchain.configTemplate flag to be passed to kvtool, usually "master". // This allows one to change the base genesis used to start the chain. - KavaConfigTemplate string + ZgChainConfigTemplate string // Whether or not to run a chain upgrade & run post-upgrade tests. Use `suite.SkipIfUpgradeDisabled()` in post-upgrade tests. IncludeAutomatedUpgrade bool // Name of the upgrade, if upgrade is enabled. - KavaUpgradeName string + ZgChainUpgradeName string // Height upgrade will be applied to the test chain, if upgrade is enabled. - KavaUpgradeHeight int64 - // Tag of kava docker image that will be upgraded to the current image before tests are run, if upgrade is enabled. - KavaUpgradeBaseImageTag string + ZgChainUpgradeHeight int64 + // Tag of 0gchain docker image that will be upgraded to the current image before tests are run, if upgrade is enabled. + ZgChainUpgradeBaseImageTag string } // LiveNetworkConfig wraps configuration options for running the end-to-end test suite // against a live network. It must be defined if E2E_RUN_KVTOOL_NETWORKS is false. type LiveNetworkConfig struct { - KavaRpcUrl string - KavaGrpcUrl string - KavaEvmRpcUrl string + ZgChainRpcUrl string + ZgChainGrpcUrl string + ZgChainEvmRpcUrl string UpgradeHeight int64 } @@ -65,8 +65,8 @@ func ParseSuiteConfig() SuiteConfig { config := SuiteConfig{ // this mnemonic is expected to be a funded account that can seed the funds for all // new accounts created during tests. it will be available under Accounts["whale"] - FundedAccountMnemonic: nonemptyStringEnv("E2E_KAVA_FUNDED_ACCOUNT_MNEMONIC"), - KavaErc20Address: nonemptyStringEnv("E2E_KAVA_ERC20_ADDRESS"), + FundedAccountMnemonic: nonemptyStringEnv("E2E_0GCHAIN_FUNDED_ACCOUNT_MNEMONIC"), + ZgchainERC20Address: nonemptyStringEnv("E2E_0GCHAIN_ERC20_ADDRESS"), IncludeIbcTests: mustParseBool("E2E_INCLUDE_IBC_TESTS"), } @@ -90,18 +90,18 @@ func ParseSuiteConfig() SuiteConfig { // ParseKvtoolConfig builds a KvtoolConfig from environment variables. func ParseKvtoolConfig() KvtoolConfig { config := KvtoolConfig{ - KavaConfigTemplate: nonemptyStringEnv("E2E_KVTOOL_KAVA_CONFIG_TEMPLATE"), + ZgChainConfigTemplate: nonemptyStringEnv("E2E_KVTOOL_0GCHAIN_CONFIG_TEMPLATE"), IncludeAutomatedUpgrade: mustParseBool("E2E_INCLUDE_AUTOMATED_UPGRADE"), } if config.IncludeAutomatedUpgrade { - config.KavaUpgradeName = nonemptyStringEnv("E2E_KAVA_UPGRADE_NAME") - config.KavaUpgradeBaseImageTag = nonemptyStringEnv("E2E_KAVA_UPGRADE_BASE_IMAGE_TAG") - upgradeHeight, err := strconv.ParseInt(nonemptyStringEnv("E2E_KAVA_UPGRADE_HEIGHT"), 10, 64) + config.ZgChainUpgradeName = nonemptyStringEnv("E2E_0GCHAIN_UPGRADE_NAME") + config.ZgChainUpgradeBaseImageTag = nonemptyStringEnv("E2E_0GCHAIN_UPGRADE_BASE_IMAGE_TAG") + upgradeHeight, err := strconv.ParseInt(nonemptyStringEnv("E2E_0GCHAIN_UPGRADE_HEIGHT"), 10, 64) if err != nil { - panic(fmt.Sprintf("E2E_KAVA_UPGRADE_HEIGHT must be a number: %s", err)) + panic(fmt.Sprintf("E2E_0GCHAIN_UPGRADE_HEIGHT must be a number: %s", err)) } - config.KavaUpgradeHeight = upgradeHeight + config.ZgChainUpgradeHeight = upgradeHeight } return config @@ -110,16 +110,16 @@ func ParseKvtoolConfig() KvtoolConfig { // ParseLiveNetworkConfig builds a LiveNetworkConfig from environment variables. func ParseLiveNetworkConfig() LiveNetworkConfig { config := LiveNetworkConfig{ - KavaRpcUrl: nonemptyStringEnv("E2E_KAVA_RPC_URL"), - KavaGrpcUrl: nonemptyStringEnv("E2E_KAVA_GRPC_URL"), - KavaEvmRpcUrl: nonemptyStringEnv("E2E_KAVA_EVM_RPC_URL"), + ZgChainRpcUrl: nonemptyStringEnv("E2E_0GCHAIN_RPC_URL"), + ZgChainGrpcUrl: nonemptyStringEnv("E2E_0GCHAIN_GRPC_URL"), + ZgChainEvmRpcUrl: nonemptyStringEnv("E2E_0GCHAIN_EVM_RPC_URL"), } - upgradeHeight := os.Getenv("E2E_KAVA_UPGRADE_HEIGHT") + upgradeHeight := os.Getenv("E2E_0GCHAIN_UPGRADE_HEIGHT") if upgradeHeight != "" { parsedHeight, err := strconv.ParseInt(upgradeHeight, 10, 64) if err != nil { - panic(fmt.Sprintf("E2E_KAVA_UPGRADE_HEIGHT must be a number: %s", err)) + panic(fmt.Sprintf("E2E_0GCHAIN_UPGRADE_HEIGHT must be a number: %s", err)) } config.UpgradeHeight = parsedHeight diff --git a/tests/e2e/testutil/init_evm.go b/tests/e2e/testutil/init_evm.go index 61baaebf..ea19296e 100644 --- a/tests/e2e/testutil/init_evm.go +++ b/tests/e2e/testutil/init_evm.go @@ -7,18 +7,18 @@ import ( "github.com/ethereum/go-ethereum/common" - "github.com/kava-labs/kava/tests/e2e/contracts/greeter" - "github.com/kava-labs/kava/x/cdp/types" - evmutiltypes "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/tests/e2e/contracts/greeter" + // "github.com/0glabs/0g-chain/x/cdp/types" + evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types" ) -// InitKavaEvmData is run after the chain is running, but before the tests are run. +// InitZgChainEvmData is run after the chain is running, but before the tests are run. // It is used to initialize some EVM state, such as deploying contracts. -func (suite *E2eTestSuite) InitKavaEvmData() { - whale := suite.Kava.GetAccount(FundedAccountName) +func (suite *E2eTestSuite) InitZgChainEvmData() { + whale := suite.ZgChain.GetAccount(FundedAccountName) // ensure funded account has nonzero erc20 balance - balance := suite.Kava.GetErc20Balance(suite.DeployedErc20.Address, whale.EvmAddress) + balance := suite.ZgChain.GetErc20Balance(suite.DeployedErc20.Address, whale.EvmAddress) if balance.Cmp(big.NewInt(0)) != 1 { panic(fmt.Sprintf( "expected funded account (%s) to have erc20 balance of token %s", @@ -28,14 +28,14 @@ func (suite *E2eTestSuite) InitKavaEvmData() { } // expect the erc20 to be enabled for conversion to sdk.Coin - params, err := suite.Kava.Grpc.Query.Evmutil.Params(context.Background(), &evmutiltypes.QueryParamsRequest{}) + params, err := suite.ZgChain.Grpc.Query.Evmutil.Params(context.Background(), &evmutiltypes.QueryParamsRequest{}) if err != nil { panic(fmt.Sprintf("failed to fetch evmutil params during init: %s", err)) } found := false erc20Addr := suite.DeployedErc20.Address.Hex() for _, p := range params.Params.EnabledConversionPairs { - if common.BytesToAddress(p.KavaERC20Address).Hex() == erc20Addr { + if common.BytesToAddress(p.ZgchainERC20Address).Hex() == erc20Addr { found = true suite.DeployedErc20.CosmosDenom = p.Denom } @@ -43,24 +43,24 @@ func (suite *E2eTestSuite) InitKavaEvmData() { if !found { panic(fmt.Sprintf("erc20 %s must be enabled for conversion to cosmos coin", erc20Addr)) } - suite.Kava.RegisterErc20(suite.DeployedErc20.Address) + suite.ZgChain.RegisterErc20(suite.DeployedErc20.Address) // expect the erc20's cosmos denom to be a supported cdp collateral type - cdpParams, err := suite.Kava.Grpc.Query.Cdp.Params(context.Background(), &types.QueryParamsRequest{}) - suite.Require().NoError(err) - found = false - for _, cp := range cdpParams.Params.CollateralParams { - if cp.Denom == suite.DeployedErc20.CosmosDenom { - found = true - suite.DeployedErc20.CdpCollateralType = cp.Type - } - } - if !found { - panic(fmt.Sprintf( - "erc20's cosmos denom %s must be valid cdp collateral type", - suite.DeployedErc20.CosmosDenom), - ) - } + // cdpParams, err := suite.ZgChain.Grpc.Query.Cdp.Params(context.Background(), &types.QueryParamsRequest{}) + // suite.Require().NoError(err) + // found = false + // for _, cp := range cdpParams.Params.CollateralParams { + // if cp.Denom == suite.DeployedErc20.CosmosDenom { + // found = true + // suite.DeployedErc20.CdpCollateralType = cp.Type + // } + // } + // if !found { + // panic(fmt.Sprintf( + // "erc20's cosmos denom %s must be valid cdp collateral type", + // suite.DeployedErc20.CosmosDenom), + // ) + // } // deploy an example contract greeterAddr, _, _, err := greeter.DeployGreeter( @@ -69,13 +69,13 @@ func (suite *E2eTestSuite) InitKavaEvmData() { "what's up!", ) suite.NoError(err, "failed to deploy a contract to the EVM") - suite.Kava.ContractAddrs["greeter"] = greeterAddr + suite.ZgChain.ContractAddrs["greeter"] = greeterAddr } -// FundKavaErc20Balance sends the pre-deployed ERC20 token to the `toAddress`. -func (suite *E2eTestSuite) FundKavaErc20Balance(toAddress common.Address, amount *big.Int) EvmTxResponse { +// FundZgChainErc20Balance sends the pre-deployed ERC20 token to the `toAddress`. +func (suite *E2eTestSuite) FundZgChainErc20Balance(toAddress common.Address, amount *big.Int) EvmTxResponse { // funded account should have erc20 balance - whale := suite.Kava.GetAccount(FundedAccountName) + whale := suite.ZgChain.GetAccount(FundedAccountName) res, err := whale.TransferErc20(suite.DeployedErc20.Address, toAddress, amount) suite.NoError(err) return res diff --git a/tests/e2e/testutil/suite.go b/tests/e2e/testutil/suite.go index 5c0d93bb..fdaecbe6 100644 --- a/tests/e2e/testutil/suite.go +++ b/tests/e2e/testutil/suite.go @@ -10,14 +10,14 @@ import ( sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/tests/e2e/runner" - "github.com/kava-labs/kava/tests/util" + "github.com/0glabs/0g-chain/chaincfg" + "github.com/0glabs/0g-chain/tests/e2e/runner" + "github.com/0glabs/0g-chain/tests/util" ) const ( FundedAccountName = "whale" - // use coin type 60 so we are compatible with accounts from `kava add keys --eth ` + // use coin type 60 so we are compatible with accounts from `0gchaind add keys --eth ` // these accounts use the ethsecp256k1 signing algorithm that allows the signing client // to manage both sdk & evm txs. Bip44CoinType = 60 @@ -27,13 +27,13 @@ const ( ) // DeployedErc20 is a type that wraps the details of the pre-deployed erc20 used by the e2e test suite. -// The Address comes from SuiteConfig.KavaErc20Address +// The Address comes from SuiteConfig.ZgchainERC20Address // The CosmosDenom is fetched from the EnabledConversionPairs param of x/evmutil. // The tests expect the following: // - the funded account has a nonzero balance of the erc20 // - the erc20 is enabled for conversion to sdk.Coin // - the corresponding sdk.Coin is enabled as a cdp collateral type -// These requirements are checked in InitKavaEvmData(). +// These requirements are checked in InitZgChainEvmData(). type DeployedErc20 struct { Address common.Address CosmosDenom string @@ -41,15 +41,15 @@ type DeployedErc20 struct { CdpCollateralType string } -// E2eTestSuite is a testify test suite for running end-to-end integration tests on Kava. +// E2eTestSuite is a testify test suite for running end-to-end integration tests on ZgChain. type E2eTestSuite struct { suite.Suite config SuiteConfig runner runner.NodeRunner - Kava *Chain - Ibc *Chain + ZgChain *Chain + Ibc *Chain UpgradeHeight int64 DeployedErc20 DeployedErc20 @@ -85,13 +85,13 @@ func (s costSummary) String() string { func (suite *E2eTestSuite) SetupSuite() { var err error fmt.Println("setting up test suite.") - app.SetSDKConfig() + chaincfg.SetSDKConfig() suiteConfig := ParseSuiteConfig() suite.config = suiteConfig suite.DeployedErc20 = DeployedErc20{ - Address: common.HexToAddress(suiteConfig.KavaErc20Address), - // Denom & CdpCollateralType are fetched in InitKavaEvmData() + Address: common.HexToAddress(suiteConfig.ZgchainERC20Address), + // Denom & CdpCollateralType are fetched in InitZgChainEvmData() } // setup the correct NodeRunner for the given config @@ -104,11 +104,11 @@ func (suite *E2eTestSuite) SetupSuite() { } chains := suite.runner.StartChains() - kavachain := chains.MustGetChain("kava") - suite.Kava, err = NewChain(suite.T(), kavachain, suiteConfig.FundedAccountMnemonic) + zgchain := chains.MustGetChain("0gchain") + suite.ZgChain, err = NewChain(suite.T(), zgchain, suiteConfig.FundedAccountMnemonic) if err != nil { suite.runner.Shutdown() - suite.T().Fatalf("failed to create kava chain querier: %s", err) + suite.T().Fatalf("failed to create 0g-chain querier: %s", err) } if suiteConfig.IncludeIbcTests { @@ -120,14 +120,14 @@ func (suite *E2eTestSuite) SetupSuite() { } } - suite.InitKavaEvmData() + suite.InitZgChainEvmData() - whale := suite.Kava.GetAccount(FundedAccountName) + whale := suite.ZgChain.GetAccount(FundedAccountName) suite.cost = costSummary{ sdkAddress: whale.SdkAddress.String(), evmAddress: whale.EvmAddress.Hex(), - sdkBalanceBefore: suite.Kava.QuerySdkForBalances(whale.SdkAddress), - erc20BalanceBefore: suite.Kava.GetErc20Balance(suite.DeployedErc20.Address, whale.EvmAddress), + sdkBalanceBefore: suite.ZgChain.QuerySdkForBalances(whale.SdkAddress), + erc20BalanceBefore: suite.ZgChain.GetErc20Balance(suite.DeployedErc20.Address, whale.EvmAddress), } } @@ -136,27 +136,27 @@ func (suite *E2eTestSuite) SetupSuite() { func (suite *E2eTestSuite) TearDownSuite() { fmt.Println("tearing down test suite.") - whale := suite.Kava.GetAccount(FundedAccountName) + whale := suite.ZgChain.GetAccount(FundedAccountName) if suite.enableRefunds { - suite.cost.sdkBalanceAfter = suite.Kava.QuerySdkForBalances(whale.SdkAddress) - suite.cost.erc20BalanceAfter = suite.Kava.GetErc20Balance(suite.DeployedErc20.Address, whale.EvmAddress) + suite.cost.sdkBalanceAfter = suite.ZgChain.QuerySdkForBalances(whale.SdkAddress) + suite.cost.erc20BalanceAfter = suite.ZgChain.GetErc20Balance(suite.DeployedErc20.Address, whale.EvmAddress) fmt.Println("==BEFORE REFUNDS==") fmt.Println(suite.cost) fmt.Println("attempting to return all unused funds") - suite.Kava.ReturnAllFunds() + suite.ZgChain.ReturnAllFunds() fmt.Println("==AFTER REFUNDS==") } // calculate & output cost summary for funded account - suite.cost.sdkBalanceAfter = suite.Kava.QuerySdkForBalances(whale.SdkAddress) - suite.cost.erc20BalanceAfter = suite.Kava.GetErc20Balance(suite.DeployedErc20.Address, whale.EvmAddress) + suite.cost.sdkBalanceAfter = suite.ZgChain.QuerySdkForBalances(whale.SdkAddress) + suite.cost.erc20BalanceAfter = suite.ZgChain.GetErc20Balance(suite.DeployedErc20.Address, whale.EvmAddress) fmt.Println(suite.cost) // close all account request channels - suite.Kava.Shutdown() + suite.ZgChain.Shutdown() if suite.Ibc != nil { suite.Ibc.Shutdown() } @@ -167,19 +167,19 @@ func (suite *E2eTestSuite) TearDownSuite() { // SetupKvtoolNodeRunner is a helper method for building a KvtoolRunnerConfig from the suite config. func (suite *E2eTestSuite) SetupKvtoolNodeRunner() *runner.KvtoolRunner { // upgrade tests are only supported on kvtool networks - suite.UpgradeHeight = suite.config.Kvtool.KavaUpgradeHeight + suite.UpgradeHeight = suite.config.Kvtool.ZgChainUpgradeHeight suite.enableRefunds = false runnerConfig := runner.KvtoolRunnerConfig{ - KavaConfigTemplate: suite.config.Kvtool.KavaConfigTemplate, + ZgChainConfigTemplate: suite.config.Kvtool.ZgChainConfigTemplate, IncludeIBC: suite.config.IncludeIbcTests, ImageTag: "local", - EnableAutomatedUpgrade: suite.config.Kvtool.IncludeAutomatedUpgrade, - KavaUpgradeName: suite.config.Kvtool.KavaUpgradeName, - KavaUpgradeHeight: suite.config.Kvtool.KavaUpgradeHeight, - KavaUpgradeBaseImageTag: suite.config.Kvtool.KavaUpgradeBaseImageTag, + EnableAutomatedUpgrade: suite.config.Kvtool.IncludeAutomatedUpgrade, + ZgChainUpgradeName: suite.config.Kvtool.ZgChainUpgradeName, + ZgChainUpgradeHeight: suite.config.Kvtool.ZgChainUpgradeHeight, + ZgChainUpgradeBaseImageTag: suite.config.Kvtool.ZgChainUpgradeBaseImageTag, SkipShutdown: suite.config.SkipShutdown, } @@ -199,10 +199,10 @@ func (suite *E2eTestSuite) SetupLiveNetworkNodeRunner() *runner.LiveNodeRunner { suite.enableRefunds = true runnerConfig := runner.LiveNodeRunnerConfig{ - KavaRpcUrl: suite.config.LiveNetwork.KavaRpcUrl, - KavaGrpcUrl: suite.config.LiveNetwork.KavaGrpcUrl, - KavaEvmRpcUrl: suite.config.LiveNetwork.KavaEvmRpcUrl, - UpgradeHeight: suite.config.LiveNetwork.UpgradeHeight, + ZgChainRpcUrl: suite.config.LiveNetwork.ZgChainRpcUrl, + ZgChainGrpcUrl: suite.config.LiveNetwork.ZgChainGrpcUrl, + ZgChainEvmRpcUrl: suite.config.LiveNetwork.ZgChainEvmRpcUrl, + UpgradeHeight: suite.config.LiveNetwork.UpgradeHeight, } return runner.NewLiveNodeRunner(runnerConfig) diff --git a/tests/util/addresses_test.go b/tests/util/addresses_test.go index 85574d7e..fe26aab8 100644 --- a/tests/util/addresses_test.go +++ b/tests/util/addresses_test.go @@ -8,13 +8,13 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/common" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/tests/util" + "github.com/0glabs/0g-chain/chaincfg" + "github.com/0glabs/0g-chain/tests/util" ) func TestAddressConversion(t *testing.T) { - app.SetSDKConfig() - bech32Addr := sdk.MustAccAddressFromBech32("kava17d2wax0zhjrrecvaszuyxdf5wcu5a0p4qlx3t5") + chaincfg.SetSDKConfig() + bech32Addr := sdk.MustAccAddressFromBech32("0g17d2wax0zhjrrecvaszuyxdf5wcu5a0p4qlx3t5") hexAddr := common.HexToAddress("0xf354ee99e2bc863cE19d80b843353476394EbC35") require.Equal(t, bech32Addr, util.EvmToSdkAddress(hexAddr)) require.Equal(t, hexAddr, util.SdkToEvmAddress(bech32Addr)) diff --git a/tests/util/kvtool.go b/tests/util/kvtool.go index 8a0429af..77a347c8 100644 --- a/tests/util/kvtool.go +++ b/tests/util/kvtool.go @@ -4,8 +4,8 @@ import ( "path/filepath" ) -// KavaHomePath returns the OS-specific filepath for the kava home directory +// ZgChainHomePath returns the OS-specific filepath for the 0g-chain home directory // Assumes network is running with kvtool installed from the sub-repository in tests/e2e/kvtool -func KavaHomePath() string { - return filepath.Join("kvtool", "full_configs", "generated", "kava", "initstate", ".kava") +func ZgChainHomePath() string { + return filepath.Join("kvtool", "full_configs", "generated", "0gchaind", "initstate", ".0gchain") } diff --git a/tests/util/sdksigner.go b/tests/util/sdksigner.go index a37676ff..d3473145 100644 --- a/tests/util/sdksigner.go +++ b/tests/util/sdksigner.go @@ -6,7 +6,7 @@ import ( "fmt" "time" - "github.com/kava-labs/kava/app/params" + "github.com/0glabs/0g-chain/app/params" "google.golang.org/grpc/codes" grpcstatus "google.golang.org/grpc/status" @@ -27,18 +27,18 @@ var ( ErrUnsuccessfulTx = errors.New("tx committed but returned nonzero code") ) -type KavaMsgRequest struct { +type ZgChainMsgRequest struct { Msgs []sdk.Msg GasLimit uint64 FeeAmount sdk.Coins Memo string - // Arbitrary data to be referenced in the corresponding KavaMsgResponse, unused - // in signing. This is mostly useful to match KavaMsgResponses with KavaMsgRequests. + // Arbitrary data to be referenced in the corresponding ZgChainMsgResponse, unused + // in signing. This is mostly useful to match ZgChainMsgResponses with ZgChainMsgRequests. Data interface{} } -type KavaMsgResponse struct { - Request KavaMsgRequest +type ZgChainMsgResponse struct { + Request ZgChainMsgRequest Tx authsigning.Tx TxBytes []byte Result sdk.TxResponse @@ -55,8 +55,8 @@ const ( txResetSequence ) -// KavaSigner broadcasts msgs to a single kava node -type KavaSigner struct { +// ZgChainSigner broadcasts msgs to a single 0g-chain node +type ZgChainSigner struct { chainID string encodingConfig params.EncodingConfig authClient authtypes.QueryClient @@ -65,15 +65,15 @@ type KavaSigner struct { inflightTxLimit uint64 } -func NewKavaSigner( +func NewZgChainSigner( chainID string, encodingConfig params.EncodingConfig, authClient authtypes.QueryClient, txClient txtypes.ServiceClient, privKey cryptotypes.PrivKey, - inflightTxLimit uint64) *KavaSigner { + inflightTxLimit uint64) *ZgChainSigner { - return &KavaSigner{ + return &ZgChainSigner{ chainID: chainID, encodingConfig: encodingConfig, authClient: authClient, @@ -83,7 +83,7 @@ func NewKavaSigner( } } -func (s *KavaSigner) pollAccountState() <-chan authtypes.AccountI { +func (s *ZgChainSigner) pollAccountState() <-chan authtypes.AccountI { accountState := make(chan authtypes.AccountI) go func() { @@ -109,7 +109,7 @@ func (s *KavaSigner) pollAccountState() <-chan authtypes.AccountI { return accountState } -func (s *KavaSigner) Run(requests <-chan KavaMsgRequest) (<-chan KavaMsgResponse, error) { +func (s *ZgChainSigner) Run(requests <-chan ZgChainMsgRequest) (<-chan ZgChainMsgResponse, error) { // poll account state in it's own goroutine // and send status updates to the signing goroutine // @@ -117,15 +117,15 @@ func (s *KavaSigner) Run(requests <-chan KavaMsgRequest) (<-chan KavaMsgResponse // websocket events with a fallback to polling accountState := s.pollAccountState() - responses := make(chan KavaMsgResponse) + responses := make(chan ZgChainMsgResponse) go func() { // wait until account is loaded to start signing account := <-accountState // store current request waiting to be broadcasted - var currentRequest *KavaMsgRequest + var currentRequest *ZgChainMsgRequest // keep track of all successfully broadcasted txs // index is sequence % inflightTxLimit - inflight := make([]*KavaMsgResponse, s.inflightTxLimit) + inflight := make([]*ZgChainMsgResponse, s.inflightTxLimit) // used for confirming sent txs only prevDeliverTxSeq := account.GetSequence() // tx sequence of already signed messages @@ -252,7 +252,7 @@ func (s *KavaSigner) Run(requests <-chan KavaMsgRequest) (<-chan KavaMsgResponse tx, txBytes, err := Sign(s.encodingConfig.TxConfig, s.privKey, txBuilder, signerData) - response = &KavaMsgResponse{ + response = &ZgChainMsgResponse{ Request: *currentRequest, Tx: tx, TxBytes: txBytes, @@ -376,7 +376,7 @@ func (s *KavaSigner) Run(requests <-chan KavaMsgRequest) (<-chan KavaMsgResponse } // Address returns the address of the Signer -func (s *KavaSigner) Address() sdk.AccAddress { +func (s *ZgChainSigner) Address() sdk.AccAddress { return GetAccAddress(s.privKey) } diff --git a/x/auction/abci.go b/x/auction/abci.go deleted file mode 100644 index 6203f6d1..00000000 --- a/x/auction/abci.go +++ /dev/null @@ -1,23 +0,0 @@ -package auction - -import ( - "errors" - "time" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/auction/keeper" - "github.com/kava-labs/kava/x/auction/types" -) - -// BeginBlocker closes all expired auctions at the end of each block. It panics if -// there's an error other than ErrAuctionNotFound. -func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - - err := k.CloseExpiredAuctions(ctx) - if err != nil && !errors.Is(err, types.ErrAuctionNotFound) { - panic(err) - } -} diff --git a/x/auction/abci_test.go b/x/auction/abci_test.go deleted file mode 100644 index e1b38470..00000000 --- a/x/auction/abci_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package auction_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/auction" - "github.com/kava-labs/kava/x/auction/testutil" - types "github.com/kava-labs/kava/x/auction/types" -) - -type abciTestSuite struct { - testutil.Suite -} - -func (suite *abciTestSuite) SetupTest() { - suite.Suite.SetupTest(4) -} - -func TestABCITestSuite(t *testing.T) { - suite.Run(t, new(abciTestSuite)) -} - -func (suite *abciTestSuite) TestKeeper_BeginBlocker() { - buyer := suite.Addrs[0] - returnAddrs := []sdk.AccAddress{suite.Addrs[1]} - returnWeights := []sdkmath.Int{sdkmath.NewInt(1)} - - suite.AddCoinsToNamedModule(suite.ModAcc.Name, cs(c("token1", 100), c("token2", 100), c("debt", 100))) - - // Start an auction and place a bid - auctionID, err := suite.Keeper.StartCollateralAuction(suite.Ctx, suite.ModAcc.Name, c("token1", 20), c("token2", 50), returnAddrs, returnWeights, c("debt", 40)) - suite.Require().NoError(err) - suite.Require().NoError(suite.Keeper.PlaceBid(suite.Ctx, auctionID, buyer, c("token2", 30))) - - // Run the beginblocker, simulating a block time 1ns before auction expiry - preExpiryTime := suite.Ctx.BlockTime().Add(types.DefaultForwardBidDuration - 1) - auction.BeginBlocker(suite.Ctx.WithBlockTime(preExpiryTime), suite.Keeper) - - // Check auction has not been closed yet - _, found := suite.Keeper.GetAuction(suite.Ctx, auctionID) - suite.True(found) - - // Run the endblocker, simulating a block time equal to auction expiry - expiryTime := suite.Ctx.BlockTime().Add(types.DefaultForwardBidDuration) - auction.BeginBlocker(suite.Ctx.WithBlockTime(expiryTime), suite.Keeper) - - // Check auction has been closed - _, found = suite.Keeper.GetAuction(suite.Ctx, auctionID) - suite.False(found) -} - -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } diff --git a/x/auction/client/cli/query.go b/x/auction/client/cli/query.go deleted file mode 100644 index 032e4f4e..00000000 --- a/x/auction/client/cli/query.go +++ /dev/null @@ -1,212 +0,0 @@ -package cli - -import ( - "context" - "fmt" - "strconv" - "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/cosmos/cosmos-sdk/version" - - "github.com/kava-labs/kava/x/auction/types" -) - -// GetQueryCmd returns the cli query commands for the auction module -func GetQueryCmd() *cobra.Command { - auctionQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName), - } - - cmds := []*cobra.Command{ - GetCmdQueryParams(), - GetCmdQueryAuction(), - GetCmdQueryAuctions(), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - auctionQueryCmd.AddCommand(cmds...) - - return auctionQueryCmd -} - -// GetCmdQueryParams queries the issuance module parameters -func GetCmdQueryParams() *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: fmt.Sprintf("get the %s module parameters", types.ModuleName), - Long: "Get the current auction module parameters.", - 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(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } -} - -// GetCmdQueryAuction queries one auction in the store -func GetCmdQueryAuction() *cobra.Command { - return &cobra.Command{ - Use: "auction [auction-id]", - Short: "get info about an auction", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - auctionID, err := strconv.Atoi(args[0]) - if err != nil { - return err - } - - params := types.QueryAuctionRequest{ - AuctionId: uint64(auctionID), - } - - res, err := queryClient.Auction(context.Background(), ¶ms) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -// Query auction flags -const ( - flagType = "type" - flagDenom = "denom" - flagPhase = "phase" - flagOwner = "owner" -) - -// GetCmdQueryAuctions queries the auctions in the store -func GetCmdQueryAuctions() *cobra.Command { - cmd := &cobra.Command{ - Use: "auctions", - Short: "query auctions with optional filters", - Long: "Query for all paginated auctions that match optional filters.", - Example: strings.Join([]string{ - fmt.Sprintf(" $ %s q %s auctions --type=(collateral|surplus|debt)", version.AppName, types.ModuleName), - fmt.Sprintf(" $ %s q %s auctions --owner=kava1hatdq32u5x4wnxrtv5wzjzmq49sxgjgsj0mffm", version.AppName, types.ModuleName), - fmt.Sprintf(" $ %s q %s auctions --denom=bnb", version.AppName, types.ModuleName), - fmt.Sprintf(" $ %s q %s auctions --phase=(forward|reverse)", version.AppName, types.ModuleName), - fmt.Sprintf(" $ %s q %s auctions --page=2 --limit=100", version.AppName, types.ModuleName), - }, "\n"), - RunE: func(cmd *cobra.Command, args []string) error { - auctionType, err := cmd.Flags().GetString(flagType) - if err != nil { - return err - } - owner, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - phase, err := cmd.Flags().GetString(flagPhase) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - if len(auctionType) != 0 { - auctionType = strings.ToLower(auctionType) - - if auctionType != types.CollateralAuctionType && - auctionType != types.SurplusAuctionType && - auctionType != types.DebtAuctionType { - return fmt.Errorf("invalid auction type %s", auctionType) - } - } - - if len(owner) != 0 { - if auctionType != types.CollateralAuctionType { - return fmt.Errorf("cannot apply owner flag to non-collateral auction type") - } - _, err := sdk.AccAddressFromBech32(owner) - if err != nil { - return fmt.Errorf("cannot parse address from auction owner %s", owner) - } - } - - if len(denom) != 0 { - err := sdk.ValidateDenom(denom) - if err != nil { - return err - } - } - - if len(phase) != 0 { - phase = strings.ToLower(phase) - - if len(auctionType) > 0 && auctionType != types.CollateralAuctionType { - return fmt.Errorf("cannot apply phase flag to non-collateral auction type") - } - if phase != types.ForwardAuctionPhase && phase != types.ReverseAuctionPhase { - return fmt.Errorf("invalid auction phase %s", phase) - } - } - - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - request := types.QueryAuctionsRequest{ - Type: auctionType, - Owner: owner, - Denom: denom, - Phase: phase, - Pagination: pageReq, - } - - res, err := queryClient.Auctions(context.Background(), &request) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, "auctions") - - cmd.Flags().String(flagType, "", "(optional) filter by auction type, type: collateral, debt, surplus") - cmd.Flags().String(flagOwner, "", "(optional) filter by collateral auction owner") - cmd.Flags().String(flagDenom, "", "(optional) filter by auction denom") - cmd.Flags().String(flagPhase, "", "(optional) filter by collateral auction phase, phase: forward/reverse") - - return cmd -} diff --git a/x/auction/client/cli/tx.go b/x/auction/client/cli/tx.go deleted file mode 100644 index 49313450..00000000 --- a/x/auction/client/cli/tx.go +++ /dev/null @@ -1,70 +0,0 @@ -package cli - -import ( - "fmt" - "strconv" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/kava-labs/kava/x/auction/types" -) - -// GetTxCmd returns the transaction cli commands for this module -func GetTxCmd() *cobra.Command { - txCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "transaction commands for the auction module", - } - - cmds := []*cobra.Command{ - GetCmdPlaceBid(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - txCmd.AddCommand(cmds...) - - return txCmd -} - -// GetCmdPlaceBid cli command for placing bids on auctions -func GetCmdPlaceBid() *cobra.Command { - return &cobra.Command{ - Use: "bid [auction-id] [amount]", - Short: "place a bid on an auction", - Long: "Place a bid on any type of auction, updating the latest bid amount to [amount]. Collateral auctions must be bid up to their maxbid before entering reverse phase.", - Example: fmt.Sprintf(" $ %s tx %s bid 34 1000usdx --from myKeyName", version.AppName, types.ModuleName), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - id, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return fmt.Errorf("auction-id '%s' not a valid uint", args[0]) - } - - amt, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - msg := types.NewMsgPlaceBid(id, clientCtx.GetFromAddress().String(), amt) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} diff --git a/x/auction/genesis.go b/x/auction/genesis.go deleted file mode 100644 index f484d7d3..00000000 --- a/x/auction/genesis.go +++ /dev/null @@ -1,74 +0,0 @@ -package auction - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/auction/keeper" - "github.com/kava-labs/kava/x/auction/types" -) - -// InitGenesis initializes the store state from a genesis state. -func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, bankKeeper types.BankKeeper, accountKeeper types.AccountKeeper, gs *types.GenesisState) { - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - keeper.SetNextAuctionID(ctx, gs.NextAuctionId) - - keeper.SetParams(ctx, gs.Params) - - totalAuctionCoins := sdk.NewCoins() - - auctions, err := types.UnpackGenesisAuctions(gs.Auctions) - if err != nil { - panic(fmt.Sprintf("failed to unpack genesis auctions: %s", err)) - } - for _, a := range auctions { - keeper.SetAuction(ctx, a) - // find the total coins that should be present in the module account - totalAuctionCoins = totalAuctionCoins.Add(a.GetModuleAccountCoins()...) - } - - // check if the module account exists - moduleAcc := accountKeeper.GetModuleAccount(ctx, types.ModuleName) - if moduleAcc == nil { - panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) - } - - maccCoins := bankKeeper.GetAllBalances(ctx, moduleAcc.GetAddress()) - - // check module coins match auction coins - // Note: Other sdk modules do not check this, instead just using the existing module account coins, or if zero, setting them. - if !maccCoins.IsEqual(totalAuctionCoins) { - panic(fmt.Sprintf("total auction coins (%s) do not equal (%s) module account (%s) ", maccCoins, types.ModuleName, totalAuctionCoins)) - } -} - -// ExportGenesis returns a GenesisState for a given context and keeper. -func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) *types.GenesisState { - nextAuctionID, err := keeper.GetNextAuctionID(ctx) - if err != nil { - panic(err) - } - - params := keeper.GetParams(ctx) - - genAuctions := []types.GenesisAuction{} // return empty list instead of nil if no auctions - keeper.IterateAuctions(ctx, func(a types.Auction) bool { - ga, ok := a.(types.GenesisAuction) - if !ok { - panic("could not convert stored auction to GenesisAuction type") - } - genAuctions = append(genAuctions, ga) - return false - }) - - gs, err := types.NewGenesisState(nextAuctionID, params, genAuctions) - if err != nil { - panic(err) - } - - return gs -} diff --git a/x/auction/genesis_test.go b/x/auction/genesis_test.go deleted file mode 100644 index b8d32399..00000000 --- a/x/auction/genesis_test.go +++ /dev/null @@ -1,159 +0,0 @@ -package auction_test - -import ( - "sort" - "testing" - "time" - - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/auction" - "github.com/kava-labs/kava/x/auction/types" -) - -var ( - _, testAddrs = app.GeneratePrivKeyAddressPairs(2) - testTime = time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - testAuction = types.NewCollateralAuction( - "seller", - c("lotdenom", 10), - testTime, - c("biddenom", 1000), - types.WeightedAddresses{Addresses: testAddrs, Weights: []sdkmath.Int{sdk.OneInt(), sdk.OneInt()}}, - c("debt", 1000), - ).WithID(3).(types.GenesisAuction) -) - -func TestInitGenesis(t *testing.T) { - t.Run("valid", func(t *testing.T) { - // setup keepers - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - - // setup module account - modBaseAcc := authtypes.NewBaseAccount(authtypes.NewModuleAddress(types.ModuleName), nil, 0, 0) - modAcc := authtypes.NewModuleAccount(modBaseAcc, types.ModuleName, []string{authtypes.Minter, authtypes.Burner}...) - tApp.GetAccountKeeper().SetModuleAccount(ctx, modAcc) - tApp.GetBankKeeper().MintCoins(ctx, types.ModuleName, testAuction.GetModuleAccountCoins()) - - // set up auction genesis state with module account - auctionGS, err := types.NewGenesisState( - 10, - types.DefaultParams(), - []types.GenesisAuction{testAuction}, - ) - require.NoError(t, err) - - // run init - keeper := tApp.GetAuctionKeeper() - require.NotPanics(t, func() { - auction.InitGenesis(ctx, keeper, tApp.GetBankKeeper(), tApp.GetAccountKeeper(), auctionGS) - }) - - // check state is as expected - actualID, err := keeper.GetNextAuctionID(ctx) - require.NoError(t, err) - require.Equal(t, auctionGS.NextAuctionId, actualID) - - require.Equal(t, auctionGS.Params, keeper.GetParams(ctx)) - - genesisAuctions, err := types.UnpackGenesisAuctions(auctionGS.Auctions) - if err != nil { - panic(err) - } - - sort.Slice(genesisAuctions, func(i, j int) bool { - return genesisAuctions[i].GetID() > genesisAuctions[j].GetID() - }) - i := 0 - keeper.IterateAuctions(ctx, func(a types.Auction) bool { - require.Equal(t, genesisAuctions[i], a) - i++ - return false - }) - }) - t.Run("invalid (invalid nextAuctionID)", func(t *testing.T) { - // setup keepers - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - - // setup module account - modBaseAcc := authtypes.NewBaseAccount(authtypes.NewModuleAddress(types.ModuleName), nil, 0, 0) - modAcc := authtypes.NewModuleAccount(modBaseAcc, types.ModuleName, []string{authtypes.Minter, authtypes.Burner}...) - tApp.GetAccountKeeper().SetModuleAccount(ctx, modAcc) - tApp.GetBankKeeper().MintCoins(ctx, types.ModuleName, testAuction.GetModuleAccountCoins()) - - // create invalid genesis - auctionGS, err := types.NewGenesisState( - 0, // next id < testAuction ID - types.DefaultParams(), - []types.GenesisAuction{testAuction}, - ) - require.NoError(t, err) - - // check init fails - require.Panics(t, func() { - auction.InitGenesis(ctx, tApp.GetAuctionKeeper(), tApp.GetBankKeeper(), tApp.GetAccountKeeper(), auctionGS) - }) - }) - t.Run("invalid (missing mod account coins)", func(t *testing.T) { - // setup keepers - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - - // invalid as there is no module account setup - - // create invalid genesis - auctionGS, err := types.NewGenesisState( - 10, - types.DefaultParams(), - []types.GenesisAuction{testAuction}, - ) - require.NoError(t, err) - - // check init fails - require.Panics(t, func() { - auction.InitGenesis(ctx, tApp.GetAuctionKeeper(), tApp.GetBankKeeper(), tApp.GetAccountKeeper(), auctionGS) - }) - }) -} - -func TestExportGenesis(t *testing.T) { - t.Run("default", func(t *testing.T) { - // setup state - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - tApp.InitializeFromGenesisStates() - - // export - gs := auction.ExportGenesis(ctx, tApp.GetAuctionKeeper()) - - // check state matches - defaultGS := types.DefaultGenesisState() - require.Equal(t, defaultGS, gs) - }) - t.Run("one auction", func(t *testing.T) { - // setup state - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - tApp.InitializeFromGenesisStates() - tApp.GetAuctionKeeper().SetAuction(ctx, testAuction) - - // export - gs := auction.ExportGenesis(ctx, tApp.GetAuctionKeeper()) - - // check state matches - expectedGenesisState := types.DefaultGenesisState() - packedGenesisAuctions, err := types.PackGenesisAuctions([]types.GenesisAuction{testAuction}) - require.NoError(t, err) - - expectedGenesisState.Auctions = append(expectedGenesisState.Auctions, packedGenesisAuctions...) - require.Equal(t, expectedGenesisState, gs) - }) -} diff --git a/x/auction/keeper/auctions.go b/x/auction/keeper/auctions.go deleted file mode 100644 index 78af906b..00000000 --- a/x/auction/keeper/auctions.go +++ /dev/null @@ -1,583 +0,0 @@ -package keeper - -import ( - "errors" - "fmt" - "time" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - "github.com/kava-labs/kava/x/auction/types" -) - -// StartSurplusAuction starts a new surplus (forward) auction. -func (k Keeper) StartSurplusAuction(ctx sdk.Context, seller string, lot sdk.Coin, bidDenom string) (uint64, error) { - auction := types.NewSurplusAuction( - seller, - lot, - bidDenom, - types.DistantFuture, - ) - - // NOTE: for the duration of the auction the auction module account holds the lot - err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, seller, types.ModuleName, sdk.NewCoins(lot)) - if err != nil { - return 0, err - } - - auctionID, err := k.StoreNewAuction(ctx, &auction) - if err != nil { - return 0, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeAuctionStart, - sdk.NewAttribute(types.AttributeKeyAuctionID, fmt.Sprintf("%d", auctionID)), - sdk.NewAttribute(types.AttributeKeyAuctionType, auction.GetType()), - sdk.NewAttribute(types.AttributeKeyBid, auction.Bid.String()), - sdk.NewAttribute(types.AttributeKeyLot, auction.Lot.String()), - ), - ) - return auctionID, nil -} - -// StartDebtAuction starts a new debt (reverse) auction. -func (k Keeper) StartDebtAuction(ctx sdk.Context, buyer string, bid sdk.Coin, initialLot sdk.Coin, debt sdk.Coin) (uint64, error) { - auction := types.NewDebtAuction( - buyer, - bid, - initialLot, - types.DistantFuture, - debt, - ) - - // This auction type mints coins at close. Need to check module account has minting privileges to avoid potential err in endblocker. - macc := k.accountKeeper.GetModuleAccount(ctx, buyer) - if !macc.HasPermission(authtypes.Minter) { - panic(fmt.Errorf("module '%s' does not have '%s' permission", buyer, authtypes.Minter)) - } - - // NOTE: for the duration of the auction the auction module account holds the debt - err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, buyer, types.ModuleName, sdk.NewCoins(debt)) - if err != nil { - return 0, err - } - - auctionID, err := k.StoreNewAuction(ctx, &auction) - if err != nil { - return 0, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeAuctionStart, - sdk.NewAttribute(types.AttributeKeyAuctionID, fmt.Sprintf("%d", auctionID)), - sdk.NewAttribute(types.AttributeKeyAuctionType, auction.GetType()), - sdk.NewAttribute(types.AttributeKeyBid, auction.Bid.String()), - sdk.NewAttribute(types.AttributeKeyLot, auction.Lot.String()), - ), - ) - return auctionID, nil -} - -// StartCollateralAuction starts a new collateral (2-phase) auction. -func (k Keeper) StartCollateralAuction( - ctx sdk.Context, seller string, lot, maxBid sdk.Coin, - lotReturnAddrs []sdk.AccAddress, lotReturnWeights []sdkmath.Int, debt sdk.Coin, -) (uint64, error) { - weightedAddresses, err := types.NewWeightedAddresses(lotReturnAddrs, lotReturnWeights) - if err != nil { - return 0, err - } - auction := types.NewCollateralAuction( - seller, - lot, - types.DistantFuture, - maxBid, - weightedAddresses, - debt, - ) - - // NOTE: for the duration of the auction the auction module account holds the debt and the lot - err = k.bankKeeper.SendCoinsFromModuleToModule(ctx, seller, types.ModuleName, sdk.NewCoins(lot)) - if err != nil { - return 0, err - } - err = k.bankKeeper.SendCoinsFromModuleToModule(ctx, seller, types.ModuleName, sdk.NewCoins(debt)) - if err != nil { - return 0, err - } - - auctionID, err := k.StoreNewAuction(ctx, &auction) - if err != nil { - return 0, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeAuctionStart, - sdk.NewAttribute(types.AttributeKeyAuctionID, fmt.Sprintf("%d", auctionID)), - sdk.NewAttribute(types.AttributeKeyAuctionType, auction.GetType()), - sdk.NewAttribute(types.AttributeKeyBid, auction.Bid.String()), - sdk.NewAttribute(types.AttributeKeyLot, auction.Lot.String()), - sdk.NewAttribute(types.AttributeKeyMaxBid, auction.MaxBid.String()), - ), - ) - return auctionID, nil -} - -// PlaceBid places a bid on any auction. -func (k Keeper) PlaceBid(ctx sdk.Context, auctionID uint64, bidder sdk.AccAddress, newAmount sdk.Coin) error { - auction, found := k.GetAuction(ctx, auctionID) - if !found { - return errorsmod.Wrapf(types.ErrAuctionNotFound, "%d", auctionID) - } - - // validation common to all auctions - if ctx.BlockTime().After(auction.GetEndTime()) { - return errorsmod.Wrapf(types.ErrAuctionHasExpired, "%d", auctionID) - } - - // move coins and return updated auction - var ( - err error - updatedAuction types.Auction - ) - switch auctionType := auction.(type) { - case *types.SurplusAuction: - updatedAuction, err = k.PlaceBidSurplus(ctx, auctionType, bidder, newAmount) - case *types.DebtAuction: - updatedAuction, err = k.PlaceBidDebt(ctx, auctionType, bidder, newAmount) - case *types.CollateralAuction: - if !auctionType.IsReversePhase() { - updatedAuction, err = k.PlaceForwardBidCollateral(ctx, auctionType, bidder, newAmount) - } else { - updatedAuction, err = k.PlaceReverseBidCollateral(ctx, auctionType, bidder, newAmount) - } - default: - err = errorsmod.Wrap(types.ErrUnrecognizedAuctionType, auction.GetType()) - } - - if err != nil { - return err - } - - k.SetAuction(ctx, updatedAuction) - - return nil -} - -// PlaceBidSurplus places a forward bid on a surplus auction, moving coins and returning the updated auction. -func (k Keeper) PlaceBidSurplus(ctx sdk.Context, auction *types.SurplusAuction, bidder sdk.AccAddress, bid sdk.Coin) (*types.SurplusAuction, error) { - // Validate new bid - if bid.Denom != auction.Bid.Denom { - return auction, errorsmod.Wrapf(types.ErrInvalidBidDenom, "%s ≠ %s", bid.Denom, auction.Bid.Denom) - } - minNewBidAmt := auction.Bid.Amount.Add( // new bids must be some % greater than old bid, and at least 1 larger to avoid replacing an old bid at no cost - sdk.MaxInt( - sdkmath.NewInt(1), - sdk.NewDecFromInt(auction.Bid.Amount).Mul(k.GetParams(ctx).IncrementSurplus).RoundInt(), - ), - ) - if bid.Amount.LT(minNewBidAmt) { - return auction, errorsmod.Wrapf(types.ErrBidTooSmall, "%s < %s%s", bid, minNewBidAmt, auction.Bid.Denom) - } - - // New bidder pays back old bidder - // Catch edge cases of a bidder replacing their own bid, or the amount being zero (sending zero coins produces meaningless send events). - if !bidder.Equals(auction.Bidder) && !auction.Bid.IsZero() { // bidder isn't same as before AND previous auction bid must exist - err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, bidder, types.ModuleName, sdk.NewCoins(auction.Bid)) - if err != nil { - return auction, err - } - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, auction.Bidder, sdk.NewCoins(auction.Bid)) - if err != nil { - return auction, err - } - } - - err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, bidder, auction.Initiator, sdk.NewCoins(bid.Sub(auction.Bid))) - if err != nil { - return auction, err - } - - // Received bid amount is burned from the module account - err = k.bankKeeper.BurnCoins(ctx, auction.Initiator, sdk.NewCoins(bid.Sub(auction.Bid))) - if err != nil { - return auction, err - } - - // Update Auction - auction.Bidder = bidder - auction.Bid = bid - if !auction.HasReceivedBids { - auction.MaxEndTime = ctx.BlockTime().Add(k.GetParams(ctx).MaxAuctionDuration) // set maximum ending time on receipt of first bid - auction.HasReceivedBids = true - } - auction.EndTime = earliestTime(ctx.BlockTime().Add(k.GetParams(ctx).ForwardBidDuration), auction.MaxEndTime) // increment timeout, up to MaxEndTime - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeAuctionBid, - sdk.NewAttribute(types.AttributeKeyAuctionID, fmt.Sprintf("%d", auction.ID)), - sdk.NewAttribute(types.AttributeKeyBidder, auction.Bidder.String()), - sdk.NewAttribute(types.AttributeKeyBid, auction.Bid.String()), - sdk.NewAttribute(types.AttributeKeyEndTime, fmt.Sprintf("%d", auction.EndTime.Unix())), - ), - ) - - return auction, nil -} - -// PlaceForwardBidCollateral places a forward bid on a collateral auction, moving coins and returning the updated auction. -func (k Keeper) PlaceForwardBidCollateral(ctx sdk.Context, auction *types.CollateralAuction, bidder sdk.AccAddress, bid sdk.Coin) (*types.CollateralAuction, error) { - // Validate new bid - if bid.Denom != auction.Bid.Denom { - return auction, errorsmod.Wrapf(types.ErrInvalidBidDenom, "%s ≠ %s", bid.Denom, auction.Bid.Denom) - } - if auction.IsReversePhase() { - panic("cannot place reverse bid on auction in forward phase") - } - minNewBidAmt := auction.Bid.Amount.Add( // new bids must be some % greater than old bid, and at least 1 larger to avoid replacing an old bid at no cost - sdk.MaxInt( - sdkmath.NewInt(1), - sdk.NewDecFromInt(auction.Bid.Amount).Mul(k.GetParams(ctx).IncrementCollateral).RoundInt(), - ), - ) - minNewBidAmt = sdk.MinInt(minNewBidAmt, auction.MaxBid.Amount) // allow new bids to hit MaxBid even though it may be less than the increment % - if bid.Amount.LT(minNewBidAmt) { - return auction, errorsmod.Wrapf(types.ErrBidTooSmall, "%s < %s%s", bid, minNewBidAmt, auction.Bid.Denom) - } - if auction.MaxBid.IsLT(bid) { - return auction, errorsmod.Wrapf(types.ErrBidTooLarge, "%s > %s", bid, auction.MaxBid) - } - - // New bidder pays back old bidder - // Catch edge cases of a bidder replacing their own bid, and the amount being zero (sending zero coins produces meaningless send events). - if !bidder.Equals(auction.Bidder) && !auction.Bid.IsZero() { - err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, bidder, types.ModuleName, sdk.NewCoins(auction.Bid)) - if err != nil { - return auction, err - } - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, auction.Bidder, sdk.NewCoins(auction.Bid)) - if err != nil { - return auction, err - } - } - // Increase in bid sent to auction initiator - bidIncrement := bid.Sub(auction.Bid) - err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, bidder, auction.Initiator, sdk.NewCoins(bidIncrement)) - if err != nil { - return auction, err - } - // Debt coins are sent to liquidator (until there is no CorrespondingDebt left). Amount sent is equal to bidIncrement (or whatever is left if < bidIncrement). - if auction.CorrespondingDebt.IsPositive() { - - debtAmountToReturn := sdk.MinInt(bidIncrement.Amount, auction.CorrespondingDebt.Amount) - debtToReturn := sdk.NewCoin(auction.CorrespondingDebt.Denom, debtAmountToReturn) - - err = k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, auction.Initiator, sdk.NewCoins(debtToReturn)) - if err != nil { - return auction, err - } - auction.CorrespondingDebt = auction.CorrespondingDebt.Sub(debtToReturn) // debtToReturn will always be ≤ auction.CorrespondingDebt from the MinInt above - } - - // Update Auction - auction.Bidder = bidder - auction.Bid = bid - if !auction.HasReceivedBids { - auction.MaxEndTime = ctx.BlockTime().Add(k.GetParams(ctx).MaxAuctionDuration) // set maximum ending time on receipt of first bid - auction.HasReceivedBids = true - } - - // If this forward bid converts this to a reverse, increase timeout with ReverseBidDuration - if auction.IsReversePhase() { - auction.EndTime = earliestTime(ctx.BlockTime().Add(k.GetParams(ctx).ReverseBidDuration), auction.MaxEndTime) // increment timeout, up to MaxEndTime - } else { - auction.EndTime = earliestTime(ctx.BlockTime().Add(k.GetParams(ctx).ForwardBidDuration), auction.MaxEndTime) // increment timeout, up to MaxEndTime - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeAuctionBid, - sdk.NewAttribute(types.AttributeKeyAuctionID, fmt.Sprintf("%d", auction.ID)), - sdk.NewAttribute(types.AttributeKeyBidder, auction.Bidder.String()), - sdk.NewAttribute(types.AttributeKeyBid, auction.Bid.String()), - sdk.NewAttribute(types.AttributeKeyEndTime, fmt.Sprintf("%d", auction.EndTime.Unix())), - ), - ) - - return auction, nil -} - -// PlaceReverseBidCollateral places a reverse bid on a collateral auction, moving coins and returning the updated auction. -func (k Keeper) PlaceReverseBidCollateral(ctx sdk.Context, auction *types.CollateralAuction, bidder sdk.AccAddress, lot sdk.Coin) (*types.CollateralAuction, error) { - // Validate new bid - if lot.Denom != auction.Lot.Denom { - return auction, errorsmod.Wrapf(types.ErrInvalidLotDenom, "%s ≠ %s", lot.Denom, auction.Lot.Denom) - } - if !auction.IsReversePhase() { - panic("cannot place forward bid on auction in reverse phase") - } - maxNewLotAmt := auction.Lot.Amount.Sub( // new lot must be some % less than old lot, and at least 1 smaller to avoid replacing an old bid at no cost - sdk.MaxInt( - sdkmath.NewInt(1), - sdk.NewDecFromInt(auction.Lot.Amount).Mul(k.GetParams(ctx).IncrementCollateral).RoundInt(), - ), - ) - if lot.Amount.GT(maxNewLotAmt) { - return auction, errorsmod.Wrapf(types.ErrLotTooLarge, "%s > %s%s", lot, maxNewLotAmt, auction.Lot.Denom) - } - if lot.IsNegative() { - return auction, errorsmod.Wrapf(types.ErrLotTooSmall, "%s < 0%s", lot, auction.Lot.Denom) - } - - // New bidder pays back old bidder - // Catch edge cases of a bidder replacing their own bid - if !bidder.Equals(auction.Bidder) { - err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, bidder, types.ModuleName, sdk.NewCoins(auction.Bid)) - if err != nil { - return auction, err - } - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, auction.Bidder, sdk.NewCoins(auction.Bid)) - if err != nil { - return auction, err - } - } - - // Decrease in lot is sent to weighted addresses (normally the CDP depositors) - // Note: splitting an integer amount across weighted buckets results in small errors. - lotPayouts, err := splitCoinIntoWeightedBuckets(auction.Lot.Sub(lot), auction.LotReturns.Weights) - if err != nil { - return auction, err - } - for i, payout := range lotPayouts { - // if the payout amount is 0, don't send 0 coins - if !payout.IsPositive() { - continue - } - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, auction.LotReturns.Addresses[i], sdk.NewCoins(payout)) - if err != nil { - return auction, err - } - } - - // Update Auction - auction.Bidder = bidder - auction.Lot = lot - if !auction.HasReceivedBids { - auction.MaxEndTime = ctx.BlockTime().Add(k.GetParams(ctx).MaxAuctionDuration) // set maximum ending time on receipt of first bid - auction.HasReceivedBids = true - } - auction.EndTime = earliestTime(ctx.BlockTime().Add(k.GetParams(ctx).ReverseBidDuration), auction.MaxEndTime) // increment timeout, up to MaxEndTime - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeAuctionBid, - sdk.NewAttribute(types.AttributeKeyAuctionID, fmt.Sprintf("%d", auction.ID)), - sdk.NewAttribute(types.AttributeKeyBidder, auction.Bidder.String()), - sdk.NewAttribute(types.AttributeKeyLot, auction.Lot.String()), - sdk.NewAttribute(types.AttributeKeyEndTime, fmt.Sprintf("%d", auction.EndTime.Unix())), - ), - ) - - return auction, nil -} - -// PlaceBidDebt places a reverse bid on a debt auction, moving coins and returning the updated auction. -func (k Keeper) PlaceBidDebt(ctx sdk.Context, auction *types.DebtAuction, bidder sdk.AccAddress, lot sdk.Coin) (*types.DebtAuction, error) { - // Validate new bid - if lot.Denom != auction.Lot.Denom { - return auction, errorsmod.Wrapf(types.ErrInvalidLotDenom, "%s ≠ %s", lot.Denom, auction.Lot.Denom) - } - maxNewLotAmt := auction.Lot.Amount.Sub( // new lot must be some % less than old lot, and at least 1 smaller to avoid replacing an old bid at no cost - sdk.MaxInt( - sdkmath.NewInt(1), - sdk.NewDecFromInt(auction.Lot.Amount).Mul(k.GetParams(ctx).IncrementDebt).RoundInt(), - ), - ) - if lot.Amount.GT(maxNewLotAmt) { - return auction, errorsmod.Wrapf(types.ErrLotTooLarge, "%s > %s%s", lot, maxNewLotAmt, auction.Lot.Denom) - } - if lot.IsNegative() { - return auction, errorsmod.Wrapf(types.ErrLotTooSmall, "%s ≤ %s%s", lot, sdk.ZeroInt(), auction.Lot.Denom) - } - - // New bidder pays back old bidder - // Catch edge cases of a bidder replacing their own bid - if !bidder.Equals(auction.Bidder) { - // Bidder sends coins to module - err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, bidder, types.ModuleName, sdk.NewCoins(auction.Bid)) - if err != nil { - return auction, err - } - // Coins are sent from module to old bidder - oldBidder := auction.Bidder - if oldBidder.Equals(authtypes.NewModuleAddress(auction.Initiator)) { // First bid on auction (where there is no previous bidder) - err = k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, auction.Initiator, sdk.NewCoins(auction.Bid)) - } else { // Second and later bids on auction (where previous bidder is a user account) - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, oldBidder, sdk.NewCoins(auction.Bid)) - } - if err != nil { - return auction, err - } - } - - // Debt coins are sent to liquidator the first time a bid is placed. Amount sent is equal to min of Bid and amount of debt. - if auction.Bidder.Equals(authtypes.NewModuleAddress(auction.Initiator)) { - // Handle debt coins for first bid - debtAmountToReturn := sdk.MinInt(auction.Bid.Amount, auction.CorrespondingDebt.Amount) - debtToReturn := sdk.NewCoin(auction.CorrespondingDebt.Denom, debtAmountToReturn) - - err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, auction.Initiator, sdk.NewCoins(debtToReturn)) - if err != nil { - return auction, err - } - auction.CorrespondingDebt = auction.CorrespondingDebt.Sub(debtToReturn) // debtToReturn will always be ≤ auction.CorrespondingDebt from the MinInt above - } - - // Update Auction - auction.Bidder = bidder - auction.Lot = lot - if !auction.HasReceivedBids { - auction.MaxEndTime = ctx.BlockTime().Add(k.GetParams(ctx).MaxAuctionDuration) // set maximum ending time on receipt of first bid - auction.HasReceivedBids = true - } - auction.EndTime = earliestTime(ctx.BlockTime().Add(k.GetParams(ctx).ForwardBidDuration), auction.MaxEndTime) // increment timeout, up to MaxEndTime - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeAuctionBid, - sdk.NewAttribute(types.AttributeKeyAuctionID, fmt.Sprintf("%d", auction.ID)), - sdk.NewAttribute(types.AttributeKeyBidder, auction.Bidder.String()), - sdk.NewAttribute(types.AttributeKeyLot, auction.Lot.String()), - sdk.NewAttribute(types.AttributeKeyEndTime, fmt.Sprintf("%d", auction.EndTime.Unix())), - ), - ) - - return auction, nil -} - -// CloseAuction closes an auction and distributes funds to the highest bidder. -func (k Keeper) CloseAuction(ctx sdk.Context, auctionID uint64) error { - auction, found := k.GetAuction(ctx, auctionID) - if !found { - return errorsmod.Wrapf(types.ErrAuctionNotFound, "%d", auctionID) - } - - if ctx.BlockTime().Before(auction.GetEndTime()) { - return errorsmod.Wrapf(types.ErrAuctionHasNotExpired, "block time %s, auction end time %s", ctx.BlockTime().UTC(), auction.GetEndTime().UTC()) - } - - // payout to the last bidder - var err error - switch auc := auction.(type) { - case *types.SurplusAuction: - err = k.PayoutSurplusAuction(ctx, auc) - case *types.DebtAuction: - err = k.PayoutDebtAuction(ctx, auc) - case *types.CollateralAuction: - err = k.PayoutCollateralAuction(ctx, auc) - default: - err = errorsmod.Wrap(types.ErrUnrecognizedAuctionType, auc.GetType()) - } - - if err != nil { - return err - } - - k.DeleteAuction(ctx, auctionID) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeAuctionClose, - sdk.NewAttribute(types.AttributeKeyAuctionID, fmt.Sprintf("%d", auctionID)), - sdk.NewAttribute(types.AttributeKeyCloseBlock, fmt.Sprintf("%d", ctx.BlockHeight())), - ), - ) - return nil -} - -// PayoutDebtAuction pays out the proceeds for a debt auction, first minting the coins. -func (k Keeper) PayoutDebtAuction(ctx sdk.Context, auction *types.DebtAuction) error { - // create the coins that are needed to pay off the debt - err := k.bankKeeper.MintCoins(ctx, auction.Initiator, sdk.NewCoins(auction.Lot)) - if err != nil { - panic(fmt.Errorf("could not mint coins: %w", err)) - } - // send the new coins from the initiator module to the bidder - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, auction.Initiator, auction.Bidder, sdk.NewCoins(auction.Lot)) - if err != nil { - return err - } - // if there is remaining debt, return it to the calling module to manage - if !auction.CorrespondingDebt.IsPositive() { - return nil - } - - return k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, auction.Initiator, sdk.NewCoins(auction.CorrespondingDebt)) -} - -// PayoutSurplusAuction pays out the proceeds for a surplus auction. -func (k Keeper) PayoutSurplusAuction(ctx sdk.Context, auction *types.SurplusAuction) error { - // Send the tokens from the auction module account where they are being managed to the bidder who won the auction - return k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, auction.Bidder, sdk.NewCoins(auction.Lot)) -} - -// PayoutCollateralAuction pays out the proceeds for a collateral auction. -func (k Keeper) PayoutCollateralAuction(ctx sdk.Context, auction *types.CollateralAuction) error { - // Send the tokens from the auction module account where they are being managed to the bidder who won the auction - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, auction.Bidder, sdk.NewCoins(auction.Lot)) - if err != nil { - return err - } - - // if there is remaining debt after the auction, send it back to the initiating module for management - if !auction.CorrespondingDebt.IsPositive() { - return nil - } - - return k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, auction.Initiator, sdk.NewCoins(auction.CorrespondingDebt)) -} - -// CloseExpiredAuctions iterates over all the auctions stored by until the current -// block timestamp and that are past (or at) their ending times and closes them, -// paying out to the highest bidder. -func (k Keeper) CloseExpiredAuctions(ctx sdk.Context) error { - var err error - k.IterateAuctionsByTime(ctx, ctx.BlockTime(), func(id uint64) (stop bool) { - err = k.CloseAuction(ctx, id) - if err != nil && !errors.Is(err, types.ErrAuctionNotFound) { - // stop iteration - return true - } - // reset error in case the last element had an ErrAuctionNotFound - err = nil - return false - }) - - return err -} - -// earliestTime returns the earliest of two times. -func earliestTime(t1, t2 time.Time) time.Time { - if t1.Before(t2) { - return t1 - } - return t2 // also returned if times are equal -} - -// splitCoinIntoWeightedBuckets divides up some amount of coins according to some weights. -func splitCoinIntoWeightedBuckets(coin sdk.Coin, buckets []sdkmath.Int) ([]sdk.Coin, error) { - amounts := splitIntIntoWeightedBuckets(coin.Amount, buckets) - result := make([]sdk.Coin, len(amounts)) - for i, a := range amounts { - result[i] = sdk.NewCoin(coin.Denom, a) - } - return result, nil -} diff --git a/x/auction/keeper/auctions_test.go b/x/auction/keeper/auctions_test.go deleted file mode 100644 index b61836c3..00000000 --- a/x/auction/keeper/auctions_test.go +++ /dev/null @@ -1,319 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - "github.com/kava-labs/kava/x/auction/testutil" - "github.com/kava-labs/kava/x/auction/types" -) - -type auctionTestSuite struct { - testutil.Suite -} - -func (suite *auctionTestSuite) SetupTest() { - suite.Suite.SetupTest(4) -} - -func TestAuctionTestSuite(t *testing.T) { - suite.Run(t, new(auctionTestSuite)) -} - -func (suite *auctionTestSuite) TestSurplusAuctionBasic() { - buyer := suite.Addrs[0] - - // TODO: use cdp.LiquidatorMacc once CDP module is available - // sellerModName := cdp.LiquidatorMacc - sellerAddr := authtypes.NewModuleAddress(suite.ModAcc.Name) - suite.AddCoinsToNamedModule(suite.ModAcc.Name, cs(c("token1", 100), c("token2", 100))) - - // Create an auction (lot: 20 token1, initialBid: 0 token2) - auctionID, err := suite.Keeper.StartSurplusAuction(suite.Ctx, suite.ModAcc.Name, c("token1", 20), "token2") // lobid denom - suite.NoError(err) - // Check seller's coins have decreased - suite.CheckAccountBalanceEqual(sellerAddr, cs(c("token1", 80), c("token2", 100))) - - // PlaceBid (bid: 10 token, lot: same as starting) - suite.NoError(suite.Keeper.PlaceBid(suite.Ctx, auctionID, buyer, c("token2", 10))) - // Check buyer's coins have decreased - suite.CheckAccountBalanceEqual(buyer, cs(c("token1", 100), c("token2", 90))) - // Check seller's coins have not increased (because proceeds are burned) - suite.CheckAccountBalanceEqual(sellerAddr, cs(c("token1", 80), c("token2", 100))) - - // increment bid same bidder - err = suite.Keeper.PlaceBid(suite.Ctx, auctionID, buyer, c("token2", 20)) - suite.NoError(err) - - // Close auction just at auction expiry time - suite.Ctx = suite.Ctx.WithBlockTime(suite.Ctx.BlockTime().Add(types.DefaultForwardBidDuration)) - suite.NoError(suite.Keeper.CloseAuction(suite.Ctx, auctionID)) - // Check buyer's coins increased - suite.CheckAccountBalanceEqual(buyer, cs(c("token1", 120), c("token2", 80))) -} - -func (suite *auctionTestSuite) TestDebtAuctionBasic() { - // Setup - seller := suite.Addrs[0] - suite.AddCoinsToNamedModule(suite.ModAcc.Name, cs(c("debt", 100))) - - // Start auction - auctionID, err := suite.Keeper.StartDebtAuction(suite.Ctx, suite.ModAcc.Name, c("token1", 20), c("token2", 99999), c("debt", 20)) - suite.NoError(err) - // Check buyer's coins have not decreased (except for debt), as lot is minted at the end - suite.CheckAccountBalanceEqual(suite.ModAcc.GetAddress(), cs(c("debt", 80))) - - // Place a bid - suite.NoError(suite.Keeper.PlaceBid(suite.Ctx, auctionID, seller, c("token2", 10))) - - // Check seller's coins have decreased - suite.CheckAccountBalanceEqual(seller, cs(c("token1", 80), c("token2", 100))) - // Check buyer's coins have increased - suite.CheckAccountBalanceEqual(suite.ModAcc.GetAddress(), cs(c("token1", 20), c("debt", 100))) - - // Close auction at just after auction expiry - ctx := suite.Ctx.WithBlockTime(suite.Ctx.BlockTime().Add(types.DefaultForwardBidDuration)) - suite.NoError(suite.Keeper.CloseAuction(ctx, auctionID)) - // Check seller's coins increased - suite.CheckAccountBalanceEqual(seller, cs(c("token1", 80), c("token2", 110))) -} - -func (suite *auctionTestSuite) TestDebtAuctionDebtRemaining() { - seller := suite.Addrs[0] - - buyerAddr := authtypes.NewModuleAddress(suite.ModAcc.Name) - suite.AddCoinsToNamedModule(suite.ModAcc.Name, cs(c("debt", 100))) - - // Start auction - auctionID, err := suite.Keeper.StartDebtAuction(suite.Ctx, suite.ModAcc.Name, c("token1", 10), c("token2", 99999), c("debt", 20)) - suite.NoError(err) - // Check buyer's coins have not decreased (except for debt), as lot is minted at the end - suite.CheckAccountBalanceEqual(buyerAddr, cs(c("debt", 80))) - - // Place a bid - suite.NoError(suite.Keeper.PlaceBid(suite.Ctx, auctionID, seller, c("token2", 10))) - // Check seller's coins have decreased - suite.CheckAccountBalanceEqual(seller, cs(c("token1", 90), c("token2", 100))) - // Check buyer's coins have increased - suite.CheckAccountBalanceEqual(buyerAddr, cs(c("token1", 10), c("debt", 90))) - - // Close auction at just after auction expiry - ctx := suite.Ctx.WithBlockTime(suite.Ctx.BlockTime().Add(types.DefaultForwardBidDuration)) - suite.NoError(suite.Keeper.CloseAuction(ctx, auctionID)) - // Check seller's coins increased - suite.CheckAccountBalanceEqual(seller, cs(c("token1", 90), c("token2", 110))) - // check that debt has increased due to corresponding debt being greater than bid - suite.CheckAccountBalanceEqual(buyerAddr, cs(c("token1", 10), c("debt", 100))) -} - -func (suite *auctionTestSuite) TestCollateralAuctionBasic() { - // Setup - buyer := suite.Addrs[0] - returnAddrs := suite.Addrs[1:] - returnWeights := is(30, 20, 10) - sellerModName := suite.ModAcc.Name - sellerAddr := suite.ModAcc.GetAddress() - suite.AddCoinsToNamedModule(sellerModName, cs(c("token1", 100), c("token2", 100), c("debt", 100))) - - // Start auction - auctionID, err := suite.Keeper.StartCollateralAuction(suite.Ctx, sellerModName, c("token1", 20), c("token2", 50), returnAddrs, returnWeights, c("debt", 40)) - suite.NoError(err) - // Check seller's coins have decreased - suite.CheckAccountBalanceEqual(sellerAddr, cs(c("token1", 80), c("token2", 100), c("debt", 60))) - - // Place a forward bid - suite.NoError(suite.Keeper.PlaceBid(suite.Ctx, auctionID, buyer, c("token2", 10))) - // Check bidder's coins have decreased - suite.CheckAccountBalanceEqual(buyer, cs(c("token1", 100), c("token2", 90))) - // Check seller's coins have increased - suite.CheckAccountBalanceEqual(sellerAddr, cs(c("token1", 80), c("token2", 110), c("debt", 70))) - // Check return addresses have not received coins - for _, ra := range suite.Addrs[1:] { - suite.CheckAccountBalanceEqual(ra, cs(c("token1", 100), c("token2", 100))) - } - - // Place a reverse bid - suite.NoError(suite.Keeper.PlaceBid(suite.Ctx, auctionID, buyer, c("token2", 50))) // first bid up to max bid to switch phases - suite.NoError(suite.Keeper.PlaceBid(suite.Ctx, auctionID, buyer, c("token1", 15))) - // Check bidder's coins have decreased - suite.CheckAccountBalanceEqual(buyer, cs(c("token1", 100), c("token2", 50))) - // Check seller's coins have increased - suite.CheckAccountBalanceEqual(sellerAddr, cs(c("token1", 80), c("token2", 150), c("debt", 100))) - // Check return addresses have received coins - suite.CheckAccountBalanceEqual(suite.Addrs[1], cs(c("token1", 102), c("token2", 100))) - suite.CheckAccountBalanceEqual(suite.Addrs[2], cs(c("token1", 102), c("token2", 100))) - suite.CheckAccountBalanceEqual(suite.Addrs[3], cs(c("token1", 101), c("token2", 100))) - - // Close auction at just after auction expiry - ctx := suite.Ctx.WithBlockTime(suite.Ctx.BlockTime().Add(types.DefaultReverseBidDuration)) - suite.NoError(suite.Keeper.CloseAuction(ctx, auctionID)) - // Check buyer's coins increased - suite.CheckAccountBalanceEqual(buyer, cs(c("token1", 115), c("token2", 50))) -} - -func (suite *auctionTestSuite) TestCollateralAuctionDebtRemaining() { - // Setup - buyer := suite.Addrs[0] - returnAddrs := suite.Addrs[1:] - returnWeights := is(30, 20, 10) - sellerModName := suite.ModAcc.Name - sellerAddr := suite.ModAcc.GetAddress() - suite.AddCoinsToNamedModule(sellerModName, cs(c("token1", 100), c("token2", 100), c("debt", 100))) - - // Start auction - auctionID, err := suite.Keeper.StartCollateralAuction(suite.Ctx, sellerModName, c("token1", 20), c("token2", 50), returnAddrs, returnWeights, c("debt", 40)) - suite.NoError(err) - // Check seller's coins have decreased - suite.CheckAccountBalanceEqual(sellerAddr, cs(c("token1", 80), c("token2", 100), c("debt", 60))) - - // Place a forward bid - suite.NoError(suite.Keeper.PlaceBid(suite.Ctx, auctionID, buyer, c("token2", 10))) - // Check bidder's coins have decreased - suite.CheckAccountBalanceEqual(buyer, cs(c("token1", 100), c("token2", 90))) - // Check seller's coins have increased - suite.CheckAccountBalanceEqual(sellerAddr, cs(c("token1", 80), c("token2", 110), c("debt", 70))) - // Check return addresses have not received coins - for _, ra := range suite.Addrs[1:] { - suite.CheckAccountBalanceEqual(ra, cs(c("token1", 100), c("token2", 100))) - } - ctx := suite.Ctx.WithBlockTime(suite.Ctx.BlockTime().Add(types.DefaultForwardBidDuration)) - suite.NoError(suite.Keeper.CloseAuction(ctx, auctionID)) - - // check that buyers coins have increased - suite.CheckAccountBalanceEqual(buyer, cs(c("token1", 120), c("token2", 90))) - // Check return addresses have not received coins - for _, ra := range suite.Addrs[1:] { - suite.CheckAccountBalanceEqual(ra, cs(c("token1", 100), c("token2", 100))) - } - // check that token2 has increased by 10, debt by 40, for a net debt increase of 30 debt - suite.CheckAccountBalanceEqual(sellerAddr, cs(c("token1", 80), c("token2", 110), c("debt", 100))) -} - -func (suite *auctionTestSuite) TestStartSurplusAuction() { - someTime := time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC) - type args struct { - seller string - lot sdk.Coin - bidDenom string - } - testCases := []struct { - name string - blockTime time.Time - args args - expectPass bool - expPanic bool - }{ - { - "normal", - someTime, - args{suite.ModAcc.Name, c("stable", 10), "gov"}, - true, false, - }, - { - "no module account", - someTime, - args{"nonExistentModule", c("stable", 10), "gov"}, - false, true, - }, - { - "not enough coins", - someTime, - args{suite.ModAcc.Name, c("stable", 101), "gov"}, - false, false, - }, - { - "incorrect denom", - someTime, - args{suite.ModAcc.Name, c("notacoin", 10), "gov"}, - false, false, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - // setup - initialLiquidatorCoins := cs(c("stable", 100)) - suite.AddCoinsToNamedModule(suite.ModAcc.Name, initialLiquidatorCoins) - - // run function under test - var ( - id uint64 - err error - ) - if tc.expPanic { - suite.Panics(func() { - _, _ = suite.Keeper.StartSurplusAuction(suite.Ctx, tc.args.seller, tc.args.lot, tc.args.bidDenom) - }, tc.name) - } else { - id, err = suite.Keeper.StartSurplusAuction(suite.Ctx, tc.args.seller, tc.args.lot, tc.args.bidDenom) - } - - // check - liquidatorCoins := suite.BankKeeper.GetAllBalances(suite.Ctx, suite.ModAcc.GetAddress()) - actualAuc, found := suite.Keeper.GetAuction(suite.Ctx, id) - if tc.expectPass { - suite.NoError(err, tc.name) - // check coins moved - suite.Equal(initialLiquidatorCoins.Sub(tc.args.lot), liquidatorCoins, tc.name) - // check auction in store and is correct - suite.True(found, tc.name) - - surplusAuction := types.SurplusAuction{BaseAuction: types.BaseAuction{ - ID: id, - Initiator: tc.args.seller, - Lot: tc.args.lot, - Bidder: nil, - Bid: c(tc.args.bidDenom, 0), - HasReceivedBids: false, - EndTime: types.DistantFuture, - MaxEndTime: types.DistantFuture, - }} - suite.Equal(&surplusAuction, actualAuc, tc.name) - } else if !tc.expPanic && !tc.expectPass { - suite.Error(err, tc.name) - // check coins not moved - suite.Equal(initialLiquidatorCoins, liquidatorCoins, tc.name) - // check auction not in store - suite.False(found, tc.name) - } - }) - } -} - -func (suite *auctionTestSuite) TestCloseAuction() { - suite.AddCoinsToNamedModule(suite.ModAcc.Name, cs(c("token1", 100), c("token2", 100))) - - // Create an auction (lot: 20 token1, initialBid: 0 token2) - id, err := suite.Keeper.StartSurplusAuction(suite.Ctx, suite.ModAcc.Name, c("token1", 20), "token2") // lot, bid denom - suite.NoError(err) - - // Attempt to close the auction before EndTime - suite.Error(suite.Keeper.CloseAuction(suite.Ctx, id)) - - // Attempt to close auction that does not exist - suite.Error(suite.Keeper.CloseAuction(suite.Ctx, 999)) -} - -func (suite *auctionTestSuite) TestCloseExpiredAuctions() { - suite.AddCoinsToNamedModule(suite.ModAcc.Name, cs(c("token1", 100), c("token2", 100))) - - // Start auction 1 - _, err := suite.Keeper.StartSurplusAuction(suite.Ctx, suite.ModAcc.Name, c("token1", 20), "token2") // lot, bid denom - suite.NoError(err) - - // Start auction 2 - _, err = suite.Keeper.StartSurplusAuction(suite.Ctx, suite.ModAcc.Name, c("token1", 20), "token2") // lot, bid denom - suite.NoError(err) - - // Fast forward the block time - ctx := suite.Ctx.WithBlockTime(suite.Ctx.BlockTime().Add(types.DefaultMaxAuctionDuration).Add(1)) - - // Close expired auctions - err = suite.Keeper.CloseExpiredAuctions(ctx) - suite.NoError(err) -} diff --git a/x/auction/keeper/bidding_test.go b/x/auction/keeper/bidding_test.go deleted file mode 100644 index 5918e62c..00000000 --- a/x/auction/keeper/bidding_test.go +++ /dev/null @@ -1,591 +0,0 @@ -package keeper_test - -import ( - "strings" - "testing" - "time" - - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/auction/types" -) - -type AuctionType int - -const ( - Invalid AuctionType = 0 - Surplus AuctionType = 1 - Debt AuctionType = 2 - Collateral AuctionType = 3 -) - -func TestAuctionBidding(t *testing.T) { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - someTime := time.Date(0o001, time.January, 1, 0, 0, 0, 0, time.UTC) - - _, addrs := app.GeneratePrivKeyAddressPairs(5) - buyer := addrs[0] - secondBuyer := addrs[1] - modName := "liquidator" - collateralAddrs := addrs[2:] - collateralWeights := is(30, 20, 10) - - initialBalance := cs(c("token1", 1000), c("token2", 1000)) - - type auctionArgs struct { - auctionType AuctionType - seller string - lot sdk.Coin - bid sdk.Coin - debt sdk.Coin - addresses []sdk.AccAddress - weights []sdkmath.Int - } - - type bidArgs struct { - bidder sdk.AccAddress - amount sdk.Coin - } - - tests := []struct { - name string - auctionArgs auctionArgs - setupBids []bidArgs - bidArgs bidArgs - expectedError error - expectedEndTime time.Time - expectedBidder sdk.AccAddress - expectedBid sdk.Coin - expectPass bool - expectPanic bool - }{ - { - "basic: auction doesn't exist", - auctionArgs{Surplus, "", c("token1", 1), c("token2", 1), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}}, - nil, - bidArgs{buyer, c("token2", 10)}, - types.ErrAuctionNotFound, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 10), - false, - true, - }, - { - "basic: closed auction", - auctionArgs{Surplus, modName, c("token1", 100), c("token2", 10), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}}, - nil, - bidArgs{buyer, c("token2", 10)}, - types.ErrAuctionHasExpired, - types.DistantFuture, - nil, - c("token2", 0), - false, - false, - }, - { - // This is the first bid on an auction with NO bids - "surplus: normal", - auctionArgs{Surplus, modName, c("token1", 100), c("token2", 10), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}}, - nil, - bidArgs{buyer, c("token2", 10)}, - nil, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 10), - true, - false, - }, - { - "surplus: second bidder", - auctionArgs{Surplus, modName, c("token1", 100), c("token2", 10), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}}, - []bidArgs{{buyer, c("token2", 10)}}, - bidArgs{secondBuyer, c("token2", 11)}, - nil, - someTime.Add(types.DefaultForwardBidDuration), - secondBuyer, - c("token2", 11), - true, - false, - }, - { - "surplus: invalid bid denom", - auctionArgs{Surplus, modName, c("token1", 100), c("token2", 10), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}}, - nil, - bidArgs{buyer, c("badtoken", 10)}, - types.ErrInvalidBidDenom, - types.DistantFuture, - nil, // surplus auctions are created with initial bidder as a nil address - c("token2", 0), - false, - false, - }, - { - "surplus: invalid bid (less than)", - auctionArgs{Surplus, modName, c("token1", 100), c("token2", 0), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}}, - []bidArgs{{buyer, c("token2", 100)}}, - bidArgs{buyer, c("token2", 99)}, - types.ErrBidTooSmall, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 100), - false, - false, - }, - { - "surplus: invalid bid (equal)", - auctionArgs{Surplus, modName, c("token1", 100), c("token2", 0), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}}, - nil, - bidArgs{buyer, c("token2", 0)}, // min bid is technically 0 at default 5%, but it's capped at 1 - types.ErrBidTooSmall, - types.DistantFuture, - nil, // surplus auctions are created with initial bidder as a nil address - c("token2", 0), - false, - false, - }, - { - "surplus: invalid bid (less than min increment)", - auctionArgs{Surplus, modName, c("token1", 100), c("token2", 0), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}}, - []bidArgs{{buyer, c("token2", 100)}}, - bidArgs{buyer, c("token2", 104)}, // min bid is 105 at default 5% - types.ErrBidTooSmall, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 100), - false, - false, - }, - { - "debt: normal", - auctionArgs{Debt, modName, c("token1", 20), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdkmath.Int{}}, // initial bid, lot - nil, - bidArgs{buyer, c("token1", 10)}, - nil, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 100), - true, - false, - }, - { - "debt: second bidder", - auctionArgs{Debt, modName, c("token1", 20), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdkmath.Int{}}, // initial bid, lot - []bidArgs{{buyer, c("token1", 10)}}, - bidArgs{secondBuyer, c("token1", 9)}, - nil, - someTime.Add(types.DefaultForwardBidDuration), - secondBuyer, - c("token2", 100), - true, - false, - }, - { - "debt: invalid lot denom", - auctionArgs{Debt, modName, c("token1", 20), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdkmath.Int{}}, // initial bid, lot - nil, - bidArgs{buyer, c("badtoken", 10)}, - types.ErrInvalidLotDenom, - types.DistantFuture, - authtypes.NewModuleAddress(modName), - c("token2", 100), - false, - false, - }, - { - "debt: invalid lot size (larger)", - auctionArgs{Debt, modName, c("token1", 20), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdkmath.Int{}}, - nil, - bidArgs{buyer, c("token1", 21)}, - types.ErrLotTooLarge, - types.DistantFuture, - authtypes.NewModuleAddress(modName), - c("token2", 100), - false, - false, - }, - { - "debt: invalid lot size (equal)", - auctionArgs{Debt, modName, c("token1", 20), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdkmath.Int{}}, - nil, - bidArgs{buyer, c("token1", 20)}, - types.ErrLotTooLarge, - types.DistantFuture, - authtypes.NewModuleAddress(modName), - c("token2", 100), - false, - false, - }, - { - "debt: invalid lot size (larger than min increment)", - auctionArgs{Debt, modName, c("token1", 60), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdkmath.Int{}}, - nil, - bidArgs{buyer, c("token1", 58)}, // max lot at default 5% is 57 - types.ErrLotTooLarge, - types.DistantFuture, - authtypes.NewModuleAddress(modName), - c("token2", 100), - false, false, - }, - { - "collateral [forward]: normal", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - nil, - bidArgs{buyer, c("token2", 10)}, - nil, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 10), - true, - false, - }, - { - "collateral [forward]: second bidder", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 10)}}, - bidArgs{secondBuyer, c("token2", 11)}, - nil, - someTime.Add(types.DefaultForwardBidDuration), - secondBuyer, - c("token2", 11), - true, - false, - }, - { - "collateral [forward]: convert to reverse (reach maxBid)", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 10)}}, - bidArgs{secondBuyer, c("token2", 100)}, - nil, - someTime.Add(types.DefaultReverseBidDuration), - secondBuyer, - c("token2", 100), - true, - false, - }, - { - "collateral [forward]: invalid bid denom", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - nil, - bidArgs{buyer, c("badtoken", 10)}, - types.ErrInvalidBidDenom, - types.DistantFuture, - nil, - c("token2", 0), - false, - false, - }, - { - "collateral [forward]: invalid bid size (smaller)", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 10)}}, - bidArgs{buyer, c("token2", 9)}, - types.ErrBidTooSmall, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 10), - false, - false, - }, - { - "collateral [forward]: invalid bid size (equal)", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - nil, - bidArgs{buyer, c("token2", 0)}, - types.ErrBidTooSmall, - types.DistantFuture, - nil, - c("token2", 0), - false, - false, - }, - { - "collateral [forward]: invalid bid size (less than min increment)", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 50)}}, - bidArgs{buyer, c("token2", 51)}, - types.ErrBidTooSmall, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 50), - false, - false, - }, - { - "collateral [forward]: less than min increment but equal to maxBid", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 99)}}, - bidArgs{buyer, c("token2", 100)}, // min bid at default 5% is 104 - nil, - someTime.Add(types.DefaultReverseBidDuration), // Converts to a reverse bid when max reached - buyer, - c("token2", 100), - true, - false, - }, - { - "collateral [forward]: invalid bid size (greater than max)", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - nil, - bidArgs{buyer, c("token2", 101)}, - types.ErrBidTooLarge, - types.DistantFuture, - nil, - c("token2", 0), - false, - false, - }, - { - "collateral [forward]: bidder replaces previous bid with only funds for difference", - auctionArgs{Collateral, modName, c("token1", 1000), c("token2", 2000), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 900)}}, - bidArgs{buyer, c("token2", 1000)}, // buyer only has enough to cover the increase from previous bid - nil, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 1000), - true, - false, - }, - { - "collateral [reverse]: normal", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 50), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 50)}}, // put auction into reverse phase - bidArgs{buyer, c("token1", 15)}, - nil, - someTime.Add(types.DefaultReverseBidDuration), - buyer, - c("token2", 50), - true, - false, - }, - { - "collateral [reverse]: second bidder", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 50), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 50)}, {buyer, c("token1", 15)}}, // put auction into reverse phase, and add a reverse phase bid - bidArgs{secondBuyer, c("token1", 14)}, - nil, - someTime.Add(types.DefaultReverseBidDuration), - secondBuyer, - c("token2", 50), - true, - false, - }, - { - "collateral [reverse]: invalid lot denom", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 50), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 50)}}, // put auction into reverse phase - bidArgs{buyer, c("badtoken", 15)}, - types.ErrInvalidLotDenom, - someTime.Add(types.DefaultReverseBidDuration), - buyer, - c("token2", 50), - false, - false, - }, - { - "collateral [reverse]: invalid lot size (greater)", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 50), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 50)}}, // put auction into reverse phase - bidArgs{buyer, c("token1", 21)}, - types.ErrLotTooLarge, - someTime.Add(types.DefaultReverseBidDuration), - buyer, - c("token2", 50), - false, - false, - }, - { - "collateral [reverse]: invalid lot size (equal)", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 50), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 50)}}, // put auction into reverse phase - bidArgs{buyer, c("token1", 20)}, - types.ErrLotTooLarge, - someTime.Add(types.DefaultReverseBidDuration), - buyer, - c("token2", 50), - false, - false, - }, - { - "collateral [reverse]: invalid lot size (larger than min increment)", - auctionArgs{Collateral, modName, c("token1", 60), c("token2", 50), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 50)}}, // put auction into reverse phase - bidArgs{buyer, c("token1", 58)}, // max lot at default 5% is 57 - types.ErrLotTooLarge, - someTime.Add(types.DefaultReverseBidDuration), - buyer, - c("token2", 50), - false, - false, - }, - { - "collateral [reverse]: bidder replaces previous bid without funds", - auctionArgs{Collateral, modName, c("token1", 1000), c("token2", 1000), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 1000)}}, - bidArgs{buyer, c("token1", 100)}, // buyer has already bid all of their token2 - nil, - someTime.Add(types.DefaultReverseBidDuration), - buyer, - c("token2", 1000), - true, - false, - }, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - // Setup test - tApp := app.NewTestApp() - - // Set up module account - modName := "liquidator" - modBaseAcc := authtypes.NewBaseAccount(authtypes.NewModuleAddress(modName), nil, 0, 0) - modAcc := authtypes.NewModuleAccount(modBaseAcc, modName, []string{authtypes.Minter, authtypes.Burner}...) - - // Set up normal accounts - addrs := []sdk.AccAddress{buyer, secondBuyer, collateralAddrs[0], collateralAddrs[1], collateralAddrs[2]} - - // Initialize app - authGS := app.NewFundedGenStateWithSameCoinsWithModuleAccount(tApp.AppCodec(), initialBalance, addrs, modAcc) - params := types.NewParams( - types.DefaultMaxAuctionDuration, - types.DefaultForwardBidDuration, - types.DefaultReverseBidDuration, - types.DefaultIncrement, - types.DefaultIncrement, - types.DefaultIncrement, - ) - - auctionGs, err := types.NewGenesisState(types.DefaultNextAuctionID, params, []types.GenesisAuction{}) - require.NoError(t, err) - - moduleGs := tApp.AppCodec().MustMarshalJSON(auctionGs) - gs := app.GenesisState{types.ModuleName: moduleGs} - tApp.InitializeFromGenesisStates(authGS, gs) - - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: someTime}) - keeper := tApp.GetAuctionKeeper() - bank := tApp.GetBankKeeper() - - err = tApp.FundModuleAccount(ctx, modName, cs(c("token1", 1000), c("token2", 1000), c("debt", 1000))) - require.NoError(t, err) - - // Start Auction - var id uint64 - switch tc.auctionArgs.auctionType { - case Surplus: - if tc.expectPanic { - require.Panics(t, func() { - id, err = keeper.StartSurplusAuction(ctx, tc.auctionArgs.seller, tc.auctionArgs.lot, tc.auctionArgs.bid.Denom) - }) - } else { - id, err = keeper.StartSurplusAuction(ctx, tc.auctionArgs.seller, tc.auctionArgs.lot, tc.auctionArgs.bid.Denom) - } - case Debt: - id, err = keeper.StartDebtAuction(ctx, tc.auctionArgs.seller, tc.auctionArgs.bid, tc.auctionArgs.lot, tc.auctionArgs.debt) - case Collateral: - id, err = keeper.StartCollateralAuction(ctx, tc.auctionArgs.seller, tc.auctionArgs.lot, tc.auctionArgs.bid, tc.auctionArgs.addresses, tc.auctionArgs.weights, tc.auctionArgs.debt) // seller, lot, maxBid, otherPerson - default: - t.Fail() - } - - require.NoError(t, err) - - // Place setup bids - for _, b := range tc.setupBids { - require.NoError(t, keeper.PlaceBid(ctx, id, b.bidder, b.amount)) - } - - // Close the auction early to test late bidding (if applicable) - if strings.Contains(tc.name, "closed") { - ctx = ctx.WithBlockTime(types.DistantFuture.Add(1)) - } - - // Store some state for use in checks - var oldBidder sdk.AccAddress - var oldBidderOldCoins sdk.Coins - - oldAuction, found := keeper.GetAuction(ctx, id) - if found { - oldBidder = oldAuction.GetBidder() - } - - if !oldBidder.Empty() { - oldBidderOldCoins = bank.GetAllBalances(ctx, oldBidder) - } - - newBidderOldCoins := bank.GetAllBalances(ctx, tc.bidArgs.bidder) - - // Place bid on auction - err = keeper.PlaceBid(ctx, id, tc.bidArgs.bidder, tc.bidArgs.amount) - - // Check success/failure - if tc.expectPass { - require.NoError(t, err) - // Check auction was found - newAuction, found := keeper.GetAuction(ctx, id) - require.True(t, found) - // Check auction values - require.Equal(t, modName, newAuction.GetInitiator()) - require.Equal(t, tc.expectedBidder, newAuction.GetBidder()) - require.Equal(t, tc.expectedBid, newAuction.GetBid()) - require.Equal(t, tc.expectedEndTime, newAuction.GetEndTime()) - - // Check coins have moved between bidder and previous bidder - bidAmt := tc.bidArgs.amount - switch tc.auctionArgs.auctionType { - case Debt: - bidAmt = oldAuction.GetBid() - case Collateral: - collatAuction, ok := oldAuction.(*types.CollateralAuction) - require.True(t, ok, tc.name) - if collatAuction.IsReversePhase() { - bidAmt = oldAuction.GetBid() - } - } - if oldBidder.Equals(tc.bidArgs.bidder) { // same bidder - require.Equal(t, newBidderOldCoins.Sub(bidAmt.Sub(oldAuction.GetBid())), bank.GetAllBalances(ctx, tc.bidArgs.bidder)) - } else { // different bidder - require.Equal(t, newBidderOldCoins.Sub(bidAmt), bank.GetAllBalances(ctx, tc.bidArgs.bidder)) // wrapping in cs() to avoid comparing nil and empty coins - - // handle checking debt coins for case debt auction has had no bids placed yet TODO make this less confusing - if oldBidder.Equals(authtypes.NewModuleAddress(oldAuction.GetInitiator())) { - require.Equal(t, oldBidderOldCoins.Add(oldAuction.GetBid()).Add(c("debt", oldAuction.GetBid().Amount.Int64())), bank.GetAllBalances(ctx, oldBidder)) - } else if oldBidder.Empty() { - require.Equal(t, oldBidderOldCoins.Add(oldAuction.GetBid()).Add(c("debt", oldAuction.GetBid().Amount.Int64())).Empty(), oldBidderOldCoins.Empty()) - } else { - require.Equal(t, cs(oldBidderOldCoins.Add(oldAuction.GetBid())...), bank.GetAllBalances(ctx, oldBidder)) - } - } - - } else { - // Check expected error code type - require.Error(t, err, "PlaceBid did not return an error") - require.ErrorIs(t, err, tc.expectedError) - - // Check auction values - newAuction, found := keeper.GetAuction(ctx, id) - if found { - require.Equal(t, modName, newAuction.GetInitiator()) - require.Equal(t, tc.expectedBidder, newAuction.GetBidder()) - require.Equal(t, tc.expectedBid, newAuction.GetBid()) - require.Equal(t, tc.expectedEndTime, newAuction.GetEndTime()) - } - - // Check coins have not moved - require.Equal(t, newBidderOldCoins, bank.GetAllBalances(ctx, tc.bidArgs.bidder)) - if !oldBidder.Empty() { - require.Equal(t, oldBidderOldCoins, bank.GetAllBalances(ctx, oldBidder)) - } - } - }) - } -} diff --git a/x/auction/keeper/grpc_query.go b/x/auction/keeper/grpc_query.go deleted file mode 100644 index be3e7b8c..00000000 --- a/x/auction/keeper/grpc_query.go +++ /dev/null @@ -1,145 +0,0 @@ -package keeper - -import ( - "context" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - - proto "github.com/cosmos/gogoproto/proto" - - "github.com/kava-labs/kava/x/auction/types" -) - -type queryServer struct { - keeper Keeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -var _ types.QueryServer = queryServer{} - -// Params implements the gRPC service handler for querying x/auction parameters. -func (s queryServer) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - params := s.keeper.GetParams(sdkCtx) - - return &types.QueryParamsResponse{Params: params}, nil -} - -// Auction implements the Query/Auction gRPC method -func (s queryServer) Auction(c context.Context, req *types.QueryAuctionRequest) (*types.QueryAuctionResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(c) - - auction, found := s.keeper.GetAuction(ctx, req.AuctionId) - if !found { - return &types.QueryAuctionResponse{}, nil - } - - msg, ok := auction.(proto.Message) - if !ok { - return nil, status.Errorf(codes.Internal, "can't protomarshal %T", msg) - } - - auctionAny, err := codectypes.NewAnyWithValue(msg) - if err != nil { - return nil, status.Errorf(codes.Internal, err.Error()) - } - - return &types.QueryAuctionResponse{ - Auction: auctionAny, - }, nil -} - -// Auctions implements the Query/Auctions gRPC method -func (s queryServer) Auctions(c context.Context, req *types.QueryAuctionsRequest) (*types.QueryAuctionsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - ctx := sdk.UnwrapSDKContext(c) - - var auctions []*codectypes.Any - auctionStore := prefix.NewStore(ctx.KVStore(s.keeper.storeKey), types.AuctionKeyPrefix) - - pageRes, err := query.FilteredPaginate(auctionStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { - result, err := s.keeper.UnmarshalAuction(value) - if err != nil { - return false, err - } - - // True if empty owner, otherwise check if auction contains owner - ownerIsMatch := req.Owner == "" - if req.Owner != "" { - if cAuc, ok := result.(*types.CollateralAuction); ok { - for _, addr := range cAuc.GetLotReturns().Addresses { - if addr.String() == req.Owner { - ownerIsMatch = true - break - } - } - } - } - - phaseIsMatch := req.Phase == "" || req.Phase == result.GetPhase() - typeIsMatch := req.Type == "" || req.Type == result.GetType() - denomIsMatch := req.Denom == "" || req.Denom == result.GetBid().Denom || req.Denom == result.GetLot().Denom - - if ownerIsMatch && phaseIsMatch && typeIsMatch && denomIsMatch { - if accumulate { - msg, ok := result.(proto.Message) - if !ok { - return false, status.Errorf(codes.Internal, "can't protomarshal %T", msg) - } - - auctionAny, err := codectypes.NewAnyWithValue(msg) - if err != nil { - return false, err - } - auctions = append(auctions, auctionAny) - } - - return true, nil - } - - return false, nil - }) - if err != nil { - return &types.QueryAuctionsResponse{}, err - } - - return &types.QueryAuctionsResponse{ - Auctions: auctions, - Pagination: pageRes, - }, nil -} - -// NextAuctionID implements the gRPC service handler for querying x/auction next auction ID. -func (s queryServer) NextAuctionID(ctx context.Context, req *types.QueryNextAuctionIDRequest) (*types.QueryNextAuctionIDResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - nextAuctionID, err := s.keeper.GetNextAuctionID(sdkCtx) - if err != nil { - return &types.QueryNextAuctionIDResponse{}, err - } - - return &types.QueryNextAuctionIDResponse{Id: nextAuctionID}, nil -} diff --git a/x/auction/keeper/grpc_query_test.go b/x/auction/keeper/grpc_query_test.go deleted file mode 100644 index 12a25aec..00000000 --- a/x/auction/keeper/grpc_query_test.go +++ /dev/null @@ -1,137 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/auction/keeper" - "github.com/kava-labs/kava/x/auction/types" - "github.com/stretchr/testify/require" -) - -func TestGrpcAuctionsFilter(t *testing.T) { - // setup - tApp := app.NewTestApp() - tApp.InitializeFromGenesisStates() - auctionsKeeper := tApp.GetAuctionKeeper() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - _, addrs := app.GeneratePrivKeyAddressPairs(2) - - auctions := []types.Auction{ - types.NewSurplusAuction( - "sellerMod", - c("swp", 12345678), - "usdx", - time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC), - ).WithID(0), - types.NewDebtAuction( - "buyerMod", - c("hard", 12345678), - c("usdx", 12345678), - time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC), - c("debt", 12345678), - ).WithID(1), - types.NewCollateralAuction( - "sellerMod", - c("ukava", 12345678), - time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC), - c("usdx", 12345678), - types.WeightedAddresses{ - Addresses: addrs, - Weights: []sdkmath.Int{sdkmath.NewInt(100)}, - }, - c("debt", 12345678), - ).WithID(2), - types.NewCollateralAuction( - "sellerMod", - c("hard", 12345678), - time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC), - c("usdx", 12345678), - types.WeightedAddresses{ - Addresses: addrs, - Weights: []sdkmath.Int{sdkmath.NewInt(100)}, - }, - c("debt", 12345678), - ).WithID(3), - } - for _, a := range auctions { - auctionsKeeper.SetAuction(ctx, a) - } - - qs := keeper.NewQueryServerImpl(auctionsKeeper) - - tests := []struct { - giveName string - giveRequest types.QueryAuctionsRequest - wantResponse []types.Auction - }{ - { - "empty request", - types.QueryAuctionsRequest{}, - auctions, - }, - { - "denom query swp", - types.QueryAuctionsRequest{ - Denom: "swp", - }, - auctions[0:1], - }, - { - "denom query usdx all", - types.QueryAuctionsRequest{ - Denom: "usdx", - }, - auctions, - }, - { - "owner", - types.QueryAuctionsRequest{ - Owner: addrs[0].String(), - }, - auctions[2:4], - }, - { - "owner and denom", - types.QueryAuctionsRequest{ - Owner: addrs[0].String(), - Denom: "hard", - }, - auctions[3:4], - }, - { - "owner, denom, type, phase", - types.QueryAuctionsRequest{ - Owner: addrs[0].String(), - Denom: "hard", - Type: types.CollateralAuctionType, - Phase: types.ForwardAuctionPhase, - }, - auctions[3:4], - }, - } - - for _, tc := range tests { - t.Run(tc.giveName, func(t *testing.T) { - res, err := qs.Auctions(sdk.WrapSDKContext(ctx), &tc.giveRequest) - require.NoError(t, err) - - var unpackedAuctions []types.Auction - - for _, anyAuction := range res.Auctions { - var auction types.Auction - err := tApp.AppCodec().UnpackAny(anyAuction, &auction) - require.NoError(t, err) - - unpackedAuctions = append(unpackedAuctions, auction) - } - - require.Equal(t, tc.wantResponse, unpackedAuctions) - }) - } -} diff --git a/x/auction/keeper/integration_test.go b/x/auction/keeper/integration_test.go deleted file mode 100644 index c808bcac..00000000 --- a/x/auction/keeper/integration_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package keeper_test - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } -func is(ns ...int64) (is []sdkmath.Int) { - for _, n := range ns { - is = append(is, sdkmath.NewInt(n)) - } - return -} diff --git a/x/auction/keeper/invariants.go b/x/auction/keeper/invariants.go deleted file mode 100644 index d83ecbc7..00000000 --- a/x/auction/keeper/invariants.go +++ /dev/null @@ -1,132 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - "github.com/kava-labs/kava/x/auction/types" -) - -// RegisterInvariants registers all staking invariants -func RegisterInvariants(ir sdk.InvariantRegistry, k Keeper) { - ir.RegisterRoute(types.ModuleName, "module-account", - ModuleAccountInvariants(k)) - ir.RegisterRoute(types.ModuleName, "valid-auctions", - ValidAuctionInvariant(k)) - ir.RegisterRoute(types.ModuleName, "valid-index", - ValidIndexInvariant(k)) -} - -// ModuleAccountInvariants checks that the module account's coins matches those stored in auctions -func ModuleAccountInvariants(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - totalAuctionCoins := sdk.NewCoins() - k.IterateAuctions(ctx, func(auction types.Auction) bool { - a, ok := auction.(types.GenesisAuction) - if !ok { - panic("stored auction type does not fulfill GenesisAuction interface") - } - totalAuctionCoins = totalAuctionCoins.Add(a.GetModuleAccountCoins()...) - return false - }) - - moduleAccCoins := k.bankKeeper.GetAllBalances(ctx, authtypes.NewModuleAddress(types.ModuleName)) - broken := !moduleAccCoins.IsEqual(totalAuctionCoins) - - invariantMessage := sdk.FormatInvariant( - types.ModuleName, - "module account", - fmt.Sprintf( - "\texpected ModuleAccount coins: %s\n"+ - "\tactual ModuleAccount coins: %s\n", - totalAuctionCoins, moduleAccCoins), - ) - return invariantMessage, broken - } -} - -// ValidAuctionInvariant verifies that all auctions in the store are independently valid -func ValidAuctionInvariant(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - var validationErr error - var invalidAuction types.Auction - k.IterateAuctions(ctx, func(auction types.Auction) bool { - a, ok := auction.(types.GenesisAuction) - if !ok { - panic("stored auction type does not fulfill GenesisAuction interface") - } - - if err := a.Validate(); err != nil { - validationErr = err - invalidAuction = a - return true - } - return false - }) - - broken := validationErr != nil - invariantMessage := sdk.FormatInvariant( - types.ModuleName, - "valid auctions", - fmt.Sprintf( - "\tfound invalid auction, reason: %s\n"+ - "\tauction:\n\t%s\n", - validationErr, invalidAuction), - ) - return invariantMessage, broken - } -} - -// ValidIndexInvariant checks that all auctions in the store are also in the index and vice versa. -func ValidIndexInvariant(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - /* Method: - - check all the auction IDs in the index have a corresponding auction in the store - - index is now valid but there could be extra auction in the store - - check for these extra auctions by checking num items in the store equals that of index (store keys are always unique) - - doesn't check the IDs in the auction structs match the IDs in the keys - */ - - // Check all auction IDs in the index are in the auction store - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AuctionKeyPrefix) - - indexIterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.AuctionByTimeKeyPrefix) - defer indexIterator.Close() - - var indexLength int - for ; indexIterator.Valid(); indexIterator.Next() { - indexLength++ - - idBytes := indexIterator.Value() - auctionBytes := store.Get(idBytes) - if auctionBytes == nil { - invariantMessage := sdk.FormatInvariant( - types.ModuleName, - "valid index", - fmt.Sprintf("\tauction with ID '%d' found in index but not in store", types.Uint64FromBytes(idBytes))) - return invariantMessage, true - } - } - - // Check length of auction store matches the length of the index - storeIterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.AuctionKeyPrefix) - defer storeIterator.Close() - var storeLength int - for ; storeIterator.Valid(); storeIterator.Next() { - storeLength++ - } - - if storeLength != indexLength { - invariantMessage := sdk.FormatInvariant( - types.ModuleName, - "valid index", - fmt.Sprintf("\tmismatched number of items in auction store (%d) and index (%d)", storeLength, indexLength)) - return invariantMessage, true - } - - return "", false - } -} diff --git a/x/auction/keeper/keeper.go b/x/auction/keeper/keeper.go deleted file mode 100644 index 4b922ecc..00000000 --- a/x/auction/keeper/keeper.go +++ /dev/null @@ -1,217 +0,0 @@ -package keeper - -import ( - "fmt" - "time" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store/prefix" - 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/cometbft/cometbft/libs/log" - - "github.com/kava-labs/kava/x/auction/types" -) - -type Keeper struct { - storeKey storetypes.StoreKey - cdc codec.Codec - paramSubspace paramtypes.Subspace - bankKeeper types.BankKeeper - accountKeeper types.AccountKeeper -} - -// NewKeeper returns a new auction keeper. -func NewKeeper(cdc codec.Codec, storeKey storetypes.StoreKey, paramstore paramtypes.Subspace, - bankKeeper types.BankKeeper, accountKeeper types.AccountKeeper, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - storeKey: storeKey, - cdc: cdc, - paramSubspace: paramstore, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - } -} - -// MustUnmarshalAuction attempts to decode and return an Auction object from -// raw encoded bytes. It panics on error. -func (k Keeper) MustUnmarshalAuction(bz []byte) types.Auction { - auction, err := k.UnmarshalAuction(bz) - if err != nil { - panic(fmt.Errorf("failed to decode auction: %w", err)) - } - - return auction -} - -// MustMarshalAuction attempts to encode an Auction object and returns the -// raw encoded bytes. It panics on error. -func (k Keeper) MustMarshalAuction(auction types.Auction) []byte { - bz, err := k.MarshalAuction(auction) - if err != nil { - panic(fmt.Errorf("failed to encode auction: %w", err)) - } - - return bz -} - -// MarshalAuction protobuf serializes an Auction interface -func (k Keeper) MarshalAuction(auctionI types.Auction) ([]byte, error) { - return k.cdc.MarshalInterface(auctionI) -} - -// UnmarshalAuction returns an Auction interface from raw encoded auction -// bytes of a Proto-based Auction type -func (k Keeper) UnmarshalAuction(bz []byte) (types.Auction, error) { - var evi types.Auction - return evi, k.cdc.UnmarshalInterface(bz, &evi) -} - -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) -} - -// SetNextAuctionID stores an ID to be used for the next created auction -func (k Keeper) SetNextAuctionID(ctx sdk.Context, id uint64) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.NextAuctionIDKey) - store.Set(types.NextAuctionIDKey, types.Uint64ToBytes(id)) -} - -// GetNextAuctionID reads the next available global ID from store -func (k Keeper) GetNextAuctionID(ctx sdk.Context) (uint64, error) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.NextAuctionIDKey) - bz := store.Get(types.NextAuctionIDKey) - if bz == nil { - return 0, types.ErrInvalidInitialAuctionID - } - return types.Uint64FromBytes(bz), nil -} - -// IncrementNextAuctionID increments the next auction ID in the store by 1. -func (k Keeper) IncrementNextAuctionID(ctx sdk.Context) error { - id, err := k.GetNextAuctionID(ctx) - if err != nil { - return err - } - k.SetNextAuctionID(ctx, id+1) - return nil -} - -// StoreNewAuction stores an auction, adding a new ID -func (k Keeper) StoreNewAuction(ctx sdk.Context, auction types.Auction) (uint64, error) { - newAuctionID, err := k.GetNextAuctionID(ctx) - if err != nil { - return 0, err - } - - auction = auction.WithID(newAuctionID) - k.SetAuction(ctx, auction) - - err = k.IncrementNextAuctionID(ctx) - if err != nil { - return 0, err - } - return newAuctionID, nil -} - -// SetAuction puts the auction into the store, and updates any indexes. -func (k Keeper) SetAuction(ctx sdk.Context, auction types.Auction) { - // remove the auction from the byTime index if it is already in there - existingAuction, found := k.GetAuction(ctx, auction.GetID()) - if found { - k.removeFromByTimeIndex(ctx, existingAuction.GetEndTime(), existingAuction.GetID()) - } - - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AuctionKeyPrefix) - - store.Set(types.GetAuctionKey(auction.GetID()), k.MustMarshalAuction(auction)) - k.InsertIntoByTimeIndex(ctx, auction.GetEndTime(), auction.GetID()) -} - -// GetAuction gets an auction from the store. -func (k Keeper) GetAuction(ctx sdk.Context, auctionID uint64) (types.Auction, bool) { - var auction types.Auction - - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AuctionKeyPrefix) - bz := store.Get(types.GetAuctionKey(auctionID)) - if bz == nil { - return auction, false - } - - return k.MustUnmarshalAuction(bz), true -} - -// DeleteAuction removes an auction from the store, and any indexes. -func (k Keeper) DeleteAuction(ctx sdk.Context, auctionID uint64) { - auction, found := k.GetAuction(ctx, auctionID) - if found { - k.removeFromByTimeIndex(ctx, auction.GetEndTime(), auctionID) - } - - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AuctionKeyPrefix) - store.Delete(types.GetAuctionKey(auctionID)) -} - -// InsertIntoByTimeIndex adds an auction ID and end time into the byTime index. -func (k Keeper) InsertIntoByTimeIndex(ctx sdk.Context, endTime time.Time, auctionID uint64) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AuctionByTimeKeyPrefix) - store.Set(types.GetAuctionByTimeKey(endTime, auctionID), types.Uint64ToBytes(auctionID)) -} - -// removeFromByTimeIndex removes an auction ID and end time from the byTime index. -func (k Keeper) removeFromByTimeIndex(ctx sdk.Context, endTime time.Time, auctionID uint64) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AuctionByTimeKeyPrefix) - store.Delete(types.GetAuctionByTimeKey(endTime, auctionID)) -} - -// IterateAuctionByTime provides an iterator over auctions ordered by auction.EndTime. -// For each auction cb will be callled. If cb returns true the iterator will close and stop. -func (k Keeper) IterateAuctionsByTime(ctx sdk.Context, inclusiveCutoffTime time.Time, cb func(auctionID uint64) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AuctionByTimeKeyPrefix) - iterator := store.Iterator( - nil, // start at the very start of the prefix store - sdk.PrefixEndBytes(sdk.FormatTimeBytes(inclusiveCutoffTime)), // include any keys with times equal to inclusiveCutoffTime - ) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - - auctionID := types.Uint64FromBytes(iterator.Value()) - - if cb(auctionID) { - break - } - } -} - -// IterateAuctions provides an iterator over all stored auctions. -// For each auction, cb will be called. If cb returns true, the iterator will close and stop. -func (k Keeper) IterateAuctions(ctx sdk.Context, cb func(auction types.Auction) (stop bool)) { - iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.AuctionKeyPrefix) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - auction := k.MustUnmarshalAuction(iterator.Value()) - - if cb(auction) { - break - } - } -} - -// GetAllAuctions returns all auctions from the store -func (k Keeper) GetAllAuctions(ctx sdk.Context) (auctions []types.Auction) { - k.IterateAuctions(ctx, func(auction types.Auction) bool { - auctions = append(auctions, auction) - return false - }) - return -} diff --git a/x/auction/keeper/keeper_test.go b/x/auction/keeper/keeper_test.go deleted file mode 100644 index 16aab50a..00000000 --- a/x/auction/keeper/keeper_test.go +++ /dev/null @@ -1,135 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/auction/types" -) - -func SetGetDeleteAuction(t *testing.T) { - // setup keeper, create auction - tApp := app.NewTestApp() - keeper := tApp.GetAuctionKeeper() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - - someTime := time.Date(43, time.January, 1, 0, 0, 0, 0, time.UTC) // need to specify UTC as tz info is lost on unmarshal - var id uint64 = 5 - auction := types.NewSurplusAuction("some_module", c("usdx", 100), "kava", someTime).WithID(id) - - // write and read from store - keeper.SetAuction(ctx, auction) - readAuction, found := keeper.GetAuction(ctx, id) - - // check before and after match - require.True(t, found) - require.Equal(t, auction, readAuction) - // check auction is in the index - keeper.IterateAuctionsByTime(ctx, auction.GetEndTime(), func(readID uint64) bool { - require.Equal(t, auction.GetID(), readID) - return false - }) - - // delete auction - keeper.DeleteAuction(ctx, id) - - // check auction does not exist - _, found = keeper.GetAuction(ctx, id) - require.False(t, found) - // check auction not in index - keeper.IterateAuctionsByTime(ctx, time.Unix(999999999, 0), func(readID uint64) bool { - require.Fail(t, "index should be empty", " found auction ID '%s", readID) - return false - }) -} - -func TestIncrementNextAuctionID(t *testing.T) { - // setup keeper - tApp := app.NewTestApp() - keeper := tApp.GetAuctionKeeper() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - - // store id - var id uint64 = 123456 - keeper.SetNextAuctionID(ctx, id) - - require.NoError(t, keeper.IncrementNextAuctionID(ctx)) - - // check id was incremented - readID, err := keeper.GetNextAuctionID(ctx) - require.NoError(t, err) - require.Equal(t, id+1, readID) -} - -func TestIterateAuctions(t *testing.T) { - // setup - tApp := app.NewTestApp() - tApp.InitializeFromGenesisStates() - keeper := tApp.GetAuctionKeeper() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - - auctions := []types.Auction{ - types.NewSurplusAuction("sellerMod", c("denom", 12345678), "anotherdenom", time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC)).WithID(0), - types.NewDebtAuction("buyerMod", c("denom", 12345678), c("anotherdenom", 12345678), time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC), c("debt", 12345678)).WithID(1), - types.NewCollateralAuction("sellerMod", c("denom", 12345678), time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC), c("anotherdenom", 12345678), types.WeightedAddresses{}, c("debt", 12345678)).WithID(2), - } - for _, a := range auctions { - keeper.SetAuction(ctx, a) - } - - // run - var readAuctions []types.Auction - keeper.IterateAuctions(ctx, func(a types.Auction) bool { - readAuctions = append(readAuctions, a) - return false - }) - - // check - require.Equal(t, auctions, readAuctions) -} - -func TestIterateAuctionsByTime(t *testing.T) { - // setup keeper - tApp := app.NewTestApp() - keeper := tApp.GetAuctionKeeper() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - - // setup byTime index - byTimeIndex := []struct { - endTime time.Time - auctionID uint64 - }{ - {time.Date(0, time.January, 1, 0, 0, 0, 0, time.UTC), 9999}, // distant past - {time.Date(1998, time.January, 1, 11, 59, 59, 999999999, time.UTC), 1}, // just before cutoff - {time.Date(1998, time.January, 1, 11, 59, 59, 999999999, time.UTC), 2}, // - {time.Date(1998, time.January, 1, 12, 0, 0, 0, time.UTC), 3}, // equal to cutoff - {time.Date(1998, time.January, 1, 12, 0, 0, 0, time.UTC), 4}, // - {time.Date(1998, time.January, 1, 12, 0, 0, 1, time.UTC), 5}, // just after cutoff - {time.Date(1998, time.January, 1, 12, 0, 0, 1, time.UTC), 6}, // - {time.Date(9999, time.January, 1, 0, 0, 0, 0, time.UTC), 0}, // distant future - } - for _, v := range byTimeIndex { - keeper.InsertIntoByTimeIndex(ctx, v.endTime, v.auctionID) - } - - // read out values from index up to a cutoff time and check they are as expected - cutoffTime := time.Date(1998, time.January, 1, 12, 0, 0, 0, time.UTC) - var expectedIndex []uint64 - for _, v := range byTimeIndex { - if v.endTime.Before(cutoffTime) || v.endTime.Equal(cutoffTime) { // endTime ≤ cutoffTime - expectedIndex = append(expectedIndex, v.auctionID) - } - } - var readIndex []uint64 - keeper.IterateAuctionsByTime(ctx, cutoffTime, func(id uint64) bool { - readIndex = append(readIndex, id) - return false - }) - - require.Equal(t, expectedIndex, readIndex) -} diff --git a/x/auction/keeper/math.go b/x/auction/keeper/math.go deleted file mode 100644 index 032da042..00000000 --- a/x/auction/keeper/math.go +++ /dev/null @@ -1,81 +0,0 @@ -package keeper - -import ( - "sort" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// splitIntIntoWeightedBuckets divides an initial +ve integer among several buckets in proportion to the buckets' weights -// It uses the largest remainder method: https://en.wikipedia.org/wiki/Largest_remainder_method -// See also: https://stackoverflow.com/questions/13483430/how-to-make-rounded-percentages-add-up-to-100 -func splitIntIntoWeightedBuckets(amount sdkmath.Int, buckets []sdkmath.Int) []sdkmath.Int { - // Limit input to +ve numbers as algorithm hasn't been scoped to work with -ve numbers. - if amount.IsNegative() { - panic("negative amount") - } - if len(buckets) < 1 { - panic("no buckets") - } - for _, bucket := range buckets { - if bucket.IsNegative() { - panic("negative bucket") - } - } - - // 1) Split the amount by weights, recording whole number part and remainder - - totalWeights := totalInts(buckets...) - if !totalWeights.IsPositive() { - panic("total weights must sum to > 0") - } - - quotients := make([]quoRem, len(buckets)) - for i := range buckets { - // amount * ( weight/total_weight ) - q := amount.Mul(buckets[i]).Quo(totalWeights) - r := amount.Mul(buckets[i]).Mod(totalWeights) - quotients[i] = quoRem{index: i, quo: q, rem: r} - } - - // 2) Calculate total left over from remainders, and apportion it to buckets with the highest remainder (to minimize error) - - // sort by decreasing remainder order - sort.Slice(quotients, func(i, j int) bool { - return quotients[i].rem.GT(quotients[j].rem) - }) - - // calculate total left over from remainders - allocated := sdk.ZeroInt() - for _, qr := range quotients { - allocated = allocated.Add(qr.quo) - } - leftToAllocate := amount.Sub(allocated) - - // apportion according to largest remainder - results := make([]sdkmath.Int, len(quotients)) - for _, qr := range quotients { - results[qr.index] = qr.quo - if !leftToAllocate.IsZero() { - results[qr.index] = results[qr.index].Add(sdk.OneInt()) - leftToAllocate = leftToAllocate.Sub(sdk.OneInt()) - } - } - return results -} - -type quoRem struct { - index int - quo sdkmath.Int - rem sdkmath.Int -} - -// totalInts adds together sdk.Ints -func totalInts(is ...sdkmath.Int) sdkmath.Int { - total := sdk.ZeroInt() - for _, i := range is { - total = total.Add(i) - } - return total -} diff --git a/x/auction/keeper/math_test.go b/x/auction/keeper/math_test.go deleted file mode 100644 index c83094c9..00000000 --- a/x/auction/keeper/math_test.go +++ /dev/null @@ -1,115 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" -) - -func TestSplitIntIntoWeightedBuckets(t *testing.T) { - testCases := []struct { - name string - amount sdkmath.Int - buckets []sdkmath.Int - want []sdkmath.Int - expectPanic bool - }{ - { - name: "0split0", - amount: i(0), - buckets: is(0), - expectPanic: true, - }, - { - name: "5splitnil", - amount: i(5), - buckets: is(), - expectPanic: true, - }, - { - name: "-2split1,1", - amount: i(-2), - buckets: is(1, 1), - expectPanic: true, - }, - { - name: "2split1,-1", - amount: i(2), - buckets: is(1, -1), - expectPanic: true, - }, - { - name: "0split0,0,0,1", - amount: i(0), - buckets: is(0, 0, 0, 1), - want: is(0, 0, 0, 0), - }, - { - name: "2split1,1", - amount: i(2), - buckets: is(1, 1), - want: is(1, 1), - }, - { - name: "100split1,9", - amount: i(100), - buckets: is(1, 9), - want: is(10, 90), - }, - { - name: "100split9,1", - amount: i(100), - buckets: is(9, 1), - want: is(90, 10), - }, - { - name: "7split1,2", - amount: i(7), - buckets: is(1, 2), - want: is(2, 5), - }, - { - name: "17split1,1,1", - amount: i(17), - buckets: is(1, 1, 1), - want: is(6, 6, 5), - }, - { - name: "10split1000000,1", - amount: i(10), - buckets: is(1000000, 1), - want: is(10, 0), - }, - { - name: "334733353split730777,31547", - amount: i(334733353), - buckets: is(730777, 31547), - want: is(320881194, 13852159), - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - var got []sdkmath.Int - run := func() { - got = splitIntIntoWeightedBuckets(tc.amount, tc.buckets) - } - if tc.expectPanic { - require.Panics(t, run) - } else { - require.NotPanics(t, run) - } - - require.Equal(t, tc.want, got) - }) - } -} - -func i(n int64) sdkmath.Int { return sdkmath.NewInt(n) } -func is(ns ...int64) (is []sdkmath.Int) { - for _, n := range ns { - is = append(is, sdkmath.NewInt(n)) - } - return -} diff --git a/x/auction/keeper/msg_server.go b/x/auction/keeper/msg_server.go deleted file mode 100644 index d2a0267d..00000000 --- a/x/auction/keeper/msg_server.go +++ /dev/null @@ -1,43 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/auction/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the auction MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -func (k msgServer) PlaceBid(goCtx context.Context, msg *types.MsgPlaceBid) (*types.MsgPlaceBidResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - bidder, err := sdk.AccAddressFromBech32(msg.Bidder) - if err != nil { - return nil, err - } - - err = k.keeper.PlaceBid(ctx, msg.AuctionId, bidder, msg.Amount) - if err != nil { - return nil, err - } - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Bidder), - ), - ) - return &types.MsgPlaceBidResponse{}, nil -} diff --git a/x/auction/keeper/params.go b/x/auction/keeper/params.go deleted file mode 100644 index 3ffc3da4..00000000 --- a/x/auction/keeper/params.go +++ /dev/null @@ -1,16 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/auction/types" -) - -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} - -func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { - k.paramSubspace.GetParamSet(ctx, ¶ms) - return -} diff --git a/x/auction/legacy/v0_16/codec.go b/x/auction/legacy/v0_16/codec.go deleted file mode 100644 index 440aaa6a..00000000 --- a/x/auction/legacy/v0_16/codec.go +++ /dev/null @@ -1,16 +0,0 @@ -package types - -import ( - types "github.com/cosmos/cosmos-sdk/codec/types" - v017auction "github.com/kava-labs/kava/x/auction/types" -) - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterInterface( - "kava.auction.v1beta1.GenesisAuction", - (*v017auction.GenesisAuction)(nil), - &v017auction.SurplusAuction{}, - &v017auction.DebtAuction{}, - &v017auction.CollateralAuction{}, - ) -} diff --git a/x/auction/legacy/v0_16/genesis.pb.go b/x/auction/legacy/v0_16/genesis.pb.go deleted file mode 100644 index 9971f9b5..00000000 --- a/x/auction/legacy/v0_16/genesis.pb.go +++ /dev/null @@ -1,761 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/auction/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/codec/types" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - github_com_gogo_protobuf_types "github.com/gogo/protobuf/types" - _ "google.golang.org/protobuf/types/known/durationpb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 auction module's genesis state. -type GenesisState struct { - NextAuctionId uint64 `protobuf:"varint,1,opt,name=next_auction_id,json=nextAuctionId,proto3" json:"next_auction_id,omitempty"` - Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` - // Genesis auctions - Auctions []*types.Any `protobuf:"bytes,3,rep,name=auctions,proto3" json:"auctions,omitempty"` -} - -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_d0e5cb58293042f7, []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 - -// Params defines the parameters for the issuance module. -type Params struct { - MaxAuctionDuration time.Duration `protobuf:"bytes,1,opt,name=max_auction_duration,json=maxAuctionDuration,proto3,stdduration" json:"max_auction_duration"` - BidDuration time.Duration `protobuf:"bytes,2,opt,name=bid_duration,json=bidDuration,proto3,stdduration" json:"bid_duration"` - IncrementSurplus github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=increment_surplus,json=incrementSurplus,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"increment_surplus"` - IncrementDebt github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=increment_debt,json=incrementDebt,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"increment_debt"` - IncrementCollateral github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=increment_collateral,json=incrementCollateral,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"increment_collateral"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_d0e5cb58293042f7, []int{1} -} -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 - -var fileDescriptor_d0e5cb58293042f7 = []byte{ - // 466 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x93, 0x31, 0x6f, 0xd3, 0x40, - 0x14, 0xc7, 0x7d, 0x4d, 0x88, 0xaa, 0x4b, 0x5a, 0xe0, 0xf0, 0xe0, 0x56, 0xc8, 0x89, 0x32, 0x54, - 0x61, 0xc8, 0x59, 0x0d, 0x1b, 0x5b, 0x4d, 0x44, 0xc5, 0x86, 0x5c, 0x75, 0x81, 0x21, 0xba, 0xb3, - 0x0f, 0x63, 0xd5, 0xf6, 0x45, 0xbe, 0x73, 0x95, 0x7c, 0x0b, 0x46, 0x3e, 0x08, 0x03, 0x13, 0x73, - 0xc4, 0xd4, 0x11, 0x31, 0x14, 0x48, 0xbe, 0x08, 0xf2, 0xdd, 0xe5, 0x82, 0x80, 0x01, 0x75, 0xca, - 0xdd, 0x7b, 0xff, 0xff, 0xef, 0xfd, 0x9f, 0x2e, 0x86, 0xc3, 0x2b, 0x72, 0x4d, 0x02, 0x52, 0xc7, - 0x32, 0xe3, 0x65, 0x70, 0x7d, 0x4a, 0x99, 0x24, 0xa7, 0x41, 0xca, 0x4a, 0x26, 0x32, 0x81, 0xe7, - 0x15, 0x97, 0x1c, 0xb9, 0x8d, 0x06, 0x1b, 0x0d, 0x36, 0x9a, 0x63, 0x37, 0xe5, 0x29, 0x57, 0x82, - 0xa0, 0x39, 0x69, 0xed, 0xf1, 0x51, 0xca, 0x79, 0x9a, 0xb3, 0x40, 0xdd, 0x68, 0xfd, 0x36, 0x20, - 0xe5, 0x72, 0xdb, 0x8a, 0xb9, 0x28, 0xb8, 0x98, 0x69, 0x8f, 0xbe, 0x98, 0x96, 0xff, 0xa7, 0x2b, - 0xa9, 0x2b, 0xa2, 0xa6, 0xa9, 0xca, 0xf0, 0x13, 0x80, 0xbd, 0x73, 0x9d, 0xe9, 0x42, 0x12, 0xc9, - 0xd0, 0x09, 0xbc, 0x5f, 0xb2, 0x85, 0x9c, 0x99, 0x50, 0xb3, 0x2c, 0xf1, 0xc0, 0x00, 0x8c, 0xda, - 0xd1, 0x41, 0x53, 0x3e, 0xd3, 0xd5, 0x97, 0x09, 0x7a, 0x06, 0x3b, 0x73, 0x52, 0x91, 0x42, 0x78, - 0x7b, 0x03, 0x30, 0xea, 0x4e, 0x1e, 0xe3, 0x7f, 0xed, 0x82, 0x5f, 0x29, 0x4d, 0xd8, 0x5e, 0xdd, - 0xf6, 0x9d, 0xc8, 0x38, 0xd0, 0x14, 0xee, 0x1b, 0x9d, 0xf0, 0x5a, 0x83, 0xd6, 0xa8, 0x3b, 0x71, - 0xb1, 0xce, 0x89, 0xb7, 0x39, 0xf1, 0x59, 0xb9, 0x0c, 0xd1, 0x97, 0x8f, 0xe3, 0x43, 0x93, 0xce, - 0x4c, 0x8e, 0xac, 0x73, 0xf8, 0xb9, 0x05, 0x3b, 0x1a, 0x8f, 0x2e, 0xa1, 0x5b, 0x90, 0x85, 0xcd, - 0xbc, 0xdd, 0x51, 0x25, 0xef, 0x4e, 0x8e, 0xfe, 0x82, 0x4f, 0x8d, 0x20, 0xdc, 0x6f, 0x72, 0x7d, - 0xf8, 0xde, 0x07, 0x11, 0x2a, 0xc8, 0xc2, 0xcc, 0xd8, 0x76, 0xd1, 0x0b, 0xd8, 0xa3, 0x59, 0xb2, - 0xc3, 0xed, 0xfd, 0x3f, 0xae, 0x4b, 0xb3, 0xc4, 0x72, 0xde, 0xc0, 0x87, 0x59, 0x19, 0x57, 0xac, - 0x60, 0xa5, 0x9c, 0x89, 0xba, 0x9a, 0xe7, 0x75, 0xb3, 0x38, 0x18, 0xf5, 0x42, 0xdc, 0x38, 0xbe, - 0xdd, 0xf6, 0x4f, 0xd2, 0x4c, 0xbe, 0xab, 0x29, 0x8e, 0x79, 0x61, 0x1e, 0xd0, 0xfc, 0x8c, 0x45, - 0x72, 0x15, 0xc8, 0xe5, 0x9c, 0x09, 0x3c, 0x65, 0x71, 0xf4, 0xc0, 0x82, 0x2e, 0x34, 0x07, 0x5d, - 0xc2, 0xc3, 0x1d, 0x3c, 0x61, 0x54, 0x7a, 0xed, 0x3b, 0x91, 0x0f, 0x2c, 0x65, 0xca, 0xa8, 0x44, - 0x04, 0xba, 0x3b, 0x6c, 0xcc, 0xf3, 0x9c, 0x48, 0x56, 0x91, 0xdc, 0xbb, 0x77, 0x27, 0xf8, 0x23, - 0xcb, 0x7a, 0x6e, 0x51, 0xe1, 0xf9, 0xea, 0xa7, 0xef, 0xac, 0xd6, 0x3e, 0xb8, 0x59, 0xfb, 0xe0, - 0xc7, 0xda, 0x07, 0xef, 0x37, 0xbe, 0x73, 0xb3, 0xf1, 0x9d, 0xaf, 0x1b, 0xdf, 0x79, 0xfd, 0xe4, - 0x37, 0x74, 0xf3, 0xd7, 0x1a, 0xe7, 0x84, 0x0a, 0x75, 0x0a, 0x16, 0xf6, 0xb3, 0x52, 0x13, 0x68, - 0x47, 0xbd, 0xc4, 0xd3, 0x5f, 0x01, 0x00, 0x00, 0xff, 0xff, 0xa5, 0x20, 0xff, 0x87, 0x73, 0x03, - 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.Auctions) > 0 { - for iNdEx := len(m.Auctions) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Auctions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.NextAuctionId != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.NextAuctionId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -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 - { - size := m.IncrementCollateral.Size() - i -= size - if _, err := m.IncrementCollateral.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.IncrementDebt.Size() - i -= size - if _, err := m.IncrementDebt.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.IncrementSurplus.Size() - i -= size - if _, err := m.IncrementSurplus.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - n2, err2 := github_com_gogo_protobuf_types.StdDurationMarshalTo(m.BidDuration, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdDuration(m.BidDuration):]) - if err2 != nil { - return 0, err2 - } - i -= n2 - i = encodeVarintGenesis(dAtA, i, uint64(n2)) - i-- - dAtA[i] = 0x12 - n3, err3 := github_com_gogo_protobuf_types.StdDurationMarshalTo(m.MaxAuctionDuration, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdDuration(m.MaxAuctionDuration):]) - if err3 != nil { - return 0, err3 - } - i -= n3 - i = encodeVarintGenesis(dAtA, i, uint64(n3)) - 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 - if m.NextAuctionId != 0 { - n += 1 + sovGenesis(uint64(m.NextAuctionId)) - } - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.Auctions) > 0 { - for _, e := range m.Auctions { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = github_com_gogo_protobuf_types.SizeOfStdDuration(m.MaxAuctionDuration) - n += 1 + l + sovGenesis(uint64(l)) - l = github_com_gogo_protobuf_types.SizeOfStdDuration(m.BidDuration) - n += 1 + l + sovGenesis(uint64(l)) - l = m.IncrementSurplus.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.IncrementDebt.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.IncrementCollateral.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 != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field NextAuctionId", wireType) - } - m.NextAuctionId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.NextAuctionId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - 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 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Auctions", 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.Auctions = append(m.Auctions, &types.Any{}) - if err := m.Auctions[len(m.Auctions)-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 (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 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: 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 { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaxAuctionDuration", 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 := github_com_gogo_protobuf_types.StdDurationUnmarshal(&m.MaxAuctionDuration, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BidDuration", 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 := github_com_gogo_protobuf_types.StdDurationUnmarshal(&m.BidDuration, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IncrementSurplus", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IncrementSurplus.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IncrementDebt", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IncrementDebt.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IncrementCollateral", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IncrementCollateral.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/auction/legacy/v0_16/testdata/v15-auction.json b/x/auction/legacy/v0_16/testdata/v15-auction.json deleted file mode 100644 index c8b24f95..00000000 --- a/x/auction/legacy/v0_16/testdata/v15-auction.json +++ /dev/null @@ -1,91 +0,0 @@ -{ - "auctions": [ - { - "type": "auction/CollateralAuction", - "value": { - "base_auction": { - "bid": { - "amount": "0", - "denom": "bnb" - }, - "bidder": "", - "end_time": "9000-01-01T00:00:00Z", - "has_received_bids": false, - "id": "3795", - "initiator": "hard", - "lot": { - "amount": "1", - "denom": "bnb" - }, - "max_end_time": "9000-01-01T00:00:00Z" - }, - "corresponding_debt": { - "amount": "0", - "denom": "debt" - }, - "lot_returns": { - "addresses": ["kava1eevfnzkf2mt6feyttyzh6ektclauq7zlayefwf"], - "weights": ["100"] - }, - "max_bid": { - "amount": "1", - "denom": "bnb" - } - } - }, - { - "type": "auction/SurplusAuction", - "value": { - "base_auction": { - "bid": { - "amount": "0", - "denom": "bnb" - }, - "bidder": "", - "end_time": "9000-01-01T00:00:00Z", - "has_received_bids": false, - "id": "3796", - "initiator": "hard", - "lot": { - "amount": "1", - "denom": "bnb" - }, - "max_end_time": "9000-01-01T00:00:00Z" - } - } - }, - { - "type": "auction/DebtAuction", - "value": { - "base_auction": { - "bid": { - "amount": "0", - "denom": "bnb" - }, - "bidder": "", - "end_time": "9000-01-01T00:00:00Z", - "has_received_bids": false, - "id": "3895", - "initiator": "hard", - "lot": { - "amount": "1", - "denom": "bnb" - }, - "max_end_time": "9000-01-01T00:00:00Z" - }, - "corresponding_debt": { - "amount": "0", - "denom": "debt" - } - } - } - ], - "next_auction_id": "12", - "params": { - "bid_duration": "600000000000", - "increment_collateral": "0.010000000000000000", - "increment_debt": "0.010000000000000000", - "increment_surplus": "0.010000000000000000", - "max_auction_duration": "172800000000000" - } -} diff --git a/x/auction/legacy/v0_16/testdata/v16-auction.json b/x/auction/legacy/v0_16/testdata/v16-auction.json deleted file mode 100644 index 17299cd3..00000000 --- a/x/auction/legacy/v0_16/testdata/v16-auction.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "next_auction_id": "12", - "params": { - "max_auction_duration": "172800s", - "bid_duration": "600s", - "increment_surplus": "0.010000000000000000", - "increment_debt": "0.010000000000000000", - "increment_collateral": "0.010000000000000000" - }, - "auctions": [ - { - "@type": "/kava.auction.v1beta1.CollateralAuction", - "base_auction": { - "id": "3795", - "initiator": "hard", - "lot": { "denom": "bnb", "amount": "1" }, - "bidder": "", - "bid": { "denom": "bnb", "amount": "0" }, - "has_received_bids": false, - "end_time": "9000-01-01T00:00:00Z", - "max_end_time": "9000-01-01T00:00:00Z" - }, - "corresponding_debt": { "denom": "debt", "amount": "0" }, - "max_bid": { "denom": "bnb", "amount": "1" }, - "lot_returns": { - "addresses": ["kava1eevfnzkf2mt6feyttyzh6ektclauq7zlayefwf"], - "weights": ["100"] - } - }, - { - "@type": "/kava.auction.v1beta1.SurplusAuction", - "base_auction": { - "id": "3796", - "initiator": "hard", - "lot": { "denom": "bnb", "amount": "1" }, - "bidder": "", - "bid": { "denom": "bnb", "amount": "0" }, - "has_received_bids": false, - "end_time": "9000-01-01T00:00:00Z", - "max_end_time": "9000-01-01T00:00:00Z" - } - }, - { - "@type": "/kava.auction.v1beta1.DebtAuction", - "base_auction": { - "id": "3895", - "initiator": "hard", - "lot": { "denom": "bnb", "amount": "1" }, - "bidder": "", - "bid": { "denom": "bnb", "amount": "0" }, - "has_received_bids": false, - "end_time": "9000-01-01T00:00:00Z", - "max_end_time": "9000-01-01T00:00:00Z" - }, - "corresponding_debt": { "denom": "debt", "amount": "0" } - } - ] -} diff --git a/x/auction/legacy/v0_17/migrate.go b/x/auction/legacy/v0_17/migrate.go deleted file mode 100644 index 3c4002d1..00000000 --- a/x/auction/legacy/v0_17/migrate.go +++ /dev/null @@ -1,25 +0,0 @@ -package v0_17 - -import ( - v016auction "github.com/kava-labs/kava/x/auction/legacy/v0_16" - v017auction "github.com/kava-labs/kava/x/auction/types" -) - -func Migrate(oldState v016auction.GenesisState) *v017auction.GenesisState { - return &v017auction.GenesisState{ - NextAuctionId: oldState.NextAuctionId, - Params: migrateParams(oldState.Params), - Auctions: oldState.Auctions, - } -} - -func migrateParams(params v016auction.Params) v017auction.Params { - return v017auction.Params{ - MaxAuctionDuration: params.MaxAuctionDuration, - ForwardBidDuration: v017auction.DefaultForwardBidDuration, - ReverseBidDuration: v017auction.DefaultReverseBidDuration, - IncrementSurplus: params.IncrementSurplus, - IncrementDebt: params.IncrementDebt, - IncrementCollateral: params.IncrementCollateral, - } -} diff --git a/x/auction/module.go b/x/auction/module.go deleted file mode 100644 index c18b968b..00000000 --- a/x/auction/module.go +++ /dev/null @@ -1,139 +0,0 @@ -package auction - -import ( - "context" - "encoding/json" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/kava-labs/kava/x/auction/client/cli" - "github.com/kava-labs/kava/x/auction/keeper" - "github.com/kava-labs/kava/x/auction/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic implements the sdk.AppModuleBasic interface. -type AppModuleBasic struct{} - -// Name returns the module name. -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) - if err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the gov module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) -} - -// GetTxCmd returns the root tx command for the swap module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the swap module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -//____________________________________________________________________________ - -// AppModule implements the sdk.AppModule interface. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper types.AccountKeeper, bankKeeper types.BankKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - } -} - -// Name module name -func (AppModule) Name() string { - return types.ModuleName -} - -// RegisterInvariants register module invariants -func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) -} - -// InitGenesis module init-genesis -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { - var genState types.GenesisState - cdc.MustUnmarshalJSON(gs, &genState) - InitGenesis(ctx, am.keeper, am.bankKeeper, am.accountKeeper, &genState) - - return []abci.ValidatorUpdate{} -} - -// ExportGenesis module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(gs) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { - BeginBlocker(ctx, am.keeper) -} - -// EndBlock module end-block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/auction/spec/01_concepts.md b/x/auction/spec/01_concepts.md deleted file mode 100644 index 9c47f348..00000000 --- a/x/auction/spec/01_concepts.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# Concepts - -Auctions are broken down into three distinct types, which correspond to three specific functionalities within the CDP system. - -* **Surplus Auction:** An auction in which a fixed lot of coins (c1) is sold for increasing amounts of other coins (c2). Bidders increment the amount of c2 they are willing to pay for the lot of c1. After the completion of a surplus auction, the winning bid of c2 is burned, and the bidder receives the lot of c1. As a concrete example, surplus auction are used to sell a fixed amount of USDX stable coins in exchange for increasing bids of KAVA governance tokens. The governance tokens are then burned and the winner receives USDX. -* **Debt Auction:** An auction in which a fixed amount of coins (c1) is bid for a decreasing lot of other coins (c2). Bidders decrement the lot of c2 they are willing to receive for the fixed amount of c1. As a concrete example, debt auctions are used to raise a certain amount of USDX stable coins in exchange for decreasing lots of KAVA governance tokens. The USDX tokens are used to recapitalize the cdp system and the winner receives KAVA. -* **Surplus Reverse Auction:** Are two phase auction is which a fixed lot of coins (c1) is sold for increasing amounts of other coins (c2). Bidders increment the amount of c2 until a specific `maxBid` is reached. Once `maxBid` is reached, a fixed amount of c2 is bid for a decreasing lot of c1. In the second phase, bidders decrement the lot of c1 they are willing to receive for a fixed amount of c2. As a concrete example, collateral auctions are used to sell collateral (ATOM, for example) for up to a `maxBid` amount of USDX. The USDX tokens are used to recapitalize the cdp system and the winner receives the specified lot of ATOM. In the event that the winning lot is smaller than the total lot, the excess ATOM is ratably returned to the original owners of the liquidated CDPs that were collateralized with that ATOM. - -Auctions are always initiated by another module, and not directly by users. Auctions start with an expiry, the time at which the auction is guaranteed to end, even if there have been no bidders. After each bid, the auction is extended by a specific amount of time, `BidDuration`. In the case that increasing the auction time by `BidDuration` would cause the auction to go past its expiry, the expiry is chosen as the ending time. diff --git a/x/auction/spec/02_state.md b/x/auction/spec/02_state.md deleted file mode 100644 index 335866e7..00000000 --- a/x/auction/spec/02_state.md +++ /dev/null @@ -1,82 +0,0 @@ - - -# State - -## Parameters and genesis state - -`parameters` define the rules according to which auctions are run. There is only one active parameter set at any given time. Updates to the parameter set can be made via on-chain parameter update proposals. - -```go -// Params governance parameters for auction module -type Params struct { - MaxAuctionDuration time.Duration `json:"max_auction_duration" yaml:"max_auction_duration"` // max length of auction - MaxBidDuration time.Duration `json:"max_bid_duration" yaml:"max_bid_duration"` // additional time added to the auction end time after each bid, capped by the expiry. - IncrementSurplus sdk.Dec `json:"increment_surplus" yaml:"increment_surplus"` // percentage change (of auc.Bid) required for a new bid on a surplus auction - IncrementDebt sdk.Dec `json:"increment_debt" yaml:"increment_debt"` // percentage change (of auc.Lot) required for a new bid on a debt auction - IncrementCollateral sdk.Dec `json:"increment_collateral" yaml:"increment_collateral"` // percentage change (of auc.Bid or auc.Lot) required for a new bid on a collateral auction -} -``` - -`GenesisState` defines the state that must be persisted when the blockchain stops/restarts in order for normal function of the auction module to resume. - -```go -// GenesisState - auction state that must be provided at genesis -type GenesisState struct { - NextAuctionID uint64 `json:"next_auction_id" yaml:"next_auction_id"` // auctionID that will be used for the next created auction - Params Params `json:"auction_params" yaml:"auction_params"` // auction params - Auctions Auctions `json:"genesis_auctions" yaml:"genesis_auctions"` // auctions currently in the store -} -``` - -## Base types - -```go -// Auction is an interface to several types of auction. -type Auction interface { - GetID() uint64 - WithID(uint64) Auction - GetEndTime() time.Time -} - -// BaseAuction is a common type shared by all Auctions. -type BaseAuction struct { - ID uint64 - Initiator string // Module name that starts the auction. Pays out Lot. - Lot sdk.Coin // Coins that will paid out by Initiator to the winning bidder. - Bidder sdk.AccAddress // Latest bidder. Receiver of Lot. - Bid sdk.Coin // Coins paid into the auction the bidder. - EndTime time.Time // Current auction closing time. Triggers at the end of the block with time ≥ EndTime. - MaxEndTime time.Time // Maximum closing time. Auctions can close before this but never after. -} - -// SurplusAuction is a forward auction that burns what it receives from bids. -// It is normally used to sell off excess pegged asset acquired by the CDP system. -type SurplusAuction struct { - BaseAuction -} - -// DebtAuction is a reverse auction that mints what it pays out. -// It is normally used to acquire pegged asset to cover the CDP system's debts that were not covered by selling collateral. -type DebtAuction struct { - BaseAuction -} - -// WeightedAddresses is a type for storing some addresses and associated weights. -type WeightedAddresses struct { - Addresses []sdk.AccAddress - Weights []sdkmath.Int -} - -// CollateralAuction is a two phase auction. -// Initially, in forward auction phase, bids can be placed up to a max bid. -// Then it switches to a reverse auction phase, where the initial amount up for auction is bid down. -// Unsold Lot is sent to LotReturns, being divided among the addresses by weight. -// Collateral auctions are normally used to sell off collateral seized from CDPs. -type CollateralAuction struct { - BaseAuction - MaxBid sdk.Coin - LotReturns WeightedAddresses -} -``` diff --git a/x/auction/spec/03_messages.md b/x/auction/spec/03_messages.md deleted file mode 100644 index 92fff7a5..00000000 --- a/x/auction/spec/03_messages.md +++ /dev/null @@ -1,36 +0,0 @@ - - -# Messages - -## Bidding - -Users can bid on auctions using the `MsgPlaceBid` message type. All auction types can be bid on using the same message type. - -```go -// MsgPlaceBid is the message type used to place a bid on any type of auction. -type MsgPlaceBid struct { - AuctionID uint64 - Bidder sdk.AccAddress - Amount sdk.Coin -} -``` - -**State Modifications:** - -* Update bidder if different than previous bidder -* For Surplus auctions: - * Update Bid to msg.Amount - * Return bid coins to previous bidder - * Burn coins equal to the increment in the bid (CurrentBid - PreviousBid) -* For Debt auctions: - * Update Lot amount to msg.Amount - * Return bid coins to previous bidder -* For Collateral auctions: - * Return bid coins to previous bidder - * If in forward phase: - * Update Bid amount to msg.Amount - * If in reverse phase: - * Update Lot amount to msg.Amount -* Extend auction by `BidDuration`, up to `MaxEndTime` diff --git a/x/auction/spec/04_events.md b/x/auction/spec/04_events.md deleted file mode 100644 index 36992c04..00000000 --- a/x/auction/spec/04_events.md +++ /dev/null @@ -1,38 +0,0 @@ - - -# Events - -The `x/auction` module emits the following events: - -## Triggered By Other Modules - -| Type | Attribute Key | Attribute Value | -|---------------|---------------|-------------------| -| auction_start | auction_id | `{auction ID}` | -| auction_start | auction_type | `{auction type}` | -| auction_start | lot | `{coin amount}` | -| auction_start | bid | `{coin amount}` | -| auction_start | max_bid | `{coin amount}` | - -## Handlers - -### MsgPlaceBid - -| Type | Attribute Key | Attribute Value | -|-------------|---------------|----------------------| -| auction_bid | auction_id | `{auction ID}` | -| auction_bid | bidder | `{latest bidder}` | -| auction_bid | bid | `{coin amount}` | -| auction_bid | lot | `{coin amount}` | -| auction_bid | end_time | `{auction end time}` | -| message | module | auction | -| message | sender | `{sender address}` | - -## BeginBlock - -| Type | Attribute Key | Attribute Value | -|---------------|---------------|-------------------| -| auction_close | auction_id | `{auction ID}` | -| auction_close | close_block | `{block height}` | diff --git a/x/auction/spec/05_params.md b/x/auction/spec/05_params.md deleted file mode 100644 index 88960f9c..00000000 --- a/x/auction/spec/05_params.md +++ /dev/null @@ -1,15 +0,0 @@ - - -# Parameters - -The auction module contains the following parameters: - -| Key | Type | Example | Description | -|---------------------|------------------------|------------------------|---------------------------------------------------------------------------------------| -| MaxAuctionDuration | string (time.Duration) | "48h0m0s" | | -| BidDuration | string (time.Duration) | "3h0m0s" | | -| IncrementSurplus | string (dec) | "0.050000000000000000" | percentage change in bid required for a new bid on a surplus auction | -| IncrementDebt | string (dec) | "0.050000000000000000" | percentage change in lot required for a new bid on a debt auction | -| IncrementCollateral | string (dec) | "0.050000000000000000" | percentage change in either bid or lot required for a new bid on a collateral auction | diff --git a/x/auction/spec/06_begin_block.md b/x/auction/spec/06_begin_block.md deleted file mode 100644 index 64c6a6a0..00000000 --- a/x/auction/spec/06_begin_block.md +++ /dev/null @@ -1,22 +0,0 @@ - - -# Begin Block - -At the start of each block, auctions that have reached `EndTime` are closed. The logic to close auctions is as follows: - -```go -var expiredAuctions []uint64 - k.IterateAuctionsByTime(ctx, ctx.BlockTime(), func(id uint64) bool { - expiredAuctions = append(expiredAuctions, id) - return false - }) - - for _, id := range expiredAuctions { - err := k.CloseAuction(ctx, id) - if err != nil { - panic(err) - } - } -``` diff --git a/x/auction/spec/README.md b/x/auction/spec/README.md deleted file mode 100644 index 5ba72788..00000000 --- a/x/auction/spec/README.md +++ /dev/null @@ -1,20 +0,0 @@ - - -# `auction` - - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** -5. **[Params](05_params.md)** -6. **[BeginBlock](06_begin_block.md)** - -## Abstract - -`x/auction` is an implementation of a Cosmos SDK Module that handles the creation, bidding, and payout of 3 distinct auction types. All auction types implement the `Auction` interface. Each auction type is used at different points during the normal functioning of the CDP system. diff --git a/x/auction/testutil/suite.go b/x/auction/testutil/suite.go deleted file mode 100644 index d4373c4d..00000000 --- a/x/auction/testutil/suite.go +++ /dev/null @@ -1,92 +0,0 @@ -package testutil - -import ( - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/auction/keeper" - "github.com/kava-labs/kava/x/auction/types" -) - -// Suite implements a test suite for the kavadist module integration tests -type Suite struct { - suite.Suite - - Keeper keeper.Keeper - BankKeeper bankkeeper.Keeper - AccountKeeper authkeeper.AccountKeeper - App app.TestApp - Ctx sdk.Context - Addrs []sdk.AccAddress - ModAcc *authtypes.ModuleAccount -} - -// SetupTest instantiates a new app, keepers, and sets suite state -func (suite *Suite) SetupTest(numAddrs int) { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - tApp := app.NewTestApp() - - _, addrs := app.GeneratePrivKeyAddressPairs(numAddrs) - - // Fund liquidator module account - coins := sdk.NewCoins( - sdk.NewCoin("token1", sdkmath.NewInt(100)), - sdk.NewCoin("token2", sdkmath.NewInt(100)), - ) - - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - modName := "liquidator" - modBaseAcc := authtypes.NewBaseAccount(authtypes.NewModuleAddress(modName), nil, 0, 0) - modAcc := authtypes.NewModuleAccount(modBaseAcc, modName, []string{authtypes.Minter, authtypes.Burner}...) - suite.ModAcc = modAcc - - authGS := app.NewFundedGenStateWithSameCoinsWithModuleAccount(tApp.AppCodec(), coins, addrs, modAcc) - - params := types.NewParams( - types.DefaultMaxAuctionDuration, - types.DefaultForwardBidDuration, - types.DefaultReverseBidDuration, - types.DefaultIncrement, - types.DefaultIncrement, - types.DefaultIncrement, - ) - - auctionGs, err := types.NewGenesisState(types.DefaultNextAuctionID, params, []types.GenesisAuction{}) - suite.Require().NoError(err) - - moduleGs := tApp.AppCodec().MustMarshalJSON(auctionGs) - gs := app.GenesisState{types.ModuleName: moduleGs} - tApp.InitializeFromGenesisStates(authGS, gs) - - suite.App = tApp - suite.Ctx = ctx - suite.Addrs = addrs - suite.Keeper = tApp.GetAuctionKeeper() - suite.BankKeeper = tApp.GetBankKeeper() - suite.AccountKeeper = tApp.GetAccountKeeper() -} - -// AddCoinsToModule adds coins to a named module account -func (suite *Suite) AddCoinsToNamedModule(moduleName string, amount sdk.Coins) { - // Does not use suite.BankKeeper.MintCoins as module account would not have permission to mint - err := suite.App.FundModuleAccount(suite.Ctx, moduleName, amount) - suite.Require().NoError(err) -} - -// CheckAccountBalanceEqual asserts that -func (suite *Suite) CheckAccountBalanceEqual(owner sdk.AccAddress, expectedCoins sdk.Coins) { - balances := suite.BankKeeper.GetAllBalances(suite.Ctx, owner) - suite.Equal(expectedCoins, balances) -} diff --git a/x/auction/types/auction.pb.go b/x/auction/types/auction.pb.go deleted file mode 100644 index 8e7191d1..00000000 --- a/x/auction/types/auction.pb.go +++ /dev/null @@ -1,1551 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/auction/v1beta1/auction.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" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 - -// BaseAuction defines common attributes of all auctions -type BaseAuction struct { - ID uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` - Initiator string `protobuf:"bytes,2,opt,name=initiator,proto3" json:"initiator,omitempty"` - Lot types.Coin `protobuf:"bytes,3,opt,name=lot,proto3" json:"lot"` - Bidder github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,4,opt,name=bidder,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"bidder,omitempty"` - Bid types.Coin `protobuf:"bytes,5,opt,name=bid,proto3" json:"bid"` - HasReceivedBids bool `protobuf:"varint,6,opt,name=has_received_bids,json=hasReceivedBids,proto3" json:"has_received_bids,omitempty"` - EndTime time.Time `protobuf:"bytes,7,opt,name=end_time,json=endTime,proto3,stdtime" json:"end_time"` - MaxEndTime time.Time `protobuf:"bytes,8,opt,name=max_end_time,json=maxEndTime,proto3,stdtime" json:"max_end_time"` -} - -func (m *BaseAuction) Reset() { *m = BaseAuction{} } -func (m *BaseAuction) String() string { return proto.CompactTextString(m) } -func (*BaseAuction) ProtoMessage() {} -func (*BaseAuction) Descriptor() ([]byte, []int) { - return fileDescriptor_b9b5dac2c776ef9e, []int{0} -} -func (m *BaseAuction) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BaseAuction) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BaseAuction.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 *BaseAuction) XXX_Merge(src proto.Message) { - xxx_messageInfo_BaseAuction.Merge(m, src) -} -func (m *BaseAuction) XXX_Size() int { - return m.Size() -} -func (m *BaseAuction) XXX_DiscardUnknown() { - xxx_messageInfo_BaseAuction.DiscardUnknown(m) -} - -var xxx_messageInfo_BaseAuction proto.InternalMessageInfo - -// SurplusAuction is a forward auction that burns what it receives from bids. -// It is normally used to sell off excess pegged asset acquired by the CDP system. -type SurplusAuction struct { - BaseAuction `protobuf:"bytes,1,opt,name=base_auction,json=baseAuction,proto3,embedded=base_auction" json:"base_auction"` -} - -func (m *SurplusAuction) Reset() { *m = SurplusAuction{} } -func (m *SurplusAuction) String() string { return proto.CompactTextString(m) } -func (*SurplusAuction) ProtoMessage() {} -func (*SurplusAuction) Descriptor() ([]byte, []int) { - return fileDescriptor_b9b5dac2c776ef9e, []int{1} -} -func (m *SurplusAuction) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SurplusAuction) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SurplusAuction.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 *SurplusAuction) XXX_Merge(src proto.Message) { - xxx_messageInfo_SurplusAuction.Merge(m, src) -} -func (m *SurplusAuction) XXX_Size() int { - return m.Size() -} -func (m *SurplusAuction) XXX_DiscardUnknown() { - xxx_messageInfo_SurplusAuction.DiscardUnknown(m) -} - -var xxx_messageInfo_SurplusAuction proto.InternalMessageInfo - -// DebtAuction is a reverse auction that mints what it pays out. -// It is normally used to acquire pegged asset to cover the CDP system's debts that were not covered by selling -// collateral. -type DebtAuction struct { - BaseAuction `protobuf:"bytes,1,opt,name=base_auction,json=baseAuction,proto3,embedded=base_auction" json:"base_auction"` - CorrespondingDebt types.Coin `protobuf:"bytes,2,opt,name=corresponding_debt,json=correspondingDebt,proto3" json:"corresponding_debt"` -} - -func (m *DebtAuction) Reset() { *m = DebtAuction{} } -func (m *DebtAuction) String() string { return proto.CompactTextString(m) } -func (*DebtAuction) ProtoMessage() {} -func (*DebtAuction) Descriptor() ([]byte, []int) { - return fileDescriptor_b9b5dac2c776ef9e, []int{2} -} -func (m *DebtAuction) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DebtAuction) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DebtAuction.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 *DebtAuction) XXX_Merge(src proto.Message) { - xxx_messageInfo_DebtAuction.Merge(m, src) -} -func (m *DebtAuction) XXX_Size() int { - return m.Size() -} -func (m *DebtAuction) XXX_DiscardUnknown() { - xxx_messageInfo_DebtAuction.DiscardUnknown(m) -} - -var xxx_messageInfo_DebtAuction proto.InternalMessageInfo - -// CollateralAuction is a two phase auction. -// Initially, in forward auction phase, bids can be placed up to a max bid. -// Then it switches to a reverse auction phase, where the initial amount up for auction is bid down. -// Unsold Lot is sent to LotReturns, being divided among the addresses by weight. -// Collateral auctions are normally used to sell off collateral seized from CDPs. -type CollateralAuction struct { - BaseAuction `protobuf:"bytes,1,opt,name=base_auction,json=baseAuction,proto3,embedded=base_auction" json:"base_auction"` - CorrespondingDebt types.Coin `protobuf:"bytes,2,opt,name=corresponding_debt,json=correspondingDebt,proto3" json:"corresponding_debt"` - MaxBid types.Coin `protobuf:"bytes,3,opt,name=max_bid,json=maxBid,proto3" json:"max_bid"` - LotReturns WeightedAddresses `protobuf:"bytes,4,opt,name=lot_returns,json=lotReturns,proto3" json:"lot_returns"` -} - -func (m *CollateralAuction) Reset() { *m = CollateralAuction{} } -func (m *CollateralAuction) String() string { return proto.CompactTextString(m) } -func (*CollateralAuction) ProtoMessage() {} -func (*CollateralAuction) Descriptor() ([]byte, []int) { - return fileDescriptor_b9b5dac2c776ef9e, []int{3} -} -func (m *CollateralAuction) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CollateralAuction) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CollateralAuction.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 *CollateralAuction) XXX_Merge(src proto.Message) { - xxx_messageInfo_CollateralAuction.Merge(m, src) -} -func (m *CollateralAuction) XXX_Size() int { - return m.Size() -} -func (m *CollateralAuction) XXX_DiscardUnknown() { - xxx_messageInfo_CollateralAuction.DiscardUnknown(m) -} - -var xxx_messageInfo_CollateralAuction proto.InternalMessageInfo - -// WeightedAddresses is a type for storing some addresses and associated weights. -type WeightedAddresses struct { - Addresses []github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,rep,name=addresses,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"addresses,omitempty"` - Weights []github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,rep,name=weights,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"weights"` -} - -func (m *WeightedAddresses) Reset() { *m = WeightedAddresses{} } -func (m *WeightedAddresses) String() string { return proto.CompactTextString(m) } -func (*WeightedAddresses) ProtoMessage() {} -func (*WeightedAddresses) Descriptor() ([]byte, []int) { - return fileDescriptor_b9b5dac2c776ef9e, []int{4} -} -func (m *WeightedAddresses) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *WeightedAddresses) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_WeightedAddresses.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 *WeightedAddresses) XXX_Merge(src proto.Message) { - xxx_messageInfo_WeightedAddresses.Merge(m, src) -} -func (m *WeightedAddresses) XXX_Size() int { - return m.Size() -} -func (m *WeightedAddresses) XXX_DiscardUnknown() { - xxx_messageInfo_WeightedAddresses.DiscardUnknown(m) -} - -var xxx_messageInfo_WeightedAddresses proto.InternalMessageInfo - -func init() { - proto.RegisterType((*BaseAuction)(nil), "kava.auction.v1beta1.BaseAuction") - proto.RegisterType((*SurplusAuction)(nil), "kava.auction.v1beta1.SurplusAuction") - proto.RegisterType((*DebtAuction)(nil), "kava.auction.v1beta1.DebtAuction") - proto.RegisterType((*CollateralAuction)(nil), "kava.auction.v1beta1.CollateralAuction") - proto.RegisterType((*WeightedAddresses)(nil), "kava.auction.v1beta1.WeightedAddresses") -} - -func init() { - proto.RegisterFile("kava/auction/v1beta1/auction.proto", fileDescriptor_b9b5dac2c776ef9e) -} - -var fileDescriptor_b9b5dac2c776ef9e = []byte{ - // 657 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x54, 0xcd, 0x6e, 0xd3, 0x4a, - 0x14, 0xce, 0x24, 0xbd, 0x49, 0x3a, 0xae, 0xee, 0x55, 0xe6, 0x56, 0xc8, 0xad, 0x90, 0x1d, 0xba, - 0x80, 0x80, 0x14, 0x5b, 0x2d, 0x1b, 0xc4, 0x06, 0xd5, 0x2d, 0xd0, 0x6e, 0xba, 0x30, 0x48, 0x48, - 0x6c, 0xcc, 0xd8, 0x33, 0x75, 0x46, 0xb5, 0x3d, 0x91, 0x67, 0x52, 0xd2, 0xb7, 0xe8, 0xc3, 0x74, - 0xc5, 0x1e, 0xa9, 0xaa, 0x84, 0x54, 0xb1, 0x42, 0x2c, 0x02, 0xa4, 0x6f, 0xc1, 0x0a, 0x8d, 0x3d, - 0x6e, 0x1b, 0xd1, 0x45, 0x90, 0x60, 0xc1, 0x2a, 0x3e, 0xdf, 0x9c, 0xf3, 0x7d, 0xe7, 0x37, 0x70, - 0xed, 0x00, 0x1f, 0x62, 0x17, 0x8f, 0x22, 0xc9, 0x78, 0xe6, 0x1e, 0xae, 0x87, 0x54, 0xe2, 0xf5, - 0xca, 0x76, 0x86, 0x39, 0x97, 0x1c, 0x2d, 0x2b, 0x1f, 0xa7, 0xc2, 0xb4, 0xcf, 0xaa, 0x15, 0x71, - 0x91, 0x72, 0xe1, 0x86, 0x58, 0xd0, 0xcb, 0xc0, 0x88, 0x33, 0x1d, 0xb5, 0xba, 0x52, 0xbe, 0x07, - 0x85, 0xe5, 0x96, 0x86, 0x7e, 0x5a, 0x8e, 0x79, 0xcc, 0x4b, 0x5c, 0x7d, 0x69, 0xd4, 0x8e, 0x39, - 0x8f, 0x13, 0xea, 0x16, 0x56, 0x38, 0xda, 0x77, 0x25, 0x4b, 0xa9, 0x90, 0x38, 0x1d, 0x96, 0x0e, - 0x6b, 0x1f, 0x1a, 0xd0, 0xf0, 0xb0, 0xa0, 0x9b, 0x65, 0x26, 0xe8, 0x16, 0xac, 0x33, 0x62, 0x82, - 0x2e, 0xe8, 0x2d, 0x78, 0xcd, 0xe9, 0xc4, 0xae, 0xef, 0x6e, 0xfb, 0x75, 0x46, 0xd0, 0x6d, 0xb8, - 0xc8, 0x32, 0x26, 0x19, 0x96, 0x3c, 0x37, 0xeb, 0x5d, 0xd0, 0x5b, 0xf4, 0xaf, 0x00, 0xb4, 0x0e, - 0x1b, 0x09, 0x97, 0x66, 0xa3, 0x0b, 0x7a, 0xc6, 0xc6, 0x8a, 0xa3, 0x13, 0x53, 0x55, 0x54, 0xa5, - 0x39, 0x5b, 0x9c, 0x65, 0xde, 0xc2, 0xe9, 0xc4, 0xae, 0xf9, 0xca, 0x17, 0xbd, 0x81, 0xcd, 0x90, - 0x11, 0x42, 0x73, 0x73, 0xa1, 0x0b, 0x7a, 0x4b, 0xde, 0xce, 0xf7, 0x89, 0xdd, 0x8f, 0x99, 0x1c, - 0x8c, 0x42, 0x27, 0xe2, 0xa9, 0x2e, 0x4e, 0xff, 0xf4, 0x05, 0x39, 0x70, 0xe5, 0xd1, 0x90, 0x0a, - 0x67, 0x33, 0x8a, 0x36, 0x09, 0xc9, 0xa9, 0x10, 0x1f, 0x4f, 0xfa, 0xff, 0x6b, 0x25, 0x8d, 0x78, - 0x47, 0x92, 0x0a, 0x5f, 0xf3, 0xaa, 0xa4, 0x42, 0x46, 0xcc, 0x7f, 0xe6, 0x4c, 0x2a, 0x64, 0x04, - 0x3d, 0x80, 0x9d, 0x01, 0x16, 0x41, 0x4e, 0x23, 0xca, 0x0e, 0x29, 0x09, 0x42, 0x46, 0x84, 0xd9, - 0xec, 0x82, 0x5e, 0xdb, 0xff, 0x6f, 0x80, 0x85, 0xaf, 0x71, 0x8f, 0x11, 0x81, 0x9e, 0xc0, 0x36, - 0xcd, 0x48, 0xa0, 0x1a, 0x6a, 0xb6, 0x0a, 0x8d, 0x55, 0xa7, 0xec, 0xb6, 0x53, 0x75, 0xdb, 0x79, - 0x59, 0x75, 0xdb, 0x6b, 0x2b, 0x91, 0xe3, 0x2f, 0x36, 0xf0, 0x5b, 0x34, 0x23, 0x0a, 0x47, 0xcf, - 0xe0, 0x52, 0x8a, 0xc7, 0xc1, 0x25, 0x49, 0xfb, 0x17, 0x48, 0x60, 0x8a, 0xc7, 0x4f, 0x4b, 0x9e, - 0xc7, 0xc6, 0xd9, 0x49, 0xbf, 0xa5, 0xe7, 0xb7, 0x96, 0xc2, 0x7f, 0x5f, 0x8c, 0xf2, 0x61, 0x32, - 0x12, 0xd5, 0x44, 0xf7, 0xe0, 0x92, 0xaa, 0x39, 0xd0, 0xbb, 0x56, 0xcc, 0xd6, 0xd8, 0xb8, 0xe3, - 0xdc, 0xb4, 0x80, 0xce, 0xb5, 0x55, 0x28, 0xd5, 0xce, 0x27, 0x36, 0xf0, 0x8d, 0xf0, 0x0a, 0x9e, - 0x95, 0x7b, 0x07, 0xa0, 0xb1, 0x4d, 0x43, 0xf9, 0x87, 0xc4, 0xd0, 0x1e, 0x44, 0x11, 0xcf, 0x73, - 0x2a, 0x86, 0x3c, 0x23, 0x2c, 0x8b, 0x03, 0x42, 0x43, 0x59, 0xec, 0xdf, 0x1c, 0x23, 0xed, 0xcc, - 0x84, 0xaa, 0x34, 0x67, 0x93, 0x3f, 0xab, 0xc3, 0xce, 0x16, 0x4f, 0x12, 0x2c, 0x69, 0x8e, 0x93, - 0xbf, 0xa4, 0x04, 0xf4, 0x08, 0xb6, 0xd4, 0xda, 0xa8, 0xd5, 0x9e, 0xf3, 0xde, 0x9a, 0x29, 0x1e, - 0x7b, 0x8c, 0xa0, 0x3d, 0x68, 0x24, 0x5c, 0x06, 0x39, 0x95, 0xa3, 0x3c, 0x13, 0xc5, 0xdd, 0x19, - 0x1b, 0xf7, 0x6e, 0x2e, 0xec, 0x15, 0x65, 0xf1, 0x40, 0x52, 0xa2, 0x2f, 0x8b, 0x0a, 0xcd, 0x05, - 0x13, 0x2e, 0xfd, 0x92, 0x60, 0xb6, 0x99, 0xef, 0x01, 0xec, 0xfc, 0x14, 0x84, 0xf6, 0xe1, 0x22, - 0xae, 0x0c, 0x13, 0x74, 0x1b, 0xbf, 0xf5, 0xd0, 0xaf, 0xa8, 0xd1, 0x0e, 0x6c, 0xbd, 0x2d, 0xc4, - 0x85, 0x59, 0x2f, 0x54, 0x1c, 0x95, 0xed, 0xe7, 0x89, 0x7d, 0x77, 0x0e, 0xa5, 0xdd, 0x4c, 0xfa, - 0x55, 0xb8, 0xf7, 0xfc, 0xf4, 0x9b, 0x55, 0x3b, 0x9d, 0x5a, 0xe0, 0x7c, 0x6a, 0x81, 0xaf, 0x53, - 0x0b, 0x1c, 0x5f, 0x58, 0xb5, 0xf3, 0x0b, 0xab, 0xf6, 0xe9, 0xc2, 0xaa, 0xbd, 0xbe, 0x7f, 0x8d, - 0x4e, 0xf5, 0xad, 0x9f, 0xe0, 0x50, 0x14, 0x5f, 0xee, 0xf8, 0xf2, 0x1f, 0xbf, 0x60, 0x0d, 0x9b, - 0xc5, 0x01, 0x3f, 0xfc, 0x11, 0x00, 0x00, 0xff, 0xff, 0x87, 0x6d, 0x9c, 0x17, 0x0e, 0x06, 0x00, - 0x00, -} - -func (m *BaseAuction) 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 *BaseAuction) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *BaseAuction) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.MaxEndTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.MaxEndTime):]) - if err1 != nil { - return 0, err1 - } - i -= n1 - i = encodeVarintAuction(dAtA, i, uint64(n1)) - i-- - dAtA[i] = 0x42 - n2, err2 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.EndTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.EndTime):]) - if err2 != nil { - return 0, err2 - } - i -= n2 - i = encodeVarintAuction(dAtA, i, uint64(n2)) - i-- - dAtA[i] = 0x3a - if m.HasReceivedBids { - i-- - if m.HasReceivedBids { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x30 - } - { - size, err := m.Bid.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - if len(m.Bidder) > 0 { - i -= len(m.Bidder) - copy(dAtA[i:], m.Bidder) - i = encodeVarintAuction(dAtA, i, uint64(len(m.Bidder))) - i-- - dAtA[i] = 0x22 - } - { - size, err := m.Lot.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Initiator) > 0 { - i -= len(m.Initiator) - copy(dAtA[i:], m.Initiator) - i = encodeVarintAuction(dAtA, i, uint64(len(m.Initiator))) - i-- - dAtA[i] = 0x12 - } - if m.ID != 0 { - i = encodeVarintAuction(dAtA, i, uint64(m.ID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *SurplusAuction) 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 *SurplusAuction) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SurplusAuction) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.BaseAuction.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *DebtAuction) 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 *DebtAuction) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DebtAuction) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.CorrespondingDebt.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.BaseAuction.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *CollateralAuction) 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 *CollateralAuction) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CollateralAuction) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.LotReturns.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.MaxBid.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.CorrespondingDebt.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.BaseAuction.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *WeightedAddresses) 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 *WeightedAddresses) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *WeightedAddresses) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Weights) > 0 { - for iNdEx := len(m.Weights) - 1; iNdEx >= 0; iNdEx-- { - { - size := m.Weights[iNdEx].Size() - i -= size - if _, err := m.Weights[iNdEx].MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Addresses) > 0 { - for iNdEx := len(m.Addresses) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Addresses[iNdEx]) - copy(dAtA[i:], m.Addresses[iNdEx]) - i = encodeVarintAuction(dAtA, i, uint64(len(m.Addresses[iNdEx]))) - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintAuction(dAtA []byte, offset int, v uint64) int { - offset -= sovAuction(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *BaseAuction) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.ID != 0 { - n += 1 + sovAuction(uint64(m.ID)) - } - l = len(m.Initiator) - if l > 0 { - n += 1 + l + sovAuction(uint64(l)) - } - l = m.Lot.Size() - n += 1 + l + sovAuction(uint64(l)) - l = len(m.Bidder) - if l > 0 { - n += 1 + l + sovAuction(uint64(l)) - } - l = m.Bid.Size() - n += 1 + l + sovAuction(uint64(l)) - if m.HasReceivedBids { - n += 2 - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.EndTime) - n += 1 + l + sovAuction(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.MaxEndTime) - n += 1 + l + sovAuction(uint64(l)) - return n -} - -func (m *SurplusAuction) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseAuction.Size() - n += 1 + l + sovAuction(uint64(l)) - return n -} - -func (m *DebtAuction) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseAuction.Size() - n += 1 + l + sovAuction(uint64(l)) - l = m.CorrespondingDebt.Size() - n += 1 + l + sovAuction(uint64(l)) - return n -} - -func (m *CollateralAuction) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseAuction.Size() - n += 1 + l + sovAuction(uint64(l)) - l = m.CorrespondingDebt.Size() - n += 1 + l + sovAuction(uint64(l)) - l = m.MaxBid.Size() - n += 1 + l + sovAuction(uint64(l)) - l = m.LotReturns.Size() - n += 1 + l + sovAuction(uint64(l)) - return n -} - -func (m *WeightedAddresses) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Addresses) > 0 { - for _, b := range m.Addresses { - l = len(b) - n += 1 + l + sovAuction(uint64(l)) - } - } - if len(m.Weights) > 0 { - for _, e := range m.Weights { - l = e.Size() - n += 1 + l + sovAuction(uint64(l)) - } - } - return n -} - -func sovAuction(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozAuction(x uint64) (n int) { - return sovAuction(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *BaseAuction) 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 ErrIntOverflowAuction - } - 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: BaseAuction: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BaseAuction: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - m.ID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Initiator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - 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 ErrInvalidLengthAuction - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Initiator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Lot", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Lot.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Bidder", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Bidder = append(m.Bidder[:0], dAtA[iNdEx:postIndex]...) - if m.Bidder == nil { - m.Bidder = []byte{} - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Bid", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Bid.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field HasReceivedBids", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.HasReceivedBids = bool(v != 0) - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EndTime", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.EndTime, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaxEndTime", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.MaxEndTime, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuction(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuction - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *SurplusAuction) 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 ErrIntOverflowAuction - } - 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: SurplusAuction: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SurplusAuction: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseAuction", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseAuction.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuction(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuction - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DebtAuction) 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 ErrIntOverflowAuction - } - 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: DebtAuction: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DebtAuction: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseAuction", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseAuction.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CorrespondingDebt", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.CorrespondingDebt.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuction(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuction - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CollateralAuction) 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 ErrIntOverflowAuction - } - 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: CollateralAuction: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CollateralAuction: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseAuction", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseAuction.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CorrespondingDebt", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.CorrespondingDebt.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaxBid", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MaxBid.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LotReturns", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.LotReturns.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuction(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuction - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *WeightedAddresses) 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 ErrIntOverflowAuction - } - 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: WeightedAddresses: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: WeightedAddresses: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Addresses", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Addresses = append(m.Addresses, make([]byte, postIndex-iNdEx)) - copy(m.Addresses[len(m.Addresses)-1], dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Weights", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var v github_com_cosmos_cosmos_sdk_types.Int - m.Weights = append(m.Weights, v) - if err := m.Weights[len(m.Weights)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuction(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuction - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipAuction(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, ErrIntOverflowAuction - } - 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, ErrIntOverflowAuction - } - 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, ErrIntOverflowAuction - } - 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, ErrInvalidLengthAuction - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupAuction - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthAuction - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthAuction = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowAuction = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupAuction = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/auction/types/auctions.go b/x/auction/types/auctions.go deleted file mode 100644 index 73fcb9cf..00000000 --- a/x/auction/types/auctions.go +++ /dev/null @@ -1,291 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "strings" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/gogoproto/proto" -) - -const ( - CollateralAuctionType = "collateral" - SurplusAuctionType = "surplus" - DebtAuctionType = "debt" - ForwardAuctionPhase = "forward" - ReverseAuctionPhase = "reverse" -) - -// DistantFuture is a very large time value to use as initial the ending time for auctions. -// It is not set to the max time supported. This can cause problems with time comparisons, see https://stackoverflow.com/a/32620397. -// Also amino panics when encoding times ≥ the start of year 10000. -var DistantFuture = time.Date(9000, 1, 1, 0, 0, 0, 0, time.UTC) - -var ( - _ Auction = &SurplusAuction{} - _ GenesisAuction = &SurplusAuction{} - _ Auction = &DebtAuction{} - _ GenesisAuction = &DebtAuction{} - _ Auction = &CollateralAuction{} - _ GenesisAuction = &CollateralAuction{} -) - -// --------------- Shared auction functionality --------------- - -// Auction is an interface for handling common actions on auctions. -type Auction interface { - proto.Message - - GetID() uint64 - WithID(uint64) Auction - - GetInitiator() string - GetLot() sdk.Coin - GetBidder() sdk.AccAddress - GetBid() sdk.Coin - GetEndTime() time.Time - GetMaxEndTime() time.Time - - GetType() string - GetPhase() string -} - -// --------------- BaseAuction --------------- - -func (a BaseAuction) GetID() uint64 { return a.ID } - -func (a BaseAuction) GetBid() sdk.Coin { return a.Bid } - -func (a BaseAuction) GetLot() sdk.Coin { return a.Lot } - -func (a BaseAuction) GetBidder() sdk.AccAddress { return a.Bidder } - -func (a BaseAuction) GetInitiator() string { return a.Initiator } - -func (a BaseAuction) GetEndTime() time.Time { return a.EndTime } - -func (a BaseAuction) GetMaxEndTime() time.Time { return a.MaxEndTime } - -// ValidateAuction verifies that the auction end time is before max end time -func ValidateAuction(a Auction) error { - // ID can be 0 for surplus, debt and collateral auctions - if strings.TrimSpace(a.GetInitiator()) == "" { - return errors.New("auction initiator cannot be blank") - } - if !a.GetLot().IsValid() { - return fmt.Errorf("invalid lot: %s", a.GetLot()) - } - if !a.GetBid().IsValid() { - return fmt.Errorf("invalid bid: %s", a.GetBid()) - } - if a.GetEndTime().Unix() <= 0 || a.GetMaxEndTime().Unix() <= 0 { - return errors.New("end time cannot be zero") - } - if a.GetEndTime().After(a.GetMaxEndTime()) { - return fmt.Errorf("MaxEndTime < EndTime (%s < %s)", a.GetMaxEndTime(), a.GetEndTime()) - } - return nil -} - -// --------------- SurplusAuction --------------- - -// NewSurplusAuction returns a new surplus auction. -func NewSurplusAuction(seller string, lot sdk.Coin, bidDenom string, endTime time.Time) SurplusAuction { - auction := SurplusAuction{ - BaseAuction: BaseAuction{ - // No Id - Initiator: seller, - Lot: lot, - Bidder: nil, - Bid: sdk.NewInt64Coin(bidDenom, 0), - HasReceivedBids: false, // new auctions don't have any bids - EndTime: endTime, - MaxEndTime: endTime, - }, - } - return auction -} - -func (a SurplusAuction) WithID(id uint64) Auction { - a.ID = id - return Auction(&a) -} - -// GetPhase returns the direction of a surplus auction, which never changes. -func (a SurplusAuction) GetPhase() string { return ForwardAuctionPhase } - -// GetType returns the auction type. Used to identify auctions in event attributes. -func (a SurplusAuction) GetType() string { return SurplusAuctionType } - -// GetModuleAccountCoins returns the total number of coins held in the module account for this auction. -// It is used in genesis initialize the module account correctly. -func (a SurplusAuction) GetModuleAccountCoins() sdk.Coins { - // a.Bid is paid out on bids, so is never stored in the module account - return sdk.NewCoins(a.Lot) -} - -func (a SurplusAuction) Validate() error { - return ValidateAuction(&a) -} - -// --------------- DebtAuction --------------- - -// NewDebtAuction returns a new debt auction. -func NewDebtAuction(buyerModAccName string, bid sdk.Coin, initialLot sdk.Coin, endTime time.Time, debt sdk.Coin) DebtAuction { - // Note: Bidder is set to the initiator's module account address instead of module name. (when the first bid is placed, it is paid out to the initiator) - // Setting to the module account address bypasses calling supply.SendCoinsFromModuleToModule, instead calls SendCoinsFromModuleToAccount. - // This isn't a problem currently, but if additional logic/validation was added for sending to coins to Module Accounts, it would be bypassed. - auction := DebtAuction{ - BaseAuction: BaseAuction{ - // no ID - Initiator: buyerModAccName, - Lot: initialLot, - Bidder: authtypes.NewModuleAddress(buyerModAccName), // send proceeds from the first bid to the buyer. - Bid: bid, // amount that the buyer is buying - doesn't change over course of auction - HasReceivedBids: false, // new auctions don't have any bids - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: debt, - } - return auction -} - -func (a DebtAuction) WithID(id uint64) Auction { - a.ID = id - return Auction(&a) -} - -// GetPhase returns the direction of a debt auction, which never changes. -func (a DebtAuction) GetPhase() string { return ReverseAuctionPhase } - -// GetType returns the auction type. Used to identify auctions in event attributes. -func (a DebtAuction) GetType() string { return DebtAuctionType } - -// GetModuleAccountCoins returns the total number of coins held in the module account for this auction. -// It is used in genesis initialize the module account correctly. -func (a DebtAuction) GetModuleAccountCoins() sdk.Coins { - // a.Lot is minted at auction close, so is never stored in the module account - // a.Bid is paid out on bids, so is never stored in the module account - return sdk.NewCoins(a.CorrespondingDebt) -} - -// Validate validates the DebtAuction fields values. -func (a DebtAuction) Validate() error { - if !a.CorrespondingDebt.IsValid() { - return fmt.Errorf("invalid corresponding debt: %s", a.CorrespondingDebt) - } - return ValidateAuction(&a) -} - -// --------------- CollateralAuction --------------- - -// NewCollateralAuction returns a new collateral auction. -func NewCollateralAuction(seller string, lot sdk.Coin, endTime time.Time, maxBid sdk.Coin, lotReturns WeightedAddresses, debt sdk.Coin) CollateralAuction { - auction := CollateralAuction{ - BaseAuction: BaseAuction{ - // no ID - Initiator: seller, - Lot: lot, - Bidder: nil, - Bid: sdk.NewInt64Coin(maxBid.Denom, 0), - HasReceivedBids: false, // new auctions don't have any bids - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: debt, - MaxBid: maxBid, - LotReturns: lotReturns, - } - return auction -} - -func (a CollateralAuction) WithID(id uint64) Auction { - a.ID = id - return Auction(&a) -} - -// GetType returns the auction type. Used to identify auctions in event attributes. -func (a CollateralAuction) GetType() string { return CollateralAuctionType } - -// IsReversePhase returns whether the auction has switched over to reverse phase or not. -// CollateralAuctions initially start in forward phase. -func (a CollateralAuction) IsReversePhase() bool { - return a.Bid.IsEqual(a.MaxBid) -} - -// GetPhase returns the direction of a collateral auction. -func (a CollateralAuction) GetPhase() string { - if a.IsReversePhase() { - return ReverseAuctionPhase - } - return ForwardAuctionPhase -} - -// GetLotReturns returns the auction's lot returns as weighted addresses -func (a CollateralAuction) GetLotReturns() WeightedAddresses { return a.LotReturns } - -// GetModuleAccountCoins returns the total number of coins held in the module account for this auction. -// It is used in genesis initialize the module account correctly. -func (a CollateralAuction) GetModuleAccountCoins() sdk.Coins { - // a.Bid is paid out on bids, so is never stored in the module account - return sdk.NewCoins(a.Lot).Add(sdk.NewCoins(a.CorrespondingDebt)...) -} - -// Validate validates the CollateralAuction fields values. -func (a CollateralAuction) Validate() error { - if !a.CorrespondingDebt.IsValid() { - return fmt.Errorf("invalid corresponding debt: %s", a.CorrespondingDebt) - } - if !a.MaxBid.IsValid() { - return fmt.Errorf("invalid max bid: %s", a.MaxBid) - } - if err := a.LotReturns.Validate(); err != nil { - return fmt.Errorf("invalid lot returns: %w", err) - } - return ValidateAuction(&a) -} - -// NewWeightedAddresses returns a new list addresses with weights. -func NewWeightedAddresses(addrs []sdk.AccAddress, weights []sdkmath.Int) (WeightedAddresses, error) { - wa := WeightedAddresses{ - Addresses: addrs, - Weights: weights, - } - if err := wa.Validate(); err != nil { - return WeightedAddresses{}, err - } - return wa, nil -} - -// Validate checks for that the weights are not negative, not all zero, and the lengths match. -func (wa WeightedAddresses) Validate() error { - if len(wa.Weights) < 1 { - return fmt.Errorf("must be at least 1 weighted address") - } - - if len(wa.Addresses) != len(wa.Weights) { - return fmt.Errorf("number of addresses doesn't match number of weights, %d ≠ %d", len(wa.Addresses), len(wa.Weights)) - } - - totalWeight := sdk.ZeroInt() - for i := range wa.Addresses { - if wa.Addresses[i].Empty() { - return fmt.Errorf("address %d cannot be empty", i) - } - if wa.Weights[i].IsNegative() { - return fmt.Errorf("weight %d contains a negative amount: %s", i, wa.Weights[i]) - } - totalWeight = totalWeight.Add(wa.Weights[i]) - } - - if !totalWeight.IsPositive() { - return fmt.Errorf("total weight must be positive") - } - - return nil -} diff --git a/x/auction/types/auctions_test.go b/x/auction/types/auctions_test.go deleted file mode 100644 index 86efb9cd..00000000 --- a/x/auction/types/auctions_test.go +++ /dev/null @@ -1,356 +0,0 @@ -package types - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - TestInitiatorModuleName = "liquidator" - TestLotDenom = "usdx" - TestLotAmount = 100 - TestBidDenom = "kava" - TestBidAmount = 20 - TestDebtDenom = "debt" - TestDebtAmount1 = 20 - TestDebtAmount2 = 15 - TestExtraEndTime = 10000 - TestAuctionID = 9999123 - testAccAddress1 = "kava1qcfdf69js922qrdr4yaww3ax7gjml6pd39p8lj" - testAccAddress2 = "kava1pdfav2cjhry9k79nu6r8kgknnjtq6a7rcr0qlr" -) - -func init() { - sdk.GetConfig().SetBech32PrefixForAccount("kava", "kava"+sdk.PrefixPublic) -} - -func d(amount string) sdk.Dec { return sdk.MustNewDecFromStr(amount) } -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } -func i(n int64) sdkmath.Int { return sdkmath.NewInt(n) } -func is(ns ...int64) (is []sdkmath.Int) { - for _, n := range ns { - is = append(is, sdkmath.NewInt(n)) - } - return -} - -func TestNewWeightedAddresses(t *testing.T) { - addr1, err := sdk.AccAddressFromBech32(testAccAddress1) - require.NoError(t, err) - - addr2, err := sdk.AccAddressFromBech32(testAccAddress2) - require.NoError(t, err) - - tests := []struct { - name string - addresses []sdk.AccAddress - weights []sdkmath.Int - expPass bool - }{ - { - "normal", - []sdk.AccAddress{addr1, addr2}, - []sdkmath.Int{sdkmath.NewInt(6), sdkmath.NewInt(8)}, - true, - }, - { - "empty address", - []sdk.AccAddress{nil, nil}, - []sdkmath.Int{sdkmath.NewInt(6), sdkmath.NewInt(8)}, - false, - }, - { - "mismatched", - []sdk.AccAddress{addr1, addr2}, - []sdkmath.Int{sdkmath.NewInt(6)}, - false, - }, - { - "negative weight", - []sdk.AccAddress{addr1, addr2}, - is(6, -8), - false, - }, - { - "zero weight", - []sdk.AccAddress{addr1, addr2}, - is(0, 0), - false, - }, - } - - // Run NewWeightedAdresses tests - for _, tc := range tests { - // Attempt to instantiate new WeightedAddresses - weightedAddresses, err := NewWeightedAddresses(tc.addresses, tc.weights) - - if tc.expPass { - require.NoError(t, err) - require.Equal(t, tc.addresses, weightedAddresses.Addresses) - require.Equal(t, tc.weights, weightedAddresses.Weights) - } else { - require.Error(t, err) - } - } -} - -func TestDebtAuctionValidate(t *testing.T) { - addr1, err := sdk.AccAddressFromBech32(testAccAddress1) - require.NoError(t, err) - - now := time.Now() - - tests := []struct { - msg string - auction DebtAuction - expPass bool - }{ - { - "valid auction", - DebtAuction{ - BaseAuction: BaseAuction{ - ID: 1, - Initiator: testAccAddress1, - Lot: c("kava", 1), - Bidder: addr1, - Bid: c("kava", 1), - EndTime: now, - MaxEndTime: now, - HasReceivedBids: true, - }, - CorrespondingDebt: c("kava", 1), - }, - true, - }, - { - "invalid corresponding debt", - DebtAuction{ - BaseAuction: BaseAuction{ - ID: 1, - Initiator: testAccAddress1, - Lot: c("kava", 1), - Bidder: addr1, - Bid: c("kava", 1), - EndTime: now, - MaxEndTime: now, - HasReceivedBids: true, - }, - CorrespondingDebt: sdk.Coin{Denom: "", Amount: sdkmath.NewInt(1)}, - }, - false, - }, - } - - for _, tc := range tests { - - err := tc.auction.Validate() - - if tc.expPass { - require.NoError(t, err, tc.msg) - } else { - require.Error(t, err, tc.msg) - } - } -} - -func TestCollateralAuctionValidate(t *testing.T) { - addr1, err := sdk.AccAddressFromBech32(testAccAddress1) - require.NoError(t, err) - - now := time.Now() - - tests := []struct { - msg string - auction CollateralAuction - expPass bool - }{ - { - "valid auction", - CollateralAuction{ - BaseAuction: BaseAuction{ - ID: 1, - Initiator: testAccAddress1, - Lot: c("kava", 1), - Bidder: addr1, - Bid: c("kava", 1), - EndTime: now, - MaxEndTime: now, - HasReceivedBids: true, - }, - CorrespondingDebt: c("kava", 1), - MaxBid: c("kava", 1), - LotReturns: WeightedAddresses{ - Addresses: []sdk.AccAddress{addr1}, - Weights: []sdkmath.Int{sdkmath.NewInt(1)}, - }, - }, - true, - }, - { - "invalid corresponding debt", - CollateralAuction{ - BaseAuction: BaseAuction{ - ID: 1, - Initiator: testAccAddress1, - Lot: c("kava", 1), - Bidder: addr1, - Bid: c("kava", 1), - EndTime: now, - MaxEndTime: now, - HasReceivedBids: true, - }, - CorrespondingDebt: sdk.Coin{Denom: "DENOM", Amount: sdkmath.NewInt(1)}, - }, - false, - }, - { - "invalid max bid", - CollateralAuction{ - BaseAuction: BaseAuction{ - ID: 1, - Initiator: testAccAddress1, - Lot: c("kava", 1), - Bidder: addr1, - Bid: c("kava", 1), - EndTime: now, - MaxEndTime: now, - HasReceivedBids: true, - }, - CorrespondingDebt: c("kava", 1), - MaxBid: sdk.Coin{Denom: "DENOM", Amount: sdkmath.NewInt(1)}, - }, - false, - }, - { - "invalid lot returns", - CollateralAuction{ - BaseAuction: BaseAuction{ - ID: 1, - Initiator: testAccAddress1, - Lot: c("kava", 1), - Bidder: addr1, - Bid: c("kava", 1), - EndTime: now, - MaxEndTime: now, - HasReceivedBids: true, - }, - CorrespondingDebt: c("kava", 1), - MaxBid: c("kava", 1), - LotReturns: WeightedAddresses{ - Addresses: []sdk.AccAddress{nil}, - Weights: []sdkmath.Int{sdkmath.NewInt(1)}, - }, - }, - false, - }, - } - - for _, tc := range tests { - - err := tc.auction.Validate() - - if tc.expPass { - require.NoError(t, err, tc.msg) - } else { - require.Error(t, err, tc.msg) - } - } -} - -func TestBaseAuctionGetters(t *testing.T) { - endTime := time.Now().Add(TestExtraEndTime) - - // Create a new BaseAuction (via SurplusAuction) - auction := NewSurplusAuction( - TestInitiatorModuleName, - c(TestLotDenom, TestLotAmount), - TestBidDenom, endTime, - ) - - auctionID := auction.GetID() - auctionBid := auction.GetBid() - auctionLot := auction.GetLot() - auctionEndTime := auction.GetEndTime() - - require.Equal(t, auction.ID, auctionID) - require.Equal(t, auction.Bid, auctionBid) - require.Equal(t, auction.Lot, auctionLot) - require.Equal(t, auction.EndTime, auctionEndTime) -} - -func TestNewSurplusAuction(t *testing.T) { - endTime := time.Now().Add(TestExtraEndTime) - - // Create a new SurplusAuction - surplusAuction := NewSurplusAuction( - TestInitiatorModuleName, - c(TestLotDenom, TestLotAmount), - TestBidDenom, endTime, - ) - - require.Equal(t, surplusAuction.Initiator, TestInitiatorModuleName) - require.Equal(t, surplusAuction.Lot, c(TestLotDenom, TestLotAmount)) - require.Equal(t, surplusAuction.Bid, c(TestBidDenom, 0)) - require.Equal(t, surplusAuction.EndTime, endTime) - require.Equal(t, surplusAuction.MaxEndTime, endTime) -} - -func TestNewDebtAuction(t *testing.T) { - endTime := time.Now().Add(TestExtraEndTime) - - // Create a new DebtAuction - debtAuction := NewDebtAuction( - TestInitiatorModuleName, - c(TestBidDenom, TestBidAmount), - c(TestLotDenom, TestLotAmount), - endTime, - c(TestDebtDenom, TestDebtAmount1), - ) - - require.Equal(t, debtAuction.Initiator, TestInitiatorModuleName) - require.Equal(t, debtAuction.Lot, c(TestLotDenom, TestLotAmount)) - require.Equal(t, debtAuction.Bid, c(TestBidDenom, TestBidAmount)) - require.Equal(t, debtAuction.EndTime, endTime) - require.Equal(t, debtAuction.MaxEndTime, endTime) - require.Equal(t, debtAuction.CorrespondingDebt, c(TestDebtDenom, TestDebtAmount1)) -} - -func TestNewCollateralAuction(t *testing.T) { - // Set up WeightedAddresses - addresses := []sdk.AccAddress{ - sdk.AccAddress([]byte(testAccAddress1)), - sdk.AccAddress([]byte(testAccAddress2)), - } - - weights := []sdkmath.Int{ - sdkmath.NewInt(6), - sdkmath.NewInt(8), - } - - weightedAddresses, _ := NewWeightedAddresses(addresses, weights) - - endTime := time.Now().Add(TestExtraEndTime) - - collateralAuction := NewCollateralAuction( - TestInitiatorModuleName, - c(TestLotDenom, TestLotAmount), - endTime, - c(TestBidDenom, TestBidAmount), - weightedAddresses, - c(TestDebtDenom, TestDebtAmount2), - ) - - require.Equal(t, collateralAuction.Initiator, TestInitiatorModuleName) - require.Equal(t, collateralAuction.Lot, c(TestLotDenom, TestLotAmount)) - require.Equal(t, collateralAuction.Bid, c(TestBidDenom, 0)) - require.Equal(t, collateralAuction.EndTime, endTime) - require.Equal(t, collateralAuction.MaxEndTime, endTime) - require.Equal(t, collateralAuction.MaxBid, c(TestBidDenom, TestBidAmount)) - require.Equal(t, collateralAuction.LotReturns, weightedAddresses) - require.Equal(t, collateralAuction.CorrespondingDebt, c(TestDebtDenom, TestDebtAmount2)) -} diff --git a/x/auction/types/codec.go b/x/auction/types/codec.go deleted file mode 100644 index 3e33b9ca..00000000 --- a/x/auction/types/codec.go +++ /dev/null @@ -1,65 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the -// governance module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgPlaceBid{}, "auction/MsgPlaceBid", nil) - - cdc.RegisterInterface((*GenesisAuction)(nil), nil) - cdc.RegisterInterface((*Auction)(nil), nil) - cdc.RegisterConcrete(&SurplusAuction{}, "auction/SurplusAuction", nil) - cdc.RegisterConcrete(&DebtAuction{}, "auction/DebtAuction", nil) - cdc.RegisterConcrete(&CollateralAuction{}, "auction/CollateralAuction", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgPlaceBid{}, - ) - - registry.RegisterInterface( - "kava.auction.v1beta1.Auction", - (*Auction)(nil), - &SurplusAuction{}, - &DebtAuction{}, - &CollateralAuction{}, - ) - - registry.RegisterInterface( - "kava.auction.v1beta1.GenesisAuction", - (*GenesisAuction)(nil), - &SurplusAuction{}, - &DebtAuction{}, - &CollateralAuction{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - - // ModuleCdc is an amino codec instance with this module's types registered. - // - // Deprecated: The codec used for serialization should be provided to this module and - // defined at the application level. - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/auction/types/errors.go b/x/auction/types/errors.go deleted file mode 100644 index 4a37f798..00000000 --- a/x/auction/types/errors.go +++ /dev/null @@ -1,30 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// DONTCOVER - -var ( - // ErrInvalidInitialAuctionID error for when the initial auction ID hasn't been set - ErrInvalidInitialAuctionID = errorsmod.Register(ModuleName, 2, "initial auction ID hasn't been set") - // ErrUnrecognizedAuctionType error for unrecognized auction type - ErrUnrecognizedAuctionType = errorsmod.Register(ModuleName, 3, "unrecognized auction type") - // ErrAuctionNotFound error for when an auction is not found - ErrAuctionNotFound = errorsmod.Register(ModuleName, 4, "auction not found") - // ErrAuctionHasNotExpired error for attempting to close an auction that has not passed its end time - ErrAuctionHasNotExpired = errorsmod.Register(ModuleName, 5, "auction can't be closed as curent block time has not passed auction end time") - // ErrAuctionHasExpired error for when an auction is closed and unavailable for bidding - ErrAuctionHasExpired = errorsmod.Register(ModuleName, 6, "auction has closed") - // ErrInvalidBidDenom error for when bid denom doesn't match auction bid denom - ErrInvalidBidDenom = errorsmod.Register(ModuleName, 7, "bid denom doesn't match auction bid denom") - // ErrInvalidLotDenom error for when lot denom doesn't match auction lot denom - ErrInvalidLotDenom = errorsmod.Register(ModuleName, 8, "lot denom doesn't match auction lot denom") - // ErrBidTooSmall error for when bid is not greater than auction's min bid amount - ErrBidTooSmall = errorsmod.Register(ModuleName, 9, "bid is not greater than auction's min new bid amount") - // ErrBidTooLarge error for when bid is larger than auction's maximum allowed bid - ErrBidTooLarge = errorsmod.Register(ModuleName, 10, "bid is greater than auction's max bid") - // ErrLotTooSmall error for when lot is less than zero - ErrLotTooSmall = errorsmod.Register(ModuleName, 11, "lot is not greater than auction's min new lot amount") - // ErrLotTooLarge error for when lot is not smaller than auction's max new lot amount - ErrLotTooLarge = errorsmod.Register(ModuleName, 12, "lot is greater than auction's max new lot amount") -) diff --git a/x/auction/types/events.go b/x/auction/types/events.go deleted file mode 100644 index b9389945..00000000 --- a/x/auction/types/events.go +++ /dev/null @@ -1,18 +0,0 @@ -package types - -// Events for the module -const ( - EventTypeAuctionStart = "auction_start" - EventTypeAuctionBid = "auction_bid" - EventTypeAuctionClose = "auction_close" - - AttributeValueCategory = ModuleName - AttributeKeyAuctionID = "auction_id" - AttributeKeyAuctionType = "auction_type" - AttributeKeyBidder = "bidder" - AttributeKeyLot = "lot" - AttributeKeyMaxBid = "max_bid" - AttributeKeyBid = "bid" - AttributeKeyEndTime = "end_time" - AttributeKeyCloseBlock = "close_block" -) diff --git a/x/auction/types/expected_keepers.go b/x/auction/types/expected_keepers.go deleted file mode 100644 index b7d65ea4..00000000 --- a/x/auction/types/expected_keepers.go +++ /dev/null @@ -1,22 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// AccountKeeper expected interface for the account keeper (noalias) -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI - GetModuleAccount(ctx sdk.Context, name string) types.ModuleAccountI -} - -// BankKeeper defines the expected interface needed to send coins -type BankKeeper interface { - SendCoinsFromModuleToModule(ctx sdk.Context, sender, recipient 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 - BurnCoins(ctx sdk.Context, name string, amt sdk.Coins) error - MintCoins(ctx sdk.Context, name string, amt sdk.Coins) error - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins -} diff --git a/x/auction/types/genesis.go b/x/auction/types/genesis.go deleted file mode 100644 index a513054a..00000000 --- a/x/auction/types/genesis.go +++ /dev/null @@ -1,127 +0,0 @@ -package types - -import ( - "fmt" - - types "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// DefaultNextAuctionID is the starting point for auction IDs. -const DefaultNextAuctionID uint64 = 1 - -// GenesisAuction extends the auction interface to add functionality -// needed for initializing auctions from genesis. -type GenesisAuction interface { - Auction - GetModuleAccountCoins() sdk.Coins - Validate() error -} - -// PackGenesisAuctions converts a GenesisAuction slice to Any slice -func PackGenesisAuctions(ga []GenesisAuction) ([]*types.Any, error) { - gaAny := make([]*types.Any, len(ga)) - for i, genesisAuction := range ga { - any, err := types.NewAnyWithValue(genesisAuction) - if err != nil { - return nil, err - } - gaAny[i] = any - } - - return gaAny, nil -} - -func mustPackGenesisAuctions(ga []GenesisAuction) []*types.Any { - anys, err := PackGenesisAuctions(ga) - if err != nil { - panic(err) - } - return anys -} - -// UnpackGenesisAuctions converts Any slice to GenesisAuctions slice -func UnpackGenesisAuctions(genesisAuctionsAny []*types.Any) ([]GenesisAuction, error) { - genesisAuctions := make([]GenesisAuction, len(genesisAuctionsAny)) - for i, any := range genesisAuctionsAny { - genesisAuction, ok := any.GetCachedValue().(GenesisAuction) - if !ok { - return nil, fmt.Errorf("expected genesis auction") - } - genesisAuctions[i] = genesisAuction - } - - return genesisAuctions, nil -} - -// Ensure this type will unpack contained interface types correctly when it is unmarshalled. -var _ types.UnpackInterfacesMessage = &GenesisState{} - -// NewGenesisState returns a new genesis state object for auctions module. -func NewGenesisState(nextID uint64, ap Params, ga []GenesisAuction) (*GenesisState, error) { - packedGA, err := PackGenesisAuctions(ga) - if err != nil { - return &GenesisState{}, err - } - - return &GenesisState{ - NextAuctionId: nextID, - Params: ap, - Auctions: packedGA, - }, nil -} - -// DefaultGenesisState returns the default genesis state for auction module. -func DefaultGenesisState() *GenesisState { - genesis, err := NewGenesisState( - DefaultNextAuctionID, - DefaultParams(), - []GenesisAuction{}, - ) - if err != nil { - panic(fmt.Sprintf("could not create default genesis state: %v", err)) - } - return genesis -} - -// Validate validates genesis inputs. It returns error if validation of any input fails. -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - - auctions, err := UnpackGenesisAuctions(gs.Auctions) - if err != nil { - return err - } - - ids := map[uint64]bool{} - for _, a := range auctions { - - if err := a.Validate(); err != nil { - return fmt.Errorf("found invalid auction: %w", err) - } - - if ids[a.GetID()] { - return fmt.Errorf("found duplicate auction ID (%d)", a.GetID()) - } - ids[a.GetID()] = true - - if a.GetID() >= gs.NextAuctionId { - return fmt.Errorf("found auction ID ≥ the nextAuctionID (%d ≥ %d)", a.GetID(), gs.NextAuctionId) - } - } - return nil -} - -// UnpackInterfaces hooks into unmarshalling to unpack any interface types contained within the GenesisState. -func (gs GenesisState) UnpackInterfaces(unpacker types.AnyUnpacker) error { - for _, any := range gs.Auctions { - var auction GenesisAuction - err := unpacker.UnpackAny(any, &auction) - if err != nil { - return err - } - } - return nil -} diff --git a/x/auction/types/genesis.pb.go b/x/auction/types/genesis.pb.go deleted file mode 100644 index d47b786a..00000000 --- a/x/auction/types/genesis.pb.go +++ /dev/null @@ -1,815 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/auction/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/codec/types" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/durationpb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 auction module's genesis state. -type GenesisState struct { - NextAuctionId uint64 `protobuf:"varint,1,opt,name=next_auction_id,json=nextAuctionId,proto3" json:"next_auction_id,omitempty"` - Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` - // Genesis auctions - Auctions []*types.Any `protobuf:"bytes,3,rep,name=auctions,proto3" json:"auctions,omitempty"` -} - -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_d0e5cb58293042f7, []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 - -// Params defines the parameters for the issuance module. -type Params struct { - MaxAuctionDuration time.Duration `protobuf:"bytes,1,opt,name=max_auction_duration,json=maxAuctionDuration,proto3,stdduration" json:"max_auction_duration"` - ForwardBidDuration time.Duration `protobuf:"bytes,6,opt,name=forward_bid_duration,json=forwardBidDuration,proto3,stdduration" json:"forward_bid_duration"` - ReverseBidDuration time.Duration `protobuf:"bytes,7,opt,name=reverse_bid_duration,json=reverseBidDuration,proto3,stdduration" json:"reverse_bid_duration"` - IncrementSurplus github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=increment_surplus,json=incrementSurplus,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"increment_surplus"` - IncrementDebt github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=increment_debt,json=incrementDebt,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"increment_debt"` - IncrementCollateral github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=increment_collateral,json=incrementCollateral,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"increment_collateral"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_d0e5cb58293042f7, []int{1} -} -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((*GenesisState)(nil), "kava.auction.v1beta1.GenesisState") - proto.RegisterType((*Params)(nil), "kava.auction.v1beta1.Params") -} - -func init() { - proto.RegisterFile("kava/auction/v1beta1/genesis.proto", fileDescriptor_d0e5cb58293042f7) -} - -var fileDescriptor_d0e5cb58293042f7 = []byte{ - // 496 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x93, 0xc1, 0x6e, 0xd3, 0x30, - 0x18, 0xc7, 0x93, 0x35, 0x94, 0xca, 0xed, 0xc6, 0x30, 0x39, 0xa4, 0x13, 0x4a, 0xab, 0x1e, 0xa6, - 0x72, 0xa8, 0xa3, 0x95, 0x1b, 0xb7, 0x85, 0x4a, 0x13, 0x9c, 0x50, 0xa6, 0x5d, 0xe0, 0x10, 0x39, - 0x89, 0x17, 0xa2, 0x25, 0x71, 0x65, 0x3b, 0xa5, 0x7d, 0x0b, 0x8e, 0x3c, 0x08, 0x87, 0x3d, 0x42, - 0xc5, 0x69, 0x47, 0xc4, 0x61, 0x40, 0xfb, 0x22, 0x28, 0x8e, 0x9b, 0x16, 0xd8, 0x65, 0x3b, 0xd5, - 0xfe, 0xbe, 0xff, 0xf7, 0xfb, 0xff, 0xed, 0x3a, 0x60, 0x70, 0x85, 0x67, 0xd8, 0xc1, 0x45, 0x28, - 0x12, 0x9a, 0x3b, 0xb3, 0x93, 0x80, 0x08, 0x7c, 0xe2, 0xc4, 0x24, 0x27, 0x3c, 0xe1, 0x68, 0xca, - 0xa8, 0xa0, 0xd0, 0x2c, 0x35, 0x48, 0x69, 0x90, 0xd2, 0x1c, 0x75, 0x43, 0xca, 0x33, 0xca, 0x7d, - 0xa9, 0x71, 0xaa, 0x4d, 0x35, 0x70, 0x64, 0xc6, 0x34, 0xa6, 0x55, 0xbd, 0x5c, 0xa9, 0x6a, 0x37, - 0xa6, 0x34, 0x4e, 0x89, 0x23, 0x77, 0x41, 0x71, 0xe9, 0xe0, 0x7c, 0xa1, 0x5a, 0xf6, 0xbf, 0xad, - 0xa8, 0x60, 0x58, 0xba, 0xc9, 0xca, 0xe0, 0x5a, 0x07, 0x9d, 0xb3, 0x2a, 0xd3, 0xb9, 0xc0, 0x82, - 0xc0, 0x63, 0xf0, 0x24, 0x27, 0x73, 0xe1, 0xab, 0x50, 0x7e, 0x12, 0x59, 0x7a, 0x5f, 0x1f, 0x1a, - 0xde, 0x7e, 0x59, 0x3e, 0xad, 0xaa, 0x6f, 0x22, 0xf8, 0x0a, 0x34, 0xa7, 0x98, 0xe1, 0x8c, 0x5b, - 0x7b, 0x7d, 0x7d, 0xd8, 0x1e, 0x3f, 0x47, 0x77, 0x9d, 0x05, 0xbd, 0x93, 0x1a, 0xd7, 0x58, 0xde, - 0xf6, 0x34, 0x4f, 0x4d, 0xc0, 0x09, 0x68, 0x29, 0x1d, 0xb7, 0x1a, 0xfd, 0xc6, 0xb0, 0x3d, 0x36, - 0x51, 0x95, 0x13, 0x6d, 0x72, 0xa2, 0xd3, 0x7c, 0xe1, 0xc2, 0x6f, 0x5f, 0x47, 0x07, 0x2a, 0x9d, - 0x72, 0xf6, 0xea, 0xc9, 0xc1, 0xb5, 0x01, 0x9a, 0x15, 0x1e, 0x5e, 0x00, 0x33, 0xc3, 0xf3, 0x3a, - 0xf3, 0xe6, 0x8c, 0x32, 0x79, 0x7b, 0xdc, 0xfd, 0x0f, 0x3e, 0x51, 0x02, 0xb7, 0x55, 0xe6, 0xfa, - 0xf2, 0xb3, 0xa7, 0x7b, 0x30, 0xc3, 0x73, 0xe5, 0xb1, 0xe9, 0x96, 0xd8, 0x4b, 0xca, 0x3e, 0x61, - 0x16, 0xf9, 0x41, 0x12, 0x6d, 0xb1, 0xcd, 0x7b, 0x60, 0x15, 0xc0, 0x4d, 0xa2, 0x5d, 0x2c, 0x23, - 0x33, 0xc2, 0x38, 0xf9, 0x1b, 0xfb, 0xf8, 0x1e, 0x58, 0x05, 0xd8, 0xc5, 0x7e, 0x00, 0x4f, 0x93, - 0x3c, 0x64, 0x24, 0x23, 0xb9, 0xf0, 0x79, 0xc1, 0xa6, 0x69, 0x51, 0x5e, 0xaf, 0x3e, 0xec, 0xb8, - 0xa8, 0x1c, 0xfc, 0x71, 0xdb, 0x3b, 0x8e, 0x13, 0xf1, 0xb1, 0x08, 0x50, 0x48, 0x33, 0xf5, 0xae, - 0xd4, 0xcf, 0x88, 0x47, 0x57, 0x8e, 0x58, 0x4c, 0x09, 0x47, 0x13, 0x12, 0x7a, 0x87, 0x35, 0xe8, - 0xbc, 0xe2, 0xc0, 0x0b, 0x70, 0xb0, 0x85, 0x47, 0x24, 0x10, 0x96, 0xf1, 0x20, 0xf2, 0x7e, 0x4d, - 0x99, 0x90, 0x40, 0x40, 0x0c, 0xcc, 0x2d, 0x36, 0xa4, 0x69, 0x8a, 0x05, 0x61, 0x38, 0xb5, 0x1e, - 0x3d, 0x08, 0xfe, 0xac, 0x66, 0xbd, 0xae, 0x51, 0x6f, 0x8d, 0xd6, 0xde, 0x61, 0xc3, 0xeb, 0xec, - 0xde, 0xb4, 0x7b, 0xb6, 0xfc, 0x6d, 0x6b, 0xcb, 0x95, 0xad, 0xdf, 0xac, 0x6c, 0xfd, 0xd7, 0xca, - 0xd6, 0x3f, 0xaf, 0x6d, 0xed, 0x66, 0x6d, 0x6b, 0xdf, 0xd7, 0xb6, 0xf6, 0xfe, 0xc5, 0x8e, 0x5d, - 0xf9, 0xa8, 0x47, 0x29, 0x0e, 0xb8, 0x5c, 0x39, 0xf3, 0xfa, 0x83, 0x96, 0xae, 0x41, 0x53, 0xfe, - 0x49, 0x2f, 0xff, 0x04, 0x00, 0x00, 0xff, 0xff, 0xe6, 0x34, 0x3b, 0x9f, 0xed, 0x03, 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.Auctions) > 0 { - for iNdEx := len(m.Auctions) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Auctions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.NextAuctionId != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.NextAuctionId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -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 - n2, err2 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.ReverseBidDuration, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.ReverseBidDuration):]) - if err2 != nil { - return 0, err2 - } - i -= n2 - i = encodeVarintGenesis(dAtA, i, uint64(n2)) - i-- - dAtA[i] = 0x3a - n3, err3 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.ForwardBidDuration, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.ForwardBidDuration):]) - if err3 != nil { - return 0, err3 - } - i -= n3 - i = encodeVarintGenesis(dAtA, i, uint64(n3)) - i-- - dAtA[i] = 0x32 - { - size := m.IncrementCollateral.Size() - i -= size - if _, err := m.IncrementCollateral.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.IncrementDebt.Size() - i -= size - if _, err := m.IncrementDebt.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.IncrementSurplus.Size() - i -= size - if _, err := m.IncrementSurplus.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - n4, err4 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.MaxAuctionDuration, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.MaxAuctionDuration):]) - if err4 != nil { - return 0, err4 - } - i -= n4 - i = encodeVarintGenesis(dAtA, i, uint64(n4)) - 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 - if m.NextAuctionId != 0 { - n += 1 + sovGenesis(uint64(m.NextAuctionId)) - } - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.Auctions) > 0 { - for _, e := range m.Auctions { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.MaxAuctionDuration) - n += 1 + l + sovGenesis(uint64(l)) - l = m.IncrementSurplus.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.IncrementDebt.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.IncrementCollateral.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.ForwardBidDuration) - n += 1 + l + sovGenesis(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.ReverseBidDuration) - 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 != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field NextAuctionId", wireType) - } - m.NextAuctionId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.NextAuctionId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - 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 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Auctions", 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.Auctions = append(m.Auctions, &types.Any{}) - if err := m.Auctions[len(m.Auctions)-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 (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 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: 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 { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaxAuctionDuration", 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 := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.MaxAuctionDuration, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IncrementSurplus", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IncrementSurplus.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IncrementDebt", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IncrementDebt.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IncrementCollateral", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IncrementCollateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ForwardBidDuration", 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 := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.ForwardBidDuration, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ReverseBidDuration", 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 := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.ReverseBidDuration, 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/auction/types/genesis_test.go b/x/auction/types/genesis_test.go deleted file mode 100644 index 5ab0c182..00000000 --- a/x/auction/types/genesis_test.go +++ /dev/null @@ -1,159 +0,0 @@ -package types - -import ( - "testing" - time "time" - - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var testCoin = sdk.NewInt64Coin("test", 20) - -func newTestModuleCodec() codec.Codec { - interfaceRegistry := codectypes.NewInterfaceRegistry() - RegisterInterfaces(interfaceRegistry) - return codec.NewProtoCodec(interfaceRegistry) -} - -func TestGenesisState_Validate(t *testing.T) { - arbitraryTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - validAuction := &CollateralAuction{ - BaseAuction: BaseAuction{ - ID: 10, - Initiator: "seller mod account", - Lot: sdk.NewInt64Coin("btc", 1e8), - Bidder: sdk.AccAddress("test bidder"), - Bid: sdk.NewInt64Coin("usdx", 5), - HasReceivedBids: true, - EndTime: arbitraryTime, - MaxEndTime: arbitraryTime.Add(time.Hour), - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 1e9), - MaxBid: sdk.NewInt64Coin("usdx", 5e4), - LotReturns: WeightedAddresses{ - Addresses: []sdk.AccAddress{sdk.AccAddress("test return address")}, - Weights: []sdkmath.Int{sdk.OneInt()}, - }, - } - - testCases := []struct { - name string - genesis *GenesisState - expectPass bool - }{ - { - "valid default genesis", - DefaultGenesisState(), - true, - }, - { - "invalid next ID", - &GenesisState{ - validAuction.ID - 1, - DefaultParams(), - mustPackGenesisAuctions( - []GenesisAuction{ - validAuction, - }, - ), - }, - false, - }, - { - "invalid auctions with repeated ID", - &GenesisState{ - validAuction.ID + 1, - DefaultParams(), - mustPackGenesisAuctions( - []GenesisAuction{ - validAuction, - validAuction, - }, - ), - }, - false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.genesis.Validate() - if tc.expectPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } -} - -func TestGenesisState_UnmarshalAnys(t *testing.T) { - cdc := newTestModuleCodec() - - arbitraryTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - - auctions := []GenesisAuction{ - &CollateralAuction{ - BaseAuction: BaseAuction{ - ID: 1, - Initiator: "seller mod account", - Lot: sdk.NewInt64Coin("btc", 1e8), - Bidder: sdk.AccAddress("test bidder"), - Bid: sdk.NewInt64Coin("usdx", 5), - HasReceivedBids: true, - EndTime: arbitraryTime, - MaxEndTime: arbitraryTime.Add(time.Hour), - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 1e9), - MaxBid: sdk.NewInt64Coin("usdx", 5e4), - LotReturns: WeightedAddresses{}, - }, - &DebtAuction{ - BaseAuction: BaseAuction{ - ID: 2, - Initiator: "mod account", - Lot: sdk.NewInt64Coin("ukava", 1e9), - Bidder: sdk.AccAddress("test bidder"), - Bid: sdk.NewInt64Coin("usdx", 5), - HasReceivedBids: true, - EndTime: arbitraryTime, - MaxEndTime: arbitraryTime.Add(time.Hour), - }, - CorrespondingDebt: testCoin, - }, - &SurplusAuction{ - BaseAuction: BaseAuction{ - ID: 3, - Initiator: "seller mod account", - Lot: sdk.NewInt64Coin("usdx", 1e9), - Bidder: sdk.AccAddress("test bidder"), - Bid: sdk.NewInt64Coin("ukava", 5), - HasReceivedBids: true, - EndTime: arbitraryTime, - MaxEndTime: arbitraryTime.Add(time.Hour), - }, - }, - } - genesis, err := NewGenesisState( - DefaultNextAuctionID, - DefaultParams(), - auctions, - ) - require.NoError(t, err) - - bz, err := cdc.MarshalJSON(genesis) - require.NoError(t, err) - - var unmarshalledGenesis GenesisState - cdc.UnmarshalJSON(bz, &unmarshalledGenesis) - - // Check the interface values are correct after unmarshalling. - unmarshalledAuctions, err := UnpackGenesisAuctions(unmarshalledGenesis.Auctions) - require.NoError(t, err) - require.Equal(t, auctions, unmarshalledAuctions) -} diff --git a/x/auction/types/keys.go b/x/auction/types/keys.go deleted file mode 100644 index 6709bbd1..00000000 --- a/x/auction/types/keys.go +++ /dev/null @@ -1,52 +0,0 @@ -package types - -import ( - "encoding/binary" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName The name that will be used throughout the module - ModuleName = "auction" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default name for parameter store - DefaultParamspace = ModuleName -) - -// Key prefixes -var ( - AuctionKeyPrefix = []byte{0x00} // prefix for keys that store auctions - AuctionByTimeKeyPrefix = []byte{0x01} // prefix for keys that are part of the auctionsByTime index - - NextAuctionIDKey = []byte{0x02} // key for the next auction id -) - -// GetAuctionKey returns the bytes of an auction key -func GetAuctionKey(auctionID uint64) []byte { - return Uint64ToBytes(auctionID) -} - -// GetAuctionByTimeKey returns the key for iterating auctions by time -func GetAuctionByTimeKey(endTime time.Time, auctionID uint64) []byte { - return append(sdk.FormatTimeBytes(endTime), Uint64ToBytes(auctionID)...) -} - -// Uint64ToBytes converts a uint64 into fixed length bytes for use in store keys. -func Uint64ToBytes(id uint64) []byte { - bz := make([]byte, 8) - binary.BigEndian.PutUint64(bz, uint64(id)) - return bz -} - -// Uint64FromBytes converts some fixed length bytes back into a uint64. -func Uint64FromBytes(bz []byte) uint64 { - return binary.BigEndian.Uint64(bz) -} diff --git a/x/auction/types/msg.go b/x/auction/types/msg.go deleted file mode 100644 index 2c94f0e3..00000000 --- a/x/auction/types/msg.go +++ /dev/null @@ -1,57 +0,0 @@ -package types - -import ( - "errors" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// ensure Msg interface compliance at compile time -var _ sdk.Msg = &MsgPlaceBid{} - -// NewMsgPlaceBid returns a new MsgPlaceBid. -func NewMsgPlaceBid(auctionID uint64, bidder string, amt sdk.Coin) MsgPlaceBid { - return MsgPlaceBid{ - AuctionId: auctionID, - Bidder: bidder, - Amount: amt, - } -} - -// Route return the message type used for routing the message. -func (msg MsgPlaceBid) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgPlaceBid) Type() string { return "place_bid" } - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgPlaceBid) ValidateBasic() error { - if msg.AuctionId == 0 { - return errors.New("auction id cannot be zero") - } - _, err := sdk.AccAddressFromBech32(msg.Bidder) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "bidder address cannot be empty or invalid") - } - if !msg.Amount.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "bid amount %s", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgPlaceBid) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgPlaceBid) GetSigners() []sdk.AccAddress { - bidder, err := sdk.AccAddressFromBech32(msg.Bidder) - if err != nil { - panic(err) - } - return []sdk.AccAddress{bidder} -} diff --git a/x/auction/types/msg_test.go b/x/auction/types/msg_test.go deleted file mode 100644 index ae12f1c1..00000000 --- a/x/auction/types/msg_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package types - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestMsgPlaceBid_ValidateBasic(t *testing.T) { - tests := []struct { - name string - msg MsgPlaceBid - expectPass bool - }{ - { - "normal", - NewMsgPlaceBid(1, testAccAddress1, c("token", 10)), - true, - }, - { - "zero id", - NewMsgPlaceBid(0, testAccAddress1, c("token", 10)), - false, - }, - { - "empty address ", - NewMsgPlaceBid(1, "", c("token", 10)), - false, - }, - { - "negative amount", - NewMsgPlaceBid(1, testAccAddress1, sdk.Coin{Denom: "token", Amount: sdkmath.NewInt(-10)}), - false, - }, - { - "zero amount", - NewMsgPlaceBid(1, testAccAddress1, c("token", 0)), - true, - }, - } - - for _, tc := range tests { - if tc.expectPass { - require.NoError(t, tc.msg.ValidateBasic(), tc.name) - } else { - require.Error(t, tc.msg.ValidateBasic(), tc.name) - } - } -} diff --git a/x/auction/types/params.go b/x/auction/types/params.go deleted file mode 100644 index eca7900f..00000000 --- a/x/auction/types/params.go +++ /dev/null @@ -1,190 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -var emptyDec = sdk.Dec{} - -// Defaults for auction params -const ( - // DefaultMaxAuctionDuration max length of auction - DefaultMaxAuctionDuration time.Duration = 2 * 24 * time.Hour - // DefaultForwardBidDuration how long an auction gets extended when someone bids for a forward auction - DefaultForwardBidDuration time.Duration = 24 * time.Hour - // DefaultReverseBidDuration how long an auction gets extended when someone bids for a reverse auction - DefaultReverseBidDuration time.Duration = 1 * time.Hour -) - -var ( - // DefaultIncrement is the smallest percent change a new bid must have from the old one - DefaultIncrement sdk.Dec = sdk.MustNewDecFromStr("0.05") - // ParamStoreKeyParams Param store key for auction params - KeyForwardBidDuration = []byte("ForwardBidDuration") - KeyReverseBidDuration = []byte("ReverseBidDuration") - KeyMaxAuctionDuration = []byte("MaxAuctionDuration") - KeyIncrementSurplus = []byte("IncrementSurplus") - KeyIncrementDebt = []byte("IncrementDebt") - KeyIncrementCollateral = []byte("IncrementCollateral") -) - -// NewParams returns a new Params object. -func NewParams( - maxAuctionDuration, forwardBidDuration, reverseBidDuration time.Duration, - incrementSurplus, - incrementDebt, - incrementCollateral sdk.Dec, -) Params { - return Params{ - MaxAuctionDuration: maxAuctionDuration, - ForwardBidDuration: forwardBidDuration, - ReverseBidDuration: reverseBidDuration, - IncrementSurplus: incrementSurplus, - IncrementDebt: incrementDebt, - IncrementCollateral: incrementCollateral, - } -} - -// DefaultParams returns the default parameters for auctions. -func DefaultParams() Params { - return NewParams( - DefaultMaxAuctionDuration, - DefaultForwardBidDuration, - DefaultReverseBidDuration, - DefaultIncrement, - DefaultIncrement, - DefaultIncrement, - ) -} - -// ParamKeyTable Key declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements the ParamSet interface and returns all the key/value pairs. -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyForwardBidDuration, &p.ForwardBidDuration, validateBidDurationParam), - paramtypes.NewParamSetPair(KeyReverseBidDuration, &p.ReverseBidDuration, validateBidDurationParam), - paramtypes.NewParamSetPair(KeyMaxAuctionDuration, &p.MaxAuctionDuration, validateMaxAuctionDurationParam), - paramtypes.NewParamSetPair(KeyIncrementSurplus, &p.IncrementSurplus, validateIncrementSurplusParam), - paramtypes.NewParamSetPair(KeyIncrementDebt, &p.IncrementDebt, validateIncrementDebtParam), - paramtypes.NewParamSetPair(KeyIncrementCollateral, &p.IncrementCollateral, validateIncrementCollateralParam), - } -} - -// Validate checks that the parameters have valid values. -func (p Params) Validate() error { - if err := validateBidDurationParam(p.ForwardBidDuration); err != nil { - return err - } - - if err := validateBidDurationParam(p.ReverseBidDuration); err != nil { - return err - } - - if err := validateMaxAuctionDurationParam(p.MaxAuctionDuration); err != nil { - return err - } - - if p.ForwardBidDuration > p.MaxAuctionDuration { - return errors.New("forward bid duration param cannot be larger than max auction duration") - } - - if p.ReverseBidDuration > p.MaxAuctionDuration { - return errors.New("reverse bid duration param cannot be larger than max auction duration") - } - - if err := validateIncrementSurplusParam(p.IncrementSurplus); err != nil { - return err - } - - if err := validateIncrementDebtParam(p.IncrementDebt); err != nil { - return err - } - - return validateIncrementCollateralParam(p.IncrementCollateral) -} - -func validateBidDurationParam(i interface{}) error { - bidDuration, ok := i.(time.Duration) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if bidDuration < 0 { - return fmt.Errorf("bid duration cannot be negative %d", bidDuration) - } - - return nil -} - -func validateMaxAuctionDurationParam(i interface{}) error { - maxAuctionDuration, ok := i.(time.Duration) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if maxAuctionDuration < 0 { - return fmt.Errorf("max auction duration cannot be negative %d", maxAuctionDuration) - } - - return nil -} - -func validateIncrementSurplusParam(i interface{}) error { - incrementSurplus, ok := i.(sdk.Dec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if incrementSurplus == emptyDec || incrementSurplus.IsNil() { - return errors.New("surplus auction increment cannot be nil or empty") - } - - if incrementSurplus.IsNegative() { - return fmt.Errorf("surplus auction increment cannot be less than zero %s", incrementSurplus) - } - - return nil -} - -func validateIncrementDebtParam(i interface{}) error { - incrementDebt, ok := i.(sdk.Dec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if incrementDebt == emptyDec || incrementDebt.IsNil() { - return errors.New("debt auction increment cannot be nil or empty") - } - - if incrementDebt.IsNegative() { - return fmt.Errorf("debt auction increment cannot be less than zero %s", incrementDebt) - } - - return nil -} - -func validateIncrementCollateralParam(i interface{}) error { - incrementCollateral, ok := i.(sdk.Dec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if incrementCollateral == emptyDec || incrementCollateral.IsNil() { - return errors.New("collateral auction increment cannot be nil or empty") - } - - if incrementCollateral.IsNegative() { - return fmt.Errorf("collateral auction increment cannot be less than zero %s", incrementCollateral) - } - - return nil -} diff --git a/x/auction/types/params_test.go b/x/auction/types/params_test.go deleted file mode 100644 index 1061977c..00000000 --- a/x/auction/types/params_test.go +++ /dev/null @@ -1,133 +0,0 @@ -package types - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" -) - -func TestParams_Validate(t *testing.T) { - testCases := []struct { - name string - Params - expectErr bool - }{ - { - "normal", - DefaultParams(), - false, - }, - { - "negativeForwardBidDuration", - Params{ - MaxAuctionDuration: 24 * time.Hour, - ForwardBidDuration: -1 * time.Hour, - ReverseBidDuration: 1 * time.Hour, - IncrementSurplus: d("0.05"), - IncrementDebt: d("0.05"), - IncrementCollateral: d("0.05"), - }, - true, - }, - { - "negativeReverseBidDuration", - Params{ - MaxAuctionDuration: 24 * time.Hour, - ForwardBidDuration: 1 * time.Hour, - ReverseBidDuration: -1 * time.Hour, - IncrementSurplus: d("0.05"), - IncrementDebt: d("0.05"), - IncrementCollateral: d("0.05"), - }, - true, - }, - { - "negativeBidDuration", - Params{ - MaxAuctionDuration: 24 * time.Hour, - ForwardBidDuration: -1 * time.Hour, - ReverseBidDuration: -1 * time.Hour, - IncrementSurplus: d("0.05"), - IncrementDebt: d("0.05"), - IncrementCollateral: d("0.05"), - }, - true, - }, - { - "negativeAuction", - Params{ - MaxAuctionDuration: -24 * time.Hour, - ForwardBidDuration: 1 * time.Hour, - ReverseBidDuration: 1 * time.Hour, - IncrementSurplus: d("0.05"), - IncrementDebt: d("0.05"), - IncrementCollateral: d("0.05"), - }, - true, - }, - { - "bid>auction", - Params{ - MaxAuctionDuration: 1 * time.Hour, - ForwardBidDuration: 24 * time.Hour, - ReverseBidDuration: 1 * time.Hour, - IncrementSurplus: d("0.05"), - IncrementDebt: d("0.05"), - IncrementCollateral: d("0.05"), - }, - true, - }, - { - "negative increment surplus", - Params{ - MaxAuctionDuration: 24 * time.Hour, - ForwardBidDuration: 1 * time.Hour, - ReverseBidDuration: 1 * time.Hour, - IncrementSurplus: d("-0.05"), - IncrementDebt: d("0.05"), - IncrementCollateral: d("0.05"), - }, - true, - }, - { - "negative increment debt", - Params{ - MaxAuctionDuration: 24 * time.Hour, - ForwardBidDuration: 1 * time.Hour, - ReverseBidDuration: 1 * time.Hour, - IncrementSurplus: d("0.05"), - IncrementDebt: d("-0.05"), - IncrementCollateral: d("0.05"), - }, - true, - }, - { - "negative increment collateral", - Params{ - MaxAuctionDuration: 24 * time.Hour, - ForwardBidDuration: 1 * time.Hour, - ReverseBidDuration: 1 * time.Hour, - IncrementSurplus: d("0.05"), - IncrementDebt: d("0.05"), - IncrementCollateral: d("-0.05"), - }, - true, - }, - { - "zero value", - Params{}, - true, - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.Params.Validate() - if tc.expectErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} diff --git a/x/auction/types/query.pb.go b/x/auction/types/query.pb.go deleted file mode 100644 index 7a6f9014..00000000 --- a/x/auction/types/query.pb.go +++ /dev/null @@ -1,1868 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/auction/v1beta1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - types "github.com/cosmos/cosmos-sdk/codec/types" - 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 defines the request type for querying x/auction parameters. -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_0afd5f8bae92c6bb, []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 defines the response type for querying x/auction parameters. -type QueryParamsResponse struct { - 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_0afd5f8bae92c6bb, []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{} -} - -// QueryAuctionRequest is the request type for the Query/Auction RPC method. -type QueryAuctionRequest struct { - AuctionId uint64 `protobuf:"varint,1,opt,name=auction_id,json=auctionId,proto3" json:"auction_id,omitempty"` -} - -func (m *QueryAuctionRequest) Reset() { *m = QueryAuctionRequest{} } -func (m *QueryAuctionRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAuctionRequest) ProtoMessage() {} -func (*QueryAuctionRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_0afd5f8bae92c6bb, []int{2} -} -func (m *QueryAuctionRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAuctionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAuctionRequest.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 *QueryAuctionRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAuctionRequest.Merge(m, src) -} -func (m *QueryAuctionRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryAuctionRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAuctionRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAuctionRequest proto.InternalMessageInfo - -// QueryAuctionResponse is the response type for the Query/Auction RPC method. -type QueryAuctionResponse struct { - Auction *types.Any `protobuf:"bytes,1,opt,name=auction,proto3" json:"auction,omitempty"` -} - -func (m *QueryAuctionResponse) Reset() { *m = QueryAuctionResponse{} } -func (m *QueryAuctionResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAuctionResponse) ProtoMessage() {} -func (*QueryAuctionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0afd5f8bae92c6bb, []int{3} -} -func (m *QueryAuctionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAuctionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAuctionResponse.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 *QueryAuctionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAuctionResponse.Merge(m, src) -} -func (m *QueryAuctionResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryAuctionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAuctionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAuctionResponse proto.InternalMessageInfo - -func (m *QueryAuctionResponse) GetAuction() *types.Any { - if m != nil { - return m.Auction - } - return nil -} - -// QueryAuctionsRequest is the request type for the Query/Auctions RPC method. -type QueryAuctionsRequest struct { - Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Denom string `protobuf:"bytes,3,opt,name=denom,proto3" json:"denom,omitempty"` - Phase string `protobuf:"bytes,4,opt,name=phase,proto3" json:"phase,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,5,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryAuctionsRequest) Reset() { *m = QueryAuctionsRequest{} } -func (m *QueryAuctionsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAuctionsRequest) ProtoMessage() {} -func (*QueryAuctionsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_0afd5f8bae92c6bb, []int{4} -} -func (m *QueryAuctionsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAuctionsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAuctionsRequest.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 *QueryAuctionsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAuctionsRequest.Merge(m, src) -} -func (m *QueryAuctionsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryAuctionsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAuctionsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAuctionsRequest proto.InternalMessageInfo - -// QueryAuctionsResponse is the response type for the Query/Auctions RPC method. -type QueryAuctionsResponse struct { - Auctions []*types.Any `protobuf:"bytes,1,rep,name=auctions,proto3" json:"auctions,omitempty"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryAuctionsResponse) Reset() { *m = QueryAuctionsResponse{} } -func (m *QueryAuctionsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAuctionsResponse) ProtoMessage() {} -func (*QueryAuctionsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0afd5f8bae92c6bb, []int{5} -} -func (m *QueryAuctionsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAuctionsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAuctionsResponse.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 *QueryAuctionsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAuctionsResponse.Merge(m, src) -} -func (m *QueryAuctionsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryAuctionsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAuctionsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAuctionsResponse proto.InternalMessageInfo - -func (m *QueryAuctionsResponse) GetAuctions() []*types.Any { - if m != nil { - return m.Auctions - } - return nil -} - -func (m *QueryAuctionsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryNextAuctionIDRequest defines the request type for querying x/auction next auction ID. -type QueryNextAuctionIDRequest struct { -} - -func (m *QueryNextAuctionIDRequest) Reset() { *m = QueryNextAuctionIDRequest{} } -func (m *QueryNextAuctionIDRequest) String() string { return proto.CompactTextString(m) } -func (*QueryNextAuctionIDRequest) ProtoMessage() {} -func (*QueryNextAuctionIDRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_0afd5f8bae92c6bb, []int{6} -} -func (m *QueryNextAuctionIDRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryNextAuctionIDRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryNextAuctionIDRequest.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 *QueryNextAuctionIDRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryNextAuctionIDRequest.Merge(m, src) -} -func (m *QueryNextAuctionIDRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryNextAuctionIDRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryNextAuctionIDRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryNextAuctionIDRequest proto.InternalMessageInfo - -// QueryNextAuctionIDResponse defines the response type for querying x/auction next auction ID. -type QueryNextAuctionIDResponse struct { - Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` -} - -func (m *QueryNextAuctionIDResponse) Reset() { *m = QueryNextAuctionIDResponse{} } -func (m *QueryNextAuctionIDResponse) String() string { return proto.CompactTextString(m) } -func (*QueryNextAuctionIDResponse) ProtoMessage() {} -func (*QueryNextAuctionIDResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0afd5f8bae92c6bb, []int{7} -} -func (m *QueryNextAuctionIDResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryNextAuctionIDResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryNextAuctionIDResponse.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 *QueryNextAuctionIDResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryNextAuctionIDResponse.Merge(m, src) -} -func (m *QueryNextAuctionIDResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryNextAuctionIDResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryNextAuctionIDResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryNextAuctionIDResponse proto.InternalMessageInfo - -func (m *QueryNextAuctionIDResponse) GetId() uint64 { - if m != nil { - return m.Id - } - return 0 -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.auction.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.auction.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryAuctionRequest)(nil), "kava.auction.v1beta1.QueryAuctionRequest") - proto.RegisterType((*QueryAuctionResponse)(nil), "kava.auction.v1beta1.QueryAuctionResponse") - proto.RegisterType((*QueryAuctionsRequest)(nil), "kava.auction.v1beta1.QueryAuctionsRequest") - proto.RegisterType((*QueryAuctionsResponse)(nil), "kava.auction.v1beta1.QueryAuctionsResponse") - proto.RegisterType((*QueryNextAuctionIDRequest)(nil), "kava.auction.v1beta1.QueryNextAuctionIDRequest") - proto.RegisterType((*QueryNextAuctionIDResponse)(nil), "kava.auction.v1beta1.QueryNextAuctionIDResponse") -} - -func init() { proto.RegisterFile("kava/auction/v1beta1/query.proto", fileDescriptor_0afd5f8bae92c6bb) } - -var fileDescriptor_0afd5f8bae92c6bb = []byte{ - // 630 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x94, 0x3f, 0x6f, 0xd3, 0x4e, - 0x18, 0xc7, 0xed, 0x34, 0x4d, 0xd3, 0xfb, 0xe9, 0xc7, 0x70, 0x18, 0x29, 0x35, 0xc1, 0x89, 0x2c, - 0xe8, 0x5f, 0x72, 0xee, 0x9f, 0xad, 0x03, 0x52, 0x0b, 0x2a, 0xea, 0x82, 0xa8, 0x47, 0x16, 0x74, - 0x4e, 0x0e, 0xd7, 0xa2, 0xf1, 0xb9, 0x39, 0xa7, 0x24, 0x42, 0x2c, 0xb0, 0x20, 0xb1, 0x20, 0x10, - 0x7b, 0x79, 0x23, 0xcc, 0x1d, 0x2b, 0x31, 0xc0, 0x84, 0x50, 0xc2, 0xc0, 0xcb, 0x40, 0xbe, 0x7b, - 0x9c, 0xc4, 0x60, 0x42, 0x36, 0xdf, 0x73, 0xdf, 0xe7, 0xb9, 0xcf, 0x3d, 0xcf, 0xf7, 0x8c, 0xea, - 0x4f, 0xe9, 0x19, 0x75, 0x68, 0xb7, 0x19, 0x07, 0x3c, 0x74, 0xce, 0xb6, 0x3c, 0x16, 0xd3, 0x2d, - 0xe7, 0xb4, 0xcb, 0x3a, 0x7d, 0x12, 0x75, 0x78, 0xcc, 0xb1, 0x91, 0x28, 0x08, 0x28, 0x08, 0x28, - 0xcc, 0xf5, 0x26, 0x17, 0x6d, 0x2e, 0x1c, 0x8f, 0x0a, 0xa6, 0xe4, 0xa3, 0xe4, 0x88, 0xfa, 0x41, - 0x48, 0xa5, 0x5a, 0x56, 0x30, 0x0d, 0x9f, 0xfb, 0x5c, 0x7e, 0x3a, 0xc9, 0x17, 0x44, 0xab, 0x3e, - 0xe7, 0xfe, 0x09, 0x73, 0x68, 0x14, 0x38, 0x34, 0x0c, 0x79, 0x2c, 0x53, 0x04, 0xec, 0x2e, 0xc1, - 0xae, 0x5c, 0x79, 0xdd, 0x27, 0x0e, 0x0d, 0x01, 0xc8, 0xb4, 0x73, 0x91, 0x7d, 0x16, 0x32, 0x11, - 0x40, 0xba, 0x6d, 0x20, 0x7c, 0x94, 0x40, 0x3d, 0xa4, 0x1d, 0xda, 0x16, 0x2e, 0x3b, 0xed, 0x32, - 0x11, 0xdb, 0x47, 0xe8, 0x6a, 0x26, 0x2a, 0x22, 0x1e, 0x0a, 0x86, 0x77, 0x51, 0x29, 0x92, 0x91, - 0x8a, 0x5e, 0xd7, 0x57, 0xff, 0xdb, 0xae, 0x92, 0xbc, 0x2b, 0x13, 0x95, 0xb5, 0x5f, 0xbc, 0xf8, - 0x56, 0xd3, 0x5c, 0xc8, 0xb0, 0xef, 0x40, 0xc9, 0x3d, 0x25, 0x86, 0x93, 0xf0, 0x0d, 0x84, 0x20, - 0xfd, 0x71, 0xd0, 0x92, 0x65, 0x8b, 0xee, 0x22, 0x44, 0x0e, 0x5b, 0xbb, 0xe5, 0xd7, 0xe7, 0x35, - 0xed, 0xe7, 0x79, 0x4d, 0xb3, 0x0f, 0x90, 0x91, 0xcd, 0x07, 0x26, 0x82, 0x16, 0x40, 0x0e, 0x50, - 0x06, 0x51, 0x1d, 0x21, 0x69, 0x47, 0xc8, 0x5e, 0xd8, 0x77, 0x53, 0x91, 0xfd, 0x49, 0xcf, 0x16, - 0x4a, 0xef, 0x8c, 0x31, 0x2a, 0xc6, 0xfd, 0x88, 0xc9, 0x2a, 0x8b, 0xae, 0xfc, 0xc6, 0x06, 0x9a, - 0xe7, 0xcf, 0x42, 0xd6, 0xa9, 0x14, 0x64, 0x50, 0x2d, 0x92, 0x68, 0x8b, 0x85, 0xbc, 0x5d, 0x99, - 0x53, 0x51, 0xb9, 0x48, 0xa2, 0xd1, 0x31, 0x15, 0xac, 0x52, 0x54, 0x51, 0xb9, 0xc0, 0x07, 0x08, - 0x8d, 0xc7, 0x5c, 0x99, 0x97, 0x84, 0xcb, 0x44, 0x79, 0x82, 0x24, 0x9e, 0x20, 0xca, 0x42, 0xe3, - 0xde, 0xf9, 0x0c, 0x88, 0xdc, 0x89, 0xcc, 0x89, 0x46, 0xbc, 0xd3, 0xd1, 0xb5, 0xdf, 0x2e, 0x00, - 0xad, 0xd8, 0x44, 0x65, 0xb8, 0x65, 0x32, 0xa0, 0xb9, 0xbf, 0xf6, 0x62, 0xa4, 0xc2, 0xf7, 0x33, - 0x74, 0x05, 0x49, 0xb7, 0xf2, 0x4f, 0x3a, 0x75, 0xdc, 0x24, 0x9e, 0x7d, 0x1d, 0x2d, 0x49, 0xa6, - 0x07, 0xac, 0x17, 0x03, 0xd7, 0xe1, 0xbd, 0xd4, 0x4d, 0xb7, 0x91, 0x99, 0xb7, 0x09, 0xd4, 0x57, - 0x50, 0x61, 0x34, 0xf9, 0x42, 0xd0, 0xda, 0xfe, 0x52, 0x44, 0xf3, 0x52, 0x8e, 0x5f, 0xe9, 0xa8, - 0xa4, 0xbc, 0x84, 0x57, 0xf3, 0x9d, 0xf6, 0xa7, 0x75, 0xcd, 0xb5, 0x19, 0x94, 0xea, 0x64, 0xfb, - 0xe6, 0xcb, 0xcf, 0x3f, 0xde, 0x17, 0x2c, 0x5c, 0x75, 0x72, 0x1f, 0x8a, 0x32, 0x2e, 0xfe, 0xa0, - 0xa3, 0x05, 0xa0, 0xc6, 0xd3, 0x8a, 0x67, 0x8d, 0x6d, 0xae, 0xcf, 0x22, 0x05, 0x90, 0x1d, 0x09, - 0xd2, 0xc0, 0x1b, 0xf9, 0x20, 0xe9, 0xb8, 0x9c, 0xe7, 0xe3, 0xa7, 0xf2, 0x02, 0xbf, 0xd1, 0x51, - 0x39, 0xb5, 0x00, 0x9e, 0xe1, 0xb4, 0x51, 0x87, 0x36, 0x66, 0xd2, 0x02, 0xda, 0xb2, 0x44, 0xab, - 0x63, 0x6b, 0x3a, 0x1a, 0xfe, 0xa8, 0xa3, 0xff, 0x33, 0xf3, 0xc5, 0xce, 0x94, 0x63, 0xf2, 0x6c, - 0x62, 0x6e, 0xce, 0x9e, 0x00, 0x70, 0x0d, 0x09, 0xb7, 0x82, 0x6f, 0xe5, 0xc3, 0x85, 0xac, 0x17, - 0x37, 0x20, 0xd8, 0x08, 0x5a, 0xfb, 0x77, 0x2f, 0x06, 0x96, 0x7e, 0x39, 0xb0, 0xf4, 0xef, 0x03, - 0x4b, 0x7f, 0x3b, 0xb4, 0xb4, 0xcb, 0xa1, 0xa5, 0x7d, 0x1d, 0x5a, 0xda, 0xa3, 0x35, 0x3f, 0x88, - 0x8f, 0xbb, 0x1e, 0x69, 0xf2, 0xb6, 0x2c, 0xd5, 0x38, 0xa1, 0x9e, 0x50, 0x45, 0x7b, 0xa3, 0xb2, - 0xc9, 0x1f, 0x41, 0x78, 0x25, 0xf9, 0x94, 0x76, 0x7e, 0x05, 0x00, 0x00, 0xff, 0xff, 0x51, 0x53, - 0x3d, 0x4a, 0x10, 0x06, 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 { - // Params queries all parameters of the auction module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Auction queries an individual Auction by auction ID - Auction(ctx context.Context, in *QueryAuctionRequest, opts ...grpc.CallOption) (*QueryAuctionResponse, error) - // Auctions queries auctions filtered by asset denom, owner address, phase, and auction type - Auctions(ctx context.Context, in *QueryAuctionsRequest, opts ...grpc.CallOption) (*QueryAuctionsResponse, error) - // NextAuctionID queries the next auction ID - NextAuctionID(ctx context.Context, in *QueryNextAuctionIDRequest, opts ...grpc.CallOption) (*QueryNextAuctionIDResponse, 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, "/kava.auction.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Auction(ctx context.Context, in *QueryAuctionRequest, opts ...grpc.CallOption) (*QueryAuctionResponse, error) { - out := new(QueryAuctionResponse) - err := c.cc.Invoke(ctx, "/kava.auction.v1beta1.Query/Auction", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Auctions(ctx context.Context, in *QueryAuctionsRequest, opts ...grpc.CallOption) (*QueryAuctionsResponse, error) { - out := new(QueryAuctionsResponse) - err := c.cc.Invoke(ctx, "/kava.auction.v1beta1.Query/Auctions", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) NextAuctionID(ctx context.Context, in *QueryNextAuctionIDRequest, opts ...grpc.CallOption) (*QueryNextAuctionIDResponse, error) { - out := new(QueryNextAuctionIDResponse) - err := c.cc.Invoke(ctx, "/kava.auction.v1beta1.Query/NextAuctionID", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries all parameters of the auction module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Auction queries an individual Auction by auction ID - Auction(context.Context, *QueryAuctionRequest) (*QueryAuctionResponse, error) - // Auctions queries auctions filtered by asset denom, owner address, phase, and auction type - Auctions(context.Context, *QueryAuctionsRequest) (*QueryAuctionsResponse, error) - // NextAuctionID queries the next auction ID - NextAuctionID(context.Context, *QueryNextAuctionIDRequest) (*QueryNextAuctionIDResponse, 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) Auction(ctx context.Context, req *QueryAuctionRequest) (*QueryAuctionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Auction not implemented") -} -func (*UnimplementedQueryServer) Auctions(ctx context.Context, req *QueryAuctionsRequest) (*QueryAuctionsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Auctions not implemented") -} -func (*UnimplementedQueryServer) NextAuctionID(ctx context.Context, req *QueryNextAuctionIDRequest) (*QueryNextAuctionIDResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method NextAuctionID 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: "/kava.auction.v1beta1.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_Auction_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAuctionRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Auction(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.auction.v1beta1.Query/Auction", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Auction(ctx, req.(*QueryAuctionRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Auctions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAuctionsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Auctions(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.auction.v1beta1.Query/Auctions", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Auctions(ctx, req.(*QueryAuctionsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_NextAuctionID_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryNextAuctionIDRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).NextAuctionID(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.auction.v1beta1.Query/NextAuctionID", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).NextAuctionID(ctx, req.(*QueryNextAuctionIDRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.auction.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Auction", - Handler: _Query_Auction_Handler, - }, - { - MethodName: "Auctions", - Handler: _Query_Auctions_Handler, - }, - { - MethodName: "NextAuctionID", - Handler: _Query_NextAuctionID_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/auction/v1beta1/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 *QueryAuctionRequest) 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 *QueryAuctionRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAuctionRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.AuctionId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.AuctionId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryAuctionResponse) 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 *QueryAuctionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAuctionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Auction != nil { - { - size, err := m.Auction.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 *QueryAuctionsRequest) 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 *QueryAuctionsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAuctionsRequest) 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] = 0x2a - } - if len(m.Phase) > 0 { - i -= len(m.Phase) - copy(dAtA[i:], m.Phase) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Phase))) - i-- - dAtA[i] = 0x22 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0x1a - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Type) > 0 { - i -= len(m.Type) - copy(dAtA[i:], m.Type) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Type))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryAuctionsResponse) 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 *QueryAuctionsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAuctionsResponse) 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.Auctions) > 0 { - for iNdEx := len(m.Auctions) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Auctions[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 (m *QueryNextAuctionIDRequest) 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 *QueryNextAuctionIDRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryNextAuctionIDRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryNextAuctionIDResponse) 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 *QueryNextAuctionIDResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryNextAuctionIDResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Id != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.Id)) - i-- - dAtA[i] = 0x8 - } - 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 *QueryAuctionRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.AuctionId != 0 { - n += 1 + sovQuery(uint64(m.AuctionId)) - } - return n -} - -func (m *QueryAuctionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Auction != nil { - l = m.Auction.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryAuctionsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Type) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Phase) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryAuctionsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Auctions) > 0 { - for _, e := range m.Auctions { - 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 (m *QueryNextAuctionIDRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryNextAuctionIDResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Id != 0 { - n += 1 + sovQuery(uint64(m.Id)) - } - 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 *QueryAuctionRequest) 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: QueryAuctionRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAuctionRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field AuctionId", wireType) - } - m.AuctionId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.AuctionId |= 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 *QueryAuctionResponse) 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: QueryAuctionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAuctionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Auction", 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.Auction == nil { - m.Auction = &types.Any{} - } - if err := m.Auction.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 *QueryAuctionsRequest) 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: QueryAuctionsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAuctionsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Type = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Phase", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Phase = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - 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 *QueryAuctionsResponse) 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: QueryAuctionsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAuctionsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Auctions", 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.Auctions = append(m.Auctions, &types.Any{}) - if err := m.Auctions[len(m.Auctions)-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 (m *QueryNextAuctionIDRequest) 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: QueryNextAuctionIDRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryNextAuctionIDRequest: 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 *QueryNextAuctionIDResponse) 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: QueryNextAuctionIDResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryNextAuctionIDResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) - } - m.Id = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Id |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := 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/auction/types/query.pb.gw.go b/x/auction/types/query.pb.gw.go deleted file mode 100644 index 9d010e8a..00000000 --- a/x/auction/types/query.pb.gw.go +++ /dev/null @@ -1,402 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/auction/v1beta1/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_Auction_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAuctionRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["auction_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "auction_id") - } - - protoReq.AuctionId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "auction_id", err) - } - - msg, err := client.Auction(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Auction_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAuctionRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["auction_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "auction_id") - } - - protoReq.AuctionId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "auction_id", err) - } - - msg, err := server.Auction(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Auctions_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Auctions_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAuctionsRequest - 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_Auctions_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Auctions(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Auctions_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAuctionsRequest - 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_Auctions_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Auctions(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_NextAuctionID_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryNextAuctionIDRequest - var metadata runtime.ServerMetadata - - msg, err := client.NextAuctionID(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_NextAuctionID_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryNextAuctionIDRequest - var metadata runtime.ServerMetadata - - msg, err := server.NextAuctionID(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_Auction_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_Auction_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_Auction_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Auctions_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_Auctions_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_Auctions_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_NextAuctionID_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_NextAuctionID_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_NextAuctionID_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_Auction_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_Auction_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_Auction_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Auctions_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_Auctions_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_Auctions_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_NextAuctionID_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_NextAuctionID_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_NextAuctionID_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{"kava", "auction", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Auction_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"kava", "auction", "v1beta1", "auctions", "auction_id"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Auctions_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "auction", "v1beta1", "auctions"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_NextAuctionID_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "auction", "v1beta1", "next-auction-id"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Auction_0 = runtime.ForwardResponseMessage - - forward_Query_Auctions_0 = runtime.ForwardResponseMessage - - forward_Query_NextAuctionID_0 = runtime.ForwardResponseMessage -) diff --git a/x/auction/types/tx.pb.go b/x/auction/types/tx.pb.go deleted file mode 100644 index 2853a56f..00000000 --- a/x/auction/types/tx.pb.go +++ /dev/null @@ -1,601 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/auction/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - 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 - -// MsgPlaceBid represents a message used by bidders to place bids on auctions -type MsgPlaceBid struct { - AuctionId uint64 `protobuf:"varint,1,opt,name=auction_id,json=auctionId,proto3" json:"auction_id,omitempty"` - Bidder string `protobuf:"bytes,2,opt,name=bidder,proto3" json:"bidder,omitempty"` - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *MsgPlaceBid) Reset() { *m = MsgPlaceBid{} } -func (m *MsgPlaceBid) String() string { return proto.CompactTextString(m) } -func (*MsgPlaceBid) ProtoMessage() {} -func (*MsgPlaceBid) Descriptor() ([]byte, []int) { - return fileDescriptor_226282be4da73be5, []int{0} -} -func (m *MsgPlaceBid) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgPlaceBid) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgPlaceBid.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 *MsgPlaceBid) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgPlaceBid.Merge(m, src) -} -func (m *MsgPlaceBid) XXX_Size() int { - return m.Size() -} -func (m *MsgPlaceBid) XXX_DiscardUnknown() { - xxx_messageInfo_MsgPlaceBid.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgPlaceBid proto.InternalMessageInfo - -// MsgPlaceBidResponse defines the Msg/PlaceBid response type. -type MsgPlaceBidResponse struct { -} - -func (m *MsgPlaceBidResponse) Reset() { *m = MsgPlaceBidResponse{} } -func (m *MsgPlaceBidResponse) String() string { return proto.CompactTextString(m) } -func (*MsgPlaceBidResponse) ProtoMessage() {} -func (*MsgPlaceBidResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_226282be4da73be5, []int{1} -} -func (m *MsgPlaceBidResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgPlaceBidResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgPlaceBidResponse.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 *MsgPlaceBidResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgPlaceBidResponse.Merge(m, src) -} -func (m *MsgPlaceBidResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgPlaceBidResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgPlaceBidResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgPlaceBidResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgPlaceBid)(nil), "kava.auction.v1beta1.MsgPlaceBid") - proto.RegisterType((*MsgPlaceBidResponse)(nil), "kava.auction.v1beta1.MsgPlaceBidResponse") -} - -func init() { proto.RegisterFile("kava/auction/v1beta1/tx.proto", fileDescriptor_226282be4da73be5) } - -var fileDescriptor_226282be4da73be5 = []byte{ - // 311 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcd, 0x4e, 0x2c, 0x4b, - 0xd4, 0x4f, 0x2c, 0x4d, 0x2e, 0xc9, 0xcc, 0xcf, 0xd3, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, - 0xd4, 0x2f, 0xa9, 0xd0, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x01, 0x49, 0xeb, 0x41, 0xa5, - 0xf5, 0xa0, 0xd2, 0x52, 0x72, 0xc9, 0xf9, 0xc5, 0xb9, 0xf9, 0xc5, 0xfa, 0x49, 0x89, 0xc5, 0xa9, - 0x70, 0x3d, 0xc9, 0xf9, 0x99, 0x79, 0x10, 0x5d, 0x52, 0x22, 0xe9, 0xf9, 0xe9, 0xf9, 0x60, 0xa6, - 0x3e, 0x88, 0x05, 0x11, 0x55, 0x6a, 0x67, 0xe4, 0xe2, 0xf6, 0x2d, 0x4e, 0x0f, 0xc8, 0x49, 0x4c, - 0x4e, 0x75, 0xca, 0x4c, 0x11, 0x92, 0xe5, 0xe2, 0x82, 0x1a, 0x1c, 0x9f, 0x99, 0x22, 0xc1, 0xa8, - 0xc0, 0xa8, 0xc1, 0x12, 0xc4, 0x09, 0x15, 0xf1, 0x4c, 0x11, 0x12, 0xe3, 0x62, 0x4b, 0xca, 0x4c, - 0x49, 0x49, 0x2d, 0x92, 0x60, 0x52, 0x60, 0xd4, 0xe0, 0x0c, 0x82, 0xf2, 0x84, 0xcc, 0xb9, 0xd8, - 0x12, 0x73, 0xf3, 0x4b, 0xf3, 0x4a, 0x24, 0x98, 0x15, 0x18, 0x35, 0xb8, 0x8d, 0x24, 0xf5, 0x20, - 0xae, 0xd1, 0x03, 0xb9, 0x06, 0xe6, 0x44, 0x3d, 0xe7, 0xfc, 0xcc, 0x3c, 0x27, 0x96, 0x13, 0xf7, - 0xe4, 0x19, 0x82, 0xa0, 0xca, 0xad, 0x38, 0x3a, 0x16, 0xc8, 0x33, 0xbc, 0x58, 0x20, 0xcf, 0xa0, - 0x24, 0xca, 0x25, 0x8c, 0xe4, 0x90, 0xa0, 0xd4, 0xe2, 0x82, 0xfc, 0xbc, 0xe2, 0x54, 0xa3, 0x78, - 0x2e, 0x66, 0xdf, 0xe2, 0x74, 0xa1, 0x08, 0x2e, 0x0e, 0xb8, 0x1b, 0x15, 0xf5, 0xb0, 0x05, 0x80, - 0x1e, 0x92, 0x6e, 0x29, 0x4d, 0x82, 0x4a, 0x60, 0x16, 0x38, 0x39, 0x9f, 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, 0x66, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, - 0xae, 0x3e, 0xc8, 0x38, 0xdd, 0x9c, 0xc4, 0xa4, 0x62, 0x30, 0x4b, 0xbf, 0x02, 0x1e, 0x3b, 0x25, - 0x95, 0x05, 0xa9, 0xc5, 0x49, 0x6c, 0xe0, 0xd0, 0x34, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0xbd, - 0x2b, 0xa7, 0xac, 0xba, 0x01, 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 { - // PlaceBid message type used by bidders to place bids on auctions - PlaceBid(ctx context.Context, in *MsgPlaceBid, opts ...grpc.CallOption) (*MsgPlaceBidResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) PlaceBid(ctx context.Context, in *MsgPlaceBid, opts ...grpc.CallOption) (*MsgPlaceBidResponse, error) { - out := new(MsgPlaceBidResponse) - err := c.cc.Invoke(ctx, "/kava.auction.v1beta1.Msg/PlaceBid", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // PlaceBid message type used by bidders to place bids on auctions - PlaceBid(context.Context, *MsgPlaceBid) (*MsgPlaceBidResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) PlaceBid(ctx context.Context, req *MsgPlaceBid) (*MsgPlaceBidResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method PlaceBid not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_PlaceBid_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgPlaceBid) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).PlaceBid(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.auction.v1beta1.Msg/PlaceBid", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).PlaceBid(ctx, req.(*MsgPlaceBid)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.auction.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "PlaceBid", - Handler: _Msg_PlaceBid_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/auction/v1beta1/tx.proto", -} - -func (m *MsgPlaceBid) 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 *MsgPlaceBid) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgPlaceBid) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Bidder) > 0 { - i -= len(m.Bidder) - copy(dAtA[i:], m.Bidder) - i = encodeVarintTx(dAtA, i, uint64(len(m.Bidder))) - i-- - dAtA[i] = 0x12 - } - if m.AuctionId != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.AuctionId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *MsgPlaceBidResponse) 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 *MsgPlaceBidResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgPlaceBidResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgPlaceBid) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.AuctionId != 0 { - n += 1 + sovTx(uint64(m.AuctionId)) - } - l = len(m.Bidder) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgPlaceBidResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgPlaceBid) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgPlaceBid: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgPlaceBid: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field AuctionId", wireType) - } - m.AuctionId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.AuctionId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Bidder", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Bidder = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgPlaceBidResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgPlaceBidResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgPlaceBidResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/bep3/abci.go b/x/bep3/abci.go deleted file mode 100644 index 194ef1f2..00000000 --- a/x/bep3/abci.go +++ /dev/null @@ -1,20 +0,0 @@ -package bep3 - -import ( - "time" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/bep3/keeper" - "github.com/kava-labs/kava/x/bep3/types" -) - -// BeginBlocker on every block expires outdated atomic swaps and removes closed -// swap from long term storage (default storage time of 1 week) -func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - - k.UpdateTimeBasedSupplyLimits(ctx) - k.UpdateExpiredAtomicSwaps(ctx) - k.DeleteClosedAtomicSwapsFromLongtermStorage(ctx) -} diff --git a/x/bep3/abci_test.go b/x/bep3/abci_test.go deleted file mode 100644 index c07f843f..00000000 --- a/x/bep3/abci_test.go +++ /dev/null @@ -1,243 +0,0 @@ -package bep3_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - tmbytes "github.com/cometbft/cometbft/libs/bytes" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/bep3" - "github.com/kava-labs/kava/x/bep3/keeper" - "github.com/kava-labs/kava/x/bep3/types" -) - -type ABCITestSuite struct { - suite.Suite - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context - addrs []sdk.AccAddress - swapIDs []tmbytes.HexBytes - randomNumbers []tmbytes.HexBytes -} - -func (suite *ABCITestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - // Set up auth GenesisState - _, addrs := app.GeneratePrivKeyAddressPairs(12) - coins := sdk.NewCoins(c("bnb", 10000000000), c("ukava", 10000000000)) - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) - // Initialize test app - tApp.InitializeFromGenesisStates(authGS, NewBep3GenStateMulti(tApp.AppCodec(), addrs[11])) - - suite.ctx = ctx - suite.app = tApp - suite.addrs = addrs - suite.ResetKeeper() -} - -func (suite *ABCITestSuite) ResetKeeper() { - suite.keeper = suite.app.GetBep3Keeper() - - var swapIDs []tmbytes.HexBytes - var randomNumbers []tmbytes.HexBytes - for i := 0; i < 10; i++ { - // Set up atomic swap variables - expireHeight := types.DefaultMinBlockLock - amount := cs(c("bnb", int64(10000))) - timestamp := ts(i) - randomNumber, _ := types.GenerateSecureRandomNumber() - randomNumberHash := types.CalculateRandomHash(randomNumber[:], timestamp) - - // Create atomic swap and check err to confirm creation - err := suite.keeper.CreateAtomicSwap(suite.ctx, randomNumberHash, timestamp, expireHeight, - suite.addrs[11], suite.addrs[i], TestSenderOtherChain, TestRecipientOtherChain, - amount, true) - suite.Nil(err) - - // Store swap's calculated ID and secret random number - swapID := types.CalculateSwapID(randomNumberHash, suite.addrs[11], TestSenderOtherChain) - swapIDs = append(swapIDs, swapID) - randomNumbers = append(randomNumbers, randomNumber[:]) - } - suite.swapIDs = swapIDs - suite.randomNumbers = randomNumbers -} - -func (suite *ABCITestSuite) TestBeginBlocker_UpdateExpiredAtomicSwaps() { - testCases := []struct { - name string - firstCtx sdk.Context - secondCtx sdk.Context - expectedStatus types.SwapStatus - expectInStorage bool - }{ - { - name: "normal", - firstCtx: suite.ctx, - secondCtx: suite.ctx.WithBlockHeight(suite.ctx.BlockHeight() + 10), - expectedStatus: types.SWAP_STATUS_OPEN, - expectInStorage: true, - }, - { - name: "after expiration", - firstCtx: suite.ctx.WithBlockHeight(suite.ctx.BlockHeight() + 400), - secondCtx: suite.ctx.WithBlockHeight(suite.ctx.BlockHeight() + 410), - expectedStatus: types.SWAP_STATUS_EXPIRED, - expectInStorage: true, - }, - { - name: "after completion", - firstCtx: suite.ctx, - secondCtx: suite.ctx.WithBlockHeight(suite.ctx.BlockHeight() + 10), - expectedStatus: types.SWAP_STATUS_COMPLETED, - expectInStorage: true, - }, - { - name: "after deletion", - firstCtx: suite.ctx.WithBlockHeight(suite.ctx.BlockHeight() + 400), - secondCtx: suite.ctx.WithBlockHeight(suite.ctx.BlockHeight() + 400 + int64(types.DefaultLongtermStorageDuration)), - expectedStatus: types.SWAP_STATUS_UNSPECIFIED, - expectInStorage: false, - }, - } - - for _, tc := range testCases { - // Reset keeper and run the initial begin blocker - suite.ResetKeeper() - suite.Run(tc.name, func() { - bep3.BeginBlocker(tc.firstCtx, suite.keeper) - - switch tc.expectedStatus { - case types.SWAP_STATUS_COMPLETED: - for i, swapID := range suite.swapIDs { - err := suite.keeper.ClaimAtomicSwap(tc.firstCtx, suite.addrs[5], swapID, suite.randomNumbers[i]) - suite.Nil(err) - } - case types.SWAP_STATUS_UNSPECIFIED: - for _, swapID := range suite.swapIDs { - err := suite.keeper.RefundAtomicSwap(tc.firstCtx, suite.addrs[5], swapID) - suite.Nil(err) - } - } - - // Run the second begin blocker - bep3.BeginBlocker(tc.secondCtx, suite.keeper) - - // Check each swap's availibility and status - for _, swapID := range suite.swapIDs { - storedSwap, found := suite.keeper.GetAtomicSwap(tc.secondCtx, swapID) - if tc.expectInStorage { - suite.True(found) - } else { - suite.False(found) - } - suite.Equal(tc.expectedStatus, storedSwap.Status) - } - }) - } -} - -func (suite *ABCITestSuite) TestBeginBlocker_DeleteClosedAtomicSwapsFromLongtermStorage() { - type Action int - const ( - NULL Action = 0x00 - Refund Action = 0x01 - Claim Action = 0x02 - ) - - testCases := []struct { - name string - firstCtx sdk.Context - action Action - secondCtx sdk.Context - expectInStorage bool - }{ - { - name: "no action with long storage duration", - firstCtx: suite.ctx, - action: NULL, - secondCtx: suite.ctx.WithBlockHeight(suite.ctx.BlockHeight() + int64(types.DefaultLongtermStorageDuration)), - expectInStorage: true, - }, - { - name: "claim with short storage duration", - firstCtx: suite.ctx, - action: Claim, - secondCtx: suite.ctx.WithBlockHeight(suite.ctx.BlockHeight() + 5000), - expectInStorage: true, - }, - { - name: "claim with long storage duration", - firstCtx: suite.ctx, - action: Claim, - secondCtx: suite.ctx.WithBlockHeight(suite.ctx.BlockHeight() + int64(types.DefaultLongtermStorageDuration)), - expectInStorage: false, - }, - { - name: "refund with short storage duration", - firstCtx: suite.ctx, - action: Refund, - secondCtx: suite.ctx.WithBlockHeight(suite.ctx.BlockHeight() + 5000), - expectInStorage: true, - }, - { - name: "refund with long storage duration", - firstCtx: suite.ctx, - action: Refund, - secondCtx: suite.ctx.WithBlockHeight(suite.ctx.BlockHeight() + int64(types.DefaultLongtermStorageDuration)), - expectInStorage: false, - }, - } - - for _, tc := range testCases { - // Reset keeper and run the initial begin blocker - suite.ResetKeeper() - suite.Run(tc.name, func() { - bep3.BeginBlocker(tc.firstCtx, suite.keeper) - - switch tc.action { - case Claim: - for i, swapID := range suite.swapIDs { - err := suite.keeper.ClaimAtomicSwap(tc.firstCtx, suite.addrs[5], swapID, suite.randomNumbers[i]) - suite.Nil(err) - } - case Refund: - for _, swapID := range suite.swapIDs { - swap, _ := suite.keeper.GetAtomicSwap(tc.firstCtx, swapID) - refundCtx := suite.ctx.WithBlockHeight(suite.ctx.BlockHeight() + int64(swap.ExpireHeight)) - bep3.BeginBlocker(refundCtx, suite.keeper) - err := suite.keeper.RefundAtomicSwap(refundCtx, suite.addrs[5], swapID) - suite.Nil(err) - // Add expire height to second ctx block height - tc.secondCtx = tc.secondCtx.WithBlockHeight(tc.secondCtx.BlockHeight() + int64(swap.ExpireHeight)) - } - } - - // Run the second begin blocker - bep3.BeginBlocker(tc.secondCtx, suite.keeper) - - // Check each swap's availability and status - for _, swapID := range suite.swapIDs { - _, found := suite.keeper.GetAtomicSwap(tc.secondCtx, swapID) - if tc.expectInStorage { - suite.True(found) - } else { - suite.False(found) - } - } - }) - } -} - -func TestABCITestSuite(t *testing.T) { - suite.Run(t, new(ABCITestSuite)) -} diff --git a/x/bep3/client/cli/query.go b/x/bep3/client/cli/query.go deleted file mode 100644 index fe7bdecc..00000000 --- a/x/bep3/client/cli/query.go +++ /dev/null @@ -1,336 +0,0 @@ -package cli - -import ( - "context" - "encoding/hex" - "fmt" - "strconv" - "strings" - - tmtime "github.com/cometbft/cometbft/types/time" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/spf13/cobra" - - "github.com/kava-labs/kava/x/bep3/types" -) - -// Query atomic swaps flags -const ( - flagInvolve = "involve" - flagExpiration = "expiration" - flagStatus = "status" - flagDirection = "direction" -) - -// GetQueryCmd returns the cli query commands for this module -func GetQueryCmd(queryRoute string) *cobra.Command { - // Group bep3 queries under a subcommand - bep3QueryCmd := &cobra.Command{ - Use: "bep3", - Short: "Querying commands for the bep3 module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - QueryCalcSwapIDCmd(queryRoute), - QueryCalcRandomNumberHashCmd(queryRoute), - QueryGetAssetSupplyCmd(queryRoute), - QueryGetAssetSuppliesCmd(queryRoute), - QueryGetAtomicSwapCmd(queryRoute), - QueryGetAtomicSwapsCmd(queryRoute), - QueryParamsCmd(queryRoute), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - bep3QueryCmd.AddCommand(cmds...) - - return bep3QueryCmd -} - -// QueryCalcRandomNumberHashCmd calculates the random number hash for a number and timestamp -func QueryCalcRandomNumberHashCmd(queryRoute string) *cobra.Command { - return &cobra.Command{ - Use: "calc-rnh [unix-timestamp]", - Short: "calculates an example random number hash from an optional timestamp", - Example: "bep3 calc-rnh now", - Args: cobra.MaximumNArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - userTimestamp := "now" - if len(args) > 0 { - userTimestamp = args[0] - } - - // Timestamp defaults to time.Now() unless it's explicitly set - var timestamp int64 - if strings.Compare(userTimestamp, "now") == 0 { - timestamp = tmtime.Now().Unix() - } else { - userTimestamp, err := strconv.ParseInt(userTimestamp, 10, 64) - if err != nil { - return err - } - timestamp = userTimestamp - } - - // Load hex-encoded cryptographically strong pseudo-random number - randomNumber, err := types.GenerateSecureRandomNumber() - if err != nil { - return err - } - randomNumberHash := types.CalculateRandomHash(randomNumber, timestamp) - - // Prepare random number, timestamp, and hash for output - randomNumberStr := fmt.Sprintf("Random number: %s\n", hex.EncodeToString(randomNumber)) - timestampStr := fmt.Sprintf("Timestamp: %d\n", timestamp) - randomNumberHashStr := fmt.Sprintf("Random number hash: %s", hex.EncodeToString(randomNumberHash)) - output := []string{randomNumberStr, timestampStr, randomNumberHashStr} - return clientCtx.PrintObjectLegacy(strings.Join(output, "")) - }, - } -} - -// QueryCalcSwapIDCmd calculates the swapID for a random number hash, sender, and sender other chain -func QueryCalcSwapIDCmd(queryRoute string) *cobra.Command { - return &cobra.Command{ - Use: "calc-swapid [random-number-hash] [sender] [sender-other-chain]", - Short: "calculate swap ID for the given random number hash, sender, and sender other chain", - Example: "bep3 calc-swapid 0677bd8a303dd981810f34d8e5cc6507f13b391899b84d3c1be6c6045a17d747 kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny bnb1ud3q90r98l3mhd87kswv3h8cgrymzeljct8qn7", - Args: cobra.MinimumNArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - // Parse query params - randomNumberHash, err := hex.DecodeString(args[0]) - if err != nil { - return err - } - sender, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } - senderOtherChain := args[2] - - // Calculate swap ID and convert to human-readable string - swapID := types.CalculateSwapID(randomNumberHash, sender, senderOtherChain) - return clientCtx.PrintObjectLegacy(hex.EncodeToString(swapID)) - }, - } -} - -// QueryGetAssetSupplyCmd queries as asset's current in swap supply, active, supply, and supply limit -func QueryGetAssetSupplyCmd(queryRoute string) *cobra.Command { - return &cobra.Command{ - Use: "supply [denom]", - Short: "get information about an asset's supply", - Example: "bep3 supply bnb", - Args: cobra.ExactArgs(1), - 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.AssetSupply(context.Background(), &types.QueryAssetSupplyRequest{ - Denom: args[0], - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -// QueryGetAssetSuppliesCmd queries AssetSupplies in the store -func QueryGetAssetSuppliesCmd(queryRoute string) *cobra.Command { - return &cobra.Command{ - Use: "supplies", - Short: "get a list of all asset supplies", - Example: "bep3 supplies", - 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.AssetSupplies(context.Background(), &types.QueryAssetSuppliesRequest{ - // TODO: Pagination here? - }) - if err != nil { - return err - } - - if len(res.AssetSupplies) == 0 { - return fmt.Errorf("there are currently no asset supplies") - } - - return clientCtx.PrintProto(res) - }, - } -} - -// QueryGetAtomicSwapCmd queries an AtomicSwap by swapID -func QueryGetAtomicSwapCmd(queryRoute string) *cobra.Command { - return &cobra.Command{ - Use: "swap [swap-id]", - Short: "get atomic swap information", - Example: "bep3 swap 6682c03cc3856879c8fb98c9733c6b0c30758299138166b6523fe94628b1d3af", - Args: cobra.ExactArgs(1), - 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.AtomicSwap(context.Background(), &types.QueryAtomicSwapRequest{ - SwapId: args[0], - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -// QueryGetAtomicSwapsCmd queries AtomicSwaps in the store -func QueryGetAtomicSwapsCmd(queryRoute string) *cobra.Command { - cmd := &cobra.Command{ - Use: "swaps", - Short: "query atomic swaps with optional filters", - Long: strings.TrimSpace(`Query for all paginated atomic swaps that match optional filters: -Example: -$ kvcli q bep3 swaps --involve=kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny -$ kvcli q bep3 swaps --expiration=280 -$ kvcli q bep3 swaps --status=(Open|Completed|Expired) -$ kvcli q bep3 swaps --direction=(Incoming|Outgoing) -$ kvcli q bep3 swaps --page=2 --limit=100 -`, - ), - RunE: func(cmd *cobra.Command, args []string) error { - bechInvolveAddr, err := cmd.Flags().GetString(flagInvolve) - if err != nil { - return err - } - strExpiration, err := cmd.Flags().GetString(flagExpiration) - if err != nil { - return err - } - strSwapStatus, err := cmd.Flags().GetString(flagStatus) - if err != nil { - return err - } - strSwapDirection, err := cmd.Flags().GetString(flagDirection) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - req := types.QueryAtomicSwapsRequest{ - Pagination: pageReq, - } - - if len(bechInvolveAddr) != 0 { - involveAddr, err := sdk.AccAddressFromBech32(bechInvolveAddr) - if err != nil { - return err - } - req.Involve = involveAddr.String() - } - - if len(strExpiration) != 0 { - expiration, err := strconv.ParseUint(strExpiration, 10, 64) - if err != nil { - return err - } - req.Expiration = expiration - } - - if len(strSwapStatus) != 0 { - swapStatus := types.NewSwapStatusFromString(strSwapStatus) - if !swapStatus.IsValid() { - return fmt.Errorf("invalid swap status %s", strSwapStatus) - } - req.Status = swapStatus - } - - if len(strSwapDirection) != 0 { - swapDirection := types.NewSwapDirectionFromString(strSwapDirection) - if !swapDirection.IsValid() { - return fmt.Errorf("invalid swap direction %s", strSwapDirection) - } - req.Direction = swapDirection - } - - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.AtomicSwaps(context.Background(), &req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - cmd.Flags().String(flagInvolve, "", "(optional) filter by atomic swaps that involve an address") - cmd.Flags().String(flagExpiration, "", "(optional) filter by atomic swaps that expire before a block height") - cmd.Flags().String(flagStatus, "", "(optional) filter by atomic swap status, status: open/completed/expired") - cmd.Flags().String(flagDirection, "", "(optional) filter by atomic swap direction, direction: incoming/outgoing") - - flags.AddPaginationFlagsToCmd(cmd, "swaps") - - return cmd -} - -// QueryParamsCmd queries the bep3 module parameters -func QueryParamsCmd(queryRoute string) *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: "get the bep3 module parameters", - Example: "bep3 params", - 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(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } -} diff --git a/x/bep3/client/cli/tx.go b/x/bep3/client/cli/tx.go deleted file mode 100644 index 62e3cc00..00000000 --- a/x/bep3/client/cli/tx.go +++ /dev/null @@ -1,195 +0,0 @@ -package cli - -import ( - "encoding/hex" - "fmt" - "strconv" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/x/bep3/types" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - bep3TxCmd := &cobra.Command{ - Use: "bep3", - Short: "bep3 transactions subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - GetCmdCreateAtomicSwap(), - GetCmdClaimAtomicSwap(), - GetCmdRefundAtomicSwap(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - bep3TxCmd.AddCommand(cmds...) - - return bep3TxCmd -} - -// GetCmdCreateAtomicSwap cli command for creating atomic swaps -func GetCmdCreateAtomicSwap() *cobra.Command { - return &cobra.Command{ - Use: "create [to] [recipient-other-chain] [sender-other-chain] [timestamp] [coins] [height-span]", - Short: "create a new atomic swap", - Example: fmt.Sprintf("%s tx %s create kava1xy7hrjy9r0algz9w3gzm8u6mrpq97kwta747gj bnb1urfermcg92dwq36572cx4xg84wpk3lfpksr5g7 bnb1uky3me9ggqypmrsvxk7ur6hqkzq7zmv4ed4ng7 now 100bnb 270 --from validator", - version.AppName, types.ModuleName), - Args: cobra.ExactArgs(6), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - from := clientCtx.GetFromAddress() // same as Kava executor's deputy address - to, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - recipientOtherChain := args[1] // same as the other executor's deputy address - senderOtherChain := args[2] - - // Timestamp defaults to time.Now() unless it's explicitly set - var timestamp int64 - if strings.Compare(args[3], "now") == 0 { - timestamp = tmtime.Now().Unix() - } else { - timestamp, err = strconv.ParseInt(args[3], 10, 64) - if err != nil { - return err - } - } - - // Generate cryptographically strong pseudo-random number - randomNumber, err := types.GenerateSecureRandomNumber() - if err != nil { - return err - } - - randomNumberHash := types.CalculateRandomHash(randomNumber, timestamp) - - // Print random number, timestamp, and hash to user's console - fmt.Printf("\nRandom number: %s\n", hex.EncodeToString(randomNumber)) - fmt.Printf("Timestamp: %d\n", timestamp) - fmt.Printf("Random number hash: %s\n\n", hex.EncodeToString(randomNumberHash)) - - coins, err := sdk.ParseCoinsNormalized(args[4]) - if err != nil { - return err - } - - heightSpan, err := strconv.ParseUint(args[5], 10, 64) - if err != nil { - return err - } - - msg := types.NewMsgCreateAtomicSwap( - from.String(), to.String(), recipientOtherChain, senderOtherChain, - randomNumberHash, timestamp, coins, heightSpan, - ) - - err = msg.ValidateBasic() - if err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -// GetCmdClaimAtomicSwap cli command for claiming an atomic swap -func GetCmdClaimAtomicSwap() *cobra.Command { - return &cobra.Command{ - Use: "claim [swap-id] [random-number]", - Short: "claim coins in an atomic swap using the secret number", - Example: fmt.Sprintf( - "%s tx %s claim 6682c03cc3856879c8fb98c9733c6b0c30758299138166b6523fe94628b1d3af 56f13e6a5cd397447f8b5f8c82fdb5bbf56127db75269f5cc14e50acd8ac9a4c --from accA", - version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - from := clientCtx.GetFromAddress() - - swapID, err := hex.DecodeString(args[0]) - if err != nil { - return err - } - - if len(strings.TrimSpace(args[1])) == 0 { - return fmt.Errorf("random-number cannot be empty") - } - randomNumber, err := hex.DecodeString(args[1]) - if err != nil { - return err - } - - msg := types.NewMsgClaimAtomicSwap(from.String(), swapID, randomNumber) - - err = msg.ValidateBasic() - if err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -// GetCmdRefundAtomicSwap cli command for claiming an atomic swap -func GetCmdRefundAtomicSwap() *cobra.Command { - return &cobra.Command{ - Use: "refund [swap-id]", - Short: "refund the coins in an atomic swap", - Example: fmt.Sprintf( - "%s tx %s refund 6682c03cc3856879c8fb98c9733c6b0c30758299138166b6523fe94628b1d3af --from accA", - version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - from := clientCtx.GetFromAddress() - - swapID, err := hex.DecodeString(args[0]) - if err != nil { - return err - } - - msg := types.NewMsgRefundAtomicSwap(from.String(), swapID) - - err = msg.ValidateBasic() - if err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} diff --git a/x/bep3/genesis.go b/x/bep3/genesis.go deleted file mode 100644 index d14e78df..00000000 --- a/x/bep3/genesis.go +++ /dev/null @@ -1,141 +0,0 @@ -package bep3 - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - "github.com/kava-labs/kava/x/bep3/keeper" - "github.com/kava-labs/kava/x/bep3/types" -) - -// InitGenesis initializes the store state from a genesis state. -func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, accountKeeper types.AccountKeeper, gs *types.GenesisState) { - // Check if the module account exists - moduleAcc := accountKeeper.GetModuleAccount(ctx, types.ModuleName) - if moduleAcc == nil { - panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) - } - - hasBurnPermissions := false - hasMintPermissions := false - for _, perm := range moduleAcc.GetPermissions() { - if perm == authtypes.Burner { - hasBurnPermissions = true - } - if perm == authtypes.Minter { - hasMintPermissions = true - } - } - if !hasBurnPermissions { - panic(fmt.Sprintf("%s module account does not have burn permissions", types.ModuleName)) - } - if !hasMintPermissions { - panic(fmt.Sprintf("%s module account does not have mint permissions", types.ModuleName)) - } - - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - keeper.SetPreviousBlockTime(ctx, gs.PreviousBlockTime) - - keeper.SetParams(ctx, gs.Params) - for _, supply := range gs.Supplies { - keeper.SetAssetSupply(ctx, supply, supply.GetDenom()) - } - - var incomingSupplies sdk.Coins - var outgoingSupplies sdk.Coins - for _, swap := range gs.AtomicSwaps { - if swap.Validate() != nil { - panic(fmt.Sprintf("invalid swap %s", swap.GetSwapID())) - } - - // Atomic swap assets must be both supported and active - err := keeper.ValidateLiveAsset(ctx, swap.Amount[0]) - if err != nil { - panic(fmt.Sprintf("swap has invalid asset: %s", err)) - } - - keeper.SetAtomicSwap(ctx, swap) - - // Add swap to block index or longterm storage based on swap.Status - // Increment incoming or outgoing supply based on swap.Direction - switch swap.Direction { - case types.SWAP_DIRECTION_INCOMING: - switch swap.Status { - case types.SWAP_STATUS_OPEN: - // This index expires unclaimed swaps - keeper.InsertIntoByBlockIndex(ctx, swap) - incomingSupplies = incomingSupplies.Add(swap.Amount...) - case types.SWAP_STATUS_EXPIRED: - incomingSupplies = incomingSupplies.Add(swap.Amount...) - case types.SWAP_STATUS_COMPLETED: - // This index stores swaps until deletion - keeper.InsertIntoLongtermStorage(ctx, swap) - default: - panic(fmt.Sprintf("swap %s has invalid status %s", swap.GetSwapID(), swap.Status.String())) - } - case types.SWAP_DIRECTION_OUTGOING: - switch swap.Status { - case types.SWAP_STATUS_OPEN: - keeper.InsertIntoByBlockIndex(ctx, swap) - outgoingSupplies = outgoingSupplies.Add(swap.Amount...) - case types.SWAP_STATUS_EXPIRED: - outgoingSupplies = outgoingSupplies.Add(swap.Amount...) - case types.SWAP_STATUS_COMPLETED: - keeper.InsertIntoLongtermStorage(ctx, swap) - default: - panic(fmt.Sprintf("swap %s has invalid status %s", swap.GetSwapID(), swap.Status.String())) - } - default: - panic(fmt.Sprintf("swap %s has invalid direction %s", swap.GetSwapID(), swap.Direction.String())) - } - } - - // Asset's given incoming/outgoing supply much match the amount of coins in incoming/outgoing atomic swaps - supplies := keeper.GetAllAssetSupplies(ctx) - for _, supply := range supplies { - incomingSupply := incomingSupplies.AmountOf(supply.GetDenom()) - if !supply.IncomingSupply.Amount.Equal(incomingSupply) { - panic(fmt.Sprintf("asset's incoming supply %s does not match amount %s in incoming atomic swaps", - supply.IncomingSupply, incomingSupply)) - } - outgoingSupply := outgoingSupplies.AmountOf(supply.GetDenom()) - if !supply.OutgoingSupply.Amount.Equal(outgoingSupply) { - panic(fmt.Sprintf("asset's outgoing supply %s does not match amount %s in outgoing atomic swaps", - supply.OutgoingSupply, outgoingSupply)) - } - limit, err := keeper.GetSupplyLimit(ctx, supply.GetDenom()) - if err != nil { - panic(fmt.Sprintf("asset's supply limit not found: %s", err)) - } - if supply.CurrentSupply.Amount.GT(limit.Limit) { - panic(fmt.Sprintf("asset's current supply %s is over the supply limit %s", supply.CurrentSupply, limit.Limit)) - } - if supply.IncomingSupply.Amount.GT(limit.Limit) { - panic(fmt.Sprintf("asset's incoming supply %s is over the supply limit %s", supply.IncomingSupply, limit.Limit)) - } - if supply.IncomingSupply.Amount.Add(supply.CurrentSupply.Amount).GT(limit.Limit) { - panic(fmt.Sprintf("asset's incoming supply + current supply %s is over the supply limit %s", supply.IncomingSupply.Add(supply.CurrentSupply), limit.Limit)) - } - if supply.OutgoingSupply.Amount.GT(limit.Limit) { - panic(fmt.Sprintf("asset's outgoing supply %s is over the supply limit %s", supply.OutgoingSupply, limit.Limit)) - } - - } -} - -// ExportGenesis writes the current store values to a genesis file, which can be imported again with InitGenesis -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) (data types.GenesisState) { - params := k.GetParams(ctx) - swaps := k.GetAllAtomicSwaps(ctx) - supplies := k.GetAllAssetSupplies(ctx) - previousBlockTime, found := k.GetPreviousBlockTime(ctx) - if !found { - previousBlockTime = types.DefaultPreviousBlockTime - } - return types.NewGenesisState(params, swaps, supplies, previousBlockTime) -} diff --git a/x/bep3/genesis_test.go b/x/bep3/genesis_test.go deleted file mode 100644 index c1eb3a15..00000000 --- a/x/bep3/genesis_test.go +++ /dev/null @@ -1,391 +0,0 @@ -package bep3_test - -import ( - "testing" - - "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/bep3/keeper" - "github.com/kava-labs/kava/x/bep3/types" -) - -type GenesisTestSuite struct { - suite.Suite - - app app.TestApp - ctx sdk.Context - keeper keeper.Keeper - addrs []sdk.AccAddress -} - -func (suite *GenesisTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - tApp := app.NewTestApp() - suite.ctx = tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - suite.keeper = tApp.GetBep3Keeper() - suite.app = tApp - - _, addrs := app.GeneratePrivKeyAddressPairs(3) - suite.addrs = addrs -} - -func (suite *GenesisTestSuite) TestModulePermissionsCheck() { - cdc := suite.app.AppCodec() - - testCases := []struct { - name string - permissions []string - expectedPanic string - }{ - {"no permissions", []string{}, "bep3 module account does not have burn permissions"}, - {"mint permissions", []string{authtypes.Minter}, "bep3 module account does not have burn permissions"}, - {"burn permissions", []string{authtypes.Burner}, "bep3 module account does not have mint permissions"}, - {"burn and mint permissions", []string{authtypes.Burner, authtypes.Minter}, ""}, - {"mint and burn permissions", []string{authtypes.Minter, authtypes.Burner}, ""}, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - authGenesis := authtypes.NewGenesisState( - authtypes.DefaultParams(), - authtypes.GenesisAccounts{authtypes.NewEmptyModuleAccount(types.ModuleName, tc.permissions...)}, - ) - bep3Genesis := types.DefaultGenesisState() - genState := app.GenesisState{ - authtypes.ModuleName: cdc.MustMarshalJSON(authGenesis), - types.ModuleName: cdc.MustMarshalJSON(&bep3Genesis), - } - - initApp := func() { suite.app.InitializeFromGenesisStates(genState) } - - if tc.expectedPanic == "" { - suite.NotPanics(initApp) - } else { - suite.PanicsWithValue(tc.expectedPanic, initApp) - } - }) - } -} - -func (suite *GenesisTestSuite) TestGenesisState() { - type GenState func() app.GenesisState - - cdc := suite.app.AppCodec() - - testCases := []struct { - name string - genState GenState - expectPass bool - expectedErr interface{} - }{ - { - name: "default", - genState: func() app.GenesisState { - return NewBep3GenStateMulti(cdc, suite.addrs[0]) - }, - expectPass: true, - }, - { - name: "import atomic swaps and asset supplies", - genState: func() app.GenesisState { - gs := baseGenState(suite.addrs[0]) - _, addrs := app.GeneratePrivKeyAddressPairs(2) - var swaps types.AtomicSwaps - var supplies types.AssetSupplies - for i := 0; i < 2; i++ { - swap, supply := loadSwapAndSupply(addrs[i], i) - swaps = append(swaps, swap) - supplies = append(supplies, supply) - } - gs.AtomicSwaps = swaps - gs.Supplies = supplies - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&gs)} - }, - expectPass: true, - }, - { - name: "0 deputy fees", - genState: func() app.GenesisState { - gs := baseGenState(suite.addrs[0]) - gs.Params.AssetParams[0].FixedFee = sdk.ZeroInt() - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&gs)} - }, - expectPass: true, - }, - { - name: "incoming supply doesn't match amount in incoming atomic swaps", - genState: func() app.GenesisState { - gs := baseGenState(suite.addrs[0]) // incoming supply is zero - _, addrs := app.GeneratePrivKeyAddressPairs(1) - swap, _ := loadSwapAndSupply(addrs[0], 0) - gs.AtomicSwaps = types.AtomicSwaps{swap} - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&gs)} - }, - expectPass: false, - expectedErr: "asset's incoming supply 0bnb does not match amount 50000 in incoming atomic swaps", - }, - { - name: "current supply above limit", - genState: func() app.GenesisState { - gs := baseGenState(suite.addrs[0]) - bnbSupplyLimit := math.ZeroInt() - for _, ap := range gs.Params.AssetParams { - if ap.Denom == "bnb" { - bnbSupplyLimit = ap.SupplyLimit.Limit - } - } - gs.Supplies = types.AssetSupplies{ - types.NewAssetSupply( - c("bnb", 0), - c("bnb", 0), - sdk.NewCoin("bnb", bnbSupplyLimit.Add(i(1))), - c("bnb", 0), - 0, - ), - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&gs)} - }, - expectPass: false, - expectedErr: "asset's current supply 350000000000001bnb is over the supply limit 350000000000000", - }, - { - name: "incoming supply above limit", - genState: func() app.GenesisState { - gs := baseGenState(suite.addrs[0]) - // Set up overlimit amount - bnbSupplyLimit := math.ZeroInt() - for _, ap := range gs.Params.AssetParams { - if ap.Denom == "bnb" { - bnbSupplyLimit = ap.SupplyLimit.Limit - } - } - overLimitAmount := bnbSupplyLimit.Add(i(1)) - - // Set up an atomic swap with amount equal to the currently asset supply - _, addrs := app.GeneratePrivKeyAddressPairs(2) - timestamp := ts(0) - randomNumber, _ := types.GenerateSecureRandomNumber() - randomNumberHash := types.CalculateRandomHash(randomNumber[:], timestamp) - swap := types.NewAtomicSwap(cs(c("bnb", overLimitAmount.Int64())), randomNumberHash, - types.DefaultMinBlockLock, timestamp, suite.addrs[0], addrs[1], TestSenderOtherChain, - TestRecipientOtherChain, 0, types.SWAP_STATUS_OPEN, true, types.SWAP_DIRECTION_INCOMING) - gs.AtomicSwaps = types.AtomicSwaps{swap} - - // Set up asset supply with overlimit current supply - gs.Supplies = types.AssetSupplies{ - types.NewAssetSupply( - c("bnb", overLimitAmount.Int64()), - c("bnb", 0), - c("bnb", 0), - c("bnb", 0), - 0, - ), - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&gs)} - }, - expectPass: false, - expectedErr: "asset's incoming supply 350000000000001bnb is over the supply limit 350000000000000", - }, - { - name: "incoming supply + current supply above limit", - genState: func() app.GenesisState { - gs := baseGenState(suite.addrs[0]) - // Set up overlimit amount - bnbSupplyLimit := math.ZeroInt() - for _, ap := range gs.Params.AssetParams { - if ap.Denom == "bnb" { - bnbSupplyLimit = ap.SupplyLimit.Limit - } - } - halfLimit := bnbSupplyLimit.Int64() / 2 - overHalfLimit := halfLimit + 1 - - // Set up an atomic swap with amount equal to the currently asset supply - _, addrs := app.GeneratePrivKeyAddressPairs(2) - timestamp := ts(0) - randomNumber, _ := types.GenerateSecureRandomNumber() - randomNumberHash := types.CalculateRandomHash(randomNumber[:], timestamp) - swap := types.NewAtomicSwap(cs(c("bnb", halfLimit)), randomNumberHash, - uint64(360), timestamp, suite.addrs[0], addrs[1], TestSenderOtherChain, - TestRecipientOtherChain, 0, types.SWAP_STATUS_OPEN, true, types.SWAP_DIRECTION_INCOMING) - gs.AtomicSwaps = types.AtomicSwaps{swap} - - // Set up asset supply with overlimit supply - gs.Supplies = types.AssetSupplies{ - types.NewAssetSupply( - c("bnb", halfLimit), - c("bnb", 0), - c("bnb", overHalfLimit), - c("bnb", 0), - 0, - ), - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&gs)} - }, - expectPass: false, - expectedErr: "asset's incoming supply + current supply 350000000000001bnb is over the supply limit 350000000000000", - }, - { - name: "outgoing supply above limit", - genState: func() app.GenesisState { - gs := baseGenState(suite.addrs[0]) - // Set up overlimit amount - bnbSupplyLimit := math.ZeroInt() - for _, ap := range gs.Params.AssetParams { - if ap.Denom == "bnb" { - bnbSupplyLimit = ap.SupplyLimit.Limit - } - } - overLimitAmount := bnbSupplyLimit.Add(i(1)) - - // Set up an atomic swap with amount equal to the currently asset supply - _, addrs := app.GeneratePrivKeyAddressPairs(2) - timestamp := ts(0) - randomNumber, _ := types.GenerateSecureRandomNumber() - randomNumberHash := types.CalculateRandomHash(randomNumber[:], timestamp) - swap := types.NewAtomicSwap(cs(c("bnb", overLimitAmount.Int64())), randomNumberHash, - types.DefaultMinBlockLock, timestamp, addrs[1], suite.addrs[0], TestSenderOtherChain, - TestRecipientOtherChain, 0, types.SWAP_STATUS_OPEN, true, types.SWAP_DIRECTION_OUTGOING) - gs.AtomicSwaps = types.AtomicSwaps{swap} - - // Set up asset supply with overlimit outgoing supply - gs.Supplies = types.AssetSupplies{ - types.NewAssetSupply( - c("bnb", 0), - c("bnb", overLimitAmount.Int64()), - c("bnb", 0), - c("bnb", 0), - 0, - ), - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&gs)} - }, - expectPass: false, - expectedErr: "asset's outgoing supply 350000000000001bnb is over the supply limit 350000000000000", - }, - { - name: "asset supply denom is not a supported asset", - genState: func() app.GenesisState { - gs := baseGenState(suite.addrs[0]) - gs.Supplies = types.AssetSupplies{ - types.NewAssetSupply( - c("fake", 0), - c("fake", 0), - c("fake", 0), - c("fake", 0), - 0, - ), - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&gs)} - }, - expectPass: false, - expectedErr: "asset's supply limit not found: fake: asset not found", - }, - { - name: "atomic swap asset type is unsupported", - genState: func() app.GenesisState { - gs := baseGenState(suite.addrs[0]) - _, addrs := app.GeneratePrivKeyAddressPairs(2) - timestamp := ts(0) - randomNumber, _ := types.GenerateSecureRandomNumber() - randomNumberHash := types.CalculateRandomHash(randomNumber[:], timestamp) - swap := types.NewAtomicSwap(cs(c("fake", 500000)), randomNumberHash, - uint64(360), timestamp, suite.addrs[0], addrs[1], TestSenderOtherChain, - TestRecipientOtherChain, 0, types.SWAP_STATUS_OPEN, true, types.SWAP_DIRECTION_INCOMING) - - gs.AtomicSwaps = types.AtomicSwaps{swap} - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&gs)} - }, - expectPass: false, - expectedErr: "swap has invalid asset: fake: asset not found", - }, - { - name: "atomic swap status is invalid", - genState: func() app.GenesisState { - gs := baseGenState(suite.addrs[0]) - _, addrs := app.GeneratePrivKeyAddressPairs(2) - timestamp := ts(0) - randomNumber, _ := types.GenerateSecureRandomNumber() - randomNumberHash := types.CalculateRandomHash(randomNumber[:], timestamp) - swap := types.NewAtomicSwap(cs(c("bnb", 5000)), randomNumberHash, - uint64(360), timestamp, suite.addrs[0], addrs[1], TestSenderOtherChain, - TestRecipientOtherChain, 0, types.SWAP_STATUS_UNSPECIFIED, true, types.SWAP_DIRECTION_INCOMING) - - gs.AtomicSwaps = types.AtomicSwaps{swap} - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&gs)} - }, - expectPass: false, - expectedErr: "failed to validate bep3 genesis state: invalid swap status", - }, - { - name: "minimum block lock cannot be > maximum block lock", - genState: func() app.GenesisState { - gs := baseGenState(suite.addrs[0]) - gs.Params.AssetParams[0].MinBlockLock = 201 - gs.Params.AssetParams[0].MaxBlockLock = 200 - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&gs)} - }, - expectPass: false, - expectedErr: "failed to validate bep3 genesis state: asset bnb has minimum block lock > maximum block lock 201 > 200", - }, - { - name: "empty supported asset denom", - genState: func() app.GenesisState { - gs := baseGenState(suite.addrs[0]) - gs.Params.AssetParams[0].Denom = "" - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&gs)} - }, - expectPass: false, - expectedErr: "failed to validate bep3 genesis state: asset denom invalid: ", - }, - { - name: "negative supported asset limit", - genState: func() app.GenesisState { - gs := baseGenState(suite.addrs[0]) - gs.Params.AssetParams[0].SupplyLimit.Limit = i(-100) - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&gs)} - }, - expectPass: false, - expectedErr: "failed to validate bep3 genesis state: asset bnb has invalid (negative) supply limit: -100", - }, - { - name: "duplicate supported asset denom", - genState: func() app.GenesisState { - gs := baseGenState(suite.addrs[0]) - gs.Params.AssetParams[1].Denom = "bnb" - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&gs)} - }, - expectPass: false, - expectedErr: "failed to validate bep3 genesis state: asset bnb cannot have duplicate denom", - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - gs := tc.genState() - if tc.expectPass { - suite.NotPanics(func() { - suite.app.InitializeFromGenesisStates(gs) - }, tc.name) - } else { - suite.PanicsWithValue(tc.expectedErr, func() { - suite.app.InitializeFromGenesisStates(gs) - }, tc.name) - } - }) - } -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(GenesisTestSuite)) -} diff --git a/x/bep3/integration_test.go b/x/bep3/integration_test.go deleted file mode 100644 index 332dad70..00000000 --- a/x/bep3/integration_test.go +++ /dev/null @@ -1,114 +0,0 @@ -package bep3_test - -import ( - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/bep3/types" -) - -const ( - TestSenderOtherChain = "bnb1uky3me9ggqypmrsvxk7ur6hqkzq7zmv4ed4ng7" - TestRecipientOtherChain = "bnb1urfermcg92dwq36572cx4xg84wpk3lfpksr5g7" - TestDeputy = "kava1xy7hrjy9r0algz9w3gzm8u6mrpq97kwta747gj" - TestUser = "kava1vry5lhegzlulehuutcr7nmdlmktw88awp0a39p" -) - -var ( - StandardSupplyLimit = i(100000000000) - DenomMap = map[int]string{0: "bnb", 1: "inc"} -) - -func i(in int64) sdkmath.Int { return sdkmath.NewInt(in) } -func d(de int64) sdk.Dec { return sdk.NewDec(de) } -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } -func ts(minOffset int) int64 { return tmtime.Now().Add(time.Duration(minOffset) * time.Minute).Unix() } - -func NewBep3GenStateMulti(cdc codec.JSONCodec, deputy sdk.AccAddress) app.GenesisState { - bep3Genesis := baseGenState(deputy) - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&bep3Genesis)} -} - -func baseGenState(deputy sdk.AccAddress) types.GenesisState { - bep3Genesis := types.GenesisState{ - Params: types.Params{ - AssetParams: types.AssetParams{ - { - Denom: "bnb", - CoinID: 714, - SupplyLimit: types.SupplyLimit{ - Limit: sdkmath.NewInt(350000000000000), - TimeLimited: false, - TimeBasedLimit: sdk.ZeroInt(), - TimePeriod: time.Hour, - }, - Active: true, - DeputyAddress: deputy, - FixedFee: sdkmath.NewInt(1000), - MinSwapAmount: sdk.OneInt(), - MaxSwapAmount: sdkmath.NewInt(1000000000000), - MinBlockLock: types.DefaultMinBlockLock, - MaxBlockLock: types.DefaultMaxBlockLock, - }, - { - Denom: "inc", - CoinID: 9999, - SupplyLimit: types.SupplyLimit{ - Limit: sdkmath.NewInt(100000000000), - TimeLimited: false, - TimeBasedLimit: sdk.ZeroInt(), - TimePeriod: time.Hour, - }, - Active: true, - DeputyAddress: deputy, - FixedFee: sdkmath.NewInt(1000), - MinSwapAmount: sdk.OneInt(), - MaxSwapAmount: sdkmath.NewInt(1000000000000), - MinBlockLock: types.DefaultMinBlockLock, - MaxBlockLock: types.DefaultMaxBlockLock, - }, - }, - }, - Supplies: types.AssetSupplies{ - types.NewAssetSupply( - sdk.NewCoin("bnb", sdk.ZeroInt()), - sdk.NewCoin("bnb", sdk.ZeroInt()), - sdk.NewCoin("bnb", sdk.ZeroInt()), - sdk.NewCoin("bnb", sdk.ZeroInt()), - time.Duration(0), - ), - types.NewAssetSupply( - sdk.NewCoin("inc", sdk.ZeroInt()), - sdk.NewCoin("inc", sdk.ZeroInt()), - sdk.NewCoin("inc", sdk.ZeroInt()), - sdk.NewCoin("inc", sdk.ZeroInt()), - time.Duration(0), - ), - }, - PreviousBlockTime: types.DefaultPreviousBlockTime, - } - return bep3Genesis -} - -func loadSwapAndSupply(addr sdk.AccAddress, index int) (types.AtomicSwap, types.AssetSupply) { - coin := c(DenomMap[index], 50000) - expireOffset := types.DefaultMinBlockLock // Default expire height + offet to match timestamp - timestamp := ts(index) // One minute apart - randomNumber, _ := types.GenerateSecureRandomNumber() - randomNumberHash := types.CalculateRandomHash(randomNumber[:], timestamp) - swap := types.NewAtomicSwap(cs(coin), randomNumberHash, - expireOffset, timestamp, addr, addr, TestSenderOtherChain, - TestRecipientOtherChain, 1, types.SWAP_STATUS_OPEN, true, types.SWAP_DIRECTION_INCOMING) - - supply := types.NewAssetSupply(coin, c(coin.Denom, 0), - c(coin.Denom, 0), c(coin.Denom, 0), time.Duration(0)) - - return swap, supply -} diff --git a/x/bep3/keeper/asset.go b/x/bep3/keeper/asset.go deleted file mode 100644 index 983d1999..00000000 --- a/x/bep3/keeper/asset.go +++ /dev/null @@ -1,184 +0,0 @@ -package keeper - -import ( - "time" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/bep3/types" -) - -// IncrementCurrentAssetSupply increments an asset's supply by the coin -func (k Keeper) IncrementCurrentAssetSupply(ctx sdk.Context, coin sdk.Coin) error { - supply, found := k.GetAssetSupply(ctx, coin.Denom) - if !found { - return errorsmod.Wrap(types.ErrAssetNotSupported, coin.Denom) - } - - limit, err := k.GetSupplyLimit(ctx, coin.Denom) - if err != nil { - return err - } - supplyLimit := sdk.NewCoin(coin.Denom, limit.Limit) - - // Resulting current supply must be under asset's limit - if supplyLimit.IsLT(supply.CurrentSupply.Add(coin)) { - return errorsmod.Wrapf(types.ErrExceedsSupplyLimit, "increase %s, asset supply %s, limit %s", coin, supply.CurrentSupply, supplyLimit) - } - - if limit.TimeLimited { - timeBasedSupplyLimit := sdk.NewCoin(coin.Denom, limit.TimeBasedLimit) - if timeBasedSupplyLimit.IsLT(supply.TimeLimitedCurrentSupply.Add(coin)) { - return errorsmod.Wrapf(types.ErrExceedsTimeBasedSupplyLimit, "increase %s, current time-based asset supply %s, limit %s", coin, supply.TimeLimitedCurrentSupply, timeBasedSupplyLimit) - } - supply.TimeLimitedCurrentSupply = supply.TimeLimitedCurrentSupply.Add(coin) - } - - supply.CurrentSupply = supply.CurrentSupply.Add(coin) - k.SetAssetSupply(ctx, supply, coin.Denom) - return nil -} - -// DecrementCurrentAssetSupply decrement an asset's supply by the coin -func (k Keeper) DecrementCurrentAssetSupply(ctx sdk.Context, coin sdk.Coin) error { - supply, found := k.GetAssetSupply(ctx, coin.Denom) - if !found { - return errorsmod.Wrap(types.ErrAssetNotSupported, coin.Denom) - } - - // Resulting current supply must be greater than or equal to 0 - // Use sdkmath.Int instead of sdk.Coin to prevent panic if true - if supply.CurrentSupply.Amount.Sub(coin.Amount).IsNegative() { - return errorsmod.Wrapf(types.ErrInvalidCurrentSupply, "decrease %s, asset supply %s", coin, supply.CurrentSupply) - } - - supply.CurrentSupply = supply.CurrentSupply.Sub(coin) - k.SetAssetSupply(ctx, supply, coin.Denom) - return nil -} - -// IncrementIncomingAssetSupply increments an asset's incoming supply -func (k Keeper) IncrementIncomingAssetSupply(ctx sdk.Context, coin sdk.Coin) error { - supply, found := k.GetAssetSupply(ctx, coin.Denom) - if !found { - return errorsmod.Wrap(types.ErrAssetNotSupported, coin.Denom) - } - - // Result of (current + incoming + amount) must be under asset's limit - totalSupply := supply.CurrentSupply.Add(supply.IncomingSupply) - - limit, err := k.GetSupplyLimit(ctx, coin.Denom) - if err != nil { - return err - } - supplyLimit := sdk.NewCoin(coin.Denom, limit.Limit) - if supplyLimit.IsLT(totalSupply.Add(coin)) { - return errorsmod.Wrapf(types.ErrExceedsSupplyLimit, "increase %s, asset supply %s, limit %s", coin, totalSupply, supplyLimit) - } - - if limit.TimeLimited { - timeLimitedTotalSupply := supply.TimeLimitedCurrentSupply.Add(supply.IncomingSupply) - timeBasedSupplyLimit := sdk.NewCoin(coin.Denom, limit.TimeBasedLimit) - if timeBasedSupplyLimit.IsLT(timeLimitedTotalSupply.Add(coin)) { - return errorsmod.Wrapf(types.ErrExceedsTimeBasedSupplyLimit, "increase %s, time-based asset supply %s, limit %s", coin, supply.TimeLimitedCurrentSupply, timeBasedSupplyLimit) - } - } - - supply.IncomingSupply = supply.IncomingSupply.Add(coin) - k.SetAssetSupply(ctx, supply, coin.Denom) - return nil -} - -// DecrementIncomingAssetSupply decrements an asset's incoming supply -func (k Keeper) DecrementIncomingAssetSupply(ctx sdk.Context, coin sdk.Coin) error { - supply, found := k.GetAssetSupply(ctx, coin.Denom) - if !found { - return errorsmod.Wrap(types.ErrAssetNotSupported, coin.Denom) - } - - // Resulting incoming supply must be greater than or equal to 0 - // Use sdkmath.Int instead of sdk.Coin to prevent panic if true - if supply.IncomingSupply.Amount.Sub(coin.Amount).IsNegative() { - return errorsmod.Wrapf(types.ErrInvalidIncomingSupply, "decrease %s, incoming supply %s", coin, supply.IncomingSupply) - } - - supply.IncomingSupply = supply.IncomingSupply.Sub(coin) - k.SetAssetSupply(ctx, supply, coin.Denom) - return nil -} - -// IncrementOutgoingAssetSupply increments an asset's outgoing supply -func (k Keeper) IncrementOutgoingAssetSupply(ctx sdk.Context, coin sdk.Coin) error { - supply, found := k.GetAssetSupply(ctx, coin.Denom) - if !found { - return errorsmod.Wrap(types.ErrAssetNotSupported, coin.Denom) - } - - // Result of (outgoing + amount) must be less than current supply - if supply.CurrentSupply.IsLT(supply.OutgoingSupply.Add(coin)) { - return errorsmod.Wrapf(types.ErrExceedsAvailableSupply, "swap amount %s, available supply %s", coin, - supply.CurrentSupply.Amount.Sub(supply.OutgoingSupply.Amount)) - } - - supply.OutgoingSupply = supply.OutgoingSupply.Add(coin) - k.SetAssetSupply(ctx, supply, coin.Denom) - return nil -} - -// DecrementOutgoingAssetSupply decrements an asset's outgoing supply -func (k Keeper) DecrementOutgoingAssetSupply(ctx sdk.Context, coin sdk.Coin) error { - supply, found := k.GetAssetSupply(ctx, coin.Denom) - if !found { - return errorsmod.Wrap(types.ErrAssetNotSupported, coin.Denom) - } - - // Resulting outgoing supply must be greater than or equal to 0 - // Use sdkmath.Int instead of sdk.Coin to prevent panic if true - if supply.OutgoingSupply.Amount.Sub(coin.Amount).IsNegative() { - return errorsmod.Wrapf(types.ErrInvalidOutgoingSupply, "decrease %s, outgoing supply %s", coin, supply.OutgoingSupply) - } - - supply.OutgoingSupply = supply.OutgoingSupply.Sub(coin) - k.SetAssetSupply(ctx, supply, coin.Denom) - return nil -} - -// CreateNewAssetSupply creates a new AssetSupply in the store for the input denom -func (k Keeper) CreateNewAssetSupply(ctx sdk.Context, denom string) types.AssetSupply { - supply := types.NewAssetSupply( - sdk.NewCoin(denom, sdk.ZeroInt()), sdk.NewCoin(denom, sdk.ZeroInt()), - sdk.NewCoin(denom, sdk.ZeroInt()), sdk.NewCoin(denom, sdk.ZeroInt()), time.Duration(0)) - k.SetAssetSupply(ctx, supply, denom) - return supply -} - -// UpdateTimeBasedSupplyLimits updates the time based supply for each asset, resetting it if the current time window has elapsed. -func (k Keeper) UpdateTimeBasedSupplyLimits(ctx sdk.Context) { - assets, found := k.GetAssets(ctx) - if !found { - return - } - previousBlockTime, found := k.GetPreviousBlockTime(ctx) - if !found { - previousBlockTime = ctx.BlockTime() - k.SetPreviousBlockTime(ctx, previousBlockTime) - } - timeElapsed := ctx.BlockTime().Sub(previousBlockTime) - for _, asset := range assets { - supply, found := k.GetAssetSupply(ctx, asset.Denom) - // if a new asset has been added by governance, create a new asset supply for it in the store - if !found { - supply = k.CreateNewAssetSupply(ctx, asset.Denom) - } - newTimeElapsed := supply.TimeElapsed + timeElapsed - if asset.SupplyLimit.TimeLimited && newTimeElapsed < asset.SupplyLimit.TimePeriod { - supply.TimeElapsed = newTimeElapsed - } else { - supply.TimeElapsed = time.Duration(0) - supply.TimeLimitedCurrentSupply = sdk.NewCoin(asset.Denom, sdk.ZeroInt()) - } - k.SetAssetSupply(ctx, supply, asset.Denom) - } - k.SetPreviousBlockTime(ctx, ctx.BlockTime()) -} diff --git a/x/bep3/keeper/asset_test.go b/x/bep3/keeper/asset_test.go deleted file mode 100644 index 4e8a7835..00000000 --- a/x/bep3/keeper/asset_test.go +++ /dev/null @@ -1,703 +0,0 @@ -package keeper_test - -import ( - "strings" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/bep3/keeper" - "github.com/kava-labs/kava/x/bep3/types" -) - -type AssetTestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context -} - -func (suite *AssetTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - // Initialize genesis state - deputy, _ := sdk.AccAddressFromBech32(TestDeputy) - tApp.InitializeFromGenesisStates(NewBep3GenStateMulti(tApp.AppCodec(), deputy)) - - keeper := tApp.GetBep3Keeper() - params := keeper.GetParams(ctx) - params.AssetParams[0].SupplyLimit.Limit = sdkmath.NewInt(50) - params.AssetParams[1].SupplyLimit.Limit = sdkmath.NewInt(100) - params.AssetParams[1].SupplyLimit.TimeBasedLimit = sdkmath.NewInt(15) - keeper.SetParams(ctx, params) - // Set asset supply with standard value for testing - supply := types.NewAssetSupply(c("bnb", 5), c("bnb", 5), c("bnb", 40), c("bnb", 0), time.Duration(0)) - keeper.SetAssetSupply(ctx, supply, supply.IncomingSupply.Denom) - - supply = types.NewAssetSupply(c("inc", 10), c("inc", 5), c("inc", 5), c("inc", 0), time.Duration(0)) - keeper.SetAssetSupply(ctx, supply, supply.IncomingSupply.Denom) - keeper.SetPreviousBlockTime(ctx, ctx.BlockTime()) - - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper -} - -func (suite *AssetTestSuite) TestIncrementCurrentAssetSupply() { - type args struct { - coin sdk.Coin - } - testCases := []struct { - name string - args args - expectPass bool - }{ - { - "normal", - args{ - coin: c("bnb", 5), - }, - true, - }, - { - "equal limit", - args{ - coin: c("bnb", 10), - }, - true, - }, - { - "exceeds limit", - args{ - coin: c("bnb", 11), - }, - false, - }, - { - "unsupported asset", - args{ - coin: c("xyz", 5), - }, - false, - }, - } - - for _, tc := range testCases { - suite.SetupTest() - suite.Run(tc.name, func() { - preSupply, found := suite.keeper.GetAssetSupply(suite.ctx, tc.args.coin.Denom) - err := suite.keeper.IncrementCurrentAssetSupply(suite.ctx, tc.args.coin) - postSupply, _ := suite.keeper.GetAssetSupply(suite.ctx, tc.args.coin.Denom) - - if tc.expectPass { - suite.True(found) - suite.NoError(err) - suite.Equal(preSupply.CurrentSupply.Add(tc.args.coin), postSupply.CurrentSupply) - } else { - suite.Error(err) - suite.Equal(preSupply.CurrentSupply, postSupply.CurrentSupply) - } - }) - } -} - -func (suite *AssetTestSuite) TestIncrementTimeLimitedCurrentAssetSupply() { - type args struct { - coin sdk.Coin - expectedSupply types.AssetSupply - } - type errArgs struct { - expectPass bool - contains string - } - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - "normal", - args{ - coin: c("inc", 5), - expectedSupply: types.AssetSupply{ - IncomingSupply: c("inc", 10), - OutgoingSupply: c("inc", 5), - CurrentSupply: c("inc", 10), - TimeLimitedCurrentSupply: c("inc", 5), - TimeElapsed: time.Duration(0), - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "over limit", - args{ - coin: c("inc", 16), - expectedSupply: types.AssetSupply{}, - }, - errArgs{ - expectPass: false, - contains: "asset supply over limit for current time period", - }, - }, - } - for _, tc := range testCases { - suite.SetupTest() - suite.Run(tc.name, func() { - err := suite.keeper.IncrementCurrentAssetSupply(suite.ctx, tc.args.coin) - if tc.errArgs.expectPass { - suite.Require().NoError(err) - supply, _ := suite.keeper.GetAssetSupply(suite.ctx, tc.args.coin.Denom) - suite.Require().Equal(tc.args.expectedSupply, supply) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *AssetTestSuite) TestDecrementCurrentAssetSupply() { - type args struct { - coin sdk.Coin - } - testCases := []struct { - name string - args args - expectPass bool - }{ - { - "normal", - args{ - coin: c("bnb", 30), - }, - true, - }, - { - "equal current", - args{ - coin: c("bnb", 40), - }, - true, - }, - { - "exceeds current", - args{ - coin: c("bnb", 41), - }, - false, - }, - { - "unsupported asset", - args{ - coin: c("xyz", 30), - }, - false, - }, - } - - for _, tc := range testCases { - suite.SetupTest() - suite.Run(tc.name, func() { - preSupply, found := suite.keeper.GetAssetSupply(suite.ctx, tc.args.coin.Denom) - err := suite.keeper.DecrementCurrentAssetSupply(suite.ctx, tc.args.coin) - postSupply, _ := suite.keeper.GetAssetSupply(suite.ctx, tc.args.coin.Denom) - - if tc.expectPass { - suite.True(found) - suite.NoError(err) - suite.True(preSupply.CurrentSupply.Sub(tc.args.coin).IsEqual(postSupply.CurrentSupply)) - } else { - suite.Error(err) - suite.Equal(preSupply.CurrentSupply, postSupply.CurrentSupply) - } - }) - } -} - -func (suite *AssetTestSuite) TestIncrementIncomingAssetSupply() { - type args struct { - coin sdk.Coin - } - testCases := []struct { - name string - args args - expectPass bool - }{ - { - "normal", - args{ - coin: c("bnb", 2), - }, - true, - }, - { - "incoming + current = limit", - args{ - coin: c("bnb", 5), - }, - true, - }, - { - "incoming + current > limit", - args{ - coin: c("bnb", 6), - }, - false, - }, - { - "unsupported asset", - args{ - coin: c("xyz", 2), - }, - false, - }, - } - - for _, tc := range testCases { - suite.SetupTest() - suite.Run(tc.name, func() { - preSupply, found := suite.keeper.GetAssetSupply(suite.ctx, tc.args.coin.Denom) - err := suite.keeper.IncrementIncomingAssetSupply(suite.ctx, tc.args.coin) - postSupply, _ := suite.keeper.GetAssetSupply(suite.ctx, tc.args.coin.Denom) - - if tc.expectPass { - suite.True(found) - suite.NoError(err) - suite.Equal(preSupply.IncomingSupply.Add(tc.args.coin), postSupply.IncomingSupply) - } else { - suite.Error(err) - suite.Equal(preSupply.IncomingSupply, postSupply.IncomingSupply) - } - }) - } -} - -func (suite *AssetTestSuite) TestIncrementTimeLimitedIncomingAssetSupply() { - type args struct { - coin sdk.Coin - expectedSupply types.AssetSupply - } - type errArgs struct { - expectPass bool - contains string - } - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - "normal", - args{ - coin: c("inc", 5), - expectedSupply: types.AssetSupply{ - IncomingSupply: c("inc", 15), - OutgoingSupply: c("inc", 5), - CurrentSupply: c("inc", 5), - TimeLimitedCurrentSupply: c("inc", 0), - TimeElapsed: time.Duration(0), - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "over limit", - args{ - coin: c("inc", 6), - expectedSupply: types.AssetSupply{}, - }, - errArgs{ - expectPass: false, - contains: "asset supply over limit for current time period", - }, - }, - } - for _, tc := range testCases { - suite.SetupTest() - suite.Run(tc.name, func() { - err := suite.keeper.IncrementIncomingAssetSupply(suite.ctx, tc.args.coin) - if tc.errArgs.expectPass { - suite.Require().NoError(err) - supply, _ := suite.keeper.GetAssetSupply(suite.ctx, tc.args.coin.Denom) - suite.Require().Equal(tc.args.expectedSupply, supply) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *AssetTestSuite) TestDecrementIncomingAssetSupply() { - type args struct { - coin sdk.Coin - } - testCases := []struct { - name string - args args - expectPass bool - }{ - { - "normal", - args{ - coin: c("bnb", 4), - }, - true, - }, - { - "equal incoming", - args{ - coin: c("bnb", 5), - }, - true, - }, - { - "exceeds incoming", - args{ - coin: c("bnb", 6), - }, - false, - }, - { - "unsupported asset", - args{ - coin: c("xyz", 4), - }, - false, - }, - } - - for _, tc := range testCases { - suite.SetupTest() - suite.Run(tc.name, func() { - preSupply, found := suite.keeper.GetAssetSupply(suite.ctx, tc.args.coin.Denom) - err := suite.keeper.DecrementIncomingAssetSupply(suite.ctx, tc.args.coin) - postSupply, _ := suite.keeper.GetAssetSupply(suite.ctx, tc.args.coin.Denom) - - if tc.expectPass { - suite.True(found) - suite.NoError(err) - suite.True(preSupply.IncomingSupply.Sub(tc.args.coin).IsEqual(postSupply.IncomingSupply)) - } else { - suite.Error(err) - suite.Equal(preSupply.IncomingSupply, postSupply.IncomingSupply) - } - }) - } -} - -func (suite *AssetTestSuite) TestIncrementOutgoingAssetSupply() { - type args struct { - coin sdk.Coin - } - testCases := []struct { - name string - args args - expectPass bool - }{ - { - "normal", - args{ - coin: c("bnb", 30), - }, - true, - }, - { - "outgoing + amount = current", - args{ - coin: c("bnb", 35), - }, - true, - }, - { - "outoing + amount > current", - args{ - coin: c("bnb", 36), - }, - false, - }, - { - "unsupported asset", - args{ - coin: c("xyz", 30), - }, - false, - }, - } - - for _, tc := range testCases { - suite.SetupTest() - suite.Run(tc.name, func() { - preSupply, found := suite.keeper.GetAssetSupply(suite.ctx, tc.args.coin.Denom) - err := suite.keeper.IncrementOutgoingAssetSupply(suite.ctx, tc.args.coin) - postSupply, _ := suite.keeper.GetAssetSupply(suite.ctx, tc.args.coin.Denom) - - if tc.expectPass { - suite.True(found) - suite.NoError(err) - suite.Equal(preSupply.OutgoingSupply.Add(tc.args.coin), postSupply.OutgoingSupply) - } else { - suite.Error(err) - suite.Equal(preSupply.OutgoingSupply, postSupply.OutgoingSupply) - } - }) - } -} - -func (suite *AssetTestSuite) TestDecrementOutgoingAssetSupply() { - type args struct { - coin sdk.Coin - } - testCases := []struct { - name string - args args - expectPass bool - }{ - { - "normal", - args{ - coin: c("bnb", 4), - }, - true, - }, - { - "equal outgoing", - args{ - coin: c("bnb", 5), - }, - true, - }, - { - "exceeds outgoing", - args{ - coin: c("bnb", 6), - }, - false, - }, - { - "unsupported asset", - args{ - coin: c("xyz", 4), - }, - false, - }, - } - - for _, tc := range testCases { - suite.SetupTest() - suite.Run(tc.name, func() { - preSupply, found := suite.keeper.GetAssetSupply(suite.ctx, tc.args.coin.Denom) - err := suite.keeper.DecrementOutgoingAssetSupply(suite.ctx, tc.args.coin) - postSupply, _ := suite.keeper.GetAssetSupply(suite.ctx, tc.args.coin.Denom) - - if tc.expectPass { - suite.True(found) - suite.NoError(err) - suite.True(preSupply.OutgoingSupply.Sub(tc.args.coin).IsEqual(postSupply.OutgoingSupply)) - } else { - suite.Error(err) - suite.Equal(preSupply.OutgoingSupply, postSupply.OutgoingSupply) - } - }) - } -} - -func (suite *AssetTestSuite) TestUpdateTimeBasedSupplyLimits() { - type args struct { - asset string - duration time.Duration - expectedSupply types.AssetSupply - } - type errArgs struct { - expectPanic bool - contains string - } - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - "rate-limited increment time", - args{ - asset: "inc", - duration: time.Second, - expectedSupply: types.NewAssetSupply(c("inc", 10), c("inc", 5), c("inc", 5), c("inc", 0), time.Second), - }, - errArgs{ - expectPanic: false, - contains: "", - }, - }, - { - "rate-limited increment time half", - args{ - asset: "inc", - duration: time.Minute * 30, - expectedSupply: types.NewAssetSupply(c("inc", 10), c("inc", 5), c("inc", 5), c("inc", 0), time.Minute*30), - }, - errArgs{ - expectPanic: false, - contains: "", - }, - }, - { - "rate-limited period change", - args{ - asset: "inc", - duration: time.Hour + time.Second, - expectedSupply: types.NewAssetSupply(c("inc", 10), c("inc", 5), c("inc", 5), c("inc", 0), time.Duration(0)), - }, - errArgs{ - expectPanic: false, - contains: "", - }, - }, - { - "rate-limited period change exact", - args{ - asset: "inc", - duration: time.Hour, - expectedSupply: types.NewAssetSupply(c("inc", 10), c("inc", 5), c("inc", 5), c("inc", 0), time.Duration(0)), - }, - errArgs{ - expectPanic: false, - contains: "", - }, - }, - { - "rate-limited period change big", - args{ - asset: "inc", - duration: time.Hour * 4, - expectedSupply: types.NewAssetSupply(c("inc", 10), c("inc", 5), c("inc", 5), c("inc", 0), time.Duration(0)), - }, - errArgs{ - expectPanic: false, - contains: "", - }, - }, - { - "non rate-limited increment time", - args{ - asset: "bnb", - duration: time.Second, - expectedSupply: types.NewAssetSupply(c("bnb", 5), c("bnb", 5), c("bnb", 40), c("bnb", 0), time.Duration(0)), - }, - errArgs{ - expectPanic: false, - contains: "", - }, - }, - { - "new asset increment time", - args{ - asset: "lol", - duration: time.Second, - expectedSupply: types.NewAssetSupply(c("lol", 0), c("lol", 0), c("lol", 0), c("lol", 0), time.Second), - }, - errArgs{ - expectPanic: false, - contains: "", - }, - }, - } - for _, tc := range testCases { - suite.SetupTest() - suite.Run(tc.name, func() { - deputy, _ := sdk.AccAddressFromBech32(TestDeputy) - newParams := types.Params{ - AssetParams: types.AssetParams{ - { - Denom: "bnb", - CoinID: 714, - SupplyLimit: types.SupplyLimit{ - Limit: sdkmath.NewInt(350000000000000), - TimeLimited: false, - TimeBasedLimit: sdk.ZeroInt(), - TimePeriod: time.Hour, - }, - Active: true, - DeputyAddress: deputy, - FixedFee: sdkmath.NewInt(1000), - MinSwapAmount: sdk.OneInt(), - MaxSwapAmount: sdkmath.NewInt(1000000000000), - MinBlockLock: types.DefaultMinBlockLock, - MaxBlockLock: types.DefaultMaxBlockLock, - }, - { - Denom: "inc", - CoinID: 9999, - SupplyLimit: types.SupplyLimit{ - Limit: sdkmath.NewInt(100), - TimeLimited: true, - TimeBasedLimit: sdkmath.NewInt(10), - TimePeriod: time.Hour, - }, - Active: false, - DeputyAddress: deputy, - FixedFee: sdkmath.NewInt(1000), - MinSwapAmount: sdk.OneInt(), - MaxSwapAmount: sdkmath.NewInt(1000000000000), - MinBlockLock: types.DefaultMinBlockLock, - MaxBlockLock: types.DefaultMaxBlockLock, - }, - { - Denom: "lol", - CoinID: 9999, - SupplyLimit: types.SupplyLimit{ - Limit: sdkmath.NewInt(100), - TimeLimited: true, - TimeBasedLimit: sdkmath.NewInt(10), - TimePeriod: time.Hour, - }, - Active: false, - DeputyAddress: deputy, - FixedFee: sdkmath.NewInt(1000), - MinSwapAmount: sdk.OneInt(), - MaxSwapAmount: sdkmath.NewInt(1000000000000), - MinBlockLock: types.DefaultMinBlockLock, - MaxBlockLock: types.DefaultMaxBlockLock, - }, - }, - } - suite.keeper.SetParams(suite.ctx, newParams) - suite.ctx = suite.ctx.WithBlockTime(suite.ctx.BlockTime().Add(tc.args.duration)) - suite.NotPanics( - func() { - suite.keeper.UpdateTimeBasedSupplyLimits(suite.ctx) - }, - ) - if !tc.errArgs.expectPanic { - supply, found := suite.keeper.GetAssetSupply(suite.ctx, tc.args.asset) - suite.Require().True(found) - suite.Require().Equal(tc.args.expectedSupply, supply) - } - }) - } -} - -func TestAssetTestSuite(t *testing.T) { - suite.Run(t, new(AssetTestSuite)) -} diff --git a/x/bep3/keeper/grpc_query.go b/x/bep3/keeper/grpc_query.go deleted file mode 100644 index 1012c82e..00000000 --- a/x/bep3/keeper/grpc_query.go +++ /dev/null @@ -1,181 +0,0 @@ -package keeper - -import ( - "context" - "encoding/hex" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - - "github.com/kava-labs/kava/x/bep3/types" -) - -type queryServer struct { - keeper Keeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -var _ types.QueryServer = queryServer{} - -// Params queries module params -func (s queryServer) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - params := s.keeper.GetParams(sdkCtx) - - return &types.QueryParamsResponse{Params: params}, nil -} - -// AssetSupply queries info about an asset's supply -func (s queryServer) AssetSupply(ctx context.Context, req *types.QueryAssetSupplyRequest) (*types.QueryAssetSupplyResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - assetSupply, ok := s.keeper.GetAssetSupply(sdkCtx, req.Denom) - if !ok { - return nil, status.Errorf(codes.NotFound, "denom not found") - } - - return &types.QueryAssetSupplyResponse{AssetSupply: mapAssetSupplyToResponse(assetSupply)}, nil -} - -// AssetSupplies queries a list of asset supplies -func (s queryServer) AssetSupplies(ctx context.Context, req *types.QueryAssetSuppliesRequest) (*types.QueryAssetSuppliesResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - var queryResults []types.AssetSupplyResponse - s.keeper.IterateAssetSupplies(sdkCtx, func(assetSupply types.AssetSupply) bool { - queryResults = append(queryResults, mapAssetSupplyToResponse(assetSupply)) - return false - }) - - return &types.QueryAssetSuppliesResponse{ - AssetSupplies: queryResults, - }, nil -} - -// AtomicSwap queries info about an atomic swap -func (s queryServer) AtomicSwap(ctx context.Context, req *types.QueryAtomicSwapRequest) (*types.QueryAtomicSwapResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - swapId, err := hex.DecodeString(req.SwapId) - if err != nil { - return nil, status.Errorf(codes.NotFound, "invalid atomic swap id") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - atomicSwap, ok := s.keeper.GetAtomicSwap(sdkCtx, swapId) - if !ok { - return nil, status.Errorf(codes.NotFound, "invalid atomic swap") - } - - return &types.QueryAtomicSwapResponse{ - AtomicSwap: mapAtomicSwapToResponse(atomicSwap), - }, nil -} - -// AtomicSwaps queries a list of atomic swaps -func (s queryServer) AtomicSwaps(ctx context.Context, req *types.QueryAtomicSwapsRequest) (*types.QueryAtomicSwapsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - store := prefix.NewStore(sdkCtx.KVStore(s.keeper.key), types.AtomicSwapKeyPrefix) - - var queryResults []types.AtomicSwapResponse - pageRes, err := query.FilteredPaginate(store, req.Pagination, func(_, value []byte, shouldAccumulate bool) (bool, error) { - var atomicSwap types.AtomicSwap - err := s.keeper.cdc.Unmarshal(value, &atomicSwap) - if err != nil { - return false, err - } - - if len(req.Involve) > 0 { - if atomicSwap.Sender.String() != req.Involve && atomicSwap.Recipient.String() != req.Involve { - return false, nil - } - } - - // match expiration block limit (if supplied) - if req.Expiration > 0 { - if atomicSwap.ExpireHeight > req.Expiration { - return false, nil - } - } - - // match status (if supplied/valid) - if req.Status.IsValid() { - if atomicSwap.Status != req.Status { - return false, nil - } - } - - // match direction (if supplied/valid) - if req.Direction.IsValid() { - if atomicSwap.Direction != req.Direction { - return false, nil - } - } - - if shouldAccumulate { - queryResults = append(queryResults, mapAtomicSwapToResponse(atomicSwap)) - } - return true, nil - }) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "paginate: %v", err) - } - - return &types.QueryAtomicSwapsResponse{ - AtomicSwaps: queryResults, - Pagination: pageRes, - }, nil -} - -func mapAssetSupplyToResponse(assetSupply types.AssetSupply) types.AssetSupplyResponse { - return types.AssetSupplyResponse{ - IncomingSupply: assetSupply.IncomingSupply, - OutgoingSupply: assetSupply.OutgoingSupply, - CurrentSupply: assetSupply.CurrentSupply, - TimeLimitedCurrentSupply: assetSupply.TimeLimitedCurrentSupply, - TimeElapsed: assetSupply.TimeElapsed, - } -} - -func mapAtomicSwapToResponse(atomicSwap types.AtomicSwap) types.AtomicSwapResponse { - return types.AtomicSwapResponse{ - Id: atomicSwap.GetSwapID().String(), - Amount: atomicSwap.Amount, - RandomNumberHash: atomicSwap.RandomNumberHash.String(), - ExpireHeight: atomicSwap.ExpireHeight, - Timestamp: atomicSwap.Timestamp, - Sender: atomicSwap.Sender.String(), - Recipient: atomicSwap.Recipient.String(), - SenderOtherChain: atomicSwap.SenderOtherChain, - RecipientOtherChain: atomicSwap.RecipientOtherChain, - ClosedBlock: atomicSwap.ClosedBlock, - Status: atomicSwap.Status, - CrossChain: atomicSwap.CrossChain, - Direction: atomicSwap.Direction, - } -} diff --git a/x/bep3/keeper/integration_test.go b/x/bep3/keeper/integration_test.go deleted file mode 100644 index ffe94eb6..00000000 --- a/x/bep3/keeper/integration_test.go +++ /dev/null @@ -1,119 +0,0 @@ -package keeper_test - -import ( - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - "github.com/cometbft/cometbft/crypto" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/bep3/types" -) - -const ( - TestSenderOtherChain = "bnb1uky3me9ggqypmrsvxk7ur6hqkzq7zmv4ed4ng7" - TestRecipientOtherChain = "bnb1urfermcg92dwq36572cx4xg84wpk3lfpksr5g7" - TestDeputy = "kava1xy7hrjy9r0algz9w3gzm8u6mrpq97kwta747gj" -) - -var ( - DenomMap = map[int]string{0: "btc", 1: "eth", 2: "bnb", 3: "xrp", 4: "dai"} - TestUser1 = sdk.AccAddress(crypto.AddressHash([]byte("KavaTestUser1"))) - TestUser2 = sdk.AccAddress(crypto.AddressHash([]byte("KavaTestUser2"))) -) - -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } -func ts(minOffset int) int64 { return tmtime.Now().Add(time.Duration(minOffset) * time.Minute).Unix() } - -func NewAuthGenStateFromAccs(cdc codec.JSONCodec, accounts ...authtypes.GenesisAccount) app.GenesisState { - authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), accounts) - return app.GenesisState{authtypes.ModuleName: cdc.MustMarshalJSON(authGenesis)} -} - -func NewBep3GenStateMulti(cdc codec.JSONCodec, deputyAddress sdk.AccAddress) app.GenesisState { - bep3Genesis := types.GenesisState{ - Params: types.Params{ - AssetParams: types.AssetParams{ - { - Denom: "bnb", - CoinID: 714, - SupplyLimit: types.SupplyLimit{ - Limit: sdkmath.NewInt(350000000000000), - TimeLimited: false, - TimeBasedLimit: sdk.ZeroInt(), - TimePeriod: time.Hour, - }, - Active: true, - DeputyAddress: deputyAddress, - FixedFee: sdkmath.NewInt(1000), - MinSwapAmount: sdk.OneInt(), - MaxSwapAmount: sdkmath.NewInt(1000000000000), - MinBlockLock: types.DefaultMinBlockLock, - MaxBlockLock: types.DefaultMaxBlockLock, - }, - { - Denom: "inc", - CoinID: 9999, - SupplyLimit: types.SupplyLimit{ - Limit: sdkmath.NewInt(100000000000000), - TimeLimited: true, - TimeBasedLimit: sdkmath.NewInt(50000000000), - TimePeriod: time.Hour, - }, - Active: false, - DeputyAddress: deputyAddress, - FixedFee: sdkmath.NewInt(1000), - MinSwapAmount: sdk.OneInt(), - MaxSwapAmount: sdkmath.NewInt(100000000000), - MinBlockLock: types.DefaultMinBlockLock, - MaxBlockLock: types.DefaultMaxBlockLock, - }, - }, - }, - Supplies: types.AssetSupplies{ - types.NewAssetSupply( - sdk.NewCoin("bnb", sdk.ZeroInt()), - sdk.NewCoin("bnb", sdk.ZeroInt()), - sdk.NewCoin("bnb", sdk.ZeroInt()), - sdk.NewCoin("bnb", sdk.ZeroInt()), - time.Duration(0), - ), - types.NewAssetSupply( - sdk.NewCoin("inc", sdk.ZeroInt()), - sdk.NewCoin("inc", sdk.ZeroInt()), - sdk.NewCoin("inc", sdk.ZeroInt()), - sdk.NewCoin("inc", sdk.ZeroInt()), - time.Duration(0), - ), - }, - PreviousBlockTime: types.DefaultPreviousBlockTime, - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&bep3Genesis)} -} - -func atomicSwaps(ctx sdk.Context, count int) types.AtomicSwaps { - var swaps types.AtomicSwaps - for i := 0; i < count; i++ { - swap := atomicSwap(ctx, i) - swaps = append(swaps, swap) - } - return swaps -} - -func atomicSwap(ctx sdk.Context, index int) types.AtomicSwap { - expireOffset := uint64(200) // Default expire height + offet to match timestamp - timestamp := ts(index) // One minute apart - randomNumber, _ := types.GenerateSecureRandomNumber() - randomNumberHash := types.CalculateRandomHash(randomNumber[:], timestamp) - - return types.NewAtomicSwap(cs(c("bnb", 50000)), randomNumberHash, - uint64(ctx.BlockHeight())+expireOffset, timestamp, TestUser1, TestUser2, - TestSenderOtherChain, TestRecipientOtherChain, 0, types.SWAP_STATUS_OPEN, true, - types.SWAP_DIRECTION_INCOMING) -} diff --git a/x/bep3/keeper/keeper.go b/x/bep3/keeper/keeper.go deleted file mode 100644 index 6a32a81b..00000000 --- a/x/bep3/keeper/keeper.go +++ /dev/null @@ -1,251 +0,0 @@ -package keeper - -import ( - "fmt" - "time" - - "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store/prefix" - 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/kava-labs/kava/x/bep3/types" -) - -// Keeper of the bep3 store -type Keeper struct { - key storetypes.StoreKey - cdc codec.Codec - paramSubspace paramtypes.Subspace - bankKeeper types.BankKeeper - accountKeeper types.AccountKeeper - Maccs map[string]bool -} - -// NewKeeper creates a bep3 keeper -func NewKeeper(cdc codec.Codec, key storetypes.StoreKey, sk types.BankKeeper, ak types.AccountKeeper, - paramstore paramtypes.Subspace, maccs map[string]bool, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - keeper := Keeper{ - key: key, - cdc: cdc, - paramSubspace: paramstore, - bankKeeper: sk, - accountKeeper: ak, - Maccs: maccs, - } - return keeper -} - -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) -} - -// ------------------------------------------ -// Atomic Swaps -// ------------------------------------------ - -// SetAtomicSwap puts the AtomicSwap into the store, and updates any indexes. -func (k Keeper) SetAtomicSwap(ctx sdk.Context, atomicSwap types.AtomicSwap) { - store := prefix.NewStore(ctx.KVStore(k.key), types.AtomicSwapKeyPrefix) - bz := k.cdc.MustMarshal(&atomicSwap) - store.Set(atomicSwap.GetSwapID(), bz) -} - -// GetAtomicSwap gets an AtomicSwap from the store. -func (k Keeper) GetAtomicSwap(ctx sdk.Context, swapID []byte) (types.AtomicSwap, bool) { - var atomicSwap types.AtomicSwap - - store := prefix.NewStore(ctx.KVStore(k.key), types.AtomicSwapKeyPrefix) - bz := store.Get(swapID) - if bz == nil { - return atomicSwap, false - } - - k.cdc.MustUnmarshal(bz, &atomicSwap) - return atomicSwap, true -} - -// RemoveAtomicSwap removes an AtomicSwap from the AtomicSwapKeyPrefix. -func (k Keeper) RemoveAtomicSwap(ctx sdk.Context, swapID []byte) { - store := prefix.NewStore(ctx.KVStore(k.key), types.AtomicSwapKeyPrefix) - store.Delete(swapID) -} - -// IterateAtomicSwaps provides an iterator over all stored AtomicSwaps. -// For each AtomicSwap, cb will be called. If cb returns true, the iterator will close and stop. -func (k Keeper) IterateAtomicSwaps(ctx sdk.Context, cb func(atomicSwap types.AtomicSwap) (stop bool)) { - iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.key), types.AtomicSwapKeyPrefix) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var atomicSwap types.AtomicSwap - k.cdc.MustUnmarshal(iterator.Value(), &atomicSwap) - - if cb(atomicSwap) { - break - } - } -} - -// GetAllAtomicSwaps returns all AtomicSwaps from the store -func (k Keeper) GetAllAtomicSwaps(ctx sdk.Context) (atomicSwaps types.AtomicSwaps) { - k.IterateAtomicSwaps(ctx, func(atomicSwap types.AtomicSwap) bool { - atomicSwaps = append(atomicSwaps, atomicSwap) - return false - }) - return -} - -// ------------------------------------------ -// Atomic Swap Block Index -// ------------------------------------------ - -// InsertIntoByBlockIndex adds a swap ID and expiration time into the byBlock index. -func (k Keeper) InsertIntoByBlockIndex(ctx sdk.Context, atomicSwap types.AtomicSwap) { - store := prefix.NewStore(ctx.KVStore(k.key), types.AtomicSwapByBlockPrefix) - store.Set(types.GetAtomicSwapByHeightKey(atomicSwap.ExpireHeight, atomicSwap.GetSwapID()), atomicSwap.GetSwapID()) -} - -// RemoveFromByBlockIndex removes an AtomicSwap from the byBlock index. -func (k Keeper) RemoveFromByBlockIndex(ctx sdk.Context, atomicSwap types.AtomicSwap) { - store := prefix.NewStore(ctx.KVStore(k.key), types.AtomicSwapByBlockPrefix) - store.Delete(types.GetAtomicSwapByHeightKey(atomicSwap.ExpireHeight, atomicSwap.GetSwapID())) -} - -// IterateAtomicSwapsByBlock provides an iterator over AtomicSwaps ordered by AtomicSwap expiration block -// For each AtomicSwap cb will be called. If cb returns true the iterator will close and stop. -func (k Keeper) IterateAtomicSwapsByBlock(ctx sdk.Context, inclusiveCutoffTime uint64, cb func(swapID []byte) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.AtomicSwapByBlockPrefix) - iterator := store.Iterator( - nil, // start at the very start of the prefix store - sdk.PrefixEndBytes(sdk.Uint64ToBigEndian(inclusiveCutoffTime)), // end of range - ) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - - id := iterator.Value() - - if cb(id) { - break - } - } -} - -// ------------------------------------------ -// Atomic Swap Longterm Storage Index -// ------------------------------------------ - -// InsertIntoLongtermStorage adds a swap ID and deletion time into the longterm storage index. -// Completed swaps are stored for 1 week. -func (k Keeper) InsertIntoLongtermStorage(ctx sdk.Context, atomicSwap types.AtomicSwap) { - store := prefix.NewStore(ctx.KVStore(k.key), types.AtomicSwapLongtermStoragePrefix) - deletionHeight := uint64(atomicSwap.ClosedBlock) + types.DefaultLongtermStorageDuration - store.Set(types.GetAtomicSwapByHeightKey(deletionHeight, atomicSwap.GetSwapID()), atomicSwap.GetSwapID()) -} - -// RemoveFromLongtermStorage removes a swap from the into the longterm storage index -func (k Keeper) RemoveFromLongtermStorage(ctx sdk.Context, atomicSwap types.AtomicSwap) { - store := prefix.NewStore(ctx.KVStore(k.key), types.AtomicSwapLongtermStoragePrefix) - deletionHeight := uint64(atomicSwap.ClosedBlock) + types.DefaultLongtermStorageDuration - store.Delete(types.GetAtomicSwapByHeightKey(deletionHeight, atomicSwap.GetSwapID())) -} - -// IterateAtomicSwapsLongtermStorage provides an iterator over AtomicSwaps ordered by deletion height. -// For each AtomicSwap cb will be called. If cb returns true the iterator will close and stop. -func (k Keeper) IterateAtomicSwapsLongtermStorage(ctx sdk.Context, inclusiveCutoffTime uint64, - cb func(swapID []byte) (stop bool), -) { - store := prefix.NewStore(ctx.KVStore(k.key), types.AtomicSwapLongtermStoragePrefix) - iterator := store.Iterator( - nil, // start at the very start of the prefix store - sdk.PrefixEndBytes(sdk.Uint64ToBigEndian(inclusiveCutoffTime)), // end of range - ) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - - id := iterator.Value() - - if cb(id) { - break - } - } -} - -// ------------------------------------------ -// Asset Supplies -// ------------------------------------------ - -// GetAssetSupply gets an asset's current supply from the store. -func (k Keeper) GetAssetSupply(ctx sdk.Context, denom string) (types.AssetSupply, bool) { - var assetSupply types.AssetSupply - store := prefix.NewStore(ctx.KVStore(k.key), types.AssetSupplyPrefix) - bz := store.Get([]byte(denom)) - if bz == nil { - return types.AssetSupply{}, false - } - k.cdc.MustUnmarshal(bz, &assetSupply) - return assetSupply, true -} - -// SetAssetSupply updates an asset's supply -func (k Keeper) SetAssetSupply(ctx sdk.Context, supply types.AssetSupply, denom string) { - store := prefix.NewStore(ctx.KVStore(k.key), types.AssetSupplyPrefix) - store.Set([]byte(denom), k.cdc.MustMarshal(&supply)) -} - -// IterateAssetSupplies provides an iterator over all stored AssetSupplies. -func (k Keeper) IterateAssetSupplies(ctx sdk.Context, cb func(supply types.AssetSupply) (stop bool)) { - iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.key), types.AssetSupplyPrefix) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var supply types.AssetSupply - k.cdc.MustUnmarshal(iterator.Value(), &supply) - - if cb(supply) { - break - } - } -} - -// GetAllAssetSupplies returns all asset supplies from the store -func (k Keeper) GetAllAssetSupplies(ctx sdk.Context) (supplies types.AssetSupplies) { - k.IterateAssetSupplies(ctx, func(supply types.AssetSupply) bool { - supplies = append(supplies, supply) - return false - }) - return -} - -// GetPreviousBlockTime get the blocktime for the previous block -func (k Keeper) GetPreviousBlockTime(ctx sdk.Context) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousBlockTimeKey) - b := store.Get(types.PreviousBlockTimeKey) - if b == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(b); err != nil { - panic(err) - } - return blockTime, true -} - -// SetPreviousBlockTime set the time of the previous block -func (k Keeper) SetPreviousBlockTime(ctx sdk.Context, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousBlockTimeKey) - b, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set(types.PreviousBlockTimeKey, b) -} diff --git a/x/bep3/keeper/keeper_test.go b/x/bep3/keeper/keeper_test.go deleted file mode 100644 index 52924720..00000000 --- a/x/bep3/keeper/keeper_test.go +++ /dev/null @@ -1,340 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/bep3/keeper" - "github.com/kava-labs/kava/x/bep3/types" -) - -const LongtermStorageDuration = 86400 - -type KeeperTestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context -} - -func (suite *KeeperTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - suite.ResetChain() -} - -func (suite *KeeperTestSuite) ResetChain() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - keeper := tApp.GetBep3Keeper() - - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper -} - -func (suite *KeeperTestSuite) TestGetSetAtomicSwap() { - suite.ResetChain() - - // Set new atomic swap - atomicSwap := atomicSwap(suite.ctx, 1) - suite.keeper.SetAtomicSwap(suite.ctx, atomicSwap) - - // Check atomic swap in store - s, found := suite.keeper.GetAtomicSwap(suite.ctx, atomicSwap.GetSwapID()) - suite.True(found) - suite.Equal(atomicSwap, s) - - // Check fake atomic swap not in store - fakeSwapID := types.CalculateSwapID(atomicSwap.RandomNumberHash, TestUser2, "otheraddress") - _, found = suite.keeper.GetAtomicSwap(suite.ctx, fakeSwapID) - suite.False(found) -} - -func (suite *KeeperTestSuite) TestRemoveAtomicSwap() { - suite.ResetChain() - - // Set new atomic swap - atomicSwap := atomicSwap(suite.ctx, 1) - suite.keeper.SetAtomicSwap(suite.ctx, atomicSwap) - - // Check atomic swap in store - s, found := suite.keeper.GetAtomicSwap(suite.ctx, atomicSwap.GetSwapID()) - suite.True(found) - suite.Equal(atomicSwap, s) - - suite.keeper.RemoveAtomicSwap(suite.ctx, atomicSwap.GetSwapID()) - - // Check atomic swap not in store - _, found = suite.keeper.GetAtomicSwap(suite.ctx, atomicSwap.GetSwapID()) - suite.False(found) -} - -func (suite *KeeperTestSuite) TestIterateAtomicSwaps() { - suite.ResetChain() - - // Set atomic swaps - atomicSwaps := atomicSwaps(suite.ctx, 4) - for _, s := range atomicSwaps { - suite.keeper.SetAtomicSwap(suite.ctx, s) - } - - // Read each atomic swap from the store - var readAtomicSwaps types.AtomicSwaps - suite.keeper.IterateAtomicSwaps(suite.ctx, func(a types.AtomicSwap) bool { - readAtomicSwaps = append(readAtomicSwaps, a) - return false - }) - - // Check expected values - suite.Equal(len(atomicSwaps), len(readAtomicSwaps)) -} - -func (suite *KeeperTestSuite) TestGetAllAtomicSwaps() { - suite.ResetChain() - - // Set atomic swaps - atomicSwaps := atomicSwaps(suite.ctx, 4) - for _, s := range atomicSwaps { - suite.keeper.SetAtomicSwap(suite.ctx, s) - } - - // Get and check atomic swaps - res := suite.keeper.GetAllAtomicSwaps(suite.ctx) - suite.Equal(4, len(res)) -} - -func (suite *KeeperTestSuite) TestInsertIntoByBlockIndex() { - suite.ResetChain() - - // Set new atomic swap in by block index - atomicSwap := atomicSwap(suite.ctx, 1) - suite.keeper.InsertIntoByBlockIndex(suite.ctx, atomicSwap) - - // Block index lacks getter methods, must use iteration to get count of swaps in store - var swapIDs [][]byte - suite.keeper.IterateAtomicSwapsByBlock(suite.ctx, atomicSwap.ExpireHeight+1, func(id []byte) bool { - swapIDs = append(swapIDs, id) - return false - }) - suite.Equal(len(swapIDs), 1) - - // Marshal the expected swapID - cdc := suite.app.LegacyAmino() - res, _ := cdc.Amino.MarshalBinaryBare(atomicSwap.GetSwapID()) - expectedSwapID := res[1:] - - suite.Equal(expectedSwapID, swapIDs[0]) -} - -func (suite *KeeperTestSuite) TestRemoveFromByBlockIndex() { - suite.ResetChain() - - // Set new atomic swap in by block index - atomicSwap := atomicSwap(suite.ctx, 1) - suite.keeper.InsertIntoByBlockIndex(suite.ctx, atomicSwap) - - // Check stored data in block index - var swapIDsPre [][]byte - suite.keeper.IterateAtomicSwapsByBlock(suite.ctx, atomicSwap.ExpireHeight+1, func(id []byte) bool { - swapIDsPre = append(swapIDsPre, id) - return false - }) - suite.Equal(len(swapIDsPre), 1) - - suite.keeper.RemoveFromByBlockIndex(suite.ctx, atomicSwap) - - // Check stored data not in block index - var swapIDsPost [][]byte - suite.keeper.IterateAtomicSwapsByBlock(suite.ctx, atomicSwap.ExpireHeight+1, func(id []byte) bool { - swapIDsPost = append(swapIDsPost, id) - return false - }) - suite.Equal(len(swapIDsPost), 0) -} - -func (suite *KeeperTestSuite) TestIterateAtomicSwapsByBlock() { - suite.ResetChain() - - type args struct { - blockCtx sdk.Context - swap types.AtomicSwap - } - - var testCases []args - for i := 0; i < 8; i++ { - // Set up context 100 blocks apart - blockCtx := suite.ctx.WithBlockHeight(int64(i) * 100) - - // Initialize a new atomic swap (different randomNumberHash = different swap IDs) - timestamp := tmtime.Now().Add(time.Duration(i) * time.Minute).Unix() - randomNumber, _ := types.GenerateSecureRandomNumber() - randomNumberHash := types.CalculateRandomHash(randomNumber[:], timestamp) - - atomicSwap := types.NewAtomicSwap(cs(c("bnb", 50000)), randomNumberHash, - uint64(blockCtx.BlockHeight()), timestamp, TestUser1, TestUser2, - TestSenderOtherChain, TestRecipientOtherChain, 0, types.SWAP_STATUS_OPEN, - true, types.SWAP_DIRECTION_INCOMING) - - // Insert into block index - suite.keeper.InsertIntoByBlockIndex(blockCtx, atomicSwap) - // Add to local block index - testCases = append(testCases, args{blockCtx, atomicSwap}) - } - - // Set up the expected swap IDs for a given cutoff block - cutoffBlock := int64(450) - var expectedSwapIDs [][]byte - for _, tc := range testCases { - if tc.blockCtx.BlockHeight() < cutoffBlock || tc.blockCtx.BlockHeight() == cutoffBlock { - expectedSwapIDs = append(expectedSwapIDs, tc.swap.GetSwapID()) - } - } - - // Read the swap IDs from store for a given cutoff block - var readSwapIDs [][]byte - suite.keeper.IterateAtomicSwapsByBlock(suite.ctx, uint64(cutoffBlock), func(id []byte) bool { - readSwapIDs = append(readSwapIDs, id) - return false - }) - - suite.Equal(expectedSwapIDs, readSwapIDs) -} - -func (suite *KeeperTestSuite) TestInsertIntoLongtermStorage() { - suite.ResetChain() - - // Set atomic swap in longterm storage - atomicSwap := atomicSwap(suite.ctx, 1) - atomicSwap.ClosedBlock = suite.ctx.BlockHeight() - suite.keeper.InsertIntoLongtermStorage(suite.ctx, atomicSwap) - - // Longterm storage lacks getter methods, must use iteration to get count of swaps in store - var swapIDs [][]byte - suite.keeper.IterateAtomicSwapsLongtermStorage(suite.ctx, uint64(atomicSwap.ClosedBlock+LongtermStorageDuration), func(id []byte) bool { - swapIDs = append(swapIDs, id) - return false - }) - suite.Equal(len(swapIDs), 1) - - // Marshal the expected swapID - cdc := suite.app.LegacyAmino() - res, _ := cdc.Amino.MarshalBinaryBare(atomicSwap.GetSwapID()) - expectedSwapID := res[1:] - - suite.Equal(expectedSwapID, swapIDs[0]) -} - -func (suite *KeeperTestSuite) TestRemoveFromLongtermStorage() { - suite.ResetChain() - - // Set atomic swap in longterm storage - atomicSwap := atomicSwap(suite.ctx, 1) - atomicSwap.ClosedBlock = suite.ctx.BlockHeight() - suite.keeper.InsertIntoLongtermStorage(suite.ctx, atomicSwap) - - // Longterm storage lacks getter methods, must use iteration to get count of swaps in store - var swapIDs [][]byte - suite.keeper.IterateAtomicSwapsLongtermStorage(suite.ctx, uint64(atomicSwap.ClosedBlock+LongtermStorageDuration), func(id []byte) bool { - swapIDs = append(swapIDs, id) - return false - }) - suite.Equal(len(swapIDs), 1) - - suite.keeper.RemoveFromLongtermStorage(suite.ctx, atomicSwap) - - // Check stored data not in block index - var swapIDsPost [][]byte - suite.keeper.IterateAtomicSwapsLongtermStorage(suite.ctx, uint64(atomicSwap.ClosedBlock+LongtermStorageDuration), func(id []byte) bool { - swapIDsPost = append(swapIDsPost, id) - return false - }) - suite.Equal(len(swapIDsPost), 0) -} - -func (suite *KeeperTestSuite) TestIterateAtomicSwapsLongtermStorage() { - suite.ResetChain() - - // Set up atomic swaps with stagged closed blocks - var swaps types.AtomicSwaps - for i := 0; i < 8; i++ { - timestamp := tmtime.Now().Unix() - randomNumber, _ := types.GenerateSecureRandomNumber() - randomNumberHash := types.CalculateRandomHash(randomNumber[:], timestamp) - - atomicSwap := types.NewAtomicSwap(cs(c("bnb", 50000)), randomNumberHash, - uint64(suite.ctx.BlockHeight()), timestamp, TestUser1, TestUser2, - TestSenderOtherChain, TestRecipientOtherChain, 100, types.SWAP_STATUS_OPEN, - true, types.SWAP_DIRECTION_INCOMING) - - // Set closed block staggered by 100 blocks and insert into longterm storage - atomicSwap.ClosedBlock = int64(i) * 100 - suite.keeper.InsertIntoLongtermStorage(suite.ctx, atomicSwap) - // Add to local longterm storage - swaps = append(swaps, atomicSwap) - } - - // Set up the expected swap IDs for a given cutoff block. - cutoffBlock := int64(LongtermStorageDuration + 350) - var expectedSwapIDs [][]byte - for _, swap := range swaps { - if swap.ClosedBlock+LongtermStorageDuration < cutoffBlock || - swap.ClosedBlock+LongtermStorageDuration == cutoffBlock { - expectedSwapIDs = append(expectedSwapIDs, swap.GetSwapID()) - } - } - - // Read the swap IDs from store for a given cutoff block - var readSwapIDs [][]byte - suite.keeper.IterateAtomicSwapsLongtermStorage(suite.ctx, uint64(cutoffBlock), func(id []byte) bool { - readSwapIDs = append(readSwapIDs, id) - return false - }) - - // At the cutoff block, iteration should return half of the swap IDs - suite.Equal(len(swaps)/2, len(expectedSwapIDs)) - suite.Equal(len(swaps)/2, len(readSwapIDs)) - // Should be the same IDs - suite.Equal(expectedSwapIDs, readSwapIDs) -} - -func (suite *KeeperTestSuite) TestGetSetAssetSupply() { - denom := "bnb" - // Put asset supply in store - assetSupply := types.NewAssetSupply(c(denom, 0), c(denom, 0), c(denom, 50000), c(denom, 0), time.Duration(0)) - suite.keeper.SetAssetSupply(suite.ctx, assetSupply, denom) - - // Check asset in store - storedAssetSupply, found := suite.keeper.GetAssetSupply(suite.ctx, denom) - suite.True(found) - suite.Equal(assetSupply, storedAssetSupply) - - // Check fake asset supply not in store - fakeDenom := "xyz" - _, found = suite.keeper.GetAssetSupply(suite.ctx, fakeDenom) - suite.False(found) -} - -func (suite *KeeperTestSuite) TestGetAllAssetSupplies() { - // Put asset supply in store - assetSupply := types.NewAssetSupply(c("bnb", 0), c("bnb", 0), c("bnb", 50000), c("bnb", 0), time.Duration(0)) - suite.keeper.SetAssetSupply(suite.ctx, assetSupply, "bnb") - assetSupply = types.NewAssetSupply(c("inc", 0), c("inc", 0), c("inc", 50000), c("inc", 0), time.Duration(0)) - suite.keeper.SetAssetSupply(suite.ctx, assetSupply, "inc") - - supplies := suite.keeper.GetAllAssetSupplies(suite.ctx) - suite.Equal(2, len(supplies)) -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} diff --git a/x/bep3/keeper/msg_server.go b/x/bep3/keeper/msg_server.go deleted file mode 100644 index 3508ad79..00000000 --- a/x/bep3/keeper/msg_server.go +++ /dev/null @@ -1,117 +0,0 @@ -package keeper - -import ( - "context" - "encoding/hex" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/bep3/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the bep3 MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -func (k msgServer) CreateAtomicSwap(goCtx context.Context, msg *types.MsgCreateAtomicSwap) (*types.MsgCreateAtomicSwapResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - from, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - return nil, err - } - to, err := sdk.AccAddressFromBech32(msg.To) - if err != nil { - return nil, err - } - randomNumberHash, err := hex.DecodeString(msg.RandomNumberHash) - if err != nil { - return nil, err - } - - if err = k.keeper.CreateAtomicSwap(ctx, randomNumberHash, msg.Timestamp, msg.HeightSpan, - from, to, msg.SenderOtherChain, msg.RecipientOtherChain, msg.Amount, true); err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From), - ), - ) - - return &types.MsgCreateAtomicSwapResponse{}, nil -} - -func (k msgServer) ClaimAtomicSwap(goCtx context.Context, msg *types.MsgClaimAtomicSwap) (*types.MsgClaimAtomicSwapResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - from, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - return nil, err - } - - swapID, err := hex.DecodeString(msg.SwapID) - if err != nil { - return nil, err - } - - randomNumber, err := hex.DecodeString(msg.RandomNumber) - if err != nil { - return nil, err - } - - err = k.keeper.ClaimAtomicSwap(ctx, from, swapID, randomNumber) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From), - ), - ) - - return &types.MsgClaimAtomicSwapResponse{}, nil -} - -func (k msgServer) RefundAtomicSwap(goCtx context.Context, msg *types.MsgRefundAtomicSwap) (*types.MsgRefundAtomicSwapResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - from, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - return nil, err - } - - swapID, err := hex.DecodeString(msg.SwapID) - if err != nil { - return nil, err - } - - err = k.keeper.RefundAtomicSwap(ctx, from, swapID) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From), - ), - ) - - return &types.MsgRefundAtomicSwapResponse{}, nil -} diff --git a/x/bep3/keeper/msg_server_test.go b/x/bep3/keeper/msg_server_test.go deleted file mode 100644 index badad26c..00000000 --- a/x/bep3/keeper/msg_server_test.go +++ /dev/null @@ -1,129 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - tmbytes "github.com/cometbft/cometbft/libs/bytes" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/bep3" - "github.com/kava-labs/kava/x/bep3/keeper" - "github.com/kava-labs/kava/x/bep3/types" -) - -type MsgServerTestSuite struct { - suite.Suite - - ctx sdk.Context - app app.TestApp - msgServer types.MsgServer - keeper keeper.Keeper - addrs []sdk.AccAddress -} - -func (suite *MsgServerTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - cdc := tApp.AppCodec() - - // Set up genesis state and initialize - _, addrs := app.GeneratePrivKeyAddressPairs(3) - coins := sdk.NewCoins(c("bnb", 10000000000), c("ukava", 10000000000)) - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) - tApp.InitializeFromGenesisStates(authGS, NewBep3GenStateMulti(cdc, addrs[0])) - - suite.addrs = addrs - suite.keeper = tApp.GetBep3Keeper() - suite.msgServer = keeper.NewMsgServerImpl(suite.keeper) - suite.app = tApp - suite.ctx = ctx -} - -func (suite *MsgServerTestSuite) AddAtomicSwap() (tmbytes.HexBytes, tmbytes.HexBytes) { - expireHeight := types.DefaultMinBlockLock - amount := cs(c("bnb", int64(50000))) - timestamp := ts(0) - randomNumber, _ := types.GenerateSecureRandomNumber() - randomNumberHash := types.CalculateRandomHash(randomNumber[:], timestamp) - - // Create atomic swap and check err to confirm creation - err := suite.keeper.CreateAtomicSwap(suite.ctx, randomNumberHash, timestamp, expireHeight, - suite.addrs[0], suite.addrs[1], TestSenderOtherChain, TestRecipientOtherChain, - amount, true) - suite.Nil(err) - - swapID := types.CalculateSwapID(randomNumberHash, suite.addrs[0], TestSenderOtherChain) - return swapID, randomNumber[:] -} - -func (suite *MsgServerTestSuite) TestMsgCreateAtomicSwap() { - amount := cs(c("bnb", int64(10000))) - timestamp := ts(0) - randomNumber, _ := types.GenerateSecureRandomNumber() - randomNumberHash := types.CalculateRandomHash(randomNumber[:], timestamp) - - msg := types.NewMsgCreateAtomicSwap( - suite.addrs[0].String(), suite.addrs[2].String(), TestRecipientOtherChain, - TestSenderOtherChain, randomNumberHash, timestamp, amount, - types.DefaultMinBlockLock) - - res, err := suite.msgServer.CreateAtomicSwap(sdk.WrapSDKContext(suite.ctx), &msg) - suite.Require().NoError(err) - suite.Require().NotNil(res) -} - -func (suite *MsgServerTestSuite) TestMsgClaimAtomicSwap() { - // Attempt claim msg on fake atomic swap - badRandomNumber, _ := types.GenerateSecureRandomNumber() - badRandomNumberHash := types.CalculateRandomHash(badRandomNumber[:], ts(0)) - badSwapID := types.CalculateSwapID(badRandomNumberHash, suite.addrs[0], TestSenderOtherChain) - badMsg := types.NewMsgClaimAtomicSwap(suite.addrs[0].String(), badSwapID, badRandomNumber[:]) - badRes, err := suite.msgServer.ClaimAtomicSwap(sdk.WrapSDKContext(suite.ctx), &badMsg) - suite.Require().Error(err) - suite.Require().Nil(badRes) - - // Add an atomic swap before attempting new claim msg - swapID, randomNumber := suite.AddAtomicSwap() - msg := types.NewMsgClaimAtomicSwap(suite.addrs[0].String(), swapID, randomNumber) - res, err := suite.msgServer.ClaimAtomicSwap(sdk.WrapSDKContext(suite.ctx), &msg) - suite.Require().NoError(err) - suite.Require().NotNil(res) -} - -func (suite *MsgServerTestSuite) TestMsgRefundAtomicSwap() { - // Attempt refund msg on fake atomic swap - badRandomNumber, _ := types.GenerateSecureRandomNumber() - badRandomNumberHash := types.CalculateRandomHash(badRandomNumber[:], ts(0)) - badSwapID := types.CalculateSwapID(badRandomNumberHash, suite.addrs[0], TestSenderOtherChain) - badMsg := types.NewMsgRefundAtomicSwap(suite.addrs[0].String(), badSwapID) - badRes, err := suite.msgServer.RefundAtomicSwap(sdk.WrapSDKContext(suite.ctx), &badMsg) - suite.Require().Error(err) - suite.Require().Nil(badRes) - - // Add an atomic swap and build refund msg - swapID, _ := suite.AddAtomicSwap() - msg := types.NewMsgRefundAtomicSwap(suite.addrs[0].String(), swapID) - - // Attempt to refund active atomic swap - res1, err := suite.msgServer.RefundAtomicSwap(sdk.WrapSDKContext(suite.ctx), &msg) - suite.Require().Error(err) - suite.Require().Nil(res1) - - // Expire the atomic swap with begin blocker and attempt refund - laterCtx := suite.ctx.WithBlockHeight(suite.ctx.BlockHeight() + 400) - bep3.BeginBlocker(laterCtx, suite.keeper) - res2, err := suite.msgServer.RefundAtomicSwap(sdk.WrapSDKContext(laterCtx), &msg) - suite.Require().NoError(err) - suite.Require().NotNil(res2) -} - -func TestMsgServerTestSuite(t *testing.T) { - suite.Run(t, new(MsgServerTestSuite)) -} diff --git a/x/bep3/keeper/params.go b/x/bep3/keeper/params.go deleted file mode 100644 index 1635ad0d..00000000 --- a/x/bep3/keeper/params.go +++ /dev/null @@ -1,167 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/bep3/types" -) - -// GetParams returns the total set of bep3 parameters. -func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { - k.paramSubspace.GetParamSet(ctx, ¶ms) - return params -} - -// SetParams sets the bep3 parameters to the param space. -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} - -// ------------------------------------------ -// Asset -// ------------------------------------------ - -// GetAsset returns the asset param associated with the input denom -func (k Keeper) GetAsset(ctx sdk.Context, denom string) (types.AssetParam, error) { - params := k.GetParams(ctx) - for _, asset := range params.AssetParams { - if denom == asset.Denom { - return asset, nil - } - } - return types.AssetParam{}, errorsmod.Wrap(types.ErrAssetNotSupported, denom) -} - -// SetAsset sets an asset in the params -func (k Keeper) SetAsset(ctx sdk.Context, asset types.AssetParam) { - params := k.GetParams(ctx) - for i := range params.AssetParams { - if params.AssetParams[i].Denom == asset.Denom { - params.AssetParams[i] = asset - } - } - k.SetParams(ctx, params) -} - -// GetAssets returns a list containing all supported assets -func (k Keeper) GetAssets(ctx sdk.Context) (types.AssetParams, bool) { - params := k.GetParams(ctx) - return params.AssetParams, len(params.AssetParams) > 0 -} - -// ------------------------------------------ -// Asset-specific getters -// ------------------------------------------ - -// GetDeputyAddress returns the deputy address for the input denom -func (k Keeper) GetDeputyAddress(ctx sdk.Context, denom string) (sdk.AccAddress, error) { - asset, err := k.GetAsset(ctx, denom) - if err != nil { - return sdk.AccAddress{}, err - } - return asset.DeputyAddress, nil -} - -// GetFixedFee returns the fixed fee for incoming swaps -func (k Keeper) GetFixedFee(ctx sdk.Context, denom string) (sdkmath.Int, error) { - asset, err := k.GetAsset(ctx, denom) - if err != nil { - return sdkmath.Int{}, err - } - return asset.FixedFee, nil -} - -// GetMinSwapAmount returns the minimum swap amount -func (k Keeper) GetMinSwapAmount(ctx sdk.Context, denom string) (sdkmath.Int, error) { - asset, err := k.GetAsset(ctx, denom) - if err != nil { - return sdkmath.Int{}, err - } - return asset.MinSwapAmount, nil -} - -// GetMaxSwapAmount returns the maximum swap amount -func (k Keeper) GetMaxSwapAmount(ctx sdk.Context, denom string) (sdkmath.Int, error) { - asset, err := k.GetAsset(ctx, denom) - if err != nil { - return sdkmath.Int{}, err - } - return asset.MaxSwapAmount, nil -} - -// GetMinBlockLock returns the minimum block lock -func (k Keeper) GetMinBlockLock(ctx sdk.Context, denom string) (uint64, error) { - asset, err := k.GetAsset(ctx, denom) - if err != nil { - return uint64(0), err - } - return asset.MinBlockLock, nil -} - -// GetMaxBlockLock returns the maximum block lock -func (k Keeper) GetMaxBlockLock(ctx sdk.Context, denom string) (uint64, error) { - asset, err := k.GetAsset(ctx, denom) - if err != nil { - return uint64(0), err - } - return asset.MaxBlockLock, nil -} - -// GetAssetByCoinID returns an asset by its denom -func (k Keeper) GetAssetByCoinID(ctx sdk.Context, coinID int64) (types.AssetParam, bool) { - params := k.GetParams(ctx) - for _, asset := range params.AssetParams { - if asset.CoinID == coinID { - return asset, true - } - } - return types.AssetParam{}, false -} - -// ValidateLiveAsset checks if an asset is both supported and active -func (k Keeper) ValidateLiveAsset(ctx sdk.Context, coin sdk.Coin) error { - asset, err := k.GetAsset(ctx, coin.Denom) - if err != nil { - return err - } - if !asset.Active { - return errorsmod.Wrap(types.ErrAssetNotActive, asset.Denom) - } - return nil -} - -// GetSupplyLimit returns the supply limit for the input denom -func (k Keeper) GetSupplyLimit(ctx sdk.Context, denom string) (types.SupplyLimit, error) { - asset, err := k.GetAsset(ctx, denom) - if err != nil { - return types.SupplyLimit{}, err - } - return asset.SupplyLimit, nil -} - -// ------------------------------------------ -// Cross Asset Getters -// ------------------------------------------ - -// GetAuthorizedAddresses returns a list of addresses that have special authorization within this module, eg all the deputies. -func (k Keeper) GetAuthorizedAddresses(ctx sdk.Context) []sdk.AccAddress { - assetParams, found := k.GetAssets(ctx) - if !found { - // no assets params is a valid genesis state - return nil - } - var addresses []sdk.AccAddress - uniqueAddresses := map[string]bool{} - - for _, ap := range assetParams { - a := ap.DeputyAddress - // de-dup addresses - if _, found := uniqueAddresses[a.String()]; !found { - addresses = append(addresses, a) - } - uniqueAddresses[a.String()] = true - } - return addresses -} diff --git a/x/bep3/keeper/params_test.go b/x/bep3/keeper/params_test.go deleted file mode 100644 index 0f339d44..00000000 --- a/x/bep3/keeper/params_test.go +++ /dev/null @@ -1,178 +0,0 @@ -package keeper_test - -import ( - "errors" - "testing" - - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/bep3/keeper" - "github.com/kava-labs/kava/x/bep3/types" -) - -type ParamsTestSuite struct { - suite.Suite - - keeper keeper.Keeper - addrs []sdk.AccAddress - ctx sdk.Context -} - -func (suite *ParamsTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - _, addrs := app.GeneratePrivKeyAddressPairs(10) - tApp.InitializeFromGenesisStates(NewBep3GenStateMulti(tApp.AppCodec(), addrs[0])) - suite.keeper = tApp.GetBep3Keeper() - suite.ctx = ctx - suite.addrs = addrs -} - -func (suite *ParamsTestSuite) TestGetSetAsset() { - asset, err := suite.keeper.GetAsset(suite.ctx, "bnb") - suite.Require().NoError(err) - suite.NotPanics(func() { suite.keeper.SetAsset(suite.ctx, asset) }) - _, err = suite.keeper.GetAsset(suite.ctx, "dne") - suite.Require().Error(err) - - _, err = suite.keeper.GetAsset(suite.ctx, "inc") - suite.Require().NoError(err) -} - -func (suite *ParamsTestSuite) TestGetAssets() { - assets, found := suite.keeper.GetAssets(suite.ctx) - suite.Require().True(found) - suite.Require().Equal(2, len(assets)) -} - -func (suite *ParamsTestSuite) TestGetSetDeputyAddress() { - asset, err := suite.keeper.GetAsset(suite.ctx, "bnb") - suite.Require().NoError(err) - asset.DeputyAddress = suite.addrs[1] - suite.NotPanics(func() { suite.keeper.SetAsset(suite.ctx, asset) }) - - asset, err = suite.keeper.GetAsset(suite.ctx, "bnb") - suite.Require().NoError(err) - suite.Equal(suite.addrs[1], asset.DeputyAddress) - addr, err := suite.keeper.GetDeputyAddress(suite.ctx, "bnb") - suite.Require().NoError(err) - suite.Equal(suite.addrs[1], addr) -} - -func (suite *ParamsTestSuite) TestGetDeputyFixedFee() { - asset, err := suite.keeper.GetAsset(suite.ctx, "bnb") - suite.Require().NoError(err) - bnbDeputyFixedFee := asset.FixedFee - - res, err := suite.keeper.GetFixedFee(suite.ctx, asset.Denom) - suite.Require().NoError(err) - suite.Equal(bnbDeputyFixedFee, res) -} - -func (suite *ParamsTestSuite) TestGetMinMaxSwapAmount() { - asset, err := suite.keeper.GetAsset(suite.ctx, "bnb") - suite.Require().NoError(err) - minAmount := asset.MinSwapAmount - - res, err := suite.keeper.GetMinSwapAmount(suite.ctx, asset.Denom) - suite.Require().NoError(err) - suite.Equal(minAmount, res) - - maxAmount := asset.MaxSwapAmount - res, err = suite.keeper.GetMaxSwapAmount(suite.ctx, asset.Denom) - suite.Require().NoError(err) - suite.Equal(maxAmount, res) -} - -func (suite *ParamsTestSuite) TestGetMinMaxBlockLock() { - asset, err := suite.keeper.GetAsset(suite.ctx, "bnb") - suite.Require().NoError(err) - minLock := asset.MinBlockLock - - res, err := suite.keeper.GetMinBlockLock(suite.ctx, asset.Denom) - suite.Require().NoError(err) - suite.Equal(minLock, res) - - maxLock := asset.MaxBlockLock - res, err = suite.keeper.GetMaxBlockLock(suite.ctx, asset.Denom) - suite.Require().NoError(err) - suite.Equal(maxLock, res) -} - -func (suite *ParamsTestSuite) TestGetAssetByCoinID() { - asset, err := suite.keeper.GetAsset(suite.ctx, "bnb") - suite.Require().NoError(err) - - res, found := suite.keeper.GetAssetByCoinID(suite.ctx, asset.CoinID) - suite.True(found) - suite.Equal(asset, res) -} - -func (suite *ParamsTestSuite) TestGetAuthorizedAddresses() { - deputyAddresses := suite.keeper.GetAuthorizedAddresses(suite.ctx) - // the test params use the same deputy address for two assets - expectedAddresses := []sdk.AccAddress{suite.addrs[0]} - - suite.Require().ElementsMatch(expectedAddresses, deputyAddresses) -} - -func (suite *AssetTestSuite) TestValidateLiveAsset() { - type args struct { - coin sdk.Coin - } - testCases := []struct { - name string - args args - expectedError error - expectPass bool - }{ - { - "normal", - args{ - coin: c("bnb", 1), - }, - nil, - true, - }, - { - "asset not supported", - args{ - coin: c("bad", 1), - }, - types.ErrAssetNotSupported, - false, - }, - { - "asset not active", - args{ - coin: c("inc", 1), - }, - types.ErrAssetNotActive, - false, - }, - } - - for _, tc := range testCases { - suite.SetupTest() - suite.Run(tc.name, func() { - err := suite.keeper.ValidateLiveAsset(suite.ctx, tc.args.coin) - - if tc.expectPass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Require().True(errors.Is(err, tc.expectedError)) - } - }) - } -} - -func TestParamsTestSuite(t *testing.T) { - suite.Run(t, new(ParamsTestSuite)) -} diff --git a/x/bep3/keeper/swap.go b/x/bep3/keeper/swap.go deleted file mode 100644 index bf3df193..00000000 --- a/x/bep3/keeper/swap.go +++ /dev/null @@ -1,309 +0,0 @@ -package keeper - -import ( - "bytes" - "encoding/hex" - "fmt" - "time" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/kava-labs/kava/x/bep3/types" -) - -// CreateAtomicSwap creates a new atomic swap. -func (k Keeper) CreateAtomicSwap(ctx sdk.Context, randomNumberHash []byte, timestamp int64, heightSpan uint64, - sender, recipient sdk.AccAddress, senderOtherChain, recipientOtherChain string, - amount sdk.Coins, crossChain bool, -) error { - // Confirm that this is not a duplicate swap - swapID := types.CalculateSwapID(randomNumberHash, sender, senderOtherChain) - _, found := k.GetAtomicSwap(ctx, swapID) - if found { - return errorsmod.Wrap(types.ErrAtomicSwapAlreadyExists, hex.EncodeToString(swapID)) - } - - // Cannot send coins to a module account - if k.Maccs[recipient.String()] { - return errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "%s is a module account", recipient) - } - - if len(amount) != 1 { - return fmt.Errorf("amount must contain exactly one coin") - } - asset, err := k.GetAsset(ctx, amount[0].Denom) - if err != nil { - return err - } - - err = k.ValidateLiveAsset(ctx, amount[0]) - if err != nil { - return err - } - - // Swap amount must be within the specified swap amount limits - if amount[0].Amount.LT(asset.MinSwapAmount) || amount[0].Amount.GT(asset.MaxSwapAmount) { - return errorsmod.Wrapf(types.ErrInvalidAmount, "amount %d outside range [%s, %s]", amount[0].Amount, asset.MinSwapAmount, asset.MaxSwapAmount) - } - - // Unix timestamp must be in range [-15 mins, 30 mins] of the current time - pastTimestampLimit := ctx.BlockTime().Add(time.Duration(-15) * time.Minute).Unix() - futureTimestampLimit := ctx.BlockTime().Add(time.Duration(30) * time.Minute).Unix() - if timestamp < pastTimestampLimit || timestamp >= futureTimestampLimit { - return errorsmod.Wrap(types.ErrInvalidTimestamp, fmt.Sprintf("block time: %s, timestamp: %s", ctx.BlockTime().String(), time.Unix(timestamp, 0).UTC().String())) - } - - var direction types.SwapDirection - if sender.Equals(asset.DeputyAddress) { - if recipient.Equals(asset.DeputyAddress) { - return errorsmod.Wrapf(types.ErrInvalidSwapAccount, "deputy cannot be both sender and receiver: %s", asset.DeputyAddress) - } - direction = types.SWAP_DIRECTION_INCOMING - } else { - if !recipient.Equals(asset.DeputyAddress) { - return errorsmod.Wrapf(types.ErrInvalidSwapAccount, "deputy must be recipient for outgoing account: %s", recipient) - } - direction = types.SWAP_DIRECTION_OUTGOING - } - - switch direction { - case types.SWAP_DIRECTION_INCOMING: - // If recipient's account doesn't exist, register it in state so that the address can send - // a claim swap tx without needing to be registered in state by receiving a coin transfer. - recipientAcc := k.accountKeeper.GetAccount(ctx, recipient) - if recipientAcc == nil { - newAcc := k.accountKeeper.NewAccountWithAddress(ctx, recipient) - k.accountKeeper.SetAccount(ctx, newAcc) - } - // Incoming swaps have already had their fees collected by the deputy during the relay process. - err = k.IncrementIncomingAssetSupply(ctx, amount[0]) - case types.SWAP_DIRECTION_OUTGOING: - - // Outgoing swaps must have a height span within the accepted range - if heightSpan < asset.MinBlockLock || heightSpan > asset.MaxBlockLock { - return errorsmod.Wrapf(types.ErrInvalidHeightSpan, "height span %d outside range [%d, %d]", heightSpan, asset.MinBlockLock, asset.MaxBlockLock) - } - // Amount in outgoing swaps must be able to pay the deputy's fixed fee. - if amount[0].Amount.LTE(asset.FixedFee.Add(asset.MinSwapAmount)) { - return errorsmod.Wrap(types.ErrInsufficientAmount, amount[0].String()) - } - err = k.IncrementOutgoingAssetSupply(ctx, amount[0]) - if err != nil { - return err - } - // Transfer coins to module - only needed for outgoing swaps - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleName, amount) - default: - err = fmt.Errorf("invalid swap direction: %s", direction.String()) - } - if err != nil { - return err - } - - // Store the details of the swap - expireHeight := uint64(ctx.BlockHeight()) + heightSpan - atomicSwap := types.NewAtomicSwap(amount, randomNumberHash, expireHeight, timestamp, sender, - recipient, senderOtherChain, recipientOtherChain, 0, types.SWAP_STATUS_OPEN, crossChain, direction) - - // Insert the atomic swap under both keys - k.SetAtomicSwap(ctx, atomicSwap) - k.InsertIntoByBlockIndex(ctx, atomicSwap) - - // Emit 'create_atomic_swap' event - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCreateAtomicSwap, - sdk.NewAttribute(types.AttributeKeySender, atomicSwap.Sender.String()), - sdk.NewAttribute(types.AttributeKeyRecipient, atomicSwap.Recipient.String()), - sdk.NewAttribute(types.AttributeKeyAtomicSwapID, hex.EncodeToString(atomicSwap.GetSwapID())), - sdk.NewAttribute(types.AttributeKeyRandomNumberHash, hex.EncodeToString(atomicSwap.RandomNumberHash)), - sdk.NewAttribute(types.AttributeKeyTimestamp, fmt.Sprintf("%d", atomicSwap.Timestamp)), - sdk.NewAttribute(types.AttributeKeySenderOtherChain, atomicSwap.SenderOtherChain), - sdk.NewAttribute(types.AttributeKeyExpireHeight, fmt.Sprintf("%d", atomicSwap.ExpireHeight)), - sdk.NewAttribute(types.AttributeKeyAmount, atomicSwap.Amount.String()), - sdk.NewAttribute(types.AttributeKeyDirection, atomicSwap.Direction.String()), - ), - ) - - return nil -} - -// ClaimAtomicSwap validates a claim attempt, and if successful, sends the escrowed amount and closes the AtomicSwap. -func (k Keeper) ClaimAtomicSwap(ctx sdk.Context, from sdk.AccAddress, swapID []byte, randomNumber []byte) error { - atomicSwap, found := k.GetAtomicSwap(ctx, swapID) - if !found { - return errorsmod.Wrapf(types.ErrAtomicSwapNotFound, "%s", swapID) - } - - // Only open atomic swaps can be claimed - if atomicSwap.Status != types.SWAP_STATUS_OPEN { - return errorsmod.Wrapf(types.ErrSwapNotClaimable, "status %s", atomicSwap.Status.String()) - } - - // Calculate hashed secret using submitted number - hashedSubmittedNumber := types.CalculateRandomHash(randomNumber, atomicSwap.Timestamp) - hashedSecret := types.CalculateSwapID(hashedSubmittedNumber, atomicSwap.Sender, atomicSwap.SenderOtherChain) - - // Confirm that secret unlocks the atomic swap - if !bytes.Equal(hashedSecret, atomicSwap.GetSwapID()) { - return errorsmod.Wrapf(types.ErrInvalidClaimSecret, "the submitted random number is incorrect") - } - - var err error - switch atomicSwap.Direction { - case types.SWAP_DIRECTION_INCOMING: - err = k.DecrementIncomingAssetSupply(ctx, atomicSwap.Amount[0]) - if err != nil { - return err - } - err = k.IncrementCurrentAssetSupply(ctx, atomicSwap.Amount[0]) - if err != nil { - return err - } - // incoming case - coins should be MINTED, then sent to user - err = k.bankKeeper.MintCoins(ctx, types.ModuleName, atomicSwap.Amount) - if err != nil { - return err - } - // Send intended recipient coins - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, atomicSwap.Recipient, atomicSwap.Amount) - if err != nil { - return err - } - case types.SWAP_DIRECTION_OUTGOING: - err = k.DecrementOutgoingAssetSupply(ctx, atomicSwap.Amount[0]) - if err != nil { - return err - } - err = k.DecrementCurrentAssetSupply(ctx, atomicSwap.Amount[0]) - if err != nil { - return err - } - // outgoing case - coins should be burned - err = k.bankKeeper.BurnCoins(ctx, types.ModuleName, atomicSwap.Amount) - if err != nil { - return err - } - default: - return fmt.Errorf("invalid swap direction: %s", atomicSwap.Direction.String()) - } - - // Complete swap - atomicSwap.Status = types.SWAP_STATUS_COMPLETED - atomicSwap.ClosedBlock = ctx.BlockHeight() - k.SetAtomicSwap(ctx, atomicSwap) - - // Remove from byBlock index and transition to longterm storage - k.RemoveFromByBlockIndex(ctx, atomicSwap) - k.InsertIntoLongtermStorage(ctx, atomicSwap) - - // Emit 'claim_atomic_swap' event - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeClaimAtomicSwap, - sdk.NewAttribute(types.AttributeKeyClaimSender, from.String()), - sdk.NewAttribute(types.AttributeKeyRecipient, atomicSwap.Recipient.String()), - sdk.NewAttribute(types.AttributeKeyAtomicSwapID, hex.EncodeToString(atomicSwap.GetSwapID())), - sdk.NewAttribute(types.AttributeKeyRandomNumberHash, hex.EncodeToString(atomicSwap.RandomNumberHash)), - sdk.NewAttribute(types.AttributeKeyRandomNumber, hex.EncodeToString(randomNumber)), - ), - ) - - return nil -} - -// RefundAtomicSwap refunds an AtomicSwap, sending assets to the original sender and closing the AtomicSwap. -func (k Keeper) RefundAtomicSwap(ctx sdk.Context, from sdk.AccAddress, swapID []byte) error { - atomicSwap, found := k.GetAtomicSwap(ctx, swapID) - if !found { - return errorsmod.Wrapf(types.ErrAtomicSwapNotFound, "%s", swapID) - } - // Only expired swaps may be refunded - if atomicSwap.Status != types.SWAP_STATUS_EXPIRED { - return errorsmod.Wrapf(types.ErrSwapNotRefundable, "status %s", atomicSwap.Status.String()) - } - - var err error - switch atomicSwap.Direction { - case types.SWAP_DIRECTION_INCOMING: - err = k.DecrementIncomingAssetSupply(ctx, atomicSwap.Amount[0]) - case types.SWAP_DIRECTION_OUTGOING: - err = k.DecrementOutgoingAssetSupply(ctx, atomicSwap.Amount[0]) - if err != nil { - return err - } - // Refund coins to original swap sender for outgoing swaps - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, atomicSwap.Sender, atomicSwap.Amount) - default: - err = fmt.Errorf("invalid swap direction: %s", atomicSwap.Direction.String()) - } - - if err != nil { - return err - } - - // Complete swap - atomicSwap.Status = types.SWAP_STATUS_COMPLETED - atomicSwap.ClosedBlock = ctx.BlockHeight() - k.SetAtomicSwap(ctx, atomicSwap) - - // Transition to longterm storage - k.InsertIntoLongtermStorage(ctx, atomicSwap) - - // Emit 'refund_atomic_swap' event - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeRefundAtomicSwap, - sdk.NewAttribute(types.AttributeKeyRefundSender, from.String()), - sdk.NewAttribute(types.AttributeKeySender, atomicSwap.Sender.String()), - sdk.NewAttribute(types.AttributeKeyAtomicSwapID, hex.EncodeToString(atomicSwap.GetSwapID())), - sdk.NewAttribute(types.AttributeKeyRandomNumberHash, hex.EncodeToString(atomicSwap.RandomNumberHash)), - ), - ) - - return nil -} - -// UpdateExpiredAtomicSwaps finds all AtomicSwaps that are past (or at) their ending times and expires them. -func (k Keeper) UpdateExpiredAtomicSwaps(ctx sdk.Context) { - var expiredSwapIDs []string - k.IterateAtomicSwapsByBlock(ctx, uint64(ctx.BlockHeight()), func(id []byte) bool { - atomicSwap, found := k.GetAtomicSwap(ctx, id) - if !found { - // NOTE: shouldn't happen. Continue to next item. - return false - } - // Expire the uncompleted swap and update both indexes - atomicSwap.Status = types.SWAP_STATUS_EXPIRED - // Note: claimed swaps have already been removed from byBlock index. - k.RemoveFromByBlockIndex(ctx, atomicSwap) - k.SetAtomicSwap(ctx, atomicSwap) - expiredSwapIDs = append(expiredSwapIDs, hex.EncodeToString(atomicSwap.GetSwapID())) - return false - }) - - // Emit 'swaps_expired' event - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeSwapsExpired, - sdk.NewAttribute(types.AttributeKeyAtomicSwapIDs, fmt.Sprintf("%s", expiredSwapIDs)), - sdk.NewAttribute(types.AttributeExpirationBlock, fmt.Sprintf("%d", ctx.BlockHeight())), - ), - ) -} - -// DeleteClosedAtomicSwapsFromLongtermStorage removes swaps one week after completion. -func (k Keeper) DeleteClosedAtomicSwapsFromLongtermStorage(ctx sdk.Context) { - k.IterateAtomicSwapsLongtermStorage(ctx, uint64(ctx.BlockHeight()), func(id []byte) bool { - swap, found := k.GetAtomicSwap(ctx, id) - if !found { - // NOTE: shouldn't happen. Continue to next item. - return false - } - k.RemoveAtomicSwap(ctx, swap.GetSwapID()) - k.RemoveFromLongtermStorage(ctx, swap) - return false - }) -} diff --git a/x/bep3/keeper/swap_test.go b/x/bep3/keeper/swap_test.go deleted file mode 100644 index 056a5147..00000000 --- a/x/bep3/keeper/swap_test.go +++ /dev/null @@ -1,829 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - tmbytes "github.com/cometbft/cometbft/libs/bytes" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/bep3" - "github.com/kava-labs/kava/x/bep3/keeper" - "github.com/kava-labs/kava/x/bep3/types" -) - -type AtomicSwapTestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context - randMacc sdk.AccAddress - deputy sdk.AccAddress - addrs []sdk.AccAddress - timestamps []int64 - randomNumberHashes []tmbytes.HexBytes - randomNumbers []tmbytes.HexBytes -} - -const ( - STARING_BNB_BALANCE = int64(3000000000000) - BNB_DENOM = "bnb" - OTHER_DENOM = "inc" - STARING_OTHER_BALANCE = int64(3000000000000) -) - -func (suite *AtomicSwapTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - cdc := tApp.AppCodec() - - // Create and load 20 accounts with bnb tokens - coins := sdk.NewCoins(c(BNB_DENOM, STARING_BNB_BALANCE), c(OTHER_DENOM, STARING_OTHER_BALANCE)) - _, addrs := app.GeneratePrivKeyAddressPairs(20) - deputy := addrs[0] - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) - - // Initialize genesis state - tApp.InitializeFromGenesisStates(authGS, NewBep3GenStateMulti(cdc, deputy)) - - keeper := tApp.GetBep3Keeper() - params := keeper.GetParams(ctx) - params.AssetParams[1].Active = true - keeper.SetParams(ctx, params) - - suite.app = tApp - suite.ctx = ctx - suite.deputy = deputy - suite.addrs = addrs - suite.keeper = keeper - - // Load a random module account to test blacklisting - i := 0 - var randModuleAcc sdk.AccAddress - for macc := range suite.keeper.Maccs { - if i == len(suite.keeper.Maccs)/2 { - acc, err := sdk.AccAddressFromBech32(macc) - suite.Nil(err) - randModuleAcc = acc - } - i = i + 1 - } - suite.randMacc = randModuleAcc - - suite.GenerateSwapDetails() -} - -func (suite *AtomicSwapTestSuite) GenerateSwapDetails() { - var timestamps []int64 - var randomNumberHashes []tmbytes.HexBytes - var randomNumbers []tmbytes.HexBytes - for i := 0; i < 15; i++ { - // Set up atomic swap details - timestamp := ts(i) - randomNumber, _ := types.GenerateSecureRandomNumber() - randomNumberHash := types.CalculateRandomHash(randomNumber[:], timestamp) - - timestamps = append(timestamps, timestamp) - randomNumberHashes = append(randomNumberHashes, randomNumberHash) - randomNumbers = append(randomNumbers, randomNumber[:]) - } - suite.timestamps = timestamps - suite.randomNumberHashes = randomNumberHashes - suite.randomNumbers = randomNumbers -} - -func (suite *AtomicSwapTestSuite) TestCreateAtomicSwap() { - currentTmTime := tmtime.Now() - type args struct { - randomNumberHash []byte - timestamp int64 - heightSpan uint64 - sender sdk.AccAddress - recipient sdk.AccAddress - senderOtherChain string - recipientOtherChain string - coins sdk.Coins - crossChain bool - direction types.SwapDirection - } - testCases := []struct { - name string - blockTime time.Time - args args - expectPass bool - shouldBeFound bool - }{ - { - "incoming swap", - currentTmTime, - args{ - randomNumberHash: suite.randomNumberHashes[0], - timestamp: suite.timestamps[0], - heightSpan: types.DefaultMinBlockLock, - sender: suite.deputy, - recipient: suite.addrs[1], - senderOtherChain: TestSenderOtherChain, - recipientOtherChain: TestRecipientOtherChain, - coins: cs(c(BNB_DENOM, 50000)), - crossChain: true, - direction: types.SWAP_DIRECTION_INCOMING, - }, - true, - true, - }, - { - "incoming swap rate limited", - currentTmTime.Add(time.Minute * 10), - args{ - randomNumberHash: suite.randomNumberHashes[12], - timestamp: suite.timestamps[12], - heightSpan: types.DefaultMinBlockLock, - sender: suite.deputy, - recipient: suite.addrs[1], - senderOtherChain: TestSenderOtherChain, - recipientOtherChain: TestRecipientOtherChain, - coins: cs(c("inc", 50000000000)), - crossChain: true, - direction: types.SWAP_DIRECTION_INCOMING, - }, - true, - true, - }, - { - "incoming swap over rate limit", - currentTmTime.Add(time.Minute * 10), - args{ - randomNumberHash: suite.randomNumberHashes[13], - timestamp: suite.timestamps[13], - heightSpan: types.DefaultMinBlockLock, - sender: suite.deputy, - recipient: suite.addrs[1], - senderOtherChain: TestSenderOtherChain, - recipientOtherChain: TestRecipientOtherChain, - coins: cs(c("inc", 50000000001)), - crossChain: true, - direction: types.SWAP_DIRECTION_INCOMING, - }, - false, - false, - }, - { - "outgoing swap", - currentTmTime, - args{ - randomNumberHash: suite.randomNumberHashes[0], - timestamp: suite.timestamps[0], - heightSpan: types.DefaultMinBlockLock, - sender: suite.addrs[1], - recipient: suite.deputy, - senderOtherChain: TestSenderOtherChain, - recipientOtherChain: TestRecipientOtherChain, - coins: cs(c(BNB_DENOM, 50000)), - crossChain: true, - direction: types.SWAP_DIRECTION_OUTGOING, - }, - true, - true, - }, - { - "outgoing swap amount not greater than fixed fee", - currentTmTime, - args{ - randomNumberHash: suite.randomNumberHashes[1], - timestamp: suite.timestamps[1], - heightSpan: types.DefaultMinBlockLock, - sender: suite.addrs[1], - recipient: suite.addrs[2], - senderOtherChain: TestSenderOtherChain, - recipientOtherChain: TestRecipientOtherChain, - coins: cs(c(BNB_DENOM, 1000)), - crossChain: true, - direction: types.SWAP_DIRECTION_OUTGOING, - }, - false, - false, - }, - { - "unsupported asset", - currentTmTime, - args{ - randomNumberHash: suite.randomNumberHashes[2], - timestamp: suite.timestamps[2], - heightSpan: types.DefaultMinBlockLock, - sender: suite.deputy, - recipient: suite.addrs[2], - senderOtherChain: TestSenderOtherChain, - recipientOtherChain: TestRecipientOtherChain, - coins: cs(c("xyz", 50000)), - crossChain: true, - direction: types.SWAP_DIRECTION_INCOMING, - }, - false, - false, - }, - { - "outside timestamp range", - currentTmTime, - args{ - randomNumberHash: suite.randomNumberHashes[3], - timestamp: suite.timestamps[3] - 2000, - heightSpan: types.DefaultMinBlockLock, - sender: suite.deputy, - recipient: suite.addrs[3], - senderOtherChain: TestSenderOtherChain, - recipientOtherChain: TestRecipientOtherChain, - coins: cs(c(BNB_DENOM, 50000)), - crossChain: true, - direction: types.SWAP_DIRECTION_INCOMING, - }, - false, - false, - }, - { - "future timestamp", - currentTmTime, - args{ - randomNumberHash: suite.randomNumberHashes[4], - timestamp: suite.timestamps[4] + 5000, - heightSpan: types.DefaultMinBlockLock, - sender: suite.deputy, - recipient: suite.addrs[4], - senderOtherChain: TestSenderOtherChain, - recipientOtherChain: TestRecipientOtherChain, - coins: cs(c(BNB_DENOM, 50000)), - crossChain: true, - direction: types.SWAP_DIRECTION_INCOMING, - }, - false, - false, - }, - { - "small height span on outgoing swap", - currentTmTime, - args{ - randomNumberHash: suite.randomNumberHashes[5], - timestamp: suite.timestamps[5], - heightSpan: uint64(100), - sender: suite.addrs[5], - recipient: suite.deputy, - senderOtherChain: TestSenderOtherChain, - recipientOtherChain: TestRecipientOtherChain, - coins: cs(c(BNB_DENOM, 50000)), - crossChain: true, - direction: types.SWAP_DIRECTION_OUTGOING, - }, - false, - false, - }, - { - "big height span on outgoing swap", - currentTmTime, - args{ - randomNumberHash: suite.randomNumberHashes[6], - timestamp: suite.timestamps[6], - heightSpan: uint64(300), - sender: suite.addrs[6], - recipient: suite.deputy, - senderOtherChain: TestSenderOtherChain, - recipientOtherChain: TestRecipientOtherChain, - coins: cs(c(BNB_DENOM, 50000)), - crossChain: true, - direction: types.SWAP_DIRECTION_OUTGOING, - }, - false, - false, - }, - { - "zero amount", - currentTmTime, - args{ - randomNumberHash: suite.randomNumberHashes[7], - timestamp: suite.timestamps[7], - heightSpan: types.DefaultMinBlockLock, - sender: suite.deputy, - recipient: suite.addrs[7], - senderOtherChain: TestSenderOtherChain, - recipientOtherChain: TestRecipientOtherChain, - coins: cs(c(BNB_DENOM, 0)), - crossChain: true, - direction: types.SWAP_DIRECTION_INCOMING, - }, - false, - false, - }, - { - "duplicate swap", - currentTmTime, - args{ - randomNumberHash: suite.randomNumberHashes[0], - timestamp: suite.timestamps[0], - heightSpan: types.DefaultMinBlockLock, - sender: suite.deputy, - recipient: suite.addrs[1], - senderOtherChain: TestSenderOtherChain, - recipientOtherChain: TestRecipientOtherChain, - coins: cs(c(BNB_DENOM, 50000)), - crossChain: true, - direction: types.SWAP_DIRECTION_INCOMING, - }, - false, - true, - }, - { - "recipient is module account", - currentTmTime, - args{ - randomNumberHash: suite.randomNumberHashes[8], - timestamp: suite.timestamps[8], - heightSpan: types.DefaultMinBlockLock, - sender: suite.deputy, - recipient: suite.randMacc, - senderOtherChain: TestSenderOtherChain, - recipientOtherChain: TestRecipientOtherChain, - coins: cs(c(BNB_DENOM, 5000)), - crossChain: true, - direction: types.SWAP_DIRECTION_INCOMING, - }, - false, - false, - }, - { - "exactly at maximum amount", - currentTmTime, - args{ - randomNumberHash: suite.randomNumberHashes[10], - timestamp: suite.timestamps[10], - heightSpan: types.DefaultMinBlockLock, - sender: suite.deputy, - recipient: suite.addrs[4], - senderOtherChain: TestSenderOtherChain, - recipientOtherChain: TestRecipientOtherChain, - coins: cs(c(BNB_DENOM, 1000000000000)), // 10,000 BNB - crossChain: true, - direction: types.SWAP_DIRECTION_INCOMING, - }, - true, - true, - }, - { - "above maximum amount", - currentTmTime, - args{ - randomNumberHash: suite.randomNumberHashes[11], - timestamp: suite.timestamps[11], - heightSpan: types.DefaultMinBlockLock, - sender: suite.deputy, - recipient: suite.addrs[5], - senderOtherChain: TestSenderOtherChain, - recipientOtherChain: TestRecipientOtherChain, - coins: cs(c(BNB_DENOM, 1000000000001)), // 10,001 BNB - crossChain: true, - direction: types.SWAP_DIRECTION_INCOMING, - }, - false, - false, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Increment current asset supply to support outgoing swaps - suite.ctx = suite.ctx.WithBlockTime(tc.blockTime) - if tc.args.direction == types.SWAP_DIRECTION_OUTGOING { - err := suite.keeper.IncrementCurrentAssetSupply(suite.ctx, tc.args.coins[0]) - suite.Nil(err) - } - - // Load asset denom (required for zero coins test case) - var swapAssetDenom string - if len(tc.args.coins) == 1 { - swapAssetDenom = tc.args.coins[0].Denom - } else { - swapAssetDenom = BNB_DENOM - } - - // Load sender's account prior to swap creation - bk := suite.app.GetBankKeeper() - - senderBalancePre := bk.GetBalance(suite.ctx, tc.args.sender, swapAssetDenom) - assetSupplyPre, _ := suite.keeper.GetAssetSupply(suite.ctx, swapAssetDenom) - - // Create atomic swap - err := suite.keeper.CreateAtomicSwap(suite.ctx, tc.args.randomNumberHash, tc.args.timestamp, - tc.args.heightSpan, tc.args.sender, tc.args.recipient, tc.args.senderOtherChain, - tc.args.recipientOtherChain, tc.args.coins, tc.args.crossChain) - - // Load sender's account after swap creation - senderBalancePost := bk.GetBalance(suite.ctx, tc.args.sender, swapAssetDenom) - assetSupplyPost, _ := suite.keeper.GetAssetSupply(suite.ctx, swapAssetDenom) - - // Load expected swap ID - expectedSwapID := types.CalculateSwapID(tc.args.randomNumberHash, tc.args.sender, tc.args.senderOtherChain) - - if tc.expectPass { - suite.NoError(err) - - // Check incoming/outgoing asset supply increased - switch tc.args.direction { - case types.SWAP_DIRECTION_INCOMING: - suite.Equal(assetSupplyPre.IncomingSupply.Add(tc.args.coins[0]), assetSupplyPost.IncomingSupply) - case types.SWAP_DIRECTION_OUTGOING: - // Check coins moved - suite.Equal(senderBalancePre.Sub(tc.args.coins[0]), senderBalancePost) - suite.Equal(assetSupplyPre.OutgoingSupply.Add(tc.args.coins[0]), assetSupplyPost.OutgoingSupply) - default: - suite.Fail("should not have invalid direction") - } - - // Check swap in store - actualSwap, found := suite.keeper.GetAtomicSwap(suite.ctx, expectedSwapID) - suite.True(found) - suite.NotNil(actualSwap) - - // Confirm swap contents - expectedSwap := types.AtomicSwap{ - Amount: tc.args.coins, - RandomNumberHash: tc.args.randomNumberHash, - ExpireHeight: uint64(suite.ctx.BlockHeight()) + tc.args.heightSpan, - Timestamp: tc.args.timestamp, - Sender: tc.args.sender, - Recipient: tc.args.recipient, - SenderOtherChain: tc.args.senderOtherChain, - RecipientOtherChain: tc.args.recipientOtherChain, - ClosedBlock: 0, - Status: types.SWAP_STATUS_OPEN, - CrossChain: tc.args.crossChain, - Direction: tc.args.direction, - } - suite.Equal(expectedSwap, actualSwap) - } else { - suite.Error(err) - // Check coins not moved - suite.Equal(senderBalancePre, senderBalancePost) - - // Check incoming/outgoing asset supply not increased - switch tc.args.direction { - case types.SWAP_DIRECTION_INCOMING: - suite.Equal(assetSupplyPre.IncomingSupply, assetSupplyPost.IncomingSupply) - case types.SWAP_DIRECTION_OUTGOING: - suite.Equal(assetSupplyPre.OutgoingSupply, assetSupplyPost.OutgoingSupply) - default: - suite.Fail("should not have invalid direction") - } - - // Check if swap found in store - _, found := suite.keeper.GetAtomicSwap(suite.ctx, expectedSwapID) - if !tc.shouldBeFound { - suite.False(found) - } else { - suite.True(found) - } - } - }) - } -} - -func (suite *AtomicSwapTestSuite) TestClaimAtomicSwap() { - suite.SetupTest() - currentTmTime := tmtime.Now() - invalidRandomNumber, _ := types.GenerateSecureRandomNumber() - type args struct { - coins sdk.Coins - swapID []byte - randomNumber []byte - direction types.SwapDirection - } - testCases := []struct { - name string - claimCtx sdk.Context - args args - expectPass bool - }{ - { - "normal incoming swap", - suite.ctx, - args{ - coins: cs(c(BNB_DENOM, 50000)), - swapID: []byte{}, - randomNumber: []byte{}, - direction: types.SWAP_DIRECTION_INCOMING, - }, - true, - }, - { - "normal incoming swap rate-limited", - suite.ctx.WithBlockTime(currentTmTime.Add(time.Minute * 10)), - args{ - coins: cs(c(OTHER_DENOM, 50000)), - swapID: []byte{}, - randomNumber: []byte{}, - direction: types.SWAP_DIRECTION_INCOMING, - }, - true, - }, - { - "normal outgoing swap", - suite.ctx, - args{ - coins: cs(c(BNB_DENOM, 50000)), - swapID: []byte{}, - randomNumber: []byte{}, - direction: types.SWAP_DIRECTION_OUTGOING, - }, - true, - }, - { - "invalid random number", - suite.ctx, - args{ - coins: cs(c(BNB_DENOM, 50000)), - swapID: []byte{}, - randomNumber: invalidRandomNumber[:], - direction: types.SWAP_DIRECTION_INCOMING, - }, - false, - }, - { - "wrong swap ID", - suite.ctx, - args{ - coins: cs(c(BNB_DENOM, 50000)), - swapID: types.CalculateSwapID(suite.randomNumberHashes[3], suite.addrs[6], TestRecipientOtherChain), - randomNumber: []byte{}, - direction: types.SWAP_DIRECTION_OUTGOING, - }, - false, - }, - { - "past expiration", - suite.ctx.WithBlockHeight(suite.ctx.BlockHeight() + 2000), - args{ - coins: cs(c(BNB_DENOM, 50000)), - swapID: []byte{}, - randomNumber: []byte{}, - direction: types.SWAP_DIRECTION_INCOMING, - }, - false, - }, - } - - for i, tc := range testCases { - suite.GenerateSwapDetails() - suite.Run(tc.name, func() { - expectedRecipient := suite.addrs[5] - sender := suite.deputy - - // Set sender to other and increment current asset supply for outgoing swap - if tc.args.direction == types.SWAP_DIRECTION_OUTGOING { - sender = suite.addrs[6] - expectedRecipient = suite.deputy - err := suite.keeper.IncrementCurrentAssetSupply(suite.ctx, tc.args.coins[0]) - suite.Nil(err) - } - - // Create atomic swap - err := suite.keeper.CreateAtomicSwap(suite.ctx, suite.randomNumberHashes[i], suite.timestamps[i], - types.DefaultMinBlockLock, sender, expectedRecipient, TestSenderOtherChain, TestRecipientOtherChain, - tc.args.coins, true) - suite.NoError(err) - - realSwapID := types.CalculateSwapID(suite.randomNumberHashes[i], sender, TestSenderOtherChain) - - // If args contains an invalid swap ID claim attempt will use it instead of the real swap ID - var claimSwapID []byte - if len(tc.args.swapID) == 0 { - claimSwapID = realSwapID - } else { - claimSwapID = tc.args.swapID - } - - // If args contains an invalid random number claim attempt will use it instead of the real random number - var claimRandomNumber []byte - if len(tc.args.randomNumber) == 0 { - claimRandomNumber = suite.randomNumbers[i] - } else { - claimRandomNumber = tc.args.randomNumber - } - - // Run the beginblocker before attempting claim - bep3.BeginBlocker(tc.claimCtx, suite.keeper) - - // Load expected recipient's account prior to claim attempt - bk := suite.app.GetBankKeeper() - expectedRecipientBalancePre := bk.GetBalance(suite.ctx, expectedRecipient, tc.args.coins[0].Denom) - // Load asset supplies prior to claim attempt - assetSupplyPre, _ := suite.keeper.GetAssetSupply(tc.claimCtx, tc.args.coins[0].Denom) - - // Attempt to claim atomic swap - err = suite.keeper.ClaimAtomicSwap(tc.claimCtx, expectedRecipient, claimSwapID, claimRandomNumber) - - // Load expected recipient's account after the claim attempt - expectedRecipientBalancePost := bk.GetBalance(suite.ctx, expectedRecipient, tc.args.coins[0].Denom) - // Load asset supplies after the claim attempt - assetSupplyPost, _ := suite.keeper.GetAssetSupply(tc.claimCtx, tc.args.coins[0].Denom) - - if tc.expectPass { - suite.NoError(err) - - // Check asset supply changes - switch tc.args.direction { - case types.SWAP_DIRECTION_INCOMING: - // Check coins moved - suite.Equal(expectedRecipientBalancePre.Add(tc.args.coins[0]), expectedRecipientBalancePost) - // Check incoming supply decreased - suite.True(assetSupplyPre.IncomingSupply.Amount.Sub(tc.args.coins[0].Amount).Equal(assetSupplyPost.IncomingSupply.Amount)) - // Check current supply increased - suite.Equal(assetSupplyPre.CurrentSupply.Add(tc.args.coins[0]), assetSupplyPost.CurrentSupply) - // Check outgoing supply not changed - suite.Equal(assetSupplyPre.OutgoingSupply, assetSupplyPost.OutgoingSupply) - case types.SWAP_DIRECTION_OUTGOING: - // Check incoming supply not changed - suite.Equal(assetSupplyPre.IncomingSupply, assetSupplyPost.IncomingSupply) - // Check current supply decreased - suite.Equal(assetSupplyPre.CurrentSupply.Sub(tc.args.coins[0]), assetSupplyPost.CurrentSupply) - // Check outgoing supply decreased - suite.True(assetSupplyPre.OutgoingSupply.Sub(tc.args.coins[0]).IsEqual(assetSupplyPost.OutgoingSupply)) - default: - suite.Fail("should not have invalid direction") - } - } else { - suite.Error(err) - // Check coins not moved - suite.Equal(expectedRecipientBalancePre, expectedRecipientBalancePost) - - // Check asset supply has not changed - switch tc.args.direction { - case types.SWAP_DIRECTION_INCOMING: - suite.Equal(assetSupplyPre.IncomingSupply, assetSupplyPost.IncomingSupply) - suite.Equal(assetSupplyPre.CurrentSupply, assetSupplyPost.CurrentSupply) - suite.Equal(assetSupplyPre.OutgoingSupply, assetSupplyPost.OutgoingSupply) - case types.SWAP_DIRECTION_OUTGOING: - suite.Equal(assetSupplyPre.IncomingSupply, assetSupplyPost.IncomingSupply) - suite.Equal(assetSupplyPre.CurrentSupply, assetSupplyPost.CurrentSupply) - suite.Equal(assetSupplyPre.OutgoingSupply, assetSupplyPost.OutgoingSupply) - default: - suite.Fail("should not have invalid direction") - } - } - }) - } -} - -func (suite *AtomicSwapTestSuite) TestRefundAtomicSwap() { - suite.SetupTest() - - type args struct { - swapID []byte - direction types.SwapDirection - } - testCases := []struct { - name string - refundCtx sdk.Context - args args - expectPass bool - }{ - { - "normal incoming swap", - suite.ctx.WithBlockHeight(suite.ctx.BlockHeight() + 400), - args{ - swapID: []byte{}, - direction: types.SWAP_DIRECTION_INCOMING, - }, - true, - }, - { - "normal outgoing swap", - suite.ctx.WithBlockHeight(suite.ctx.BlockHeight() + 400), - args{ - swapID: []byte{}, - direction: types.SWAP_DIRECTION_OUTGOING, - }, - true, - }, - { - "before expiration", - suite.ctx, - args{ - swapID: []byte{}, - direction: types.SWAP_DIRECTION_INCOMING, - }, - false, - }, - { - "wrong swapID", - suite.ctx, - args{ - swapID: types.CalculateSwapID(suite.randomNumberHashes[6], suite.addrs[1], TestRecipientOtherChain), - direction: types.SWAP_DIRECTION_INCOMING, - }, - false, - }, - } - - for i, tc := range testCases { - suite.GenerateSwapDetails() - suite.Run(tc.name, func() { - // Create atomic swap - expectedRefundAmount := cs(c(BNB_DENOM, 50000)) - sender := suite.deputy - expectedRecipient := suite.addrs[9] - - // Set sender to other and increment current asset supply for outgoing swap - if tc.args.direction == types.SWAP_DIRECTION_OUTGOING { - sender = suite.addrs[6] - expectedRecipient = suite.deputy - err := suite.keeper.IncrementCurrentAssetSupply(suite.ctx, expectedRefundAmount[0]) - suite.Nil(err) - } - - err := suite.keeper.CreateAtomicSwap(suite.ctx, suite.randomNumberHashes[i], suite.timestamps[i], - types.DefaultMinBlockLock, sender, expectedRecipient, TestSenderOtherChain, TestRecipientOtherChain, - expectedRefundAmount, true) - suite.NoError(err) - - realSwapID := types.CalculateSwapID(suite.randomNumberHashes[i], sender, TestSenderOtherChain) - - // If args contains an invalid swap ID refund attempt will use it instead of the real swap ID - var refundSwapID []byte - if len(tc.args.swapID) == 0 { - refundSwapID = realSwapID - } else { - refundSwapID = tc.args.swapID - } - - // Run the beginblocker before attempting refund - bep3.BeginBlocker(tc.refundCtx, suite.keeper) - - // Load sender's account prior to swap refund - bk := suite.app.GetBankKeeper() - originalSenderBalancePre := bk.GetBalance(suite.ctx, sender, expectedRefundAmount[0].Denom) - // Load asset supply prior to swap refund - assetSupplyPre, _ := suite.keeper.GetAssetSupply(tc.refundCtx, expectedRefundAmount[0].Denom) - - // Attempt to refund atomic swap - err = suite.keeper.RefundAtomicSwap(tc.refundCtx, sender, refundSwapID) - - // Load sender's account after refund - originalSenderBalancePost := bk.GetBalance(suite.ctx, sender, expectedRefundAmount[0].Denom) - // Load asset supply after to swap refund - assetSupplyPost, _ := suite.keeper.GetAssetSupply(tc.refundCtx, expectedRefundAmount[0].Denom) - - if tc.expectPass { - suite.NoError(err) - - // Check asset supply changes - switch tc.args.direction { - case types.SWAP_DIRECTION_INCOMING: - // Check incoming supply decreased - suite.True(assetSupplyPre.IncomingSupply.Sub(expectedRefundAmount[0]).IsEqual(assetSupplyPost.IncomingSupply)) - // Check current, outgoing supply not changed - suite.Equal(assetSupplyPre.CurrentSupply, assetSupplyPost.CurrentSupply) - suite.Equal(assetSupplyPre.OutgoingSupply, assetSupplyPost.OutgoingSupply) - case types.SWAP_DIRECTION_OUTGOING: - // Check coins moved - suite.Equal(originalSenderBalancePre.Add(expectedRefundAmount[0]), originalSenderBalancePost) - // Check incoming, current supply not changed - suite.Equal(assetSupplyPre.IncomingSupply, assetSupplyPost.IncomingSupply) - suite.Equal(assetSupplyPre.CurrentSupply, assetSupplyPost.CurrentSupply) - // Check outgoing supply decreased - suite.True(assetSupplyPre.OutgoingSupply.Sub(expectedRefundAmount[0]).IsEqual(assetSupplyPost.OutgoingSupply)) - default: - suite.Fail("should not have invalid direction") - } - } else { - suite.Error(err) - // Check coins not moved - suite.Equal(originalSenderBalancePre, originalSenderBalancePost) - - // Check asset supply has not changed - switch tc.args.direction { - case types.SWAP_DIRECTION_INCOMING: - suite.Equal(assetSupplyPre.IncomingSupply, assetSupplyPost.IncomingSupply) - suite.Equal(assetSupplyPre.CurrentSupply, assetSupplyPost.CurrentSupply) - suite.Equal(assetSupplyPre.OutgoingSupply, assetSupplyPost.OutgoingSupply) - case types.SWAP_DIRECTION_OUTGOING: - suite.Equal(assetSupplyPre.IncomingSupply, assetSupplyPost.IncomingSupply) - suite.Equal(assetSupplyPre.CurrentSupply, assetSupplyPost.CurrentSupply) - suite.Equal(assetSupplyPre.OutgoingSupply, assetSupplyPost.OutgoingSupply) - default: - suite.Fail("should not have invalid direction") - } - } - }) - } -} - -func TestAtomicSwapTestSuite(t *testing.T) { - suite.Run(t, new(AtomicSwapTestSuite)) -} diff --git a/x/bep3/legacy/v0_17/migrate.go b/x/bep3/legacy/v0_17/migrate.go deleted file mode 100644 index e830b7dd..00000000 --- a/x/bep3/legacy/v0_17/migrate.go +++ /dev/null @@ -1,57 +0,0 @@ -package v0_16 - -import ( - "fmt" - - "github.com/kava-labs/kava/x/bep3/types" -) - -// resetSwapForZeroHeight updates swap expiry/close heights to work when the chain height is reset to zero. -func resetSwapForZeroHeight(swap types.AtomicSwap) types.AtomicSwap { - switch status := swap.Status; status { - case types.SWAP_STATUS_COMPLETED: - // Reset closed block to one so completed swaps are not held in long term storage too long. - swap.ClosedBlock = 1 - case types.SWAP_STATUS_OPEN: - switch dir := swap.Direction; dir { - case types.SWAP_DIRECTION_INCOMING: - // Open incoming swaps can be expired safely. They haven't been claimed yet, so the outgoing swap on bnb will just timeout. - // The chain downtime cannot be accurately predicted, so it's easier to expire than to recalculate a correct expire height. - swap.ExpireHeight = 1 - swap.Status = types.SWAP_STATUS_EXPIRED - case types.SWAP_DIRECTION_OUTGOING: - // Open outgoing swaps should be extended to allow enough time to claim after the chain launches. - // They cannot be expired as there could be an open/claimed bnb swap. - swap.ExpireHeight = 1 + 24686 // default timeout used when sending swaps from kava - case types.SWAP_DIRECTION_UNSPECIFIED: - default: - panic(fmt.Sprintf("unknown bep3 swap direction '%s'", dir)) - } - case types.SWAP_STATUS_EXPIRED: - // Once a swap is marked expired the expire height is ignored. However reset to 1 to be sure. - swap.ExpireHeight = 1 - case types.SWAP_STATUS_UNSPECIFIED: - default: - panic(fmt.Sprintf("unknown bep3 swap status '%s'", status)) - } - - return swap -} - -func resetSwapsForZeroHeight(oldSwaps types.AtomicSwaps) types.AtomicSwaps { - newSwaps := make(types.AtomicSwaps, len(oldSwaps)) - for i, oldSwap := range oldSwaps { - swap := resetSwapForZeroHeight(oldSwap) - newSwaps[i] = swap - } - return newSwaps -} - -func Migrate(oldState types.GenesisState) *types.GenesisState { - return &types.GenesisState{ - PreviousBlockTime: oldState.PreviousBlockTime, - Params: oldState.Params, - AtomicSwaps: resetSwapsForZeroHeight(oldState.AtomicSwaps), - Supplies: oldState.Supplies, - } -} diff --git a/x/bep3/legacy/v0_17/migrate_test.go b/x/bep3/legacy/v0_17/migrate_test.go deleted file mode 100644 index e648f297..00000000 --- a/x/bep3/legacy/v0_17/migrate_test.go +++ /dev/null @@ -1,175 +0,0 @@ -package v0_16 - -import ( - "io/ioutil" - "path/filepath" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/libs/bytes" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - app "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/bep3/types" -) - -type migrateTestSuite struct { - suite.Suite - - addresses []sdk.AccAddress - v16genstate types.GenesisState - cdc codec.Codec -} - -func (s *migrateTestSuite) SetupTest() { - app.SetSDKConfig() - - s.v16genstate = types.GenesisState{ - PreviousBlockTime: time.Date(2021, 4, 8, 15, 0, 0, 0, time.UTC), - Params: types.Params{}, - Supplies: types.AssetSupplies{}, - AtomicSwaps: types.AtomicSwaps{}, - } - - config := app.MakeEncodingConfig() - s.cdc = config.Marshaler - - _, accAddresses := app.GeneratePrivKeyAddressPairs(10) - s.addresses = accAddresses -} - -func (s *migrateTestSuite) TestMigrate_JSON() { - // Migrate v16 bep3 to v17 - file := filepath.Join("testdata", "v16-bep3.json") - data, err := ioutil.ReadFile(file) - s.Require().NoError(err) - err = s.cdc.UnmarshalJSON(data, &s.v16genstate) - s.Require().NoError(err) - genstate := Migrate(s.v16genstate) - - // Compare expect v16 bep3 json with migrated json - actual := s.cdc.MustMarshalJSON(genstate) - file = filepath.Join("testdata", "v17-bep3.json") - expected, err := ioutil.ReadFile(file) - s.Require().NoError(err) - s.Require().JSONEq(string(expected), string(actual)) -} - -func (s *migrateTestSuite) TestMigrate_Swaps() { - type swap struct { - ExpireHeight uint64 - CloseBlock int64 - Status types.SwapStatus - Direction types.SwapDirection - } - testcases := []struct { - name string - oldSwap swap - newSwap swap - }{ - { - name: "incoming open swap", - oldSwap: swap{ - // expire and close not set in open swaps - Status: types.SWAP_STATUS_OPEN, - Direction: types.SWAP_DIRECTION_INCOMING, - }, - newSwap: swap{ - ExpireHeight: 1, - Status: types.SWAP_STATUS_EXPIRED, - Direction: types.SWAP_DIRECTION_INCOMING, - }, - }, - { - name: "outgoing open swap", - oldSwap: swap{ - // expire and close not set in open swaps - Status: types.SWAP_STATUS_OPEN, - Direction: types.SWAP_DIRECTION_OUTGOING, - }, - newSwap: swap{ - ExpireHeight: 24687, - Status: types.SWAP_STATUS_OPEN, - Direction: types.SWAP_DIRECTION_OUTGOING, - }, - }, - { - name: "completed swap", - oldSwap: swap{ - ExpireHeight: 1000, - CloseBlock: 900, - Status: types.SWAP_STATUS_COMPLETED, - Direction: types.SWAP_DIRECTION_INCOMING, - }, - newSwap: swap{ - ExpireHeight: 1000, - CloseBlock: 1, - Status: types.SWAP_STATUS_COMPLETED, - Direction: types.SWAP_DIRECTION_INCOMING, - }, - }, - { - name: "expired swap", - oldSwap: swap{ - ExpireHeight: 1000, - CloseBlock: 900, - Status: types.SWAP_STATUS_EXPIRED, - Direction: types.SWAP_DIRECTION_INCOMING, - }, - newSwap: swap{ - ExpireHeight: 1, - CloseBlock: 900, - Status: types.SWAP_STATUS_EXPIRED, - Direction: types.SWAP_DIRECTION_INCOMING, - }, - }, - } - - for _, tc := range testcases { - s.Run(tc.name, func() { - oldSwaps := types.AtomicSwaps{ - { - Amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(12))), - RandomNumberHash: bytes.HexBytes{}, - ExpireHeight: tc.oldSwap.ExpireHeight, - Timestamp: 1110, - Sender: s.addresses[0], - Recipient: s.addresses[1], - RecipientOtherChain: s.addresses[0].String(), - SenderOtherChain: s.addresses[1].String(), - ClosedBlock: tc.oldSwap.CloseBlock, - Status: tc.oldSwap.Status, - CrossChain: true, - Direction: tc.oldSwap.Direction, - }, - } - expectedSwaps := types.AtomicSwaps{ - { - Amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(12))), - RandomNumberHash: bytes.HexBytes{}, - ExpireHeight: tc.newSwap.ExpireHeight, - Timestamp: 1110, - Sender: s.addresses[0], - Recipient: s.addresses[1], - RecipientOtherChain: s.addresses[0].String(), - SenderOtherChain: s.addresses[1].String(), - ClosedBlock: tc.newSwap.CloseBlock, - Status: tc.newSwap.Status, - CrossChain: true, - Direction: tc.newSwap.Direction, - }, - } - s.v16genstate.AtomicSwaps = oldSwaps - genState := Migrate(s.v16genstate) - s.Require().Len(genState.AtomicSwaps, 1) - s.Equal(expectedSwaps, genState.AtomicSwaps) - }) - } -} - -func TestMigrateTestSuite(t *testing.T) { - suite.Run(t, new(migrateTestSuite)) -} diff --git a/x/bep3/legacy/v0_17/testdata/v16-bep3.json b/x/bep3/legacy/v0_17/testdata/v16-bep3.json deleted file mode 100644 index 1e040204..00000000 --- a/x/bep3/legacy/v0_17/testdata/v16-bep3.json +++ /dev/null @@ -1,212 +0,0 @@ -{ - "atomic_swaps": [ - { - "amount": [ - { - "amount": "1999955998", - "denom": "btcb" - } - ], - "closed_block": "838115", - "cross_chain": true, - "direction": "SWAP_DIRECTION_INCOMING", - "expire_height": "838627", - "random_number_hash": "6F1CF8F2E13A0C0F0A359F54E47E4E265D766B8E006D2F00BDF994ABDEF1E9E4", - "recipient": "kava1fl2hs6y9vz986g5v52pdan9ga923n9mn5cxxkw", - "recipient_other_chain": "bnb1xz3xqf4p2ygrw9lhp5g5df4ep4nd20vsywnmpr", - "sender": "kava14qsmvzprqvhwmgql9fr0u3zv9n2qla8zhnm5pc", - "sender_other_chain": "bnb19k9wuv2j7c7ck8tmc7kav0r0cnt3esmkrpf25x", - "status": "SWAP_STATUS_COMPLETED", - "timestamp": "1636034914" - }, - { - "amount": [ - { - "amount": "19000000000", - "denom": "bnb" - } - ], - "closed_block": "1712118", - "cross_chain": true, - "direction": "SWAP_DIRECTION_OUTGOING", - "expire_height": "1736797", - "random_number_hash": "280EB832A37F2265CC82F3957CE603AAD57BAD7038B876A1F28953AFA29FA1C3", - "recipient": "kava1r4v2zdhdalfj2ydazallqvrus9fkphmglhn6u6", - "recipient_other_chain": "bnb18nsgj50zvc4uq93w4j0ltz5gaxhwv7aq4qnq0p", - "sender": "kava1zw6gg4ztvly7zf25pa33mclav3spvj3ympxxna", - "sender_other_chain": "bnb1jh7uv2rm6339yue8k4mj9406k3509kr4wt5nxn", - "status": "SWAP_STATUS_COMPLETED", - "timestamp": "1641976566" - }, - { - "amount": [ - { - "amount": "999595462080", - "denom": "busd" - } - ], - "closed_block": "787122", - "cross_chain": true, - "direction": "SWAP_DIRECTION_INCOMING", - "expire_height": "811799", - "random_number_hash": "BFB7CC82DA0E0C8556AC37843F5AB136B9A7A066054368F5948944282B414D83", - "recipient": "kava1eufgf0w9d7hf5mgtek4zr2upkxag9stmzx6unl", - "recipient_other_chain": "bnb10zq89008gmedc6rrwzdfukjk94swynd7dl97w8", - "sender": "kava1hh4x3a4suu5zyaeauvmv7ypf7w9llwlfufjmuu", - "sender_other_chain": "bnb1vl3wn4x8kqajg2j9wxa5y5amgzdxchutkxr6at", - "status": "SWAP_STATUS_EXPIRED", - "timestamp": "1635694492" - }, - { - "amount": [ - { - "amount": "999595462080", - "denom": "busd" - } - ], - "closed_block": "787122", - "cross_chain": true, - "direction": "SWAP_DIRECTION_OUTGOING", - "expire_height": "811799", - "random_number_hash": "BFB7CC82DA0E0C8556AC37843F5AB136B9A7A066054368F5948944282B414D83", - "recipient": "kava1hh4x3a4suu5zyaeauvmv7ypf7w9llwlfufjmuu", - "recipient_other_chain": "bnb1vl3wn4x8kqajg2j9wxa5y5amgzdxchutkxr6at", - "sender": "kava1eufgf0w9d7hf5mgtek4zr2upkxag9stmzx6unl", - "sender_other_chain": "bnb10zq89008gmedc6rrwzdfukjk94swynd7dl97w8", - "status": "SWAP_STATUS_EXPIRED", - "timestamp": "1635694492" - }, - { - "amount": [ - { - "amount": "1000000", - "denom": "btcb" - } - ], - "closed_block": "0", - "cross_chain": true, - "direction": "SWAP_DIRECTION_OUTGOING", - "expire_height": "1730589", - "random_number_hash": "A74EA1AB58D312FDF1E872D18583CACCF294E639DDA4F303939E9ADCEC081D93", - "recipient": "kava14qsmvzprqvhwmgql9fr0u3zv9n2qla8zhnm5pc", - "recipient_other_chain": "bnb1lhk5ndlgf5wz55t8k35cqj6h9l3m4l5ek2w7q6", - "sender": "kava1d2u28azje7rhqyjtxc2ex8q0cxxpw7dfm7ltq5", - "sender_other_chain": "bnb1xz3xqf4p2ygrw9lhp5g5df4ep4nd20vsywnmpr", - "status": "SWAP_STATUS_OPEN", - "timestamp": "1641934114" - }, - { - "amount": [ - { - "amount": "1000000", - "denom": "btcb" - } - ], - "closed_block": "0", - "cross_chain": true, - "direction": "SWAP_DIRECTION_INCOMING", - "expire_height": "1740000", - "random_number_hash": "39E9ADCEC081D93A74EA1A83CACCF294E639DDA4F3039B58D312FDF1E872D185", - "recipient": "kava1d2u28azje7rhqyjtxc2ex8q0cxxpw7dfm7ltq5", - "recipient_other_chain": "bnb1xz3xqf4p2ygrw9lhp5g5df4ep4nd20vsywnmpr", - "sender": "kava14qsmvzprqvhwmgql9fr0u3zv9n2qla8zhnm5pc", - "sender_other_chain": "bnb1lhk5ndlgf5wz55t8k35cqj6h9l3m4l5ek2w7q6", - "status": "SWAP_STATUS_OPEN", - "timestamp": "1641934114" - } - ], - "params": { - "asset_params": [ - { - "active": true, - "coin_id": "0", - "denom": "btcb", - "deputy_address": "kava1kla4wl0ccv7u85cemvs3y987hqk0afcv7vue84", - "fixed_fee": "2", - "max_block_lock": "86400", - "max_swap_amount": "2000000000", - "min_block_lock": "24686", - "min_swap_amount": "3", - "supply_limit": { - "limit": "100000000000", - "time_based_limit": "0", - "time_limited": false, - "time_period": "0s" - } - }, - { - "active": true, - "coin_id": "144", - "denom": "xrpb", - "deputy_address": "kava14q5sawxdxtpap5x5sgzj7v4sp3ucncjlpuk3hs", - "fixed_fee": "100000", - "max_block_lock": "86400", - "max_swap_amount": "250000000000000", - "min_block_lock": "24686", - "min_swap_amount": "100001", - "supply_limit": { - "limit": "2000000000000000", - "time_based_limit": "0", - "time_limited": false, - "time_period": "0s" - } - }, - { - "active": true, - "coin_id": "714", - "denom": "bnb", - "deputy_address": "kava1agcvt07tcw0tglu0hmwdecsnuxp2yd45f3avgm", - "fixed_fee": "1000", - "max_block_lock": "86400", - "max_swap_amount": "500000000000", - "min_block_lock": "24686", - "min_swap_amount": "1001", - "supply_limit": { - "limit": "100000000000000", - "time_based_limit": "0", - "time_limited": false, - "time_period": "0s" - } - }, - { - "active": true, - "coin_id": "727", - "denom": "busd", - "deputy_address": "kava1j9je7f6s0v6k7dmgv6u5k5ru202f5ffsc7af04", - "fixed_fee": "20000", - "max_block_lock": "86400", - "max_swap_amount": "100000000000000", - "min_block_lock": "24686", - "min_swap_amount": "20001", - "supply_limit": { - "limit": "2000000000000000", - "time_based_limit": "0", - "time_limited": false, - "time_period": "0s" - } - } - ] - }, - "previous_block_time": "1970-01-01T00:00:00Z", - "supplies": [ - { - "current_supply": { - "amount": "30467559434006", - "denom": "bnb" - }, - "incoming_supply": { - "amount": "0", - "denom": "bnb" - }, - "outgoing_supply": { - "amount": "0", - "denom": "bnb" - }, - "time_elapsed": "0s", - "time_limited_current_supply": { - "amount": "0", - "denom": "bnb" - } - } - ] -} \ No newline at end of file diff --git a/x/bep3/legacy/v0_17/testdata/v17-bep3.json b/x/bep3/legacy/v0_17/testdata/v17-bep3.json deleted file mode 100644 index 3861ff92..00000000 --- a/x/bep3/legacy/v0_17/testdata/v17-bep3.json +++ /dev/null @@ -1,212 +0,0 @@ -{ - "atomic_swaps": [ - { - "amount": [ - { - "amount": "1999955998", - "denom": "btcb" - } - ], - "closed_block": "1", - "cross_chain": true, - "direction": "SWAP_DIRECTION_INCOMING", - "expire_height": "838627", - "random_number_hash": "6F1CF8F2E13A0C0F0A359F54E47E4E265D766B8E006D2F00BDF994ABDEF1E9E4", - "recipient": "kava1fl2hs6y9vz986g5v52pdan9ga923n9mn5cxxkw", - "recipient_other_chain": "bnb1xz3xqf4p2ygrw9lhp5g5df4ep4nd20vsywnmpr", - "sender": "kava14qsmvzprqvhwmgql9fr0u3zv9n2qla8zhnm5pc", - "sender_other_chain": "bnb19k9wuv2j7c7ck8tmc7kav0r0cnt3esmkrpf25x", - "status": "SWAP_STATUS_COMPLETED", - "timestamp": "1636034914" - }, - { - "amount": [ - { - "amount": "19000000000", - "denom": "bnb" - } - ], - "closed_block": "1", - "cross_chain": true, - "direction": "SWAP_DIRECTION_OUTGOING", - "expire_height": "1736797", - "random_number_hash": "280EB832A37F2265CC82F3957CE603AAD57BAD7038B876A1F28953AFA29FA1C3", - "recipient": "kava1r4v2zdhdalfj2ydazallqvrus9fkphmglhn6u6", - "recipient_other_chain": "bnb18nsgj50zvc4uq93w4j0ltz5gaxhwv7aq4qnq0p", - "sender": "kava1zw6gg4ztvly7zf25pa33mclav3spvj3ympxxna", - "sender_other_chain": "bnb1jh7uv2rm6339yue8k4mj9406k3509kr4wt5nxn", - "status": "SWAP_STATUS_COMPLETED", - "timestamp": "1641976566" - }, - { - "amount": [ - { - "amount": "999595462080", - "denom": "busd" - } - ], - "closed_block": "787122", - "cross_chain": true, - "direction": "SWAP_DIRECTION_INCOMING", - "expire_height": "1", - "random_number_hash": "BFB7CC82DA0E0C8556AC37843F5AB136B9A7A066054368F5948944282B414D83", - "recipient": "kava1eufgf0w9d7hf5mgtek4zr2upkxag9stmzx6unl", - "recipient_other_chain": "bnb10zq89008gmedc6rrwzdfukjk94swynd7dl97w8", - "sender": "kava1hh4x3a4suu5zyaeauvmv7ypf7w9llwlfufjmuu", - "sender_other_chain": "bnb1vl3wn4x8kqajg2j9wxa5y5amgzdxchutkxr6at", - "status": "SWAP_STATUS_EXPIRED", - "timestamp": "1635694492" - }, - { - "amount": [ - { - "amount": "999595462080", - "denom": "busd" - } - ], - "closed_block": "787122", - "cross_chain": true, - "direction": "SWAP_DIRECTION_OUTGOING", - "expire_height": "1", - "random_number_hash": "BFB7CC82DA0E0C8556AC37843F5AB136B9A7A066054368F5948944282B414D83", - "recipient": "kava1hh4x3a4suu5zyaeauvmv7ypf7w9llwlfufjmuu", - "recipient_other_chain": "bnb1vl3wn4x8kqajg2j9wxa5y5amgzdxchutkxr6at", - "sender": "kava1eufgf0w9d7hf5mgtek4zr2upkxag9stmzx6unl", - "sender_other_chain": "bnb10zq89008gmedc6rrwzdfukjk94swynd7dl97w8", - "status": "SWAP_STATUS_EXPIRED", - "timestamp": "1635694492" - }, - { - "amount": [ - { - "amount": "1000000", - "denom": "btcb" - } - ], - "closed_block": "0", - "cross_chain": true, - "direction": "SWAP_DIRECTION_OUTGOING", - "expire_height": "24687", - "random_number_hash": "A74EA1AB58D312FDF1E872D18583CACCF294E639DDA4F303939E9ADCEC081D93", - "recipient": "kava14qsmvzprqvhwmgql9fr0u3zv9n2qla8zhnm5pc", - "recipient_other_chain": "bnb1lhk5ndlgf5wz55t8k35cqj6h9l3m4l5ek2w7q6", - "sender": "kava1d2u28azje7rhqyjtxc2ex8q0cxxpw7dfm7ltq5", - "sender_other_chain": "bnb1xz3xqf4p2ygrw9lhp5g5df4ep4nd20vsywnmpr", - "status": "SWAP_STATUS_OPEN", - "timestamp": "1641934114" - }, - { - "amount": [ - { - "amount": "1000000", - "denom": "btcb" - } - ], - "closed_block": "0", - "cross_chain": true, - "direction": "SWAP_DIRECTION_INCOMING", - "expire_height": "1", - "random_number_hash": "39E9ADCEC081D93A74EA1A83CACCF294E639DDA4F3039B58D312FDF1E872D185", - "recipient": "kava1d2u28azje7rhqyjtxc2ex8q0cxxpw7dfm7ltq5", - "recipient_other_chain": "bnb1xz3xqf4p2ygrw9lhp5g5df4ep4nd20vsywnmpr", - "sender": "kava14qsmvzprqvhwmgql9fr0u3zv9n2qla8zhnm5pc", - "sender_other_chain": "bnb1lhk5ndlgf5wz55t8k35cqj6h9l3m4l5ek2w7q6", - "status": "SWAP_STATUS_EXPIRED", - "timestamp": "1641934114" - } - ], - "params": { - "asset_params": [ - { - "active": true, - "coin_id": "0", - "denom": "btcb", - "deputy_address": "kava1kla4wl0ccv7u85cemvs3y987hqk0afcv7vue84", - "fixed_fee": "2", - "max_block_lock": "86400", - "max_swap_amount": "2000000000", - "min_block_lock": "24686", - "min_swap_amount": "3", - "supply_limit": { - "limit": "100000000000", - "time_based_limit": "0", - "time_limited": false, - "time_period": "0s" - } - }, - { - "active": true, - "coin_id": "144", - "denom": "xrpb", - "deputy_address": "kava14q5sawxdxtpap5x5sgzj7v4sp3ucncjlpuk3hs", - "fixed_fee": "100000", - "max_block_lock": "86400", - "max_swap_amount": "250000000000000", - "min_block_lock": "24686", - "min_swap_amount": "100001", - "supply_limit": { - "limit": "2000000000000000", - "time_based_limit": "0", - "time_limited": false, - "time_period": "0s" - } - }, - { - "active": true, - "coin_id": "714", - "denom": "bnb", - "deputy_address": "kava1agcvt07tcw0tglu0hmwdecsnuxp2yd45f3avgm", - "fixed_fee": "1000", - "max_block_lock": "86400", - "max_swap_amount": "500000000000", - "min_block_lock": "24686", - "min_swap_amount": "1001", - "supply_limit": { - "limit": "100000000000000", - "time_based_limit": "0", - "time_limited": false, - "time_period": "0s" - } - }, - { - "active": true, - "coin_id": "727", - "denom": "busd", - "deputy_address": "kava1j9je7f6s0v6k7dmgv6u5k5ru202f5ffsc7af04", - "fixed_fee": "20000", - "max_block_lock": "86400", - "max_swap_amount": "100000000000000", - "min_block_lock": "24686", - "min_swap_amount": "20001", - "supply_limit": { - "limit": "2000000000000000", - "time_based_limit": "0", - "time_limited": false, - "time_period": "0s" - } - } - ] - }, - "previous_block_time": "1970-01-01T00:00:00Z", - "supplies": [ - { - "current_supply": { - "amount": "30467559434006", - "denom": "bnb" - }, - "incoming_supply": { - "amount": "0", - "denom": "bnb" - }, - "outgoing_supply": { - "amount": "0", - "denom": "bnb" - }, - "time_elapsed": "0s", - "time_limited_current_supply": { - "amount": "0", - "denom": "bnb" - } - } - ] -} \ No newline at end of file diff --git a/x/bep3/module.go b/x/bep3/module.go deleted file mode 100644 index a2ef32c3..00000000 --- a/x/bep3/module.go +++ /dev/null @@ -1,144 +0,0 @@ -package bep3 - -import ( - "context" - "encoding/json" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/kava-labs/kava/x/bep3/client/cli" - "github.com/kava-labs/kava/x/bep3/keeper" - "github.com/kava-labs/kava/x/bep3/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic defines the basic application module used by the bep3 module. -type AppModuleBasic struct{} - -// Name returns the bep3 module's name. -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis returns default genesis state as raw bytes for the bep3 -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - gs := types.DefaultGenesisState() - return cdc.MustMarshalJSON(&gs) -} - -// ValidateGenesis performs genesis state validation for the bep3 module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) - if err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the gov module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) -} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// GetTxCmd returns the root tx command for the bep3 module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the bep3 module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd(types.StoreKey) -} - -//____________________________________________________________________________ - -// AppModule implements the sdk.AppModule interface. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper types.AccountKeeper, bankKeeper types.BankKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - } -} - -// Name returns the bep3 module's name. -func (AppModule) Name() string { - return types.ModuleName -} - -// RegisterInvariants registers the bep3 module invariants. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) -} - -// InitGenesis performs genesis initialization for the bep3 module. 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, am.accountKeeper, &genState) - return []abci.ValidatorUpdate{} -} - -// ExportGenesis returns the exported genesis state as raw bytes for the bep3 -// module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(&gs) -} - -// BeginBlock returns the begin blocker for the bep3 module. -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { - BeginBlocker(ctx, am.keeper) -} - -// EndBlock returns the end blocker for the bep3 module. It returns no validator updates. -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/bep3/spec/01_concepts.md b/x/bep3/spec/01_concepts.md deleted file mode 100644 index 6972388e..00000000 --- a/x/bep3/spec/01_concepts.md +++ /dev/null @@ -1,40 +0,0 @@ - - -# Concepts - - The BEP3 module implements the [BEP3 protocol](https://github.com/binance-chain/BEPs/blob/master/BEP3.md) for secure cross-chain asset transfers between Kava and other BEP3 compatible chains, such as Binance Chain. Transactions are witnessed and relayed between the two blockchains by Binance's BEP3 deputy process. The deputy maintains an address on both chains and is responsible for delivering tokens upon the successful completion of an Atomic Swap. Learn more about the BEP3 deputy process [here](https://github.com/binance-chain/bep3-deputy). - -## Requirements -Kava -- The deputy’s Kava address on mainnet is **kava1r4v2zdhdalfj2ydazallqvrus9fkphmglhn6u6**. -- Kava's official API endpoint is https://kava3.data.kava.io. - -Binance Chain -- The deputy’s Binance Chain address on mainnet is **bnb1jh7uv2rm6339yue8k4mj9406k3509kr4wt5nxn**. -- We recommend using https://testnet-dex.binance.org/ as Binance Chain’s API endpoint. - -Kava's [JavaScript SDK](https://github.com/Kava-Labs/javascript-sdk) and Binance Chain’s [JavaScript SDK](https://github.com/binance-chain/javascript-sdk) can be used to create, claim, and refund swaps. - -## Binance Chain to Kava - -When a user wants to transfer tokens from Binance Chain to Kava, the following steps are taken: -1. User’s tokens are locked on Binance Chain along with the hash of a secret only known to the user. If the secret is not revealed before the deadline, the tokens are refundable. -2. The deputy sends a message to Kava saying “a user has locked X tokens, if their secret is revealed before the deadline issue them an equivalent amount of pegged tokens”. -3. The user reveals the secret on Kava and receives the pegged tokens. -4. The deputy relays the secret to Binance Chain and the original tokens are locked permanently. - - -![Binance Chain to Kava Diagram](./diagrams/BEP3_binance_chain_to_kava.jpg) - -## Kava to Binance Chain -1. When a user wants to transfer tokens from Kava to Binance Chain by redeeming pegged tokens, the following steps are taken: -User’s pegged tokens are locked on Kava along with the hash of a secret only known to the user. If the secret is not revealed before the deadline, the tokens are refundable. -2. The deputy sends a message to Binance Chain saying “a user has locked X pegged tokens, if their secret is revealed before the deadline issue them an equivalent amount of tokens”. -3. The user reveals the secret on Binance Chain and receives the tokens. -4. The deputy relays the secret to Kava and the pegged tokens are locked permanently. - - -![Kava to Binance Chain Diagram](./diagrams/BEP3_kava_to_binance_chain.jpg) - diff --git a/x/bep3/spec/02_state.md b/x/bep3/spec/02_state.md deleted file mode 100644 index 5741f8ea..00000000 --- a/x/bep3/spec/02_state.md +++ /dev/null @@ -1,100 +0,0 @@ - - -# State - -## Parameters and genesis state - -`parameters` define the rules according to which swaps are executed. Parameter updates can be made via on-chain parameter update proposals. - -```go -// Params governance parameters for bep3 module -type Params struct { - BnbDeputyAddress sdk.AccAddress `json:"bnb_deputy_address" yaml:"bnb_deputy_address"` // Bnbchain deputy address - BnbDeputyFixedFee sdkmath.Int `json:"bnb_deputy_fixed_fee" yaml:"bnb_deputy_fixed_fee"` // Deputy fixed fee in BNB - MinAmount sdkmath.Int `json:"min_amount" yaml:"min_amount"` // Minimum swap amount - MaxAmount sdkmath.Int `json:"max_amount" yaml:"max_amount"` // Maximum swap amount - MinBlockLock uint64 `json:"min_block_lock" yaml:"min_block_lock"` // Minimum swap block lock - MaxBlockLock uint64 `json:"max_block_lock" yaml:"max_block_lock"` // Maximum swap block lock - SupportedAssets AssetParams `json:"supported_assets" yaml:"supported_assets"` // Supported assets -} - -// AssetParam governance parameters for each asset within a supported chain -type AssetParam struct { - Denom string `json:"denom" yaml:"denom"` // name of the asset - CoinID int `json:"coin_id" yaml:"coin_id"` // internationally recognized coin ID - Limit sdkmath.Int `json:"limit" yaml:"limit"` // asset supply limit - Active bool `json:"active" yaml:"active"` // denotes if asset is active or paused -} -``` - -`GenesisState` defines the state that must be persisted when the blockchain stops/restarts in order for normal function of the bep3 module to resume. - -```go -// GenesisState - all bep3 state that must be provided at genesis -type GenesisState struct { - Params Params `json:"params" yaml:"params"` - AtomicSwaps AtomicSwaps `json:"atomic_swaps" yaml:"atomic_swaps"` - AssetSupplies AssetSupplies `json:"assets_supplies" yaml:"assets_supplies"` -} -``` - -## Types - -AtomicSwap stores information about an individual atomic swap, including the sender, recipient, amount, random number hash (used to validate the secret and unlock funds), the status (open, completed, or expired). There are two types of atomic swaps: -- Incoming: assets are being sent to Kava from another blockchain. -- Outgoing: assets are being send to another blockchain from Kava. - -```go -// AtomicSwap contains the information for an atomic swap -type AtomicSwap struct { - Amount sdk.Coins `json:"amount" yaml:"amount"` - RandomNumberHash tmbytes.HexBytes `json:"random_number_hash" yaml:"random_number_hash"` - ExpireHeight int64 `json:"expire_height" yaml:"expire_height"` - Timestamp int64 `json:"timestamp" yaml:"timestamp"` - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - Recipient sdk.AccAddress `json:"recipient" yaml:"recipient"` - SenderOtherChain string `json:"sender_other_chain" yaml:"sender_other_chain"` - RecipientOtherChain string `json:"recipient_other_chain" yaml:"recipient_other_chain"` - ClosedBlock int64 `json:"closed_block" yaml:"closed_block"` - Status SwapStatus `json:"status" yaml:"status"` - Direction SwapDirection `json:"direction" yaml:"direction"` -} - -// SwapStatus is the status of an AtomicSwap -type SwapStatus byte - -const ( - NULL SwapStatus = 0x00 - Open SwapStatus = 0x01 - Completed SwapStatus = 0x02 - Expired SwapStatus = 0x03 -) - -// SwapDirection is the direction of an AtomicSwap -type SwapDirection byte - -const ( - INVALID SwapDirection = 0x00 - Incoming SwapDirection = 0x01 - Outgoing SwapDirection = 0x02 -) -``` - -AssetSupply stores information about an individual asset's BEP3 supply: -- Incoming supply: total amount in incoming swaps (being sent to the chain). -- Outgoing supply: total amount in outgoing swaps (being sent off the chain). It cannot be greater than the current supply. -- Current supply: the amount that the deputy has released - it is the active supply on Kava. It is equal to the total amount successfully claimed from incoming swaps minus the total amount claimed from outgoing swaps. -- Supply limit: the maximum amount currently allowed on Kava. The supply limit can be increased by Kava's stability committee, subject to an on-chain proposal vote. - -```go -// AssetSupply contains information about an asset's supply -type AssetSupply struct { - Denom string `json:"denom" yaml:"denom"` - IncomingSupply sdk.Coin `json:"incoming_supply" yaml:"incoming_supply"` - OutgoingSupply sdk.Coin `json:"outgoing_supply" yaml:"outgoing_supply"` - CurrentSupply sdk.Coin `json:"current_supply" yaml:"current_supply"` - SupplyLimit sdk.Coin `json:"supply_limit" yaml:"supply_limit"` -} -``` \ No newline at end of file diff --git a/x/bep3/spec/03_messages.md b/x/bep3/spec/03_messages.md deleted file mode 100644 index 38c72037..00000000 --- a/x/bep3/spec/03_messages.md +++ /dev/null @@ -1,48 +0,0 @@ - - -# Messages - -## Create swap - -Swaps are created using the `MsgCreateAtomicSwap` message type. - -```go -// MsgCreateAtomicSwap contains an AtomicSwap struct -type MsgCreateAtomicSwap struct { - From sdk.AccAddress `json:"from" yaml:"from"` - To sdk.AccAddress `json:"to" yaml:"to"` - RecipientOtherChain string `json:"recipient_other_chain" yaml:"recipient_other_chain"` - SenderOtherChain string `json:"sender_other_chain" yaml:"sender_other_chain"` - RandomNumberHash tmbytes.HexBytes `json:"random_number_hash" yaml:"random_number_hash"` - Timestamp int64 `json:"timestamp" yaml:"timestamp"` - Amount sdk.Coins `json:"amount" yaml:"amount"` - HeightSpan int64 `json:"height_span" yaml:"height_span"` -} -``` - -## Claim swap - -Active swaps are claimed using the `MsgClaimAtomicSwap` message type. - -```go -// MsgClaimAtomicSwap defines a AtomicSwap claim -type MsgClaimAtomicSwap struct { - From sdk.AccAddress `json:"from" yaml:"from"` - SwapID tmbytes.HexBytes `json:"swap_id" yaml:"swap_id"` - RandomNumber tmbytes.HexBytes `json:"random_number" yaml:"random_number"` -} -``` - -## Refund swap - -Expired swaps are refunded using the `MsgRefundAtomicSwap` message type. - -```go -// MsgRefundAtomicSwap defines a refund msg -type MsgRefundAtomicSwap struct { - From sdk.AccAddress `json:"from" yaml:"from"` - SwapID tmbytes.HexBytes `json:"swap_id" yaml:"swap_id"` -} -``` \ No newline at end of file diff --git a/x/bep3/spec/04_events.md b/x/bep3/spec/04_events.md deleted file mode 100644 index 8fcd59ad..00000000 --- a/x/bep3/spec/04_events.md +++ /dev/null @@ -1,55 +0,0 @@ - - -# Events - -The `x/bep3` module emits the following events: - -## Handlers - -### MsgCreateAtomicSwap - -| Type | Attribute Key | Attribute Value | -|--------------------|--------------------|---------------------------| -| create_atomic_swap | sender | `{sender address}` | -| create_atomic_swap | recipient | `{recipient address}` | -| create_atomic_swap | atomic_swap_id | `{swap ID}` | -| create_atomic_swap | random_number_hash | `{random number hash}` | -| create_atomic_swap | timestamp | `{timestamp}` | -| create_atomic_swap | sender_other_chain | `{sender other chain}` | -| create_atomic_swap | expire_height | `{swap expiration block}` | -| create_atomic_swap | amount | `{coin amount}` | -| create_atomic_swap | direction | `{incoming or outgoing}` | -| message | module | bep3 | -| message | sender | `{sender address}` | - -### MsgClaimAtomicSwap - -| Type | Attribute Key | Attribute Value | -|--------------------|--------------------|---------------------------| -| claim_atomic_swap | claim_sender | `{sender address}` | -| claim_atomic_swap | recipient | `{recipient address}` | -| claim_atomic_swap | atomic_swap_id | `{swap ID}` | -| claim_atomic_swap | random_number_hash | `{random number hash}` | -| claim_atomic_swap | random_number | `{secret random number}` | -| message | module | bep3 | -| message | sender | `{sender address}` | - -## MsgRefundAtomicSwap - -| Type | Attribute Key | Attribute Value | -|--------------------|--------------------|---------------------------| -| refund_atomic_swap | refund_sender | `{sender address}` | -| refund_atomic_swap | sender | `{swap creator address}` | -| refund_atomic_swap | atomic_swap_id | `{swap ID}` | -| refund_atomic_swap | random_number_hash | `{random number hash}` | -| message | module | bep3 | -| message | sender | `{sender address}` | - -## BeginBlock - -| Type | Attribute Key | Attribute Value | -|---------------|------------------|----------------------------------| -| swaps_expired | atomic_swap_ids | `{array of swap IDs}` | -| swaps_expired | expiration_block | `{block height at expiration}` | diff --git a/x/bep3/spec/05_params.md b/x/bep3/spec/05_params.md deleted file mode 100644 index 8aefa3d6..00000000 --- a/x/bep3/spec/05_params.md +++ /dev/null @@ -1,26 +0,0 @@ - - -# Parameters - -The bep3 module contains the following parameters: - -| Key | Type | Example | Description | -| ----------------- | -------------- | --------------------------------------------- | -------------------------- | -| BnbDeputyAddress | sdk.AccAddress | "kava1r4v2zdhdalfj2ydazallqvrus9fkphmglhn6u6" | deputy's Kava address | -| BnbDeputyFixedFee | sdkmath.Int | sdkmath.NewInt(1000) | deputy's fixed bnb fee | -| MinAmount | sdkmath.Int | sdkmath.NewInt(0) | minimum swap amount | -| MaxAmount | sdkmath.Int | sdkmath.NewInt(1000000000000) | maximum swap amount | -| MinBlockLock | uint64 | 220 | minimum swap expire height | -| MaxBlockLock | uint64 | 270 | maximum swap expire height | -| SupportedAssets | AssetParams | []AssetParam | array of supported assets | - -Each AssetParam has the following parameters: - -| Key | Type | Example | Description | -| ----------------- | ----------- | ------------------- | ----------------------------- | -| AssetParam.Denom | string | "bnb" | asset's name | -| AssetParam.CoinID | int64 | 714 | asset's international coin ID | -| AssetParam.Limit | sdkmath.Int | sdkmath.NewInt(100) | asset's supply limit | -| AssetParam.Active | boolean | true | asset's state: live or paused | diff --git a/x/bep3/spec/06_begin_block.md b/x/bep3/spec/06_begin_block.md deleted file mode 100644 index a1d9f74d..00000000 --- a/x/bep3/spec/06_begin_block.md +++ /dev/null @@ -1,50 +0,0 @@ - - -# Begin Block - -At the start of each block, atomic swaps that meet certain criteria are expired or deleted. - -```go -func BeginBlocker(ctx sdk.Context, k Keeper) { - k.UpdateExpiredAtomicSwaps(ctx) - k.DeleteClosedAtomicSwapsFromLongtermStorage(ctx) -} -``` - -## Expiration - -If an atomic swap's `ExpireHeight` is greater than the current block height, it will be expired. The logic to expire atomic swaps is as follows: - -```go - var expiredSwapIDs []string - k.IterateAtomicSwapsByBlock(ctx, uint64(ctx.BlockHeight()), func(id []byte) bool { - atomicSwap, found := k.GetAtomicSwap(ctx, id) - if !found { - return false - } - // Expire the uncompleted swap and update both indexes - atomicSwap.Status = types.Expired - k.RemoveFromByBlockIndex(ctx, atomicSwap) - k.SetAtomicSwap(ctx, atomicSwap) - expiredSwapIDs = append(expiredSwapIDs, hex.EncodeToString(atomicSwap.GetSwapID())) - return false - }) -``` - -## Deletion - -Atomic swaps are deleted 86400 blocks (one week, assuming a block time of 7 seconds) after being completed. The logic to delete atomic swaps is as follows: - -```go -k.IterateAtomicSwapsLongtermStorage(ctx, uint64(ctx.BlockHeight()), func(id []byte) bool { - swap, found := k.GetAtomicSwap(ctx, id) - if !found { - return false - } - k.RemoveAtomicSwap(ctx, swap.GetSwapID()) - k.RemoveFromLongtermStorage(ctx, swap) - return false -}) -``` \ No newline at end of file diff --git a/x/bep3/spec/README.md b/x/bep3/spec/README.md deleted file mode 100644 index 39895db8..00000000 --- a/x/bep3/spec/README.md +++ /dev/null @@ -1,27 +0,0 @@ - - -# `bep3` - - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** -5. **[Params](05_params.md)** -6. **[BeginBlock](06_begin_block.md)** - -## Abstract - -`x/bep3` is a module that handles cross-chain atomic swaps between Kava and blockchains that implement the BEP3 protocol. Atomic swaps are created, then either claimed before their expiration block or refunded after they've expired. - -Several user interfaces support Kava BEP3 swaps: -- [Trust Wallet](https://trustwallet.com/) -- [Cosmostation](https://wallet.cosmostation.io/?network=kava) -- [Frontier Wallet](https://frontierwallet.com/) - -Swaps can also be created, claimed, and refunded using Kava's [Javascript SDK](https://github.com/Kava-Labs/javascript-sdk) or CLI. diff --git a/x/bep3/spec/diagrams/BEP3_binance_chain_to_kava.jpg b/x/bep3/spec/diagrams/BEP3_binance_chain_to_kava.jpg deleted file mode 100644 index 350d659a..00000000 Binary files a/x/bep3/spec/diagrams/BEP3_binance_chain_to_kava.jpg and /dev/null differ diff --git a/x/bep3/spec/diagrams/BEP3_kava_to_binance_chain.jpg b/x/bep3/spec/diagrams/BEP3_kava_to_binance_chain.jpg deleted file mode 100644 index a0d0650e..00000000 Binary files a/x/bep3/spec/diagrams/BEP3_kava_to_binance_chain.jpg and /dev/null differ diff --git a/x/bep3/types/bep3.pb.go b/x/bep3/types/bep3.pb.go deleted file mode 100644 index 5a9c3ab5..00000000 --- a/x/bep3/types/bep3.pb.go +++ /dev/null @@ -1,2411 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/bep3/v1beta1/bep3.proto - -package types - -import ( - fmt "fmt" - github_com_cometbft_cometbft_libs_bytes "github.com/cometbft/cometbft/libs/bytes" - _ "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" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/durationpb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 - -// SwapStatus is the status of an AtomicSwap -type SwapStatus int32 - -const ( - // SWAP_STATUS_UNSPECIFIED represents an unspecified status - SWAP_STATUS_UNSPECIFIED SwapStatus = 0 - // SWAP_STATUS_OPEN represents an open swap - SWAP_STATUS_OPEN SwapStatus = 1 - // SWAP_STATUS_COMPLETED represents a completed swap - SWAP_STATUS_COMPLETED SwapStatus = 2 - // SWAP_STATUS_EXPIRED represents an expired swap - SWAP_STATUS_EXPIRED SwapStatus = 3 -) - -var SwapStatus_name = map[int32]string{ - 0: "SWAP_STATUS_UNSPECIFIED", - 1: "SWAP_STATUS_OPEN", - 2: "SWAP_STATUS_COMPLETED", - 3: "SWAP_STATUS_EXPIRED", -} - -var SwapStatus_value = map[string]int32{ - "SWAP_STATUS_UNSPECIFIED": 0, - "SWAP_STATUS_OPEN": 1, - "SWAP_STATUS_COMPLETED": 2, - "SWAP_STATUS_EXPIRED": 3, -} - -func (x SwapStatus) String() string { - return proto.EnumName(SwapStatus_name, int32(x)) -} - -func (SwapStatus) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_01a01937d931b013, []int{0} -} - -// SwapDirection is the direction of an AtomicSwap -type SwapDirection int32 - -const ( - // SWAP_DIRECTION_UNSPECIFIED represents unspecified or invalid swap direcation - SWAP_DIRECTION_UNSPECIFIED SwapDirection = 0 - // SWAP_DIRECTION_INCOMING represents is incoming swap (to the kava chain) - SWAP_DIRECTION_INCOMING SwapDirection = 1 - // SWAP_DIRECTION_OUTGOING represents an outgoing swap (from the kava chain) - SWAP_DIRECTION_OUTGOING SwapDirection = 2 -) - -var SwapDirection_name = map[int32]string{ - 0: "SWAP_DIRECTION_UNSPECIFIED", - 1: "SWAP_DIRECTION_INCOMING", - 2: "SWAP_DIRECTION_OUTGOING", -} - -var SwapDirection_value = map[string]int32{ - "SWAP_DIRECTION_UNSPECIFIED": 0, - "SWAP_DIRECTION_INCOMING": 1, - "SWAP_DIRECTION_OUTGOING": 2, -} - -func (x SwapDirection) String() string { - return proto.EnumName(SwapDirection_name, int32(x)) -} - -func (SwapDirection) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_01a01937d931b013, []int{1} -} - -// Params defines the parameters for the bep3 module. -type Params struct { - // asset_params define the parameters for each bep3 asset - AssetParams AssetParams `protobuf:"bytes,1,rep,name=asset_params,json=assetParams,proto3,castrepeated=AssetParams" json:"asset_params"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_01a01937d931b013, []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 (m *Params) GetAssetParams() AssetParams { - if m != nil { - return m.AssetParams - } - return nil -} - -// AssetParam defines parameters for each bep3 asset. -type AssetParam struct { - // denom represents the denominatin for this asset - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - // coin_id represents the registered coin type to use (https://github.com/satoshilabs/slips/blob/master/slip-0044.md) - CoinID int64 `protobuf:"varint,2,opt,name=coin_id,json=coinId,proto3" json:"coin_id,omitempty"` - // supply_limit defines the maximum supply allowed for the asset - a total or time based rate limit - SupplyLimit SupplyLimit `protobuf:"bytes,3,opt,name=supply_limit,json=supplyLimit,proto3" json:"supply_limit"` - // active specifies if the asset is live or paused - Active bool `protobuf:"varint,4,opt,name=active,proto3" json:"active,omitempty"` - // deputy_address the kava address of the deputy - DeputyAddress github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,5,opt,name=deputy_address,json=deputyAddress,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"deputy_address,omitempty"` - // fixed_fee defines the fee for incoming swaps - FixedFee github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,6,opt,name=fixed_fee,json=fixedFee,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"fixed_fee"` - // min_swap_amount defines the minimum amount able to be swapped in a single message - MinSwapAmount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,7,opt,name=min_swap_amount,json=minSwapAmount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"min_swap_amount"` - // max_swap_amount defines the maximum amount able to be swapped in a single message - MaxSwapAmount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,8,opt,name=max_swap_amount,json=maxSwapAmount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"max_swap_amount"` - // min_block_lock defined the minimum blocks to lock - MinBlockLock uint64 `protobuf:"varint,9,opt,name=min_block_lock,json=minBlockLock,proto3" json:"min_block_lock,omitempty"` - // min_block_lock defined the maximum blocks to lock - MaxBlockLock uint64 `protobuf:"varint,10,opt,name=max_block_lock,json=maxBlockLock,proto3" json:"max_block_lock,omitempty"` -} - -func (m *AssetParam) Reset() { *m = AssetParam{} } -func (m *AssetParam) String() string { return proto.CompactTextString(m) } -func (*AssetParam) ProtoMessage() {} -func (*AssetParam) Descriptor() ([]byte, []int) { - return fileDescriptor_01a01937d931b013, []int{1} -} -func (m *AssetParam) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AssetParam) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AssetParam.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 *AssetParam) XXX_Merge(src proto.Message) { - xxx_messageInfo_AssetParam.Merge(m, src) -} -func (m *AssetParam) XXX_Size() int { - return m.Size() -} -func (m *AssetParam) XXX_DiscardUnknown() { - xxx_messageInfo_AssetParam.DiscardUnknown(m) -} - -var xxx_messageInfo_AssetParam proto.InternalMessageInfo - -func (m *AssetParam) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *AssetParam) GetCoinID() int64 { - if m != nil { - return m.CoinID - } - return 0 -} - -func (m *AssetParam) GetSupplyLimit() SupplyLimit { - if m != nil { - return m.SupplyLimit - } - return SupplyLimit{} -} - -func (m *AssetParam) GetActive() bool { - if m != nil { - return m.Active - } - return false -} - -func (m *AssetParam) GetDeputyAddress() github_com_cosmos_cosmos_sdk_types.AccAddress { - if m != nil { - return m.DeputyAddress - } - return nil -} - -func (m *AssetParam) GetMinBlockLock() uint64 { - if m != nil { - return m.MinBlockLock - } - return 0 -} - -func (m *AssetParam) GetMaxBlockLock() uint64 { - if m != nil { - return m.MaxBlockLock - } - return 0 -} - -// SupplyLimit define the absolute and time-based limits for an assets's supply. -type SupplyLimit struct { - // limit defines the total supply allowed - Limit github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,1,opt,name=limit,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"limit"` - // time_limited enables or disables time based supply limiting - TimeLimited bool `protobuf:"varint,2,opt,name=time_limited,json=timeLimited,proto3" json:"time_limited,omitempty"` - // time_period specifies the duration that time_based_limit is evalulated - TimePeriod time.Duration `protobuf:"bytes,3,opt,name=time_period,json=timePeriod,proto3,stdduration" json:"time_period"` - // time_based_limit defines the maximum supply that can be swapped within time_period - TimeBasedLimit github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,4,opt,name=time_based_limit,json=timeBasedLimit,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"time_based_limit"` -} - -func (m *SupplyLimit) Reset() { *m = SupplyLimit{} } -func (m *SupplyLimit) String() string { return proto.CompactTextString(m) } -func (*SupplyLimit) ProtoMessage() {} -func (*SupplyLimit) Descriptor() ([]byte, []int) { - return fileDescriptor_01a01937d931b013, []int{2} -} -func (m *SupplyLimit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SupplyLimit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SupplyLimit.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 *SupplyLimit) XXX_Merge(src proto.Message) { - xxx_messageInfo_SupplyLimit.Merge(m, src) -} -func (m *SupplyLimit) XXX_Size() int { - return m.Size() -} -func (m *SupplyLimit) XXX_DiscardUnknown() { - xxx_messageInfo_SupplyLimit.DiscardUnknown(m) -} - -var xxx_messageInfo_SupplyLimit proto.InternalMessageInfo - -func (m *SupplyLimit) GetTimeLimited() bool { - if m != nil { - return m.TimeLimited - } - return false -} - -func (m *SupplyLimit) GetTimePeriod() time.Duration { - if m != nil { - return m.TimePeriod - } - return 0 -} - -// AtomicSwap defines an atomic swap between chains for the pricefeed module. -type AtomicSwap struct { - // amount represents the amount being swapped - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` - // random_number_hash represents the hash of the random number - RandomNumberHash github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,2,opt,name=random_number_hash,json=randomNumberHash,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"random_number_hash,omitempty"` - // expire_height represents the height when the swap expires - ExpireHeight uint64 `protobuf:"varint,3,opt,name=expire_height,json=expireHeight,proto3" json:"expire_height,omitempty"` - // timestamp represents the timestamp of the swap - Timestamp int64 `protobuf:"varint,4,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - // sender is the kava chain sender of the swap - Sender github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,5,opt,name=sender,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"sender,omitempty"` - // recipient is the kava chain recipient of the swap - Recipient github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,6,opt,name=recipient,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"recipient,omitempty"` - // sender_other_chain is the sender on the other chain - SenderOtherChain string `protobuf:"bytes,7,opt,name=sender_other_chain,json=senderOtherChain,proto3" json:"sender_other_chain,omitempty"` - // recipient_other_chain is the recipient on the other chain - RecipientOtherChain string `protobuf:"bytes,8,opt,name=recipient_other_chain,json=recipientOtherChain,proto3" json:"recipient_other_chain,omitempty"` - // closed_block is the block when the swap is closed - ClosedBlock int64 `protobuf:"varint,9,opt,name=closed_block,json=closedBlock,proto3" json:"closed_block,omitempty"` - // status represents the current status of the swap - Status SwapStatus `protobuf:"varint,10,opt,name=status,proto3,enum=kava.bep3.v1beta1.SwapStatus" json:"status,omitempty"` - // cross_chain identifies whether the atomic swap is cross chain - CrossChain bool `protobuf:"varint,11,opt,name=cross_chain,json=crossChain,proto3" json:"cross_chain,omitempty"` - // direction identifies if the swap is incoming or outgoing - Direction SwapDirection `protobuf:"varint,12,opt,name=direction,proto3,enum=kava.bep3.v1beta1.SwapDirection" json:"direction,omitempty"` -} - -func (m *AtomicSwap) Reset() { *m = AtomicSwap{} } -func (m *AtomicSwap) String() string { return proto.CompactTextString(m) } -func (*AtomicSwap) ProtoMessage() {} -func (*AtomicSwap) Descriptor() ([]byte, []int) { - return fileDescriptor_01a01937d931b013, []int{3} -} -func (m *AtomicSwap) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AtomicSwap) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AtomicSwap.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 *AtomicSwap) XXX_Merge(src proto.Message) { - xxx_messageInfo_AtomicSwap.Merge(m, src) -} -func (m *AtomicSwap) XXX_Size() int { - return m.Size() -} -func (m *AtomicSwap) XXX_DiscardUnknown() { - xxx_messageInfo_AtomicSwap.DiscardUnknown(m) -} - -var xxx_messageInfo_AtomicSwap proto.InternalMessageInfo - -func (m *AtomicSwap) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -func (m *AtomicSwap) GetRandomNumberHash() github_com_cometbft_cometbft_libs_bytes.HexBytes { - if m != nil { - return m.RandomNumberHash - } - return nil -} - -func (m *AtomicSwap) GetExpireHeight() uint64 { - if m != nil { - return m.ExpireHeight - } - return 0 -} - -func (m *AtomicSwap) GetTimestamp() int64 { - if m != nil { - return m.Timestamp - } - return 0 -} - -func (m *AtomicSwap) GetSender() github_com_cosmos_cosmos_sdk_types.AccAddress { - if m != nil { - return m.Sender - } - return nil -} - -func (m *AtomicSwap) GetRecipient() github_com_cosmos_cosmos_sdk_types.AccAddress { - if m != nil { - return m.Recipient - } - return nil -} - -func (m *AtomicSwap) GetSenderOtherChain() string { - if m != nil { - return m.SenderOtherChain - } - return "" -} - -func (m *AtomicSwap) GetRecipientOtherChain() string { - if m != nil { - return m.RecipientOtherChain - } - return "" -} - -func (m *AtomicSwap) GetClosedBlock() int64 { - if m != nil { - return m.ClosedBlock - } - return 0 -} - -func (m *AtomicSwap) GetStatus() SwapStatus { - if m != nil { - return m.Status - } - return SWAP_STATUS_UNSPECIFIED -} - -func (m *AtomicSwap) GetCrossChain() bool { - if m != nil { - return m.CrossChain - } - return false -} - -func (m *AtomicSwap) GetDirection() SwapDirection { - if m != nil { - return m.Direction - } - return SWAP_DIRECTION_UNSPECIFIED -} - -// AssetSupply defines information about an asset's supply. -type AssetSupply struct { - // incoming_supply represents the incoming supply of an asset - IncomingSupply types.Coin `protobuf:"bytes,1,opt,name=incoming_supply,json=incomingSupply,proto3" json:"incoming_supply"` - // outgoing_supply represents the outgoing supply of an asset - OutgoingSupply types.Coin `protobuf:"bytes,2,opt,name=outgoing_supply,json=outgoingSupply,proto3" json:"outgoing_supply"` - // current_supply represents the current on-chain supply of an asset - CurrentSupply types.Coin `protobuf:"bytes,3,opt,name=current_supply,json=currentSupply,proto3" json:"current_supply"` - // time_limited_current_supply represents the time limited current supply of an asset - TimeLimitedCurrentSupply types.Coin `protobuf:"bytes,4,opt,name=time_limited_current_supply,json=timeLimitedCurrentSupply,proto3" json:"time_limited_current_supply"` - // time_elapsed represents the time elapsed - TimeElapsed time.Duration `protobuf:"bytes,5,opt,name=time_elapsed,json=timeElapsed,proto3,stdduration" json:"time_elapsed"` -} - -func (m *AssetSupply) Reset() { *m = AssetSupply{} } -func (m *AssetSupply) String() string { return proto.CompactTextString(m) } -func (*AssetSupply) ProtoMessage() {} -func (*AssetSupply) Descriptor() ([]byte, []int) { - return fileDescriptor_01a01937d931b013, []int{4} -} -func (m *AssetSupply) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AssetSupply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AssetSupply.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 *AssetSupply) XXX_Merge(src proto.Message) { - xxx_messageInfo_AssetSupply.Merge(m, src) -} -func (m *AssetSupply) XXX_Size() int { - return m.Size() -} -func (m *AssetSupply) XXX_DiscardUnknown() { - xxx_messageInfo_AssetSupply.DiscardUnknown(m) -} - -var xxx_messageInfo_AssetSupply proto.InternalMessageInfo - -func (m *AssetSupply) GetIncomingSupply() types.Coin { - if m != nil { - return m.IncomingSupply - } - return types.Coin{} -} - -func (m *AssetSupply) GetOutgoingSupply() types.Coin { - if m != nil { - return m.OutgoingSupply - } - return types.Coin{} -} - -func (m *AssetSupply) GetCurrentSupply() types.Coin { - if m != nil { - return m.CurrentSupply - } - return types.Coin{} -} - -func (m *AssetSupply) GetTimeLimitedCurrentSupply() types.Coin { - if m != nil { - return m.TimeLimitedCurrentSupply - } - return types.Coin{} -} - -func (m *AssetSupply) GetTimeElapsed() time.Duration { - if m != nil { - return m.TimeElapsed - } - return 0 -} - -func init() { - proto.RegisterEnum("kava.bep3.v1beta1.SwapStatus", SwapStatus_name, SwapStatus_value) - proto.RegisterEnum("kava.bep3.v1beta1.SwapDirection", SwapDirection_name, SwapDirection_value) - proto.RegisterType((*Params)(nil), "kava.bep3.v1beta1.Params") - proto.RegisterType((*AssetParam)(nil), "kava.bep3.v1beta1.AssetParam") - proto.RegisterType((*SupplyLimit)(nil), "kava.bep3.v1beta1.SupplyLimit") - proto.RegisterType((*AtomicSwap)(nil), "kava.bep3.v1beta1.AtomicSwap") - proto.RegisterType((*AssetSupply)(nil), "kava.bep3.v1beta1.AssetSupply") -} - -func init() { proto.RegisterFile("kava/bep3/v1beta1/bep3.proto", fileDescriptor_01a01937d931b013) } - -var fileDescriptor_01a01937d931b013 = []byte{ - // 1147 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x56, 0x4d, 0x6f, 0x1a, 0x57, - 0x17, 0xf6, 0x18, 0x4c, 0xec, 0x03, 0x26, 0xbc, 0xd7, 0xc9, 0x1b, 0xec, 0xa4, 0x40, 0x9c, 0xaa, - 0x42, 0x51, 0x0d, 0xf9, 0x68, 0x77, 0x55, 0x55, 0x06, 0x70, 0x8c, 0xe4, 0x00, 0x1a, 0x6c, 0xf5, - 0x63, 0xd1, 0xe9, 0x9d, 0x99, 0x0b, 0x5c, 0x99, 0x99, 0x3b, 0x9a, 0x3b, 0x24, 0xf8, 0x1f, 0x74, - 0xd1, 0x45, 0xbb, 0xeb, 0xbe, 0xbb, 0x2e, 0xab, 0xfc, 0x88, 0x2c, 0xa3, 0xac, 0xaa, 0x2e, 0x9c, - 0xca, 0xf9, 0x17, 0xd9, 0xb4, 0xba, 0x1f, 0x06, 0x9c, 0xba, 0x15, 0x0b, 0x36, 0xf6, 0x9c, 0xaf, - 0xe7, 0x9c, 0xb9, 0x73, 0x9e, 0xe7, 0x02, 0x77, 0x4e, 0xf0, 0x33, 0x5c, 0x75, 0x48, 0xf8, 0xb8, - 0xfa, 0xec, 0xa1, 0x43, 0x62, 0xfc, 0x50, 0x1a, 0x95, 0x30, 0x62, 0x31, 0x43, 0xff, 0x13, 0xd1, - 0x8a, 0x74, 0xe8, 0xe8, 0x4e, 0xc1, 0x65, 0xdc, 0x67, 0xbc, 0xea, 0x60, 0x4e, 0xa6, 0x25, 0x2e, - 0xa3, 0x81, 0x2a, 0xd9, 0xd9, 0x56, 0x71, 0x5b, 0x5a, 0x55, 0x65, 0xe8, 0xd0, 0x8d, 0x01, 0x1b, - 0x30, 0xe5, 0x17, 0x4f, 0xda, 0x5b, 0x18, 0x30, 0x36, 0x18, 0x91, 0xaa, 0xb4, 0x9c, 0x71, 0xbf, - 0xea, 0x8d, 0x23, 0x1c, 0x53, 0xa6, 0x01, 0x77, 0x6d, 0x48, 0x75, 0x71, 0x84, 0x7d, 0x8e, 0x8e, - 0x21, 0x83, 0x39, 0x27, 0xb1, 0x1d, 0x4a, 0x3b, 0x6f, 0x94, 0x12, 0xe5, 0xf4, 0xa3, 0x0f, 0x2a, - 0xff, 0x18, 0xb2, 0x52, 0x13, 0x69, 0xb2, 0xca, 0xdc, 0x7a, 0x79, 0x56, 0x5c, 0xf9, 0xf5, 0x4d, - 0x31, 0x3d, 0xf3, 0x71, 0x2b, 0x8d, 0x67, 0xc6, 0xee, 0x0f, 0x6b, 0x00, 0xb3, 0x20, 0xba, 0x01, - 0x6b, 0x1e, 0x09, 0x98, 0x9f, 0x37, 0x4a, 0x46, 0x79, 0xc3, 0x52, 0x06, 0xba, 0x07, 0xd7, 0xc4, - 0x4b, 0xda, 0xd4, 0xcb, 0xaf, 0x96, 0x8c, 0x72, 0xc2, 0x84, 0xf3, 0xb3, 0x62, 0xaa, 0xce, 0x68, - 0xd0, 0x6a, 0x58, 0x29, 0x11, 0x6a, 0x79, 0xe8, 0x09, 0x64, 0xf8, 0x38, 0x0c, 0x47, 0xa7, 0xf6, - 0x88, 0xfa, 0x34, 0xce, 0x27, 0x4a, 0x46, 0x39, 0xfd, 0xa8, 0x70, 0xc5, 0x80, 0x3d, 0x99, 0x76, - 0x28, 0xb2, 0xcc, 0xa4, 0x98, 0xd0, 0x4a, 0xf3, 0x99, 0x0b, 0xfd, 0x1f, 0x52, 0xd8, 0x8d, 0xe9, - 0x33, 0x92, 0x4f, 0x96, 0x8c, 0xf2, 0xba, 0xa5, 0x2d, 0xc4, 0x20, 0xeb, 0x91, 0x70, 0x1c, 0x9f, - 0xda, 0xd8, 0xf3, 0x22, 0xc2, 0x79, 0x7e, 0xad, 0x64, 0x94, 0x33, 0xe6, 0xc1, 0xbb, 0xb3, 0xe2, - 0xde, 0x80, 0xc6, 0xc3, 0xb1, 0x53, 0x71, 0x99, 0xaf, 0x8f, 0x5d, 0xff, 0xdb, 0xe3, 0xde, 0x49, - 0x35, 0x3e, 0x0d, 0x09, 0xaf, 0xd4, 0x5c, 0xb7, 0xa6, 0x0a, 0x5f, 0xbf, 0xd8, 0xdb, 0xd2, 0x1f, - 0x47, 0x7b, 0xcc, 0xd3, 0x98, 0x70, 0x6b, 0x53, 0xe1, 0x6b, 0x1f, 0xfa, 0x1a, 0x36, 0xfa, 0x74, - 0x42, 0x3c, 0xbb, 0x4f, 0x48, 0x3e, 0x25, 0x0e, 0xc4, 0xfc, 0x4c, 0x8c, 0xfb, 0xc7, 0x59, 0xf1, - 0xa3, 0x05, 0xfa, 0xb5, 0x82, 0xf8, 0xf5, 0x8b, 0x3d, 0xd0, 0x8d, 0x5a, 0x41, 0x6c, 0xad, 0x4b, - 0xb8, 0x7d, 0x42, 0x90, 0x07, 0xd7, 0x7d, 0x1a, 0xd8, 0xfc, 0x39, 0x0e, 0x6d, 0xec, 0xb3, 0x71, - 0x10, 0xe7, 0xaf, 0x2d, 0xa1, 0xc1, 0xa6, 0x4f, 0x83, 0xde, 0x73, 0x1c, 0xd6, 0x24, 0xa4, 0xec, - 0x82, 0x27, 0x97, 0xba, 0xac, 0x2f, 0xa5, 0x0b, 0x9e, 0xcc, 0x75, 0xf9, 0x10, 0xb2, 0xe2, 0x5d, - 0x9c, 0x11, 0x73, 0x4f, 0x6c, 0xf1, 0x27, 0xbf, 0x51, 0x32, 0xca, 0x49, 0x2b, 0xe3, 0xd3, 0xc0, - 0x14, 0xf6, 0x21, 0x73, 0x4f, 0x64, 0x16, 0x9e, 0xcc, 0x67, 0x81, 0xce, 0xc2, 0x93, 0x69, 0xd6, - 0xee, 0x6f, 0xab, 0x90, 0x9e, 0x5b, 0x0f, 0x64, 0xc1, 0x9a, 0xda, 0x26, 0x63, 0x09, 0x73, 0x2b, - 0x28, 0x74, 0x17, 0x32, 0x31, 0xf5, 0x89, 0x5a, 0x53, 0xa2, 0x56, 0x7a, 0xdd, 0x4a, 0x0b, 0xdf, - 0xa1, 0x72, 0xa1, 0x06, 0x48, 0xd3, 0x0e, 0x49, 0x44, 0x99, 0xa7, 0x57, 0x79, 0xbb, 0xa2, 0xc8, - 0x5a, 0xb9, 0x20, 0x6b, 0xa5, 0xa1, 0xc9, 0x6a, 0xae, 0x8b, 0xb9, 0x7e, 0x7e, 0x53, 0x34, 0x2c, - 0x10, 0x75, 0x5d, 0x59, 0x86, 0xfa, 0x90, 0x93, 0x28, 0x42, 0x2d, 0x3c, 0xcd, 0x8a, 0xe4, 0x12, - 0xde, 0x23, 0x2b, 0x50, 0x4d, 0x01, 0x2a, 0xe7, 0xdd, 0xfd, 0x4b, 0x70, 0x38, 0x66, 0x3e, 0x75, - 0xc5, 0x57, 0x41, 0x2e, 0xa4, 0xf4, 0xc7, 0x56, 0x1a, 0xb1, 0x5d, 0xd1, 0xb5, 0x62, 0x8e, 0x29, - 0x09, 0x05, 0x7b, 0xcd, 0x07, 0x5a, 0x1f, 0xca, 0x0b, 0xcc, 0x21, 0x0a, 0xb8, 0xa5, 0xa1, 0x91, - 0x03, 0x28, 0xc2, 0x81, 0xc7, 0x7c, 0x3b, 0x18, 0xfb, 0x0e, 0x89, 0xec, 0x21, 0xe6, 0x43, 0x79, - 0x94, 0x19, 0xf3, 0x93, 0x77, 0x67, 0xc5, 0x07, 0x97, 0x10, 0x7d, 0x12, 0x3b, 0xfd, 0x78, 0xf6, - 0x30, 0xa2, 0x0e, 0xaf, 0x3a, 0x82, 0x73, 0x95, 0x03, 0x32, 0x51, 0xe4, 0xcb, 0x29, 0xbc, 0xb6, - 0x84, 0x3b, 0xc0, 0x7c, 0x88, 0xee, 0xc1, 0x26, 0x99, 0x84, 0x34, 0x22, 0xf6, 0x90, 0xd0, 0xc1, - 0x50, 0x49, 0x4a, 0xd2, 0xca, 0x28, 0xe7, 0x81, 0xf4, 0xa1, 0x3b, 0xb0, 0x21, 0x8e, 0x83, 0xc7, - 0xd8, 0x0f, 0xe5, 0xe9, 0x26, 0xac, 0x99, 0x03, 0x7d, 0x07, 0x29, 0x4e, 0x02, 0x8f, 0x44, 0x4b, - 0xd7, 0x0a, 0x8d, 0x8b, 0xfa, 0xb0, 0x11, 0x11, 0x97, 0x86, 0x94, 0x04, 0xb1, 0x14, 0x89, 0x65, - 0x36, 0x99, 0x41, 0xa3, 0x8f, 0x01, 0xa9, 0x8e, 0x36, 0x8b, 0x87, 0x24, 0xb2, 0xdd, 0x21, 0xa6, - 0x81, 0x12, 0x0d, 0x2b, 0xa7, 0x22, 0x1d, 0x11, 0xa8, 0x0b, 0x3f, 0x7a, 0x04, 0x37, 0xa7, 0xa5, - 0x97, 0x0a, 0x24, 0xff, 0xad, 0xad, 0x69, 0x70, 0xae, 0xe6, 0x2e, 0x64, 0xdc, 0x11, 0x13, 0xab, - 0xea, 0x4c, 0x59, 0x9c, 0xb0, 0xd2, 0xca, 0x27, 0x29, 0x8a, 0x3e, 0x85, 0x14, 0x8f, 0x71, 0x3c, - 0xe6, 0x92, 0xbc, 0xd9, 0x2b, 0xaf, 0x1f, 0xb1, 0x83, 0x3d, 0x99, 0x64, 0xe9, 0x64, 0x54, 0x84, - 0xb4, 0x1b, 0x31, 0xce, 0xf5, 0x0c, 0x69, 0x49, 0x38, 0x90, 0x2e, 0xd5, 0xfa, 0x73, 0xd8, 0xf0, - 0x68, 0x44, 0x5c, 0x41, 0xa6, 0x7c, 0x46, 0x42, 0x97, 0xfe, 0x05, 0xba, 0x71, 0x91, 0x67, 0xcd, - 0x4a, 0x76, 0x7f, 0x4a, 0x80, 0xba, 0xe2, 0x94, 0x76, 0xa0, 0x03, 0xb8, 0x4e, 0x03, 0x97, 0xf9, - 0x34, 0x18, 0xd8, 0xea, 0x6a, 0x91, 0x02, 0xf2, 0x9f, 0x5c, 0x50, 0x37, 0x51, 0xf6, 0xa2, 0x6e, - 0x86, 0xc4, 0xc6, 0xf1, 0x80, 0xcd, 0x21, 0xad, 0x2e, 0x88, 0x74, 0x51, 0xa7, 0x91, 0xf6, 0x21, - 0xeb, 0x8e, 0xa3, 0x48, 0x7c, 0x10, 0x0d, 0x94, 0x58, 0x0c, 0x68, 0x53, 0x97, 0x69, 0x9c, 0x6f, - 0xe1, 0xf6, 0xbc, 0x7c, 0xd9, 0xef, 0x81, 0x26, 0x17, 0x03, 0xcd, 0xcf, 0xc9, 0x5d, 0xfd, 0x12, - 0xfe, 0xbe, 0x96, 0x47, 0x32, 0xc2, 0x21, 0x27, 0x9e, 0x24, 0xce, 0x82, 0xe2, 0x27, 0x45, 0xb3, - 0xa9, 0xea, 0xee, 0x9f, 0x02, 0xcc, 0x56, 0x01, 0xdd, 0x86, 0x5b, 0xbd, 0x2f, 0x6b, 0x5d, 0xbb, - 0x77, 0x54, 0x3b, 0x3a, 0xee, 0xd9, 0xc7, 0xed, 0x5e, 0xb7, 0x59, 0x6f, 0xed, 0xb7, 0x9a, 0x8d, - 0xdc, 0x0a, 0xba, 0x01, 0xb9, 0xf9, 0x60, 0xa7, 0xdb, 0x6c, 0xe7, 0x0c, 0xb4, 0x0d, 0x37, 0xe7, - 0xbd, 0xf5, 0xce, 0xd3, 0xee, 0x61, 0xf3, 0xa8, 0xd9, 0xc8, 0xad, 0xa2, 0x5b, 0xb0, 0x35, 0x1f, - 0x6a, 0x7e, 0xd5, 0x6d, 0x59, 0xcd, 0x46, 0x2e, 0xb1, 0x93, 0xfc, 0xfe, 0x97, 0xc2, 0xca, 0x7d, - 0x06, 0x9b, 0x97, 0x56, 0x05, 0x15, 0x60, 0x47, 0xe6, 0x37, 0x5a, 0x56, 0xb3, 0x7e, 0xd4, 0xea, - 0xb4, 0xdf, 0x1b, 0xe0, 0x62, 0xba, 0x59, 0xbc, 0xd5, 0xae, 0x77, 0x9e, 0xb6, 0xda, 0x4f, 0x72, - 0xc6, 0x15, 0xc1, 0xce, 0xf1, 0xd1, 0x93, 0x8e, 0x08, 0xae, 0xaa, 0x86, 0xe6, 0x17, 0x2f, 0xcf, - 0x0b, 0xc6, 0xab, 0xf3, 0x82, 0xf1, 0xe7, 0x79, 0xc1, 0xf8, 0xf1, 0x6d, 0x61, 0xe5, 0xd5, 0xdb, - 0xc2, 0xca, 0xef, 0x6f, 0x0b, 0x2b, 0xdf, 0xcc, 0x2b, 0xbc, 0x58, 0xe8, 0xbd, 0x11, 0x76, 0xb8, - 0x7c, 0xaa, 0x4e, 0xd4, 0x2f, 0x4f, 0xa9, 0x05, 0x4e, 0x4a, 0x9e, 0xeb, 0xe3, 0xbf, 0x03, 0x00, - 0x00, 0xff, 0xff, 0x79, 0xfe, 0xe7, 0xb2, 0x93, 0x0a, 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 - if len(m.AssetParams) > 0 { - for iNdEx := len(m.AssetParams) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.AssetParams[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintBep3(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *AssetParam) 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 *AssetParam) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AssetParam) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.MaxBlockLock != 0 { - i = encodeVarintBep3(dAtA, i, uint64(m.MaxBlockLock)) - i-- - dAtA[i] = 0x50 - } - if m.MinBlockLock != 0 { - i = encodeVarintBep3(dAtA, i, uint64(m.MinBlockLock)) - i-- - dAtA[i] = 0x48 - } - { - size := m.MaxSwapAmount.Size() - i -= size - if _, err := m.MaxSwapAmount.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintBep3(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - { - size := m.MinSwapAmount.Size() - i -= size - if _, err := m.MinSwapAmount.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintBep3(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - { - size := m.FixedFee.Size() - i -= size - if _, err := m.FixedFee.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintBep3(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - if len(m.DeputyAddress) > 0 { - i -= len(m.DeputyAddress) - copy(dAtA[i:], m.DeputyAddress) - i = encodeVarintBep3(dAtA, i, uint64(len(m.DeputyAddress))) - i-- - dAtA[i] = 0x2a - } - if m.Active { - i-- - if m.Active { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x20 - } - { - size, err := m.SupplyLimit.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintBep3(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if m.CoinID != 0 { - i = encodeVarintBep3(dAtA, i, uint64(m.CoinID)) - i-- - dAtA[i] = 0x10 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintBep3(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *SupplyLimit) 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 *SupplyLimit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SupplyLimit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.TimeBasedLimit.Size() - i -= size - if _, err := m.TimeBasedLimit.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintBep3(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - n2, err2 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.TimePeriod, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.TimePeriod):]) - if err2 != nil { - return 0, err2 - } - i -= n2 - i = encodeVarintBep3(dAtA, i, uint64(n2)) - i-- - dAtA[i] = 0x1a - if m.TimeLimited { - i-- - if m.TimeLimited { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x10 - } - { - size := m.Limit.Size() - i -= size - if _, err := m.Limit.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintBep3(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *AtomicSwap) 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 *AtomicSwap) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AtomicSwap) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Direction != 0 { - i = encodeVarintBep3(dAtA, i, uint64(m.Direction)) - i-- - dAtA[i] = 0x60 - } - if m.CrossChain { - i-- - if m.CrossChain { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x58 - } - if m.Status != 0 { - i = encodeVarintBep3(dAtA, i, uint64(m.Status)) - i-- - dAtA[i] = 0x50 - } - if m.ClosedBlock != 0 { - i = encodeVarintBep3(dAtA, i, uint64(m.ClosedBlock)) - i-- - dAtA[i] = 0x48 - } - if len(m.RecipientOtherChain) > 0 { - i -= len(m.RecipientOtherChain) - copy(dAtA[i:], m.RecipientOtherChain) - i = encodeVarintBep3(dAtA, i, uint64(len(m.RecipientOtherChain))) - i-- - dAtA[i] = 0x42 - } - if len(m.SenderOtherChain) > 0 { - i -= len(m.SenderOtherChain) - copy(dAtA[i:], m.SenderOtherChain) - i = encodeVarintBep3(dAtA, i, uint64(len(m.SenderOtherChain))) - i-- - dAtA[i] = 0x3a - } - if len(m.Recipient) > 0 { - i -= len(m.Recipient) - copy(dAtA[i:], m.Recipient) - i = encodeVarintBep3(dAtA, i, uint64(len(m.Recipient))) - i-- - dAtA[i] = 0x32 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintBep3(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0x2a - } - if m.Timestamp != 0 { - i = encodeVarintBep3(dAtA, i, uint64(m.Timestamp)) - i-- - dAtA[i] = 0x20 - } - if m.ExpireHeight != 0 { - i = encodeVarintBep3(dAtA, i, uint64(m.ExpireHeight)) - i-- - dAtA[i] = 0x18 - } - if len(m.RandomNumberHash) > 0 { - i -= len(m.RandomNumberHash) - copy(dAtA[i:], m.RandomNumberHash) - i = encodeVarintBep3(dAtA, i, uint64(len(m.RandomNumberHash))) - i-- - dAtA[i] = 0x12 - } - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintBep3(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *AssetSupply) 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 *AssetSupply) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AssetSupply) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - n3, err3 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.TimeElapsed, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.TimeElapsed):]) - if err3 != nil { - return 0, err3 - } - i -= n3 - i = encodeVarintBep3(dAtA, i, uint64(n3)) - i-- - dAtA[i] = 0x2a - { - size, err := m.TimeLimitedCurrentSupply.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintBep3(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.CurrentSupply.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintBep3(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.OutgoingSupply.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintBep3(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.IncomingSupply.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintBep3(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintBep3(dAtA []byte, offset int, v uint64) int { - offset -= sovBep3(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 - if len(m.AssetParams) > 0 { - for _, e := range m.AssetParams { - l = e.Size() - n += 1 + l + sovBep3(uint64(l)) - } - } - return n -} - -func (m *AssetParam) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovBep3(uint64(l)) - } - if m.CoinID != 0 { - n += 1 + sovBep3(uint64(m.CoinID)) - } - l = m.SupplyLimit.Size() - n += 1 + l + sovBep3(uint64(l)) - if m.Active { - n += 2 - } - l = len(m.DeputyAddress) - if l > 0 { - n += 1 + l + sovBep3(uint64(l)) - } - l = m.FixedFee.Size() - n += 1 + l + sovBep3(uint64(l)) - l = m.MinSwapAmount.Size() - n += 1 + l + sovBep3(uint64(l)) - l = m.MaxSwapAmount.Size() - n += 1 + l + sovBep3(uint64(l)) - if m.MinBlockLock != 0 { - n += 1 + sovBep3(uint64(m.MinBlockLock)) - } - if m.MaxBlockLock != 0 { - n += 1 + sovBep3(uint64(m.MaxBlockLock)) - } - return n -} - -func (m *SupplyLimit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Limit.Size() - n += 1 + l + sovBep3(uint64(l)) - if m.TimeLimited { - n += 2 - } - l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.TimePeriod) - n += 1 + l + sovBep3(uint64(l)) - l = m.TimeBasedLimit.Size() - n += 1 + l + sovBep3(uint64(l)) - return n -} - -func (m *AtomicSwap) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovBep3(uint64(l)) - } - } - l = len(m.RandomNumberHash) - if l > 0 { - n += 1 + l + sovBep3(uint64(l)) - } - if m.ExpireHeight != 0 { - n += 1 + sovBep3(uint64(m.ExpireHeight)) - } - if m.Timestamp != 0 { - n += 1 + sovBep3(uint64(m.Timestamp)) - } - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovBep3(uint64(l)) - } - l = len(m.Recipient) - if l > 0 { - n += 1 + l + sovBep3(uint64(l)) - } - l = len(m.SenderOtherChain) - if l > 0 { - n += 1 + l + sovBep3(uint64(l)) - } - l = len(m.RecipientOtherChain) - if l > 0 { - n += 1 + l + sovBep3(uint64(l)) - } - if m.ClosedBlock != 0 { - n += 1 + sovBep3(uint64(m.ClosedBlock)) - } - if m.Status != 0 { - n += 1 + sovBep3(uint64(m.Status)) - } - if m.CrossChain { - n += 2 - } - if m.Direction != 0 { - n += 1 + sovBep3(uint64(m.Direction)) - } - return n -} - -func (m *AssetSupply) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.IncomingSupply.Size() - n += 1 + l + sovBep3(uint64(l)) - l = m.OutgoingSupply.Size() - n += 1 + l + sovBep3(uint64(l)) - l = m.CurrentSupply.Size() - n += 1 + l + sovBep3(uint64(l)) - l = m.TimeLimitedCurrentSupply.Size() - n += 1 + l + sovBep3(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.TimeElapsed) - n += 1 + l + sovBep3(uint64(l)) - return n -} - -func sovBep3(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozBep3(x uint64) (n int) { - return sovBep3(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 ErrIntOverflowBep3 - } - 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 { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AssetParams", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthBep3 - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AssetParams = append(m.AssetParams, AssetParam{}) - if err := m.AssetParams[len(m.AssetParams)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipBep3(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthBep3 - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *AssetParam) 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 ErrIntOverflowBep3 - } - 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: AssetParam: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AssetParam: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - 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 ErrInvalidLengthBep3 - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CoinID", wireType) - } - m.CoinID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CoinID |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SupplyLimit", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthBep3 - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SupplyLimit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Active", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Active = bool(v != 0) - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DeputyAddress", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthBep3 - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DeputyAddress = append(m.DeputyAddress[:0], dAtA[iNdEx:postIndex]...) - if m.DeputyAddress == nil { - m.DeputyAddress = []byte{} - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FixedFee", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - 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 ErrInvalidLengthBep3 - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FixedFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MinSwapAmount", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - 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 ErrInvalidLengthBep3 - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MinSwapAmount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaxSwapAmount", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - 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 ErrInvalidLengthBep3 - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MaxSwapAmount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 9: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field MinBlockLock", wireType) - } - m.MinBlockLock = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.MinBlockLock |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 10: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field MaxBlockLock", wireType) - } - m.MaxBlockLock = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.MaxBlockLock |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipBep3(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthBep3 - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *SupplyLimit) 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 ErrIntOverflowBep3 - } - 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: SupplyLimit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SupplyLimit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - 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 ErrInvalidLengthBep3 - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Limit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TimeLimited", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.TimeLimited = bool(v != 0) - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TimePeriod", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthBep3 - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.TimePeriod, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TimeBasedLimit", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - 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 ErrInvalidLengthBep3 - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TimeBasedLimit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipBep3(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthBep3 - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *AtomicSwap) 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 ErrIntOverflowBep3 - } - 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: AtomicSwap: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AtomicSwap: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthBep3 - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-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 RandomNumberHash", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthBep3 - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RandomNumberHash = append(m.RandomNumberHash[:0], dAtA[iNdEx:postIndex]...) - if m.RandomNumberHash == nil { - m.RandomNumberHash = []byte{} - } - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ExpireHeight", wireType) - } - m.ExpireHeight = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ExpireHeight |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) - } - m.Timestamp = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Timestamp |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthBep3 - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = append(m.Sender[:0], dAtA[iNdEx:postIndex]...) - if m.Sender == nil { - m.Sender = []byte{} - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Recipient", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthBep3 - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Recipient = append(m.Recipient[:0], dAtA[iNdEx:postIndex]...) - if m.Recipient == nil { - m.Recipient = []byte{} - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SenderOtherChain", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - 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 ErrInvalidLengthBep3 - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SenderOtherChain = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RecipientOtherChain", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - 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 ErrInvalidLengthBep3 - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RecipientOtherChain = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 9: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ClosedBlock", wireType) - } - m.ClosedBlock = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ClosedBlock |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 10: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) - } - m.Status = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Status |= SwapStatus(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 11: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CrossChain", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CrossChain = bool(v != 0) - case 12: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Direction", wireType) - } - m.Direction = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Direction |= SwapDirection(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipBep3(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthBep3 - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *AssetSupply) 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 ErrIntOverflowBep3 - } - 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: AssetSupply: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AssetSupply: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IncomingSupply", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthBep3 - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IncomingSupply.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OutgoingSupply", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthBep3 - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.OutgoingSupply.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CurrentSupply", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthBep3 - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.CurrentSupply.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TimeLimitedCurrentSupply", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthBep3 - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TimeLimitedCurrentSupply.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TimeElapsed", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBep3 - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthBep3 - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthBep3 - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.TimeElapsed, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipBep3(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthBep3 - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipBep3(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, ErrIntOverflowBep3 - } - 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, ErrIntOverflowBep3 - } - 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, ErrIntOverflowBep3 - } - 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, ErrInvalidLengthBep3 - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupBep3 - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthBep3 - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthBep3 = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowBep3 = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupBep3 = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/bep3/types/codec.go b/x/bep3/types/codec.go deleted file mode 100644 index dce4de11..00000000 --- a/x/bep3/types/codec.go +++ /dev/null @@ -1,49 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the -// bep3 module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgCreateAtomicSwap{}, "bep3/MsgCreateAtomicSwap", nil) - cdc.RegisterConcrete(&MsgRefundAtomicSwap{}, "bep3/MsgRefundAtomicSwap", nil) - cdc.RegisterConcrete(&MsgClaimAtomicSwap{}, "bep3/MsgClaimAtomicSwap", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgCreateAtomicSwap{}, - &MsgRefundAtomicSwap{}, - &MsgClaimAtomicSwap{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - - // ModuleCdc references the global x/bep3 module codec. Note, the codec should - // ONLY be used in certain instances of tests and for JSON encoding as Amino is - // still used for that purpose. - // - // The actual codec used for serialization should be provided to x/bep3 and - // defined at the application level. - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/bep3/types/common_test.go b/x/bep3/types/common_test.go deleted file mode 100644 index d566a3b0..00000000 --- a/x/bep3/types/common_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package types_test - -import ( - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/x/bep3/types" -) - -func i(in int64) sdkmath.Int { return sdkmath.NewInt(in) } -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } -func ts(minOffset int) int64 { return tmtime.Now().Add(time.Duration(minOffset) * time.Minute).Unix() } - -func atomicSwaps(count int) types.AtomicSwaps { - var swaps types.AtomicSwaps - for i := 0; i < count; i++ { - swap := atomicSwap(i) - swaps = append(swaps, swap) - } - return swaps -} - -func atomicSwap(index int) types.AtomicSwap { - expireOffset := uint64((index * 15) + 360) // Default expire height + offet to match timestamp - timestamp := ts(index) // One minute apart - randomNumber, _ := types.GenerateSecureRandomNumber() - randomNumberHash := types.CalculateRandomHash(randomNumber[:], timestamp) - - swap := types.NewAtomicSwap(cs(c("bnb", 50000)), randomNumberHash, expireOffset, timestamp, kavaAddrs[0], - kavaAddrs[1], binanceAddrs[0].String(), binanceAddrs[1].String(), 1, types.SWAP_STATUS_OPEN, true, types.SWAP_DIRECTION_INCOMING) - - return swap -} diff --git a/x/bep3/types/errors.go b/x/bep3/types/errors.go deleted file mode 100644 index 5a691a47..00000000 --- a/x/bep3/types/errors.go +++ /dev/null @@ -1,46 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// DONTCOVER - -var ( - // ErrInvalidTimestamp error for when an timestamp is outside of bounds. Assumes block time of 10 seconds. - ErrInvalidTimestamp = errorsmod.Register(ModuleName, 2, "timestamp can neither be 15 minutes ahead of the current time, nor 30 minutes later") - // ErrInvalidHeightSpan error for when a proposed height span is outside of lock time range - ErrInvalidHeightSpan = errorsmod.Register(ModuleName, 3, "height span is outside acceptable range") - // ErrInsufficientAmount error for when a swap's amount cannot cover the deputy's fixed fee - ErrInsufficientAmount = errorsmod.Register(ModuleName, 4, "amount cannot cover the deputy fixed fee") - // ErrAssetNotSupported error for when an asset is not supported - ErrAssetNotSupported = errorsmod.Register(ModuleName, 5, "asset not found") - // ErrAssetNotActive error for when an asset is currently inactive - ErrAssetNotActive = errorsmod.Register(ModuleName, 6, "asset is currently inactive") - // ErrAssetSupplyNotFound error for when an asset's supply is not found in the store - ErrAssetSupplyNotFound = errorsmod.Register(ModuleName, 7, "asset supply not found in store") - // ErrExceedsSupplyLimit error for when the proposed supply increase would put the supply above limit - ErrExceedsSupplyLimit = errorsmod.Register(ModuleName, 8, "asset supply over limit") - // ErrExceedsAvailableSupply error for when the proposed outgoing amount exceeds the total available supply - ErrExceedsAvailableSupply = errorsmod.Register(ModuleName, 9, "outgoing swap exceeds total available supply") - // ErrInvalidCurrentSupply error for when the proposed decrease would result in a negative current supplyx - ErrInvalidCurrentSupply = errorsmod.Register(ModuleName, 10, "supply decrease puts current asset supply below 0") - // ErrInvalidIncomingSupply error for when the proposed decrease would result in a negative incoming supply - ErrInvalidIncomingSupply = errorsmod.Register(ModuleName, 11, "supply decrease puts incoming asset supply below 0") - // ErrInvalidOutgoingSupply error for when the proposed decrease would result in a negative outgoing supply - ErrInvalidOutgoingSupply = errorsmod.Register(ModuleName, 12, "supply decrease puts outgoing asset supply below 0") - // ErrInvalidClaimSecret error when a submitted secret doesn't match an AtomicSwap's swapID - ErrInvalidClaimSecret = errorsmod.Register(ModuleName, 13, "hashed claim attempt does not match") - // ErrAtomicSwapAlreadyExists error for when an AtomicSwap with this swapID already exists - ErrAtomicSwapAlreadyExists = errorsmod.Register(ModuleName, 14, "atomic swap already exists") - // ErrAtomicSwapNotFound error for when an atomic swap is not found - ErrAtomicSwapNotFound = errorsmod.Register(ModuleName, 15, "atomic swap not found") - // ErrSwapNotRefundable error for when an AtomicSwap has not expired and cannot be refunded - ErrSwapNotRefundable = errorsmod.Register(ModuleName, 16, "atomic swap is still active and cannot be refunded") - // ErrSwapNotClaimable error for when an atomic swap is not open and cannot be claimed - ErrSwapNotClaimable = errorsmod.Register(ModuleName, 17, "atomic swap is not claimable") - // ErrInvalidAmount error for when a swap's amount is outside acceptable range - ErrInvalidAmount = errorsmod.Register(ModuleName, 18, "amount is outside acceptable range") - // ErrInvalidSwapAccount error for when a swap involves an invalid account - ErrInvalidSwapAccount = errorsmod.Register(ModuleName, 19, "atomic swap has invalid account") - // ErrExceedsTimeBasedSupplyLimit error for when the proposed supply increase would put the supply above limit for the current time period - ErrExceedsTimeBasedSupplyLimit = errorsmod.Register(ModuleName, 20, "asset supply over limit for current time period") -) diff --git a/x/bep3/types/events.go b/x/bep3/types/events.go deleted file mode 100644 index 72743b41..00000000 --- a/x/bep3/types/events.go +++ /dev/null @@ -1,25 +0,0 @@ -package types - -// Events for bep3 module -const ( - EventTypeCreateAtomicSwap = "create_atomic_swap" - EventTypeClaimAtomicSwap = "claim_atomic_swap" - EventTypeRefundAtomicSwap = "refund_atomic_swap" - EventTypeSwapsExpired = "swaps_expired" - - AttributeValueCategory = ModuleName - AttributeKeySender = "sender" - AttributeKeyRecipient = "recipient" - AttributeKeyAtomicSwapID = "atomic_swap_id" - AttributeKeyRandomNumberHash = "random_number_hash" - AttributeKeyTimestamp = "timestamp" - AttributeKeySenderOtherChain = "sender_other_chain" - AttributeKeyExpireHeight = "expire_height" - AttributeKeyAmount = "amount" - AttributeKeyDirection = "direction" - AttributeKeyClaimSender = "claim_sender" - AttributeKeyRandomNumber = "random_number" - AttributeKeyRefundSender = "refund_sender" - AttributeKeyAtomicSwapIDs = "atomic_swap_ids" - AttributeExpirationBlock = "expiration_block" -) diff --git a/x/bep3/types/expected_keepers.go b/x/bep3/types/expected_keepers.go deleted file mode 100644 index c9d1f7e9..00000000 --- a/x/bep3/types/expected_keepers.go +++ /dev/null @@ -1,26 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// BankKeeper defines the expected interface needed to retrieve account balances. -type BankKeeper interface { - 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 - BurnCoins(ctx sdk.Context, name string, amt sdk.Coins) error - MintCoins(ctx sdk.Context, name string, amt sdk.Coins) error -} - -// AccountKeeper defines the expected account keeper -type AccountKeeper interface { - GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, moduleName string) authtypes.ModuleAccountI - GetModuleAddressAndPermissions(moduleName string) (sdk.AccAddress, []string) - SetModuleAccount(ctx sdk.Context, macc authtypes.ModuleAccountI) - - GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI - NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI - SetAccount(ctx sdk.Context, acc authtypes.AccountI) -} diff --git a/x/bep3/types/genesis.go b/x/bep3/types/genesis.go deleted file mode 100644 index f1984e7c..00000000 --- a/x/bep3/types/genesis.go +++ /dev/null @@ -1,59 +0,0 @@ -package types - -import ( - "encoding/hex" - "fmt" - "time" -) - -// NewGenesisState creates a new GenesisState object -func NewGenesisState(params Params, swaps AtomicSwaps, supplies AssetSupplies, previousBlockTime time.Time) GenesisState { - return GenesisState{ - Params: params, - AtomicSwaps: swaps, - Supplies: supplies, - PreviousBlockTime: previousBlockTime, - } -} - -// DefaultGenesisState - default GenesisState used by Cosmos Hub -func DefaultGenesisState() GenesisState { - return NewGenesisState( - DefaultParams(), - AtomicSwaps{}, - AssetSupplies{}, - DefaultPreviousBlockTime, - ) -} - -// Validate validates genesis inputs. It returns error if validation of any input fails. -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - - ids := map[string]bool{} - for _, swap := range gs.AtomicSwaps { - if ids[hex.EncodeToString(swap.GetSwapID())] { - return fmt.Errorf("found duplicate atomic swap ID %s", hex.EncodeToString(swap.GetSwapID())) - } - - if err := swap.Validate(); err != nil { - return err - } - - ids[hex.EncodeToString(swap.GetSwapID())] = true - } - - supplyDenoms := map[string]bool{} - for _, supply := range gs.Supplies { - if err := supply.Validate(); err != nil { - return err - } - if supplyDenoms[supply.GetDenom()] { - return fmt.Errorf("found duplicate denom in asset supplies %s", supply.GetDenom()) - } - supplyDenoms[supply.GetDenom()] = true - } - return nil -} diff --git a/x/bep3/types/genesis.pb.go b/x/bep3/types/genesis.pb.go deleted file mode 100644 index 83cc2815..00000000 --- a/x/bep3/types/genesis.pb.go +++ /dev/null @@ -1,514 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/bep3/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 pricefeed module's genesis state. -type GenesisState struct { - // params defines all the parameters of the module. - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - // atomic_swaps represents the state of stored atomic swaps - AtomicSwaps AtomicSwaps `protobuf:"bytes,2,rep,name=atomic_swaps,json=atomicSwaps,proto3,castrepeated=AtomicSwaps" json:"atomic_swaps"` - // supplies represents the supply information of each atomic swap - Supplies AssetSupplies `protobuf:"bytes,3,rep,name=supplies,proto3,castrepeated=AssetSupplies" json:"supplies"` - // previous_block_time represents the time of the previous block - PreviousBlockTime time.Time `protobuf:"bytes,4,opt,name=previous_block_time,json=previousBlockTime,proto3,stdtime" json:"previous_block_time"` -} - -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_ad8c98a16ce5aad0, []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) GetAtomicSwaps() AtomicSwaps { - if m != nil { - return m.AtomicSwaps - } - return nil -} - -func (m *GenesisState) GetSupplies() AssetSupplies { - if m != nil { - return m.Supplies - } - return nil -} - -func (m *GenesisState) GetPreviousBlockTime() time.Time { - if m != nil { - return m.PreviousBlockTime - } - return time.Time{} -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.bep3.v1beta1.GenesisState") -} - -func init() { proto.RegisterFile("kava/bep3/v1beta1/genesis.proto", fileDescriptor_ad8c98a16ce5aad0) } - -var fileDescriptor_ad8c98a16ce5aad0 = []byte{ - // 356 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x91, 0xb1, 0x6e, 0xea, 0x30, - 0x14, 0x86, 0x13, 0x40, 0x08, 0x25, 0xdc, 0x81, 0x70, 0xaf, 0x94, 0x8b, 0xda, 0x04, 0x75, 0xa8, - 0x58, 0x6a, 0x0b, 0x18, 0xba, 0xb6, 0x59, 0xba, 0xb6, 0x81, 0x2e, 0x5d, 0x90, 0x83, 0xdc, 0xd4, - 0x22, 0xa9, 0x2d, 0x8e, 0x03, 0xe5, 0x2d, 0x78, 0x8e, 0xbe, 0x48, 0x19, 0x19, 0x3b, 0x95, 0x0a, - 0x5e, 0xa4, 0xb2, 0x13, 0xca, 0x00, 0x9b, 0xed, 0xf3, 0x9d, 0xef, 0x9c, 0xfc, 0xb1, 0xfc, 0x09, - 0x99, 0x11, 0x1c, 0x51, 0xd1, 0xc7, 0xb3, 0x6e, 0x44, 0x25, 0xe9, 0xe2, 0x98, 0xbe, 0x52, 0x60, - 0x80, 0xc4, 0x94, 0x4b, 0xee, 0x34, 0x14, 0x80, 0x14, 0x80, 0x0a, 0xa0, 0xf5, 0x37, 0xe6, 0x31, - 0xd7, 0x55, 0xac, 0x4e, 0x39, 0xd8, 0xf2, 0x63, 0xce, 0xe3, 0x84, 0x62, 0x7d, 0x8b, 0xb2, 0x67, - 0x2c, 0x59, 0x4a, 0x41, 0x92, 0x54, 0x14, 0xc0, 0xd9, 0xf1, 0x28, 0xad, 0xd5, 0xd5, 0x8b, 0x8f, - 0x92, 0x55, 0xbf, 0xcb, 0x27, 0x0f, 0x24, 0x91, 0xd4, 0xb9, 0xb6, 0xaa, 0x82, 0x4c, 0x49, 0x0a, - 0xae, 0xd9, 0x36, 0x3b, 0x76, 0xef, 0x3f, 0x3a, 0xda, 0x04, 0xdd, 0x6b, 0x20, 0xa8, 0xac, 0xbe, - 0x7c, 0x23, 0x2c, 0x70, 0xe7, 0xd1, 0xaa, 0x13, 0xc9, 0x53, 0x36, 0x1e, 0xc1, 0x9c, 0x08, 0x70, - 0x4b, 0xed, 0x72, 0xc7, 0xee, 0x9d, 0x9f, 0x68, 0xbf, 0xd5, 0xd8, 0x60, 0x4e, 0x44, 0xd0, 0x54, - 0x8a, 0xf7, 0x8d, 0x6f, 0x1f, 0xde, 0x20, 0xb4, 0xc9, 0xe1, 0xe2, 0x3c, 0x58, 0x35, 0xc8, 0x84, - 0x48, 0x18, 0x05, 0xb7, 0xac, 0x95, 0xde, 0x29, 0x25, 0x00, 0x95, 0x03, 0xc5, 0x2d, 0x82, 0x7f, - 0x85, 0xf3, 0xcf, 0xe1, 0x91, 0x51, 0x08, 0x7f, 0x35, 0xce, 0xd0, 0x6a, 0x8a, 0x29, 0x9d, 0x31, - 0x9e, 0xc1, 0x28, 0x4a, 0xf8, 0x78, 0x32, 0x52, 0x99, 0xb9, 0x15, 0xfd, 0xbd, 0x2d, 0x94, 0x07, - 0x8a, 0xf6, 0x81, 0xa2, 0xe1, 0x3e, 0xd0, 0xa0, 0xa6, 0xcc, 0xcb, 0x8d, 0x6f, 0x86, 0x8d, 0xbd, - 0x20, 0x50, 0xfd, 0x8a, 0x08, 0x6e, 0x56, 0x5b, 0xcf, 0x5c, 0x6f, 0x3d, 0xf3, 0x7b, 0xeb, 0x99, - 0xcb, 0x9d, 0x67, 0xac, 0x77, 0x9e, 0xf1, 0xb9, 0xf3, 0x8c, 0xa7, 0xcb, 0x98, 0xc9, 0x97, 0x2c, - 0x42, 0x63, 0x9e, 0x62, 0xb5, 0xfa, 0x55, 0x42, 0x22, 0xd0, 0x27, 0xfc, 0x96, 0xff, 0x18, 0xb9, - 0x10, 0x14, 0xa2, 0xaa, 0x1e, 0xd9, 0xff, 0x09, 0x00, 0x00, 0xff, 0xff, 0x24, 0x63, 0x3b, 0x63, - 0x1d, 0x02, 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 - n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.PreviousBlockTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousBlockTime):]) - if err1 != nil { - return 0, err1 - } - i -= n1 - i = encodeVarintGenesis(dAtA, i, uint64(n1)) - i-- - dAtA[i] = 0x22 - if len(m.Supplies) > 0 { - for iNdEx := len(m.Supplies) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Supplies[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.AtomicSwaps) > 0 { - for iNdEx := len(m.AtomicSwaps) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.AtomicSwaps[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.AtomicSwaps) > 0 { - for _, e := range m.AtomicSwaps { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.Supplies) > 0 { - for _, e := range m.Supplies { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousBlockTime) - 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 AtomicSwaps", 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.AtomicSwaps = append(m.AtomicSwaps, AtomicSwap{}) - if err := m.AtomicSwaps[len(m.AtomicSwaps)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Supplies", 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.Supplies = append(m.Supplies, AssetSupply{}) - if err := m.Supplies[len(m.Supplies)-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 PreviousBlockTime", 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 := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.PreviousBlockTime, 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/bep3/types/genesis_test.go b/x/bep3/types/genesis_test.go deleted file mode 100644 index 31ecc22e..00000000 --- a/x/bep3/types/genesis_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package types_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/bep3/types" -) - -type GenesisTestSuite struct { - suite.Suite - swaps types.AtomicSwaps - supplies types.AssetSupplies -} - -func (suite *GenesisTestSuite) SetupTest() { - coin := sdk.NewCoin("kava", sdk.OneInt()) - suite.swaps = atomicSwaps(10) - - supply := types.NewAssetSupply(coin, coin, coin, coin, time.Duration(0)) - suite.supplies = types.AssetSupplies{supply} -} - -func (suite *GenesisTestSuite) TestValidate() { - type args struct { - swaps types.AtomicSwaps - supplies types.AssetSupplies - previousBlockTime time.Time - } - testCases := []struct { - name string - args args - expectPass bool - }{ - { - "default", - args{ - swaps: types.AtomicSwaps{}, - previousBlockTime: types.DefaultPreviousBlockTime, - }, - true, - }, - { - "with swaps", - args{ - swaps: suite.swaps, - previousBlockTime: types.DefaultPreviousBlockTime, - }, - true, - }, - { - "with supplies", - args{ - swaps: types.AtomicSwaps{}, - supplies: suite.supplies, - previousBlockTime: types.DefaultPreviousBlockTime, - }, - true, - }, - { - "invalid supply", - args{ - swaps: types.AtomicSwaps{}, - supplies: types.AssetSupplies{{IncomingSupply: sdk.Coin{Denom: "Invalid", Amount: sdk.ZeroInt()}}}, - previousBlockTime: types.DefaultPreviousBlockTime, - }, - false, - }, - { - "duplicate swaps", - args{ - swaps: types.AtomicSwaps{suite.swaps[2], suite.swaps[2]}, - previousBlockTime: types.DefaultPreviousBlockTime, - }, - false, - }, - { - "invalid swap", - args{ - swaps: types.AtomicSwaps{{Amount: sdk.Coins{sdk.Coin{Denom: "Invalid Denom", Amount: sdkmath.NewInt(-1)}}}}, - previousBlockTime: types.DefaultPreviousBlockTime, - }, - false, - }, - { - "blocktime not set", - args{ - swaps: types.AtomicSwaps{}, - }, - true, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - var gs types.GenesisState - if tc.name == "default" { - gs = types.DefaultGenesisState() - } else { - gs = types.NewGenesisState(types.DefaultParams(), tc.args.swaps, tc.args.supplies, tc.args.previousBlockTime) - } - - err := gs.Validate() - if tc.expectPass { - suite.Require().NoError(err, tc.name) - } else { - suite.Require().Error(err, tc.name) - } - }) - } -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(GenesisTestSuite)) -} diff --git a/x/bep3/types/hash.go b/x/bep3/types/hash.go deleted file mode 100644 index fffab2e9..00000000 --- a/x/bep3/types/hash.go +++ /dev/null @@ -1,36 +0,0 @@ -package types - -import ( - "crypto/rand" - "encoding/binary" - "strings" - - "github.com/cometbft/cometbft/crypto/tmhash" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// GenerateSecureRandomNumber generates cryptographically strong pseudo-random number -func GenerateSecureRandomNumber() ([]byte, error) { - bytes := make([]byte, 32) - if _, err := rand.Read(bytes); err != nil { - return []byte{}, err - } - return bytes, nil -} - -// CalculateRandomHash calculates the hash of a number and timestamp -func CalculateRandomHash(randomNumber []byte, timestamp int64) []byte { - data := make([]byte, RandomNumberLength+Int64Size) - copy(data[:RandomNumberLength], randomNumber) - binary.BigEndian.PutUint64(data[RandomNumberLength:], uint64(timestamp)) - return tmhash.Sum(data) -} - -// CalculateSwapID calculates the hash of a RandomNumberHash, sdk.AccAddress, and string -func CalculateSwapID(randomNumberHash []byte, sender sdk.AccAddress, senderOtherChain string) []byte { - senderOtherChain = strings.ToLower(senderOtherChain) - data := randomNumberHash - data = append(data, sender.Bytes()...) - data = append(data, []byte(senderOtherChain)...) - return tmhash.Sum(data) -} diff --git a/x/bep3/types/hash_test.go b/x/bep3/types/hash_test.go deleted file mode 100644 index 66f844e4..00000000 --- a/x/bep3/types/hash_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package types_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/bep3/types" -) - -type HashTestSuite struct { - suite.Suite - addrs []sdk.AccAddress - timestamps []int64 -} - -func (suite *HashTestSuite) SetupTest() { - // Generate 10 addresses - _, addrs := app.GeneratePrivKeyAddressPairs(10) - - // Generate 10 timestamps - var timestamps []int64 - for i := 0; i < 10; i++ { - timestamps = append(timestamps, ts(i)) - } - - suite.addrs = addrs - suite.timestamps = timestamps -} - -func (suite *HashTestSuite) TestGenerateSecureRandomNumber() { - secureRandomNumber, err := types.GenerateSecureRandomNumber() - suite.Nil(err) - suite.NotNil(secureRandomNumber) - suite.Equal(32, len(secureRandomNumber)) -} - -func (suite *HashTestSuite) TestCalculateRandomHash() { - randomNumber, _ := types.GenerateSecureRandomNumber() - hash := types.CalculateRandomHash(randomNumber[:], suite.timestamps[0]) - suite.NotNil(hash) - suite.Equal(32, len(hash)) -} - -func (suite *HashTestSuite) TestCalculateSwapID() { - randomNumber, _ := types.GenerateSecureRandomNumber() - hash := types.CalculateRandomHash(randomNumber[:], suite.timestamps[3]) - swapID := types.CalculateSwapID(hash, suite.addrs[3], suite.addrs[5].String()) - suite.NotNil(swapID) - suite.Equal(32, len(swapID)) - - diffHash := types.CalculateRandomHash(randomNumber[:], suite.timestamps[2]) - diffSwapID := types.CalculateSwapID(diffHash, suite.addrs[3], suite.addrs[5].String()) - suite.NotEqual(swapID, diffSwapID) -} - -func TestHashTestSuite(t *testing.T) { - suite.Run(t, new(HashTestSuite)) -} diff --git a/x/bep3/types/keys.go b/x/bep3/types/keys.go deleted file mode 100644 index d4e5ddfc..00000000 --- a/x/bep3/types/keys.go +++ /dev/null @@ -1,36 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName is the name of the module - ModuleName = "bep3" - - // StoreKey to be used when creating the KVStore - StoreKey = ModuleName - - // RouterKey to be used for routing msgs - RouterKey = ModuleName - - // DefaultParamspace default namestore - DefaultParamspace = ModuleName - - // DefaultLongtermStorageDuration is 1 week (assuming a block time of 7 seconds) - DefaultLongtermStorageDuration uint64 = 86400 -) - -// Key prefixes -var ( - AtomicSwapKeyPrefix = []byte{0x00} // prefix for keys that store AtomicSwaps - AtomicSwapByBlockPrefix = []byte{0x01} // prefix for keys of the AtomicSwapsByBlock index - AtomicSwapLongtermStoragePrefix = []byte{0x02} // prefix for keys of the AtomicSwapLongtermStorage index - AssetSupplyPrefix = []byte{0x03} - PreviousBlockTimeKey = []byte{0x04} -) - -// GetAtomicSwapByHeightKey is used by the AtomicSwapByBlock index and AtomicSwapLongtermStorage index -func GetAtomicSwapByHeightKey(height uint64, swapID []byte) []byte { - return append(sdk.Uint64ToBigEndian(height), swapID...) -} diff --git a/x/bep3/types/msg.go b/x/bep3/types/msg.go deleted file mode 100644 index fe299fd1..00000000 --- a/x/bep3/types/msg.go +++ /dev/null @@ -1,258 +0,0 @@ -package types - -import ( - "encoding/hex" - "errors" - "fmt" - "strings" - - "github.com/cometbft/cometbft/crypto" - tmbytes "github.com/cometbft/cometbft/libs/bytes" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -const ( - CreateAtomicSwap = "createAtomicSwap" - ClaimAtomicSwap = "claimAtomicSwap" - RefundAtomicSwap = "refundAtomicSwap" - CalcSwapID = "calcSwapID" - - Int64Size = 8 - RandomNumberHashLength = 32 - RandomNumberLength = 32 - MaxOtherChainAddrLength = 64 - SwapIDLength = 32 - MaxExpectedIncomeLength = 64 -) - -// ensure Msg interface compliance at compile time -var ( - _ sdk.Msg = &MsgCreateAtomicSwap{} - _ sdk.Msg = &MsgClaimAtomicSwap{} - _ sdk.Msg = &MsgRefundAtomicSwap{} - AtomicSwapCoinsAccAddr = sdk.AccAddress(crypto.AddressHash([]byte("KavaAtomicSwapCoins"))) -) - -// NewMsgCreateAtomicSwap initializes a new MsgCreateAtomicSwap -func NewMsgCreateAtomicSwap(from, to string, recipientOtherChain, - senderOtherChain string, randomNumberHash tmbytes.HexBytes, timestamp int64, - amount sdk.Coins, heightSpan uint64, -) MsgCreateAtomicSwap { - return MsgCreateAtomicSwap{ - From: from, - To: to, - RecipientOtherChain: recipientOtherChain, - SenderOtherChain: senderOtherChain, - RandomNumberHash: randomNumberHash.String(), - Timestamp: timestamp, - Amount: amount, - HeightSpan: heightSpan, - } -} - -// Route establishes the route for the MsgCreateAtomicSwap -func (msg MsgCreateAtomicSwap) Route() string { return RouterKey } - -// Type is the name of MsgCreateAtomicSwap -func (msg MsgCreateAtomicSwap) Type() string { return CreateAtomicSwap } - -// String prints the MsgCreateAtomicSwap -func (msg MsgCreateAtomicSwap) String() string { - return fmt.Sprintf("AtomicSwap{%v#%v#%v#%v#%v#%v#%v#%v}", - msg.From, msg.To, msg.RecipientOtherChain, msg.SenderOtherChain, - msg.RandomNumberHash, msg.Timestamp, msg.Amount, msg.HeightSpan) -} - -// GetInvolvedAddresses gets the addresses involved in a MsgCreateAtomicSwap -func (msg MsgCreateAtomicSwap) GetInvolvedAddresses() []sdk.AccAddress { - return append(msg.GetSigners(), AtomicSwapCoinsAccAddr) -} - -// GetSigners gets the signers of a MsgCreateAtomicSwap -func (msg MsgCreateAtomicSwap) GetSigners() []sdk.AccAddress { - from, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - panic(err) - } - return []sdk.AccAddress{from} -} - -// ValidateBasic validates the MsgCreateAtomicSwap -func (msg MsgCreateAtomicSwap) ValidateBasic() error { - from, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - to, err := sdk.AccAddressFromBech32(msg.To) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - if from.Empty() { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty") - } - if to.Empty() { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "recipient address cannot be empty") - } - if strings.TrimSpace(msg.RecipientOtherChain) == "" { - return errors.New("missing recipient address on other chain") - } - if len(msg.RecipientOtherChain) > MaxOtherChainAddrLength { - return fmt.Errorf("the length of recipient address on other chain should be less than %d", MaxOtherChainAddrLength) - } - if len(msg.SenderOtherChain) > MaxOtherChainAddrLength { - return fmt.Errorf("the length of sender address on other chain should be less than %d", MaxOtherChainAddrLength) - } - randomNumberHash, err := hex.DecodeString(msg.RandomNumberHash) - if err != nil { - return fmt.Errorf("random number hash should be valid hex: %v", err) - } - if len(randomNumberHash) != RandomNumberHashLength { - return fmt.Errorf("the length of random number hash should be %d", RandomNumberHashLength) - } - if msg.Timestamp <= 0 { - return errors.New("timestamp must be positive") - } - if len(msg.Amount) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, "amount cannot be empty") - } - if !msg.Amount.IsValid() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) - } - if msg.HeightSpan <= 0 { - return errors.New("height span must be positive") - } - return nil -} - -// GetSignBytes gets the sign bytes of a MsgCreateAtomicSwap -func (msg MsgCreateAtomicSwap) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// NewMsgClaimAtomicSwap initializes a new MsgClaimAtomicSwap -func NewMsgClaimAtomicSwap(from string, swapID, randomNumber tmbytes.HexBytes) MsgClaimAtomicSwap { - return MsgClaimAtomicSwap{ - From: from, - SwapID: swapID.String(), - RandomNumber: randomNumber.String(), - } -} - -// Route establishes the route for the MsgClaimAtomicSwap -func (msg MsgClaimAtomicSwap) Route() string { return RouterKey } - -// Type is the name of MsgClaimAtomicSwap -func (msg MsgClaimAtomicSwap) Type() string { return ClaimAtomicSwap } - -// String prints the MsgClaimAtomicSwap -func (msg MsgClaimAtomicSwap) String() string { - return fmt.Sprintf("claimAtomicSwap{%v#%v#%v}", msg.From, msg.SwapID, msg.RandomNumber) -} - -// GetInvolvedAddresses gets the addresses involved in a MsgClaimAtomicSwap -func (msg MsgClaimAtomicSwap) GetInvolvedAddresses() []sdk.AccAddress { - return append(msg.GetSigners(), AtomicSwapCoinsAccAddr) -} - -// GetSigners gets the signers of a MsgClaimAtomicSwap -func (msg MsgClaimAtomicSwap) GetSigners() []sdk.AccAddress { - from, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - panic(err) - } - return []sdk.AccAddress{from} -} - -// ValidateBasic validates the MsgClaimAtomicSwap -func (msg MsgClaimAtomicSwap) ValidateBasic() error { - from, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - if from.Empty() { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty") - } - swapID, err := hex.DecodeString(msg.SwapID) - if err != nil { - return fmt.Errorf("swap id should be valid hex: %v", err) - } - if len(swapID) != SwapIDLength { - return fmt.Errorf("the length of swapID should be %d", SwapIDLength) - } - randomNumber, err := hex.DecodeString(msg.RandomNumber) - if err != nil { - return fmt.Errorf("random number should be valid hex: %v", err) - } - if len(randomNumber) != RandomNumberLength { - return fmt.Errorf("the length of random number should be %d", RandomNumberLength) - } - return nil -} - -// GetSignBytes gets the sign bytes of a MsgClaimAtomicSwap -func (msg MsgClaimAtomicSwap) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// NewMsgRefundAtomicSwap initializes a new MsgRefundAtomicSwap -func NewMsgRefundAtomicSwap(from string, swapID tmbytes.HexBytes) MsgRefundAtomicSwap { - return MsgRefundAtomicSwap{ - From: from, - SwapID: swapID.String(), - } -} - -// Route establishes the route for the MsgRefundAtomicSwap -func (msg MsgRefundAtomicSwap) Route() string { return RouterKey } - -// Type is the name of MsgRefundAtomicSwap -func (msg MsgRefundAtomicSwap) Type() string { return RefundAtomicSwap } - -// String prints the MsgRefundAtomicSwap -func (msg MsgRefundAtomicSwap) String() string { - return fmt.Sprintf("refundAtomicSwap{%v#%v}", msg.From, msg.SwapID) -} - -// GetInvolvedAddresses gets the addresses involved in a MsgRefundAtomicSwap -func (msg MsgRefundAtomicSwap) GetInvolvedAddresses() []sdk.AccAddress { - return append(msg.GetSigners(), AtomicSwapCoinsAccAddr) -} - -// GetSigners gets the signers of a MsgRefundAtomicSwap -func (msg MsgRefundAtomicSwap) GetSigners() []sdk.AccAddress { - from, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - panic(err) - } - return []sdk.AccAddress{from} -} - -// ValidateBasic validates the MsgRefundAtomicSwap -func (msg MsgRefundAtomicSwap) ValidateBasic() error { - from, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - if from.Empty() { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty") - } - swapID, err := hex.DecodeString(msg.SwapID) - if err != nil { - return fmt.Errorf("swap id should be valid hex: %v", err) - } - if len(swapID) != SwapIDLength { - return fmt.Errorf("the length of swapID should be %d", SwapIDLength) - } - return nil -} - -// GetSignBytes gets the sign bytes of a MsgRefundAtomicSwap -func (msg MsgRefundAtomicSwap) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} diff --git a/x/bep3/types/msg_test.go b/x/bep3/types/msg_test.go deleted file mode 100644 index 9bcf43b6..00000000 --- a/x/bep3/types/msg_test.go +++ /dev/null @@ -1,143 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/cometbft/cometbft/crypto" - tmbytes "github.com/cometbft/cometbft/libs/bytes" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/bep3/types" -) - -var ( - coinsSingle = sdk.NewCoins(sdk.NewInt64Coin("bnb", 50000)) - binanceAddrs = []sdk.AccAddress{} - kavaAddrs = []sdk.AccAddress{} - randomNumberBytes = []byte{15} - timestampInt64 = int64(100) - randomNumberHash = tmbytes.HexBytes(types.CalculateRandomHash(randomNumberBytes, timestampInt64)) -) - -func init() { - app.SetSDKConfig() - - // Must be set after SetSDKConfig to use kava Bech32 prefix instead of cosmos - binanceAddrs = []sdk.AccAddress{ - sdk.AccAddress(crypto.AddressHash([]byte("BinanceTest1"))), - sdk.AccAddress(crypto.AddressHash([]byte("BinanceTest2"))), - } - kavaAddrs = []sdk.AccAddress{ - sdk.AccAddress(crypto.AddressHash([]byte("KavaTest1"))), - sdk.AccAddress(crypto.AddressHash([]byte("KavaTest2"))), - } -} - -type MsgTestSuite struct { - suite.Suite -} - -func (suite *MsgTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) -} - -func (suite *MsgTestSuite) TestMsgCreateAtomicSwap() { - tests := []struct { - description string - from sdk.AccAddress - to sdk.AccAddress - recipientOtherChain string - senderOtherChain string - randomNumberHash string - timestamp int64 - amount sdk.Coins - heightSpan uint64 - expectPass bool - }{ - {"normal cross-chain", binanceAddrs[0], kavaAddrs[0], kavaAddrs[0].String(), binanceAddrs[0].String(), randomNumberHash.String(), timestampInt64, coinsSingle, 500, true}, - {"without other chain fields", binanceAddrs[0], kavaAddrs[0], "", "", randomNumberHash.String(), timestampInt64, coinsSingle, 500, false}, - {"invalid amount", binanceAddrs[0], kavaAddrs[0], kavaAddrs[0].String(), binanceAddrs[0].String(), randomNumberHash.String(), timestampInt64, nil, 500, false}, - {"invalid from address", sdk.AccAddress{}, kavaAddrs[0], kavaAddrs[0].String(), binanceAddrs[0].String(), randomNumberHash.String(), timestampInt64, coinsSingle, 500, false}, - {"invalid to address", binanceAddrs[0], sdk.AccAddress{}, kavaAddrs[0].String(), binanceAddrs[0].String(), randomNumberHash.String(), timestampInt64, coinsSingle, 500, false}, - {"invalid rand hash", binanceAddrs[0], kavaAddrs[0], kavaAddrs[0].String(), binanceAddrs[0].String(), "ff", timestampInt64, coinsSingle, 500, false}, - } - - for i, tc := range tests { - msg := types.MsgCreateAtomicSwap{ - tc.from.String(), - tc.to.String(), - tc.recipientOtherChain, - tc.senderOtherChain, - tc.randomNumberHash, - tc.timestamp, - tc.amount, - tc.heightSpan, - } - if tc.expectPass { - suite.NoError(msg.ValidateBasic(), "test: %v", i) - } else { - suite.Error(msg.ValidateBasic(), "test: %v", i) - } - } -} - -func (suite *MsgTestSuite) TestMsgClaimAtomicSwap() { - swapID := types.CalculateSwapID(randomNumberHash, binanceAddrs[0], "") - - tests := []struct { - description string - from sdk.AccAddress - swapID tmbytes.HexBytes - randomNumber tmbytes.HexBytes - expectPass bool - }{ - {"normal", binanceAddrs[0], swapID, randomNumberHash, true}, - {"invalid from address", sdk.AccAddress{}, swapID, randomNumberHash, false}, - } - - for i, tc := range tests { - msg := types.NewMsgClaimAtomicSwap( - tc.from.String(), - tc.swapID, - tc.randomNumber, - ) - if tc.expectPass { - suite.NoError(msg.ValidateBasic(), "test: %v", i) - } else { - suite.Error(msg.ValidateBasic(), "test: %v", i) - } - } -} - -func (suite *MsgTestSuite) TestMsgRefundAtomicSwap() { - swapID := types.CalculateSwapID(randomNumberHash, binanceAddrs[0], "") - - tests := []struct { - description string - from sdk.AccAddress - swapID tmbytes.HexBytes - expectPass bool - }{ - {"normal", binanceAddrs[0], swapID, true}, - {"invalid from address", sdk.AccAddress{}, swapID, false}, - } - - for i, tc := range tests { - msg := types.NewMsgRefundAtomicSwap( - tc.from.String(), - tc.swapID, - ) - if tc.expectPass { - suite.NoError(msg.ValidateBasic(), "test: %v", i) - } else { - suite.Error(msg.ValidateBasic(), "test: %v", i) - } - } -} - -func TestMsgTestSuite(t *testing.T) { - suite.Run(t, new(MsgTestSuite)) -} diff --git a/x/bep3/types/params.go b/x/bep3/types/params.go deleted file mode 100644 index 0ec12dc1..00000000 --- a/x/bep3/types/params.go +++ /dev/null @@ -1,150 +0,0 @@ -package types - -import ( - "fmt" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - - tmtime "github.com/cometbft/cometbft/types/time" -) - -const ( - bech32MainPrefix = "kava" -) - -// Parameter keys -var ( - KeyAssetParams = []byte("AssetParams") - - DefaultBnbDeputyFixedFee sdkmath.Int = sdkmath.NewInt(1000) // 0.00001 BNB - DefaultMinAmount sdkmath.Int = sdk.ZeroInt() - DefaultMaxAmount sdkmath.Int = sdkmath.NewInt(1000000000000) // 10,000 BNB - DefaultMinBlockLock uint64 = 220 - DefaultMaxBlockLock uint64 = 270 - DefaultPreviousBlockTime = tmtime.Canonical(time.Unix(1, 0)) -) - -// NewParams returns a new params object -func NewParams(ap []AssetParam) Params { - return Params{ - AssetParams: ap, - } -} - -// DefaultParams returns default params for bep3 module -func DefaultParams() Params { - return NewParams(AssetParams{}) -} - -// NewAssetParam returns a new AssetParam -func NewAssetParam( - denom string, coinID int64, limit SupplyLimit, active bool, - deputyAddr sdk.AccAddress, fixedFee sdkmath.Int, minSwapAmount sdkmath.Int, - maxSwapAmount sdkmath.Int, minBlockLock uint64, maxBlockLock uint64, -) AssetParam { - return AssetParam{ - Denom: denom, - CoinID: coinID, - SupplyLimit: limit, - Active: active, - DeputyAddress: deputyAddr, - FixedFee: fixedFee, - MinSwapAmount: minSwapAmount, - MaxSwapAmount: maxSwapAmount, - MinBlockLock: minBlockLock, - MaxBlockLock: maxBlockLock, - } -} - -// AssetParams array of AssetParam -type AssetParams []AssetParam - -// Equals returns true if two supply limits are equal -func (sl SupplyLimit) Equals(sl2 SupplyLimit) bool { - return sl.Limit.Equal(sl2.Limit) && sl.TimeLimited == sl2.TimeLimited && sl.TimePeriod == sl2.TimePeriod && sl.TimeBasedLimit.Equal(sl2.TimeBasedLimit) -} - -// ParamKeyTable Key declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements the ParamSet interface and returns all the key/value pairs -// pairs of bep3 module's parameters. -// nolint -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyAssetParams, &p.AssetParams, validateAssetParams), - } -} - -// Validate ensure that params have valid values -func (p Params) Validate() error { - return validateAssetParams(p.AssetParams) -} - -func validateAssetParams(i interface{}) error { - assetParams, ok := i.(AssetParams) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - coinDenoms := make(map[string]bool) - for _, asset := range assetParams { - if err := sdk.ValidateDenom(asset.Denom); err != nil { - return fmt.Errorf(fmt.Sprintf("asset denom invalid: %s", asset.Denom)) - } - - if asset.CoinID < 0 { - return fmt.Errorf(fmt.Sprintf("asset %s coin id must be a non negative integer", asset.Denom)) - } - - if asset.SupplyLimit.Limit.IsNegative() { - return fmt.Errorf(fmt.Sprintf("asset %s has invalid (negative) supply limit: %s", asset.Denom, asset.SupplyLimit.Limit)) - } - - if asset.SupplyLimit.TimeBasedLimit.IsNegative() { - return fmt.Errorf(fmt.Sprintf("asset %s has invalid (negative) supply time limit: %s", asset.Denom, asset.SupplyLimit.TimeBasedLimit)) - } - - if asset.SupplyLimit.TimeBasedLimit.GT(asset.SupplyLimit.Limit) { - return fmt.Errorf(fmt.Sprintf("asset %s cannot have supply time limit > supply limit: %s>%s", asset.Denom, asset.SupplyLimit.TimeBasedLimit, asset.SupplyLimit.Limit)) - } - - _, found := coinDenoms[asset.Denom] - if found { - return fmt.Errorf(fmt.Sprintf("asset %s cannot have duplicate denom", asset.Denom)) - } - - coinDenoms[asset.Denom] = true - - if asset.DeputyAddress.Empty() { - return fmt.Errorf("deputy address cannot be empty for %s", asset.Denom) - } - - if asset.FixedFee.IsNegative() { - return fmt.Errorf("asset %s cannot have a negative fixed fee %s", asset.Denom, asset.FixedFee) - } - - if asset.MinBlockLock > asset.MaxBlockLock { - return fmt.Errorf("asset %s has minimum block lock > maximum block lock %d > %d", asset.Denom, asset.MinBlockLock, asset.MaxBlockLock) - } - - if !asset.MinSwapAmount.IsPositive() { - return fmt.Errorf(fmt.Sprintf("asset %s must have a positive minimum swap amount, got %s", asset.Denom, asset.MinSwapAmount)) - } - - if !asset.MaxSwapAmount.IsPositive() { - return fmt.Errorf(fmt.Sprintf("asset %s must have a positive maximum swap amount, got %s", asset.Denom, asset.MaxSwapAmount)) - } - - if asset.MinSwapAmount.GT(asset.MaxSwapAmount) { - return fmt.Errorf("asset %s has minimum swap amount > maximum swap amount %s > %s", asset.Denom, asset.MinSwapAmount, asset.MaxSwapAmount) - } - } - - return nil -} diff --git a/x/bep3/types/params_test.go b/x/bep3/types/params_test.go deleted file mode 100644 index a9de43a6..00000000 --- a/x/bep3/types/params_test.go +++ /dev/null @@ -1,249 +0,0 @@ -package types_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/bep3/types" -) - -type ParamsTestSuite struct { - suite.Suite - addr sdk.AccAddress - supply []types.SupplyLimit -} - -func (suite *ParamsTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - _, addrs := app.GeneratePrivKeyAddressPairs(1) - suite.addr = addrs[0] - supply1 := types.SupplyLimit{ - Limit: sdkmath.NewInt(10000000000000), - TimeLimited: false, - TimeBasedLimit: sdk.ZeroInt(), - TimePeriod: time.Hour, - } - supply2 := types.SupplyLimit{ - Limit: sdkmath.NewInt(10000000000000), - TimeLimited: true, - TimeBasedLimit: sdkmath.NewInt(100000000000), - TimePeriod: time.Hour * 24, - } - suite.supply = append(suite.supply, supply1, supply2) -} - -func (suite *ParamsTestSuite) TestParamValidation() { - type args struct { - assetParams types.AssetParams - } - - testCases := []struct { - name string - args args - expectPass bool - expectedErr string - }{ - { - name: "default", - args: args{ - assetParams: types.AssetParams{}, - }, - expectPass: true, - expectedErr: "", - }, - { - name: "valid single asset", - args: args{ - assetParams: types.AssetParams{types.NewAssetParam( - "bnb", 714, suite.supply[0], true, - suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000), - types.DefaultMinBlockLock, types.DefaultMaxBlockLock)}, - }, - expectPass: true, - expectedErr: "", - }, - { - name: "valid single asset time limited", - args: args{ - assetParams: types.AssetParams{types.NewAssetParam( - "bnb", 714, suite.supply[1], true, - suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000), - types.DefaultMinBlockLock, types.DefaultMaxBlockLock)}, - }, - expectPass: true, - expectedErr: "", - }, - { - name: "valid multi asset", - args: args{ - assetParams: types.AssetParams{ - types.NewAssetParam( - "bnb", 714, suite.supply[0], true, - suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000), - types.DefaultMinBlockLock, types.DefaultMaxBlockLock), - types.NewAssetParam( - "btcb", 0, suite.supply[1], true, - suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(10000000), sdkmath.NewInt(100000000000), - types.DefaultMinBlockLock, types.DefaultMaxBlockLock), - }, - }, - expectPass: true, - expectedErr: "", - }, - { - name: "invalid denom - empty", - args: args{ - assetParams: types.AssetParams{types.NewAssetParam( - "", 714, suite.supply[0], true, - suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000), - types.DefaultMinBlockLock, types.DefaultMaxBlockLock)}, - }, - expectPass: false, - expectedErr: "denom invalid", - }, - { - name: "min block lock equal max block lock", - args: args{ - assetParams: types.AssetParams{types.NewAssetParam( - "bnb", 714, suite.supply[0], true, - suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000), - 243, 243)}, - }, - expectPass: true, - expectedErr: "", - }, - { - name: "min block lock greater max block lock", - args: args{ - assetParams: types.AssetParams{types.NewAssetParam( - "bnb", 714, suite.supply[0], true, - suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000), - 244, 243)}, - }, - expectPass: false, - expectedErr: "minimum block lock > maximum block lock", - }, - { - name: "min swap not positive", - args: args{ - assetParams: types.AssetParams{types.NewAssetParam( - "bnb", 714, suite.supply[0], true, - suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(0), sdkmath.NewInt(10000000000), - types.DefaultMinBlockLock, types.DefaultMaxBlockLock)}, - }, - expectPass: false, - expectedErr: "must have a positive minimum swap", - }, - { - name: "max swap not positive", - args: args{ - assetParams: types.AssetParams{types.NewAssetParam( - "bnb", 714, suite.supply[0], true, - suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(10000), sdkmath.NewInt(0), - types.DefaultMinBlockLock, types.DefaultMaxBlockLock)}, - }, - expectPass: false, - expectedErr: "must have a positive maximum swap", - }, - { - name: "min swap greater max swap", - args: args{ - assetParams: types.AssetParams{types.NewAssetParam( - "bnb", 714, suite.supply[0], true, - suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000000), sdkmath.NewInt(10000000000), - types.DefaultMinBlockLock, types.DefaultMaxBlockLock)}, - }, - expectPass: false, - expectedErr: "minimum swap amount > maximum swap amount", - }, - { - name: "negative coin id", - args: args{ - assetParams: types.AssetParams{types.NewAssetParam( - "bnb", -714, suite.supply[0], true, - suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000), - types.DefaultMinBlockLock, types.DefaultMaxBlockLock)}, - }, - expectPass: false, - expectedErr: "coin id must be a non negative", - }, - { - name: "negative asset limit", - args: args{ - assetParams: types.AssetParams{types.NewAssetParam( - "bnb", 714, - types.SupplyLimit{sdkmath.NewInt(-10000000000000), false, time.Hour, sdk.ZeroInt()}, true, - suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000), - types.DefaultMinBlockLock, types.DefaultMaxBlockLock)}, - }, - expectPass: false, - expectedErr: "invalid (negative) supply limit", - }, - { - name: "negative asset time limit", - args: args{ - assetParams: types.AssetParams{types.NewAssetParam( - "bnb", 714, - types.SupplyLimit{sdkmath.NewInt(10000000000000), false, time.Hour, sdkmath.NewInt(-10000000000000)}, true, - suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000), - types.DefaultMinBlockLock, types.DefaultMaxBlockLock)}, - }, - expectPass: false, - expectedErr: "invalid (negative) supply time limit", - }, - { - name: "asset time limit greater than overall limit", - args: args{ - assetParams: types.AssetParams{types.NewAssetParam( - "bnb", 714, - types.SupplyLimit{sdkmath.NewInt(10000000000000), true, time.Hour, sdkmath.NewInt(100000000000000)}, - true, - suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000), - types.DefaultMinBlockLock, types.DefaultMaxBlockLock)}, - }, - expectPass: false, - expectedErr: "supply time limit > supply limit", - }, - { - name: "duplicate denom", - args: args{ - assetParams: types.AssetParams{ - types.NewAssetParam( - "bnb", 714, suite.supply[0], true, - suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000), - types.DefaultMinBlockLock, types.DefaultMaxBlockLock), - types.NewAssetParam( - "bnb", 0, suite.supply[0], true, - suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(10000000), sdkmath.NewInt(100000000000), - types.DefaultMinBlockLock, types.DefaultMaxBlockLock), - }, - }, - expectPass: false, - expectedErr: "duplicate denom", - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - params := types.NewParams(tc.args.assetParams) - err := params.Validate() - if tc.expectPass { - suite.Require().NoError(err, tc.name) - } else { - suite.Require().Error(err, tc.name) - suite.Require().Contains(err.Error(), tc.expectedErr) - } - }) - } -} - -func TestParamsTestSuite(t *testing.T) { - suite.Run(t, new(ParamsTestSuite)) -} diff --git a/x/bep3/types/query.pb.go b/x/bep3/types/query.pb.go deleted file mode 100644 index 55eaa124..00000000 --- a/x/bep3/types/query.pb.go +++ /dev/null @@ -1,3384 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/bep3/v1beta1/query.proto - -package types - -import ( - context "context" - 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" - 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" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - _ "google.golang.org/protobuf/types/known/durationpb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 defines the request type for querying x/bep3 parameters. -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_a5e4082d53c18bf6, []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 defines the response type for querying x/bep3 parameters. -type QueryParamsResponse struct { - // params represents the parameters of the 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_a5e4082d53c18bf6, []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{} -} - -// QueryAssetSupplyRequest is the request type for the Query/AssetSupply RPC method. -type QueryAssetSupplyRequest struct { - // denom filters the asset response for the specified denom - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` -} - -func (m *QueryAssetSupplyRequest) Reset() { *m = QueryAssetSupplyRequest{} } -func (m *QueryAssetSupplyRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAssetSupplyRequest) ProtoMessage() {} -func (*QueryAssetSupplyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_a5e4082d53c18bf6, []int{2} -} -func (m *QueryAssetSupplyRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAssetSupplyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAssetSupplyRequest.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 *QueryAssetSupplyRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAssetSupplyRequest.Merge(m, src) -} -func (m *QueryAssetSupplyRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryAssetSupplyRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAssetSupplyRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAssetSupplyRequest proto.InternalMessageInfo - -// AssetSupplyResponse defines information about an asset's supply. -type AssetSupplyResponse struct { - // incoming_supply represents the incoming supply of an asset - IncomingSupply types.Coin `protobuf:"bytes,1,opt,name=incoming_supply,json=incomingSupply,proto3" json:"incoming_supply"` - // outgoing_supply represents the outgoing supply of an asset - OutgoingSupply types.Coin `protobuf:"bytes,2,opt,name=outgoing_supply,json=outgoingSupply,proto3" json:"outgoing_supply"` - // current_supply represents the current on-chain supply of an asset - CurrentSupply types.Coin `protobuf:"bytes,3,opt,name=current_supply,json=currentSupply,proto3" json:"current_supply"` - // time_limited_current_supply represents the time limited current supply of an asset - TimeLimitedCurrentSupply types.Coin `protobuf:"bytes,4,opt,name=time_limited_current_supply,json=timeLimitedCurrentSupply,proto3" json:"time_limited_current_supply"` - // time_elapsed represents the time elapsed - TimeElapsed time.Duration `protobuf:"bytes,5,opt,name=time_elapsed,json=timeElapsed,proto3,stdduration" json:"time_elapsed"` -} - -func (m *AssetSupplyResponse) Reset() { *m = AssetSupplyResponse{} } -func (m *AssetSupplyResponse) String() string { return proto.CompactTextString(m) } -func (*AssetSupplyResponse) ProtoMessage() {} -func (*AssetSupplyResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_a5e4082d53c18bf6, []int{3} -} -func (m *AssetSupplyResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AssetSupplyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AssetSupplyResponse.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 *AssetSupplyResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_AssetSupplyResponse.Merge(m, src) -} -func (m *AssetSupplyResponse) XXX_Size() int { - return m.Size() -} -func (m *AssetSupplyResponse) XXX_DiscardUnknown() { - xxx_messageInfo_AssetSupplyResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_AssetSupplyResponse proto.InternalMessageInfo - -func (m *AssetSupplyResponse) GetIncomingSupply() types.Coin { - if m != nil { - return m.IncomingSupply - } - return types.Coin{} -} - -func (m *AssetSupplyResponse) GetOutgoingSupply() types.Coin { - if m != nil { - return m.OutgoingSupply - } - return types.Coin{} -} - -func (m *AssetSupplyResponse) GetCurrentSupply() types.Coin { - if m != nil { - return m.CurrentSupply - } - return types.Coin{} -} - -func (m *AssetSupplyResponse) GetTimeLimitedCurrentSupply() types.Coin { - if m != nil { - return m.TimeLimitedCurrentSupply - } - return types.Coin{} -} - -func (m *AssetSupplyResponse) GetTimeElapsed() time.Duration { - if m != nil { - return m.TimeElapsed - } - return 0 -} - -// QueryAssetSupplyResponse is the response type for the Query/AssetSupply RPC method. -type QueryAssetSupplyResponse struct { - // asset_supply represents the supply of the asset - AssetSupply AssetSupplyResponse `protobuf:"bytes,1,opt,name=asset_supply,json=assetSupply,proto3" json:"asset_supply"` -} - -func (m *QueryAssetSupplyResponse) Reset() { *m = QueryAssetSupplyResponse{} } -func (m *QueryAssetSupplyResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAssetSupplyResponse) ProtoMessage() {} -func (*QueryAssetSupplyResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_a5e4082d53c18bf6, []int{4} -} -func (m *QueryAssetSupplyResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAssetSupplyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAssetSupplyResponse.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 *QueryAssetSupplyResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAssetSupplyResponse.Merge(m, src) -} -func (m *QueryAssetSupplyResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryAssetSupplyResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAssetSupplyResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAssetSupplyResponse proto.InternalMessageInfo - -func (m *QueryAssetSupplyResponse) GetAssetSupply() AssetSupplyResponse { - if m != nil { - return m.AssetSupply - } - return AssetSupplyResponse{} -} - -// QueryAssetSuppliesRequest is the request type for the Query/AssetSupplies RPC method. -type QueryAssetSuppliesRequest struct { -} - -func (m *QueryAssetSuppliesRequest) Reset() { *m = QueryAssetSuppliesRequest{} } -func (m *QueryAssetSuppliesRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAssetSuppliesRequest) ProtoMessage() {} -func (*QueryAssetSuppliesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_a5e4082d53c18bf6, []int{5} -} -func (m *QueryAssetSuppliesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAssetSuppliesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAssetSuppliesRequest.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 *QueryAssetSuppliesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAssetSuppliesRequest.Merge(m, src) -} -func (m *QueryAssetSuppliesRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryAssetSuppliesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAssetSuppliesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAssetSuppliesRequest proto.InternalMessageInfo - -// QueryAssetSuppliesResponse is the response type for the Query/AssetSupplies RPC method. -type QueryAssetSuppliesResponse struct { - // asset_supplies represents the supplies of returned assets - AssetSupplies []AssetSupplyResponse `protobuf:"bytes,1,rep,name=asset_supplies,json=assetSupplies,proto3" json:"asset_supplies"` -} - -func (m *QueryAssetSuppliesResponse) Reset() { *m = QueryAssetSuppliesResponse{} } -func (m *QueryAssetSuppliesResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAssetSuppliesResponse) ProtoMessage() {} -func (*QueryAssetSuppliesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_a5e4082d53c18bf6, []int{6} -} -func (m *QueryAssetSuppliesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAssetSuppliesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAssetSuppliesResponse.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 *QueryAssetSuppliesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAssetSuppliesResponse.Merge(m, src) -} -func (m *QueryAssetSuppliesResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryAssetSuppliesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAssetSuppliesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAssetSuppliesResponse proto.InternalMessageInfo - -func (m *QueryAssetSuppliesResponse) GetAssetSupplies() []AssetSupplyResponse { - if m != nil { - return m.AssetSupplies - } - return nil -} - -// QueryAtomicSwapRequest is the request type for the Query/AtomicSwap RPC method. -type QueryAtomicSwapRequest struct { - // swap_id represents the id of the swap to query - SwapId string `protobuf:"bytes,1,opt,name=swap_id,json=swapId,proto3" json:"swap_id,omitempty"` -} - -func (m *QueryAtomicSwapRequest) Reset() { *m = QueryAtomicSwapRequest{} } -func (m *QueryAtomicSwapRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAtomicSwapRequest) ProtoMessage() {} -func (*QueryAtomicSwapRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_a5e4082d53c18bf6, []int{7} -} -func (m *QueryAtomicSwapRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAtomicSwapRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAtomicSwapRequest.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 *QueryAtomicSwapRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAtomicSwapRequest.Merge(m, src) -} -func (m *QueryAtomicSwapRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryAtomicSwapRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAtomicSwapRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAtomicSwapRequest proto.InternalMessageInfo - -// QueryAtomicSwapResponse is the response type for the Query/AtomicSwap RPC method. -type QueryAtomicSwapResponse struct { - AtomicSwap AtomicSwapResponse `protobuf:"bytes,2,opt,name=atomic_swap,json=atomicSwap,proto3" json:"atomic_swap"` -} - -func (m *QueryAtomicSwapResponse) Reset() { *m = QueryAtomicSwapResponse{} } -func (m *QueryAtomicSwapResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAtomicSwapResponse) ProtoMessage() {} -func (*QueryAtomicSwapResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_a5e4082d53c18bf6, []int{8} -} -func (m *QueryAtomicSwapResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAtomicSwapResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAtomicSwapResponse.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 *QueryAtomicSwapResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAtomicSwapResponse.Merge(m, src) -} -func (m *QueryAtomicSwapResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryAtomicSwapResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAtomicSwapResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAtomicSwapResponse proto.InternalMessageInfo - -func (m *QueryAtomicSwapResponse) GetAtomicSwap() AtomicSwapResponse { - if m != nil { - return m.AtomicSwap - } - return AtomicSwapResponse{} -} - -// AtomicSwapResponse represents the returned atomic swap properties -type AtomicSwapResponse struct { - // id represents the id of the atomic swap - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - // amount represents the amount being swapped - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` - // random_number_hash represents the hash of the random number - RandomNumberHash string `protobuf:"bytes,3,opt,name=random_number_hash,json=randomNumberHash,proto3" json:"random_number_hash,omitempty"` - // expire_height represents the height when the swap expires - ExpireHeight uint64 `protobuf:"varint,4,opt,name=expire_height,json=expireHeight,proto3" json:"expire_height,omitempty"` - // timestamp represents the timestamp of the swap - Timestamp int64 `protobuf:"varint,5,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - // sender is the kava chain sender of the swap - Sender string `protobuf:"bytes,6,opt,name=sender,proto3" json:"sender,omitempty"` - // recipient is the kava chain recipient of the swap - Recipient string `protobuf:"bytes,7,opt,name=recipient,proto3" json:"recipient,omitempty"` - // sender_other_chain is the sender on the other chain - SenderOtherChain string `protobuf:"bytes,8,opt,name=sender_other_chain,json=senderOtherChain,proto3" json:"sender_other_chain,omitempty"` - // recipient_other_chain is the recipient on the other chain - RecipientOtherChain string `protobuf:"bytes,9,opt,name=recipient_other_chain,json=recipientOtherChain,proto3" json:"recipient_other_chain,omitempty"` - // closed_block is the block when the swap is closed - ClosedBlock int64 `protobuf:"varint,10,opt,name=closed_block,json=closedBlock,proto3" json:"closed_block,omitempty"` - // status represents the current status of the swap - Status SwapStatus `protobuf:"varint,11,opt,name=status,proto3,enum=kava.bep3.v1beta1.SwapStatus" json:"status,omitempty"` - // cross_chain identifies whether the atomic swap is cross chain - CrossChain bool `protobuf:"varint,12,opt,name=cross_chain,json=crossChain,proto3" json:"cross_chain,omitempty"` - // direction identifies if the swap is incoming or outgoing - Direction SwapDirection `protobuf:"varint,13,opt,name=direction,proto3,enum=kava.bep3.v1beta1.SwapDirection" json:"direction,omitempty"` -} - -func (m *AtomicSwapResponse) Reset() { *m = AtomicSwapResponse{} } -func (m *AtomicSwapResponse) String() string { return proto.CompactTextString(m) } -func (*AtomicSwapResponse) ProtoMessage() {} -func (*AtomicSwapResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_a5e4082d53c18bf6, []int{9} -} -func (m *AtomicSwapResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AtomicSwapResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AtomicSwapResponse.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 *AtomicSwapResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_AtomicSwapResponse.Merge(m, src) -} -func (m *AtomicSwapResponse) XXX_Size() int { - return m.Size() -} -func (m *AtomicSwapResponse) XXX_DiscardUnknown() { - xxx_messageInfo_AtomicSwapResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_AtomicSwapResponse proto.InternalMessageInfo - -func (m *AtomicSwapResponse) GetId() string { - if m != nil { - return m.Id - } - return "" -} - -func (m *AtomicSwapResponse) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -func (m *AtomicSwapResponse) GetRandomNumberHash() string { - if m != nil { - return m.RandomNumberHash - } - return "" -} - -func (m *AtomicSwapResponse) GetExpireHeight() uint64 { - if m != nil { - return m.ExpireHeight - } - return 0 -} - -func (m *AtomicSwapResponse) GetTimestamp() int64 { - if m != nil { - return m.Timestamp - } - return 0 -} - -func (m *AtomicSwapResponse) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *AtomicSwapResponse) GetRecipient() string { - if m != nil { - return m.Recipient - } - return "" -} - -func (m *AtomicSwapResponse) GetSenderOtherChain() string { - if m != nil { - return m.SenderOtherChain - } - return "" -} - -func (m *AtomicSwapResponse) GetRecipientOtherChain() string { - if m != nil { - return m.RecipientOtherChain - } - return "" -} - -func (m *AtomicSwapResponse) GetClosedBlock() int64 { - if m != nil { - return m.ClosedBlock - } - return 0 -} - -func (m *AtomicSwapResponse) GetStatus() SwapStatus { - if m != nil { - return m.Status - } - return SWAP_STATUS_UNSPECIFIED -} - -func (m *AtomicSwapResponse) GetCrossChain() bool { - if m != nil { - return m.CrossChain - } - return false -} - -func (m *AtomicSwapResponse) GetDirection() SwapDirection { - if m != nil { - return m.Direction - } - return SWAP_DIRECTION_UNSPECIFIED -} - -// QueryAtomicSwapsRequest is the request type for the Query/AtomicSwaps RPC method. -type QueryAtomicSwapsRequest struct { - // involve filters by address - Involve string `protobuf:"bytes,1,opt,name=involve,proto3" json:"involve,omitempty"` - // expiration filters by expiration block height - Expiration uint64 `protobuf:"varint,2,opt,name=expiration,proto3" json:"expiration,omitempty"` - // status filters by swap status - Status SwapStatus `protobuf:"varint,3,opt,name=status,proto3,enum=kava.bep3.v1beta1.SwapStatus" json:"status,omitempty"` - // direction fitlers by swap direction - Direction SwapDirection `protobuf:"varint,4,opt,name=direction,proto3,enum=kava.bep3.v1beta1.SwapDirection" json:"direction,omitempty"` - Pagination *query.PageRequest `protobuf:"bytes,5,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryAtomicSwapsRequest) Reset() { *m = QueryAtomicSwapsRequest{} } -func (m *QueryAtomicSwapsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAtomicSwapsRequest) ProtoMessage() {} -func (*QueryAtomicSwapsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_a5e4082d53c18bf6, []int{10} -} -func (m *QueryAtomicSwapsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAtomicSwapsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAtomicSwapsRequest.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 *QueryAtomicSwapsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAtomicSwapsRequest.Merge(m, src) -} -func (m *QueryAtomicSwapsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryAtomicSwapsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAtomicSwapsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAtomicSwapsRequest proto.InternalMessageInfo - -// QueryAtomicSwapsResponse is the response type for the Query/AtomicSwaps RPC method. -type QueryAtomicSwapsResponse struct { - // atomic_swap represents the returned atomic swaps for the request - AtomicSwaps []AtomicSwapResponse `protobuf:"bytes,1,rep,name=atomic_swaps,json=atomicSwaps,proto3" json:"atomic_swaps"` - Pagination *query.PageResponse `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryAtomicSwapsResponse) Reset() { *m = QueryAtomicSwapsResponse{} } -func (m *QueryAtomicSwapsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAtomicSwapsResponse) ProtoMessage() {} -func (*QueryAtomicSwapsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_a5e4082d53c18bf6, []int{11} -} -func (m *QueryAtomicSwapsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAtomicSwapsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAtomicSwapsResponse.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 *QueryAtomicSwapsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAtomicSwapsResponse.Merge(m, src) -} -func (m *QueryAtomicSwapsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryAtomicSwapsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAtomicSwapsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAtomicSwapsResponse proto.InternalMessageInfo - -func (m *QueryAtomicSwapsResponse) GetAtomicSwaps() []AtomicSwapResponse { - if m != nil { - return m.AtomicSwaps - } - return nil -} - -func (m *QueryAtomicSwapsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.bep3.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.bep3.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryAssetSupplyRequest)(nil), "kava.bep3.v1beta1.QueryAssetSupplyRequest") - proto.RegisterType((*AssetSupplyResponse)(nil), "kava.bep3.v1beta1.AssetSupplyResponse") - proto.RegisterType((*QueryAssetSupplyResponse)(nil), "kava.bep3.v1beta1.QueryAssetSupplyResponse") - proto.RegisterType((*QueryAssetSuppliesRequest)(nil), "kava.bep3.v1beta1.QueryAssetSuppliesRequest") - proto.RegisterType((*QueryAssetSuppliesResponse)(nil), "kava.bep3.v1beta1.QueryAssetSuppliesResponse") - proto.RegisterType((*QueryAtomicSwapRequest)(nil), "kava.bep3.v1beta1.QueryAtomicSwapRequest") - proto.RegisterType((*QueryAtomicSwapResponse)(nil), "kava.bep3.v1beta1.QueryAtomicSwapResponse") - proto.RegisterType((*AtomicSwapResponse)(nil), "kava.bep3.v1beta1.AtomicSwapResponse") - proto.RegisterType((*QueryAtomicSwapsRequest)(nil), "kava.bep3.v1beta1.QueryAtomicSwapsRequest") - proto.RegisterType((*QueryAtomicSwapsResponse)(nil), "kava.bep3.v1beta1.QueryAtomicSwapsResponse") -} - -func init() { proto.RegisterFile("kava/bep3/v1beta1/query.proto", fileDescriptor_a5e4082d53c18bf6) } - -var fileDescriptor_a5e4082d53c18bf6 = []byte{ - // 1176 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x56, 0x4f, 0x6f, 0x1b, 0xc5, - 0x1b, 0xb6, 0x9d, 0xc4, 0x8d, 0x5f, 0x3b, 0xf9, 0xfd, 0x98, 0x06, 0xba, 0x71, 0x5b, 0xdb, 0x5d, - 0x54, 0xd7, 0x2d, 0x8d, 0xb7, 0x4d, 0x05, 0x08, 0x90, 0x10, 0x4d, 0x4a, 0x08, 0x52, 0x95, 0xc2, - 0xe6, 0xc6, 0x81, 0xd5, 0x78, 0x77, 0x58, 0x8f, 0xe2, 0xdd, 0xd9, 0xec, 0xac, 0xd3, 0x86, 0xaa, - 0x07, 0x38, 0x71, 0x42, 0x48, 0x20, 0x04, 0xb7, 0x9e, 0xb9, 0x82, 0xf8, 0x0c, 0x3d, 0x56, 0x70, - 0xe1, 0x02, 0x45, 0x09, 0x07, 0x3e, 0x06, 0x9a, 0x3f, 0x6b, 0xaf, 0x63, 0x27, 0x71, 0x4e, 0xf6, - 0xbe, 0xef, 0xfb, 0x3c, 0xef, 0x33, 0x33, 0xcf, 0xfc, 0x81, 0xcb, 0x3b, 0x78, 0x0f, 0x5b, 0x1d, - 0x12, 0xdd, 0xb1, 0xf6, 0x6e, 0x77, 0x48, 0x82, 0x6f, 0x5b, 0xbb, 0x7d, 0x12, 0xef, 0xb7, 0xa3, - 0x98, 0x25, 0x0c, 0xbd, 0x24, 0xd2, 0x6d, 0x91, 0x6e, 0xeb, 0x74, 0xf5, 0x86, 0xcb, 0x78, 0xc0, - 0xb8, 0xd5, 0xc1, 0x9c, 0xa8, 0xda, 0x01, 0x32, 0xc2, 0x3e, 0x0d, 0x71, 0x42, 0x59, 0xa8, 0xe0, - 0xd5, 0x5a, 0xb6, 0x36, 0xad, 0x72, 0x19, 0x4d, 0xf3, 0xcb, 0x2a, 0xef, 0xc8, 0x2f, 0x4b, 0x7d, - 0xe8, 0xd4, 0x92, 0xcf, 0x7c, 0xa6, 0xe2, 0xe2, 0x9f, 0x8e, 0x5e, 0xf2, 0x19, 0xf3, 0x7b, 0xc4, - 0xc2, 0x11, 0xb5, 0x70, 0x18, 0xb2, 0x44, 0x76, 0x4b, 0x31, 0x35, 0x9d, 0x95, 0x5f, 0x9d, 0xfe, - 0x67, 0x96, 0xd7, 0x8f, 0xb3, 0x72, 0x2e, 0x8d, 0x0f, 0x56, 0x0e, 0x4d, 0x66, 0xcd, 0x25, 0x40, - 0x1f, 0x8b, 0xe1, 0x7c, 0x84, 0x63, 0x1c, 0x70, 0x9b, 0xec, 0xf6, 0x09, 0x4f, 0xcc, 0x2d, 0x38, - 0x3f, 0x12, 0xe5, 0x11, 0x0b, 0x39, 0x41, 0x6f, 0x42, 0x31, 0x92, 0x11, 0x23, 0xdf, 0xc8, 0xb7, - 0xca, 0xab, 0xcb, 0xed, 0xb1, 0x99, 0x6a, 0x2b, 0xc8, 0xda, 0xec, 0xb3, 0xbf, 0xea, 0x39, 0x5b, - 0x97, 0x9b, 0x6f, 0xc1, 0x05, 0xc9, 0x77, 0x97, 0x73, 0x92, 0x6c, 0xf7, 0xa3, 0xa8, 0xb7, 0xaf, - 0x5b, 0xa1, 0x25, 0x98, 0xf3, 0x48, 0xc8, 0x02, 0x49, 0x59, 0xb2, 0xd5, 0xc7, 0xdb, 0xf3, 0x5f, - 0x3d, 0xad, 0xe7, 0xfe, 0x7d, 0x5a, 0xcf, 0x99, 0x3f, 0xce, 0xc0, 0xf9, 0x11, 0x98, 0xd6, 0xb2, - 0x09, 0xff, 0xa3, 0xa1, 0xcb, 0x02, 0x1a, 0xfa, 0x0e, 0x97, 0xa9, 0x81, 0x28, 0x3d, 0xa5, 0x62, - 0xfe, 0x07, 0xb2, 0xd6, 0x19, 0x0d, 0xb5, 0xa8, 0xc5, 0x14, 0xa7, 0x18, 0x05, 0x13, 0xeb, 0x27, - 0x3e, 0xcb, 0x30, 0x15, 0xa6, 0x64, 0x4a, 0x71, 0x9a, 0x69, 0x03, 0x16, 0xdd, 0x7e, 0x1c, 0x93, - 0x30, 0x49, 0x89, 0x66, 0xa6, 0x23, 0x5a, 0xd0, 0x30, 0xcd, 0xf3, 0x29, 0x5c, 0x4c, 0x68, 0x40, - 0x9c, 0x1e, 0x0d, 0x68, 0x42, 0x3c, 0xe7, 0x08, 0xe9, 0xec, 0x74, 0xa4, 0x86, 0xe0, 0xb8, 0xaf, - 0x28, 0xd6, 0x47, 0xf8, 0x37, 0xa0, 0x22, 0xf9, 0x49, 0x0f, 0x47, 0x9c, 0x78, 0xc6, 0x9c, 0x26, - 0x54, 0x4e, 0x6a, 0xa7, 0x4e, 0x6a, 0xdf, 0xd3, 0x4e, 0x5a, 0x9b, 0x17, 0x84, 0x3f, 0xbc, 0xa8, - 0xe7, 0xed, 0xb2, 0x00, 0xbe, 0xaf, 0x70, 0xe6, 0x0e, 0x18, 0xe3, 0xcb, 0xaa, 0xd7, 0xe7, 0x01, - 0x54, 0xb0, 0x08, 0x8f, 0x2e, 0x4e, 0x73, 0x82, 0x63, 0x26, 0xa0, 0xf5, 0x08, 0xca, 0x78, 0x98, - 0x32, 0xaf, 0xc2, 0xf2, 0x91, 0x66, 0x94, 0xa4, 0x86, 0xcd, 0xf8, 0x65, 0x17, 0xaa, 0x93, 0xca, - 0xb4, 0xaa, 0x6d, 0x58, 0xcc, 0xa8, 0xa2, 0x44, 0x38, 0x79, 0xe6, 0xcc, 0xba, 0x16, 0x70, 0x96, - 0xdc, 0x7c, 0x07, 0x5e, 0x51, 0x2d, 0x13, 0x16, 0x50, 0x77, 0xfb, 0x21, 0x8e, 0x52, 0x73, 0x5f, - 0x80, 0x73, 0xfc, 0x21, 0x8e, 0x1c, 0xea, 0x69, 0x7b, 0x17, 0xc5, 0xe7, 0x87, 0x5e, 0x46, 0xaf, - 0x9f, 0x6e, 0x8d, 0x0c, 0x58, 0x8b, 0xbd, 0x0f, 0x65, 0x2c, 0xa3, 0x8e, 0x40, 0x69, 0x53, 0x5e, - 0x9d, 0xa4, 0x74, 0x0c, 0xab, 0x85, 0x02, 0x1e, 0x64, 0xcc, 0x2f, 0xe6, 0x00, 0x4d, 0x68, 0xb2, - 0x08, 0x85, 0x81, 0xba, 0x02, 0xf5, 0x90, 0x0b, 0x45, 0x1c, 0xb0, 0x7e, 0x98, 0x18, 0x05, 0x39, - 0x33, 0x27, 0xd8, 0xec, 0x96, 0xe8, 0xf1, 0xd3, 0x8b, 0x7a, 0xcb, 0xa7, 0x49, 0xb7, 0xdf, 0x69, - 0xbb, 0x2c, 0xd0, 0xc7, 0x99, 0xfe, 0x59, 0xe1, 0xde, 0x8e, 0x95, 0xec, 0x47, 0x84, 0x4b, 0x00, - 0xb7, 0x35, 0x35, 0xba, 0x09, 0x28, 0xc6, 0xa1, 0xc7, 0x02, 0x27, 0xec, 0x07, 0x1d, 0x12, 0x3b, - 0x5d, 0xcc, 0xbb, 0x72, 0xb3, 0x94, 0xec, 0xff, 0xab, 0xcc, 0x96, 0x4c, 0x6c, 0x62, 0xde, 0x45, - 0xaf, 0xc2, 0x02, 0x79, 0x14, 0xd1, 0x98, 0x38, 0x5d, 0x42, 0xfd, 0x6e, 0x22, 0x37, 0xc0, 0xac, - 0x5d, 0x51, 0xc1, 0x4d, 0x19, 0x43, 0x97, 0xa0, 0x24, 0xac, 0xc9, 0x13, 0x1c, 0x44, 0xd2, 0xd0, - 0x33, 0xf6, 0x30, 0x80, 0x6e, 0x41, 0x91, 0x93, 0xd0, 0x23, 0xb1, 0x51, 0x14, 0x4d, 0xd6, 0x8c, - 0xdf, 0x7e, 0x59, 0x59, 0xd2, 0x03, 0xbb, 0xeb, 0x79, 0x31, 0xe1, 0x7c, 0x3b, 0x89, 0x69, 0xe8, - 0xdb, 0xba, 0x0e, 0xbd, 0x01, 0xa5, 0x98, 0xb8, 0x34, 0xa2, 0x24, 0x4c, 0x8c, 0x73, 0xa7, 0x80, - 0x86, 0xa5, 0x62, 0x68, 0x8a, 0xc1, 0x61, 0x49, 0x97, 0xc4, 0x8e, 0xdb, 0xc5, 0x34, 0x34, 0xe6, - 0xd5, 0xd0, 0x54, 0xe6, 0x81, 0x48, 0xac, 0x8b, 0x38, 0x5a, 0x85, 0x97, 0x07, 0xd0, 0x11, 0x40, - 0x49, 0x02, 0xce, 0x0f, 0x92, 0x19, 0xcc, 0x15, 0xa8, 0xb8, 0x3d, 0xc6, 0x89, 0xe7, 0x74, 0x7a, - 0xcc, 0xdd, 0x31, 0x40, 0x0e, 0xb6, 0xac, 0x62, 0x6b, 0x22, 0x84, 0x5e, 0x87, 0x22, 0x4f, 0x70, - 0xd2, 0xe7, 0x46, 0xb9, 0x91, 0x6f, 0x2d, 0xae, 0x5e, 0x9e, 0x60, 0x1a, 0xe1, 0x82, 0x6d, 0x59, - 0x64, 0xeb, 0x62, 0x54, 0x87, 0xb2, 0x1b, 0x33, 0xce, 0xb5, 0x86, 0x4a, 0x23, 0xdf, 0x9a, 0xb7, - 0x41, 0x86, 0x54, 0xeb, 0x77, 0xa1, 0xe4, 0xd1, 0x98, 0xb8, 0xe2, 0x50, 0x30, 0x16, 0x24, 0x75, - 0xe3, 0x18, 0xea, 0x7b, 0x69, 0x9d, 0x3d, 0x84, 0x98, 0xbf, 0x16, 0xc6, 0xdc, 0x9e, 0x6e, 0x61, - 0xb4, 0x0a, 0xe7, 0x68, 0xb8, 0xc7, 0x7a, 0x7b, 0x44, 0xb9, 0xf1, 0x84, 0xe9, 0x4e, 0x0b, 0x51, - 0x0d, 0x40, 0x9a, 0x40, 0x9e, 0x52, 0x72, 0x83, 0xcc, 0xda, 0x99, 0x48, 0x66, 0x1e, 0x66, 0xce, - 0x32, 0x0f, 0x23, 0xc3, 0x9c, 0x3d, 0xf3, 0x30, 0xd1, 0x06, 0xc0, 0xf0, 0x55, 0xa0, 0x4f, 0xd7, - 0xe6, 0xc8, 0x3e, 0x52, 0xcf, 0x8d, 0xe1, 0x9d, 0xe9, 0x13, 0x3d, 0x0d, 0x76, 0x06, 0x99, 0x39, - 0x25, 0x7e, 0xce, 0xa7, 0x47, 0x6d, 0x76, 0xe2, 0xf4, 0x16, 0xde, 0x82, 0x4a, 0xe6, 0x9c, 0x48, - 0x8f, 0xb4, 0x33, 0x1d, 0x14, 0xe5, 0xe1, 0x41, 0xc1, 0xd1, 0x07, 0x23, 0xf2, 0xd5, 0x15, 0x76, - 0xed, 0x54, 0xf9, 0x8a, 0x2f, 0xab, 0x7f, 0xf5, 0xcf, 0x39, 0x98, 0x93, 0xaa, 0xd1, 0xe7, 0x50, - 0x54, 0x0f, 0x03, 0x34, 0x49, 0xd6, 0xf8, 0x0b, 0xa4, 0xda, 0x3c, 0xad, 0x4c, 0xb5, 0x33, 0xaf, - 0x7c, 0xf9, 0xfb, 0x3f, 0xdf, 0x16, 0x2e, 0xa2, 0x65, 0x6b, 0xfc, 0x99, 0xa3, 0x1e, 0x1f, 0xe8, - 0xfb, 0x3c, 0x94, 0x33, 0x67, 0x39, 0xba, 0x71, 0x1c, 0xf5, 0xf8, 0xeb, 0xa4, 0xfa, 0xda, 0x54, - 0xb5, 0x5a, 0x4b, 0x5b, 0x6a, 0x69, 0xa1, 0xe6, 0x04, 0x2d, 0xf2, 0xc6, 0x50, 0x57, 0xa1, 0xf5, - 0x58, 0xbe, 0x71, 0x9e, 0x08, 0x61, 0x0b, 0x23, 0xd7, 0x14, 0xba, 0x79, 0x7a, 0xbb, 0xe1, 0xa5, - 0x57, 0x5d, 0x99, 0xb2, 0x5a, 0xcb, 0x6b, 0x49, 0x79, 0x26, 0x6a, 0x9c, 0x28, 0x4f, 0xc8, 0xf8, - 0x2e, 0x0f, 0x30, 0xb4, 0x0a, 0xba, 0x7e, 0x6c, 0x9f, 0xa3, 0x17, 0x5e, 0xf5, 0xc6, 0x34, 0xa5, - 0x5a, 0x8f, 0x25, 0xf5, 0x5c, 0x47, 0xd7, 0x26, 0xe9, 0x91, 0xe5, 0xc2, 0xce, 0xd6, 0x63, 0x7d, - 0x83, 0x3e, 0x41, 0x5f, 0x8b, 0x85, 0xcc, 0xf8, 0x74, 0x8a, 0x66, 0xfc, 0xf4, 0x85, 0x1c, 0xdf, - 0x50, 0x66, 0x53, 0x2a, 0x6b, 0xa0, 0xda, 0x89, 0xca, 0xf8, 0xda, 0x7b, 0xcf, 0x0e, 0x6a, 0xf9, - 0xe7, 0x07, 0xb5, 0xfc, 0xdf, 0x07, 0xb5, 0xfc, 0x37, 0x87, 0xb5, 0xdc, 0xf3, 0xc3, 0x5a, 0xee, - 0x8f, 0xc3, 0x5a, 0xee, 0x93, 0x66, 0xe6, 0x4a, 0x14, 0x1c, 0x2b, 0x3d, 0xdc, 0xe1, 0x8a, 0xed, - 0x91, 0xe2, 0x93, 0xd7, 0x62, 0xa7, 0x28, 0xdf, 0x5a, 0x77, 0xfe, 0x0b, 0x00, 0x00, 0xff, 0xff, - 0xd4, 0xac, 0x57, 0x4a, 0x92, 0x0c, 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 { - // Params queries module params - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // AssetSupply queries info about an asset's supply - AssetSupply(ctx context.Context, in *QueryAssetSupplyRequest, opts ...grpc.CallOption) (*QueryAssetSupplyResponse, error) - // AssetSupplies queries a list of asset supplies - AssetSupplies(ctx context.Context, in *QueryAssetSuppliesRequest, opts ...grpc.CallOption) (*QueryAssetSuppliesResponse, error) - // AtomicSwap queries info about an atomic swap - AtomicSwap(ctx context.Context, in *QueryAtomicSwapRequest, opts ...grpc.CallOption) (*QueryAtomicSwapResponse, error) - // AtomicSwaps queries a list of atomic swaps - AtomicSwaps(ctx context.Context, in *QueryAtomicSwapsRequest, opts ...grpc.CallOption) (*QueryAtomicSwapsResponse, 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, "/kava.bep3.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) AssetSupply(ctx context.Context, in *QueryAssetSupplyRequest, opts ...grpc.CallOption) (*QueryAssetSupplyResponse, error) { - out := new(QueryAssetSupplyResponse) - err := c.cc.Invoke(ctx, "/kava.bep3.v1beta1.Query/AssetSupply", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) AssetSupplies(ctx context.Context, in *QueryAssetSuppliesRequest, opts ...grpc.CallOption) (*QueryAssetSuppliesResponse, error) { - out := new(QueryAssetSuppliesResponse) - err := c.cc.Invoke(ctx, "/kava.bep3.v1beta1.Query/AssetSupplies", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) AtomicSwap(ctx context.Context, in *QueryAtomicSwapRequest, opts ...grpc.CallOption) (*QueryAtomicSwapResponse, error) { - out := new(QueryAtomicSwapResponse) - err := c.cc.Invoke(ctx, "/kava.bep3.v1beta1.Query/AtomicSwap", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) AtomicSwaps(ctx context.Context, in *QueryAtomicSwapsRequest, opts ...grpc.CallOption) (*QueryAtomicSwapsResponse, error) { - out := new(QueryAtomicSwapsResponse) - err := c.cc.Invoke(ctx, "/kava.bep3.v1beta1.Query/AtomicSwaps", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries module params - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // AssetSupply queries info about an asset's supply - AssetSupply(context.Context, *QueryAssetSupplyRequest) (*QueryAssetSupplyResponse, error) - // AssetSupplies queries a list of asset supplies - AssetSupplies(context.Context, *QueryAssetSuppliesRequest) (*QueryAssetSuppliesResponse, error) - // AtomicSwap queries info about an atomic swap - AtomicSwap(context.Context, *QueryAtomicSwapRequest) (*QueryAtomicSwapResponse, error) - // AtomicSwaps queries a list of atomic swaps - AtomicSwaps(context.Context, *QueryAtomicSwapsRequest) (*QueryAtomicSwapsResponse, 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) AssetSupply(ctx context.Context, req *QueryAssetSupplyRequest) (*QueryAssetSupplyResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method AssetSupply not implemented") -} -func (*UnimplementedQueryServer) AssetSupplies(ctx context.Context, req *QueryAssetSuppliesRequest) (*QueryAssetSuppliesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method AssetSupplies not implemented") -} -func (*UnimplementedQueryServer) AtomicSwap(ctx context.Context, req *QueryAtomicSwapRequest) (*QueryAtomicSwapResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method AtomicSwap not implemented") -} -func (*UnimplementedQueryServer) AtomicSwaps(ctx context.Context, req *QueryAtomicSwapsRequest) (*QueryAtomicSwapsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method AtomicSwaps 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: "/kava.bep3.v1beta1.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_AssetSupply_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAssetSupplyRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).AssetSupply(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.bep3.v1beta1.Query/AssetSupply", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).AssetSupply(ctx, req.(*QueryAssetSupplyRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_AssetSupplies_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAssetSuppliesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).AssetSupplies(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.bep3.v1beta1.Query/AssetSupplies", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).AssetSupplies(ctx, req.(*QueryAssetSuppliesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_AtomicSwap_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAtomicSwapRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).AtomicSwap(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.bep3.v1beta1.Query/AtomicSwap", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).AtomicSwap(ctx, req.(*QueryAtomicSwapRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_AtomicSwaps_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAtomicSwapsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).AtomicSwaps(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.bep3.v1beta1.Query/AtomicSwaps", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).AtomicSwaps(ctx, req.(*QueryAtomicSwapsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.bep3.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "AssetSupply", - Handler: _Query_AssetSupply_Handler, - }, - { - MethodName: "AssetSupplies", - Handler: _Query_AssetSupplies_Handler, - }, - { - MethodName: "AtomicSwap", - Handler: _Query_AtomicSwap_Handler, - }, - { - MethodName: "AtomicSwaps", - Handler: _Query_AtomicSwaps_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/bep3/v1beta1/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 *QueryAssetSupplyRequest) 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 *QueryAssetSupplyRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAssetSupplyRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *AssetSupplyResponse) 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 *AssetSupplyResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AssetSupplyResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - n2, err2 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.TimeElapsed, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.TimeElapsed):]) - if err2 != nil { - return 0, err2 - } - i -= n2 - i = encodeVarintQuery(dAtA, i, uint64(n2)) - i-- - dAtA[i] = 0x2a - { - size, err := m.TimeLimitedCurrentSupply.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.CurrentSupply.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.OutgoingSupply.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.IncomingSupply.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 *QueryAssetSupplyResponse) 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 *QueryAssetSupplyResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAssetSupplyResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.AssetSupply.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 *QueryAssetSuppliesRequest) 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 *QueryAssetSuppliesRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAssetSuppliesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryAssetSuppliesResponse) 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 *QueryAssetSuppliesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAssetSuppliesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.AssetSupplies) > 0 { - for iNdEx := len(m.AssetSupplies) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.AssetSupplies[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 (m *QueryAtomicSwapRequest) 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 *QueryAtomicSwapRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAtomicSwapRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.SwapId) > 0 { - i -= len(m.SwapId) - copy(dAtA[i:], m.SwapId) - i = encodeVarintQuery(dAtA, i, uint64(len(m.SwapId))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryAtomicSwapResponse) 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 *QueryAtomicSwapResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAtomicSwapResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.AtomicSwap.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - return len(dAtA) - i, nil -} - -func (m *AtomicSwapResponse) 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 *AtomicSwapResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AtomicSwapResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Direction != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.Direction)) - i-- - dAtA[i] = 0x68 - } - if m.CrossChain { - i-- - if m.CrossChain { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x60 - } - if m.Status != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.Status)) - i-- - dAtA[i] = 0x58 - } - if m.ClosedBlock != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.ClosedBlock)) - i-- - dAtA[i] = 0x50 - } - if len(m.RecipientOtherChain) > 0 { - i -= len(m.RecipientOtherChain) - copy(dAtA[i:], m.RecipientOtherChain) - i = encodeVarintQuery(dAtA, i, uint64(len(m.RecipientOtherChain))) - i-- - dAtA[i] = 0x4a - } - if len(m.SenderOtherChain) > 0 { - i -= len(m.SenderOtherChain) - copy(dAtA[i:], m.SenderOtherChain) - i = encodeVarintQuery(dAtA, i, uint64(len(m.SenderOtherChain))) - i-- - dAtA[i] = 0x42 - } - if len(m.Recipient) > 0 { - i -= len(m.Recipient) - copy(dAtA[i:], m.Recipient) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Recipient))) - i-- - dAtA[i] = 0x3a - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0x32 - } - if m.Timestamp != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.Timestamp)) - i-- - dAtA[i] = 0x28 - } - if m.ExpireHeight != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.ExpireHeight)) - i-- - dAtA[i] = 0x20 - } - if len(m.RandomNumberHash) > 0 { - i -= len(m.RandomNumberHash) - copy(dAtA[i:], m.RandomNumberHash) - i = encodeVarintQuery(dAtA, i, uint64(len(m.RandomNumberHash))) - i-- - dAtA[i] = 0x1a - } - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Id) > 0 { - i -= len(m.Id) - copy(dAtA[i:], m.Id) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Id))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryAtomicSwapsRequest) 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 *QueryAtomicSwapsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAtomicSwapsRequest) 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] = 0x2a - } - if m.Direction != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.Direction)) - i-- - dAtA[i] = 0x20 - } - if m.Status != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.Status)) - i-- - dAtA[i] = 0x18 - } - if m.Expiration != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.Expiration)) - i-- - dAtA[i] = 0x10 - } - if len(m.Involve) > 0 { - i -= len(m.Involve) - copy(dAtA[i:], m.Involve) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Involve))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryAtomicSwapsResponse) 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 *QueryAtomicSwapsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAtomicSwapsResponse) 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] = 0x1a - } - if len(m.AtomicSwaps) > 0 { - for iNdEx := len(m.AtomicSwaps) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.AtomicSwaps[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 *QueryAssetSupplyRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *AssetSupplyResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.IncomingSupply.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.OutgoingSupply.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.CurrentSupply.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.TimeLimitedCurrentSupply.Size() - n += 1 + l + sovQuery(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.TimeElapsed) - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryAssetSupplyResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.AssetSupply.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryAssetSuppliesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryAssetSuppliesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.AssetSupplies) > 0 { - for _, e := range m.AssetSupplies { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryAtomicSwapRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.SwapId) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryAtomicSwapResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.AtomicSwap.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *AtomicSwapResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Id) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - l = len(m.RandomNumberHash) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.ExpireHeight != 0 { - n += 1 + sovQuery(uint64(m.ExpireHeight)) - } - if m.Timestamp != 0 { - n += 1 + sovQuery(uint64(m.Timestamp)) - } - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Recipient) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.SenderOtherChain) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.RecipientOtherChain) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.ClosedBlock != 0 { - n += 1 + sovQuery(uint64(m.ClosedBlock)) - } - if m.Status != 0 { - n += 1 + sovQuery(uint64(m.Status)) - } - if m.CrossChain { - n += 2 - } - if m.Direction != 0 { - n += 1 + sovQuery(uint64(m.Direction)) - } - return n -} - -func (m *QueryAtomicSwapsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Involve) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Expiration != 0 { - n += 1 + sovQuery(uint64(m.Expiration)) - } - if m.Status != 0 { - n += 1 + sovQuery(uint64(m.Status)) - } - if m.Direction != 0 { - n += 1 + sovQuery(uint64(m.Direction)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryAtomicSwapsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.AtomicSwaps) > 0 { - for _, e := range m.AtomicSwaps { - 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 *QueryAssetSupplyRequest) 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: QueryAssetSupplyRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAssetSupplyRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - 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 *AssetSupplyResponse) 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: AssetSupplyResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AssetSupplyResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IncomingSupply", 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.IncomingSupply.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OutgoingSupply", 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.OutgoingSupply.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CurrentSupply", 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.CurrentSupply.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TimeLimitedCurrentSupply", 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.TimeLimitedCurrentSupply.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TimeElapsed", 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 := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.TimeElapsed, 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 *QueryAssetSupplyResponse) 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: QueryAssetSupplyResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAssetSupplyResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AssetSupply", 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.AssetSupply.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 *QueryAssetSuppliesRequest) 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: QueryAssetSuppliesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAssetSuppliesRequest: 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 *QueryAssetSuppliesResponse) 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: QueryAssetSuppliesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAssetSuppliesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AssetSupplies", 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.AssetSupplies = append(m.AssetSupplies, AssetSupplyResponse{}) - if err := m.AssetSupplies[len(m.AssetSupplies)-1].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 *QueryAtomicSwapRequest) 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: QueryAtomicSwapRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAtomicSwapRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SwapId", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SwapId = string(dAtA[iNdEx:postIndex]) - 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 *QueryAtomicSwapResponse) 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: QueryAtomicSwapResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAtomicSwapResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AtomicSwap", 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.AtomicSwap.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 *AtomicSwapResponse) 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: AtomicSwapResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AtomicSwapResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Id = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", 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.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RandomNumberHash", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RandomNumberHash = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ExpireHeight", wireType) - } - m.ExpireHeight = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ExpireHeight |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) - } - m.Timestamp = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Timestamp |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Recipient", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Recipient = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SenderOtherChain", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SenderOtherChain = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RecipientOtherChain", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RecipientOtherChain = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 10: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ClosedBlock", wireType) - } - m.ClosedBlock = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ClosedBlock |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 11: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) - } - m.Status = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Status |= SwapStatus(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 12: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CrossChain", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CrossChain = bool(v != 0) - case 13: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Direction", wireType) - } - m.Direction = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Direction |= SwapDirection(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 *QueryAtomicSwapsRequest) 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: QueryAtomicSwapsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAtomicSwapsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Involve", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Involve = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Expiration", wireType) - } - m.Expiration = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Expiration |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) - } - m.Status = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Status |= SwapStatus(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Direction", wireType) - } - m.Direction = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Direction |= SwapDirection(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 5: - 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 *QueryAtomicSwapsResponse) 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: QueryAtomicSwapsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAtomicSwapsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AtomicSwaps", 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.AtomicSwaps = append(m.AtomicSwaps, AtomicSwapResponse{}) - if err := m.AtomicSwaps[len(m.AtomicSwaps)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field 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/bep3/types/query.pb.gw.go b/x/bep3/types/query.pb.gw.go deleted file mode 100644 index 66c597e2..00000000 --- a/x/bep3/types/query.pb.gw.go +++ /dev/null @@ -1,503 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/bep3/v1beta1/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_AssetSupply_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAssetSupplyRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["denom"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "denom") - } - - protoReq.Denom, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "denom", err) - } - - msg, err := client.AssetSupply(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_AssetSupply_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAssetSupplyRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["denom"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "denom") - } - - protoReq.Denom, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "denom", err) - } - - msg, err := server.AssetSupply(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_AssetSupplies_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAssetSuppliesRequest - var metadata runtime.ServerMetadata - - msg, err := client.AssetSupplies(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_AssetSupplies_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAssetSuppliesRequest - var metadata runtime.ServerMetadata - - msg, err := server.AssetSupplies(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_AtomicSwap_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAtomicSwapRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["swap_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "swap_id") - } - - protoReq.SwapId, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "swap_id", err) - } - - msg, err := client.AtomicSwap(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_AtomicSwap_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAtomicSwapRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["swap_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "swap_id") - } - - protoReq.SwapId, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "swap_id", err) - } - - msg, err := server.AtomicSwap(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_AtomicSwaps_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_AtomicSwaps_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAtomicSwapsRequest - 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_AtomicSwaps_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.AtomicSwaps(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_AtomicSwaps_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAtomicSwapsRequest - 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_AtomicSwaps_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.AtomicSwaps(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_AssetSupply_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_AssetSupply_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_AssetSupply_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_AssetSupplies_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_AssetSupplies_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_AssetSupplies_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_AtomicSwap_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_AtomicSwap_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_AtomicSwap_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_AtomicSwaps_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_AtomicSwaps_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_AtomicSwaps_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_AssetSupply_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_AssetSupply_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_AssetSupply_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_AssetSupplies_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_AssetSupplies_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_AssetSupplies_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_AtomicSwap_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_AtomicSwap_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_AtomicSwap_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_AtomicSwaps_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_AtomicSwaps_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_AtomicSwaps_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{"kava", "bep3", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_AssetSupply_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"kava", "bep3", "v1beta1", "assetsupply", "denom"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_AssetSupplies_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "bep3", "v1beta1", "assetsupplies"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_AtomicSwap_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"kava", "bep3", "v1beta1", "atomicswap", "swap_id"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_AtomicSwaps_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "bep3", "v1beta1", "atomicswaps"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_AssetSupply_0 = runtime.ForwardResponseMessage - - forward_Query_AssetSupplies_0 = runtime.ForwardResponseMessage - - forward_Query_AtomicSwap_0 = runtime.ForwardResponseMessage - - forward_Query_AtomicSwaps_0 = runtime.ForwardResponseMessage -) diff --git a/x/bep3/types/supply.go b/x/bep3/types/supply.go deleted file mode 100644 index f9526f68..00000000 --- a/x/bep3/types/supply.go +++ /dev/null @@ -1,64 +0,0 @@ -package types - -import ( - "fmt" - "time" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// NewAssetSupply initializes a new AssetSupply -func NewAssetSupply(incomingSupply, outgoingSupply, currentSupply, timeLimitedSupply sdk.Coin, timeElapsed time.Duration) AssetSupply { - return AssetSupply{ - IncomingSupply: incomingSupply, - OutgoingSupply: outgoingSupply, - CurrentSupply: currentSupply, - TimeLimitedCurrentSupply: timeLimitedSupply, - TimeElapsed: timeElapsed, - } -} - -// Validate performs a basic validation of an asset supply fields. -func (a AssetSupply) Validate() error { - if !a.IncomingSupply.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "incoming supply %s", a.IncomingSupply) - } - if !a.OutgoingSupply.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "outgoing supply %s", a.OutgoingSupply) - } - if !a.CurrentSupply.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "current supply %s", a.CurrentSupply) - } - if !a.TimeLimitedCurrentSupply.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "time-limited current supply %s", a.TimeLimitedCurrentSupply) - } - denom := a.CurrentSupply.Denom - if (a.IncomingSupply.Denom != denom) || - (a.OutgoingSupply.Denom != denom) || - (a.TimeLimitedCurrentSupply.Denom != denom) { - return fmt.Errorf("asset supply denoms do not match %s %s %s %s", a.CurrentSupply.Denom, a.IncomingSupply.Denom, a.OutgoingSupply.Denom, a.TimeLimitedCurrentSupply.Denom) - } - return nil -} - -// Equal returns if two asset supplies are equal -func (a AssetSupply) Equal(b AssetSupply) bool { - if a.GetDenom() != b.GetDenom() { - return false - } - return (a.IncomingSupply.IsEqual(b.IncomingSupply) && - a.CurrentSupply.IsEqual(b.CurrentSupply) && - a.OutgoingSupply.IsEqual(b.OutgoingSupply) && - a.TimeLimitedCurrentSupply.IsEqual(b.TimeLimitedCurrentSupply) && - a.TimeElapsed == b.TimeElapsed) -} - -// GetDenom getter method for the denom of the asset supply -func (a AssetSupply) GetDenom() string { - return a.CurrentSupply.Denom -} - -// AssetSupplies is a slice of AssetSupply -type AssetSupplies []AssetSupply diff --git a/x/bep3/types/supply_test.go b/x/bep3/types/supply_test.go deleted file mode 100644 index cefbf0e8..00000000 --- a/x/bep3/types/supply_test.go +++ /dev/null @@ -1,122 +0,0 @@ -package types - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestAssetSupplyValidate(t *testing.T) { - coin := sdk.NewCoin("kava", sdk.OneInt()) - invalidCoin := sdk.Coin{Denom: "Invalid Denom", Amount: sdkmath.NewInt(-1)} - testCases := []struct { - msg string - asset AssetSupply - expPass bool - }{ - { - msg: "valid asset", - asset: NewAssetSupply(coin, coin, coin, coin, time.Duration(0)), - expPass: true, - }, - { - "invalid incoming supply", - AssetSupply{IncomingSupply: invalidCoin}, - false, - }, - { - "invalid outgoing supply", - AssetSupply{ - IncomingSupply: coin, - OutgoingSupply: invalidCoin, - }, - false, - }, - { - "invalid current supply", - AssetSupply{ - IncomingSupply: coin, - OutgoingSupply: coin, - CurrentSupply: invalidCoin, - }, - false, - }, - { - "invalid time limitedcurrent supply", - AssetSupply{ - IncomingSupply: coin, - OutgoingSupply: coin, - CurrentSupply: coin, - TimeLimitedCurrentSupply: invalidCoin, - }, - false, - }, - { - "non matching denoms", - AssetSupply{ - IncomingSupply: coin, - OutgoingSupply: coin, - CurrentSupply: coin, - TimeLimitedCurrentSupply: sdk.NewCoin("lol", sdk.ZeroInt()), - TimeElapsed: time.Hour, - }, - false, - }, - } - - for _, tc := range testCases { - err := tc.asset.Validate() - if tc.expPass { - require.NoError(t, err, tc.msg) - } else { - require.Error(t, err, tc.msg) - } - } -} - -func TestAssetSupplyEquality(t *testing.T) { - coin := sdk.NewCoin("test", sdk.OneInt()) - coin2 := sdk.NewCoin("other", sdk.OneInt()) - testCases := []struct { - name string - asset1 AssetSupply - asset2 AssetSupply - expPass bool - }{ - { - name: "equal", - asset1: NewAssetSupply(coin, coin, coin, coin, time.Duration(0)), - asset2: NewAssetSupply(coin, coin, coin, coin, time.Duration(0)), - expPass: true, - }, - { - name: "not equal duration", - asset1: NewAssetSupply(coin, coin, coin, coin, time.Duration(0)), - asset2: NewAssetSupply(coin, coin, coin, coin, time.Duration(1)), - expPass: false, - }, - { - name: "not equal coin amount", - asset1: NewAssetSupply(coin, coin, coin, coin, time.Duration(0)), - asset2: NewAssetSupply(sdk.NewCoin("test", sdk.ZeroInt()), coin, coin, coin, time.Duration(1)), - expPass: false, - }, - { - name: "not equal coin denom", - asset1: NewAssetSupply(coin, coin, coin, coin, time.Duration(0)), - asset2: NewAssetSupply(coin2, coin2, coin2, coin2, time.Duration(1)), - expPass: false, - }, - } - - for _, tc := range testCases { - if tc.expPass { - require.True(t, tc.asset1.Equal(tc.asset2), tc.name) - } else { - require.False(t, tc.asset1.Equal(tc.asset2), tc.name) - } - } -} diff --git a/x/bep3/types/swap.go b/x/bep3/types/swap.go deleted file mode 100644 index d5203223..00000000 --- a/x/bep3/types/swap.go +++ /dev/null @@ -1,170 +0,0 @@ -package types - -import ( - "encoding/hex" - "errors" - "fmt" - "strings" - - tmbytes "github.com/cometbft/cometbft/libs/bytes" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// NewAtomicSwap returns a new AtomicSwap -func NewAtomicSwap(amount sdk.Coins, randomNumberHash tmbytes.HexBytes, expireHeight uint64, timestamp int64, - sender, recipient sdk.AccAddress, senderOtherChain, recipientOtherChain string, closedBlock int64, - status SwapStatus, crossChain bool, direction SwapDirection, -) AtomicSwap { - return AtomicSwap{ - Amount: amount, - RandomNumberHash: randomNumberHash, - ExpireHeight: expireHeight, - Timestamp: timestamp, - Sender: sender, - Recipient: recipient, - SenderOtherChain: senderOtherChain, - RecipientOtherChain: recipientOtherChain, - ClosedBlock: closedBlock, - Status: status, - CrossChain: crossChain, - Direction: direction, - } -} - -// GetSwapID calculates the ID of an atomic swap -func (a AtomicSwap) GetSwapID() tmbytes.HexBytes { - return CalculateSwapID(a.RandomNumberHash, a.Sender, a.SenderOtherChain) -} - -// GetCoins returns the swap's amount as sdk.Coins -func (a AtomicSwap) GetCoins() sdk.Coins { - return sdk.NewCoins(a.Amount...) -} - -// Validate performs a basic validation of an atomic swap fields. -func (a AtomicSwap) Validate() error { - if !a.Amount.IsValid() { - return fmt.Errorf("invalid amount: %s", a.Amount) - } - if !a.Amount.IsAllPositive() { - return fmt.Errorf("the swapped out coin must be positive: %s", a.Amount) - } - if len(a.RandomNumberHash) != RandomNumberHashLength { - return fmt.Errorf("the length of random number hash should be %d", RandomNumberHashLength) - } - if a.ExpireHeight == 0 { - return errors.New("expire height cannot be 0") - } - if a.Timestamp == 0 { - return errors.New("timestamp cannot be 0") - } - if a.Sender.Empty() { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender cannot be empty") - } - if a.Recipient.Empty() { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "recipient cannot be empty") - } - // NOTE: These adresses may not have a bech32 prefix. - if strings.TrimSpace(a.SenderOtherChain) == "" { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender other chain cannot be blank") - } - if strings.TrimSpace(a.RecipientOtherChain) == "" { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "recipient other chain cannot be blank") - } - if a.Status == SWAP_STATUS_COMPLETED && a.ClosedBlock == 0 { - return errors.New("closed block cannot be 0") - } - if a.Status == SWAP_STATUS_UNSPECIFIED || a.Status > 3 { - return errors.New("invalid swap status") - } - if a.Direction == SWAP_DIRECTION_UNSPECIFIED || a.Direction > 2 { - return errors.New("invalid swap direction") - } - return nil -} - -// AtomicSwaps is a slice of AtomicSwap -type AtomicSwaps []AtomicSwap - -// NewSwapStatusFromString converts string to SwapStatus type -func NewSwapStatusFromString(str string) SwapStatus { - switch str { - case "Open", "open": - return SWAP_STATUS_OPEN - case "Completed", "completed": - return SWAP_STATUS_COMPLETED - case "Expired", "expired": - return SWAP_STATUS_EXPIRED - default: - return SWAP_STATUS_UNSPECIFIED - } -} - -// IsValid returns true if the swap status is valid and false otherwise. -func (status SwapStatus) IsValid() bool { - return status == SWAP_STATUS_OPEN || - status == SWAP_STATUS_COMPLETED || - status == SWAP_STATUS_EXPIRED -} - -// NewSwapDirectionFromString converts string to SwapDirection type -func NewSwapDirectionFromString(str string) SwapDirection { - switch str { - case "Incoming", "incoming", "inc", "I", "i": - return SWAP_DIRECTION_INCOMING - case "Outgoing", "outgoing", "out", "O", "o": - return SWAP_DIRECTION_OUTGOING - default: - return SWAP_DIRECTION_UNSPECIFIED - } -} - -// IsValid returns true if the swap direction is valid and false otherwise. -func (direction SwapDirection) IsValid() bool { - return direction == SWAP_DIRECTION_INCOMING || - direction == SWAP_DIRECTION_OUTGOING -} - -// LegacyAugmentedAtomicSwap defines an ID and AtomicSwap fields on the top level. -// This should be removed when legacy REST endpoints are removed. -type LegacyAugmentedAtomicSwap struct { - ID string `json:"id" yaml:"id"` - - // Embed AtomicSwap fields explicity in order to output as top level JSON fields - // This prevents breaking changes for clients using REST API - Amount sdk.Coins `json:"amount" yaml:"amount"` - RandomNumberHash tmbytes.HexBytes `json:"random_number_hash" yaml:"random_number_hash"` - ExpireHeight uint64 `json:"expire_height" yaml:"expire_height"` - Timestamp int64 `json:"timestamp" yaml:"timestamp"` - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - Recipient sdk.AccAddress `json:"recipient" yaml:"recipient"` - SenderOtherChain string `json:"sender_other_chain" yaml:"sender_other_chain"` - RecipientOtherChain string `json:"recipient_other_chain" yaml:"recipient_other_chain"` - ClosedBlock int64 `json:"closed_block" yaml:"closed_block"` - Status SwapStatus `json:"status" yaml:"status"` - CrossChain bool `json:"cross_chain" yaml:"cross_chain"` - Direction SwapDirection `json:"direction" yaml:"direction"` -} - -func NewLegacyAugmentedAtomicSwap(swap AtomicSwap) LegacyAugmentedAtomicSwap { - return LegacyAugmentedAtomicSwap{ - ID: hex.EncodeToString(swap.GetSwapID()), - Amount: swap.Amount, - RandomNumberHash: swap.RandomNumberHash, - ExpireHeight: swap.ExpireHeight, - Timestamp: swap.Timestamp, - Sender: swap.Sender, - Recipient: swap.Recipient, - SenderOtherChain: swap.SenderOtherChain, - RecipientOtherChain: swap.RecipientOtherChain, - ClosedBlock: swap.ClosedBlock, - Status: swap.Status, - CrossChain: swap.CrossChain, - Direction: swap.Direction, - } -} - -type LegacyAugmentedAtomicSwaps []LegacyAugmentedAtomicSwap diff --git a/x/bep3/types/swap_test.go b/x/bep3/types/swap_test.go deleted file mode 100644 index ca0d6071..00000000 --- a/x/bep3/types/swap_test.go +++ /dev/null @@ -1,254 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - tmbytes "github.com/cometbft/cometbft/libs/bytes" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/bep3/types" -) - -type AtomicSwapTestSuite struct { - suite.Suite - addrs []sdk.AccAddress - timestamps []int64 - randomNumberHashes []tmbytes.HexBytes -} - -func (suite *AtomicSwapTestSuite) SetupTest() { - // Generate 10 addresses - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - _, addrs := app.GeneratePrivKeyAddressPairs(10) - - // Generate 10 timestamps and random number hashes - var timestamps []int64 - var randomNumberHashes []tmbytes.HexBytes - for i := 0; i < 10; i++ { - timestamp := ts(i) - randomNumber, _ := types.GenerateSecureRandomNumber() - randomNumberHash := types.CalculateRandomHash(randomNumber[:], timestamp) - timestamps = append(timestamps, timestamp) - randomNumberHashes = append(randomNumberHashes, randomNumberHash) - } - - suite.addrs = addrs - suite.timestamps = timestamps - suite.randomNumberHashes = randomNumberHashes -} - -func (suite *AtomicSwapTestSuite) TestNewAtomicSwap() { - testCases := []struct { - msg string - swap types.AtomicSwap - expectPass bool - }{ - { - "valid Swap", - types.AtomicSwap{ - Amount: cs(c("bnb", 50000)), - RandomNumberHash: suite.randomNumberHashes[0], - ExpireHeight: 360, - Timestamp: suite.timestamps[0], - Sender: suite.addrs[0], - Recipient: suite.addrs[5], - RecipientOtherChain: "bnb1urfermcg92dwq36572cx4xg84wpk3lfpksr5g7", - SenderOtherChain: "bnb1uky3me9ggqypmrsvxk7ur6hqkzq7zmv4ed4ng7", - ClosedBlock: 1, - Status: types.SWAP_STATUS_OPEN, - CrossChain: true, - Direction: types.SWAP_DIRECTION_INCOMING, - }, - true, - }, - { - "invalid amount", - types.AtomicSwap{ - Amount: sdk.Coins{sdk.Coin{Denom: "BNB", Amount: sdkmath.NewInt(10)}}, - }, - false, - }, - { - "amount not positive", - types.AtomicSwap{ - Amount: cs(c("bnb", 0)), - }, - false, - }, - { - "invalid random number hash length", - types.AtomicSwap{ - Amount: cs(c("bnb", 50000)), - RandomNumberHash: suite.randomNumberHashes[1][0:20], - }, - false, - }, - { - "exp height 0", - types.AtomicSwap{ - Amount: cs(c("bnb", 50000)), - RandomNumberHash: suite.randomNumberHashes[0], - ExpireHeight: 0, - }, - false, - }, - { - "timestamp 0", - types.AtomicSwap{ - Amount: cs(c("bnb", 50000)), - RandomNumberHash: suite.randomNumberHashes[0], - ExpireHeight: 10, - Timestamp: 0, - }, - false, - }, - { - "empty sender", - types.AtomicSwap{ - Amount: cs(c("bnb", 50000)), - RandomNumberHash: suite.randomNumberHashes[0], - ExpireHeight: 10, - Timestamp: 10, - Sender: nil, - }, - false, - }, - { - "empty recipient", - types.AtomicSwap{ - Amount: cs(c("bnb", 50000)), - RandomNumberHash: suite.randomNumberHashes[0], - ExpireHeight: 10, - Timestamp: 10, - Sender: suite.addrs[0], - Recipient: nil, - }, - false, - }, - { - "invalid sender length", - types.AtomicSwap{ - Amount: cs(c("bnb", 50000)), - RandomNumberHash: suite.randomNumberHashes[0], - ExpireHeight: 10, - Timestamp: 10, - Sender: suite.addrs[0][:10], - Recipient: suite.addrs[5], - }, - false, - }, - { - "invalid recipient length", - types.AtomicSwap{ - Amount: cs(c("bnb", 50000)), - RandomNumberHash: suite.randomNumberHashes[0], - ExpireHeight: 10, - Timestamp: 10, - Sender: suite.addrs[0], - Recipient: suite.addrs[5][:10], - }, - false, - }, - { - "invalid sender other chain", - types.AtomicSwap{ - Amount: cs(c("bnb", 50000)), - RandomNumberHash: suite.randomNumberHashes[0], - ExpireHeight: 10, - Timestamp: 10, - Sender: suite.addrs[0], - Recipient: suite.addrs[5], - SenderOtherChain: "", - }, - false, - }, - { - "invalid recipient other chain", - types.AtomicSwap{ - Amount: cs(c("bnb", 50000)), - RandomNumberHash: suite.randomNumberHashes[0], - ExpireHeight: 10, - Timestamp: 10, - Sender: suite.addrs[0], - Recipient: suite.addrs[5], - SenderOtherChain: "bnb1uky3me9ggqypmrsvxk7ur6hqkzq7zmv4ed4ng7", - RecipientOtherChain: "", - }, - false, - }, - { - "closed block 0", - types.AtomicSwap{ - Amount: cs(c("bnb", 50000)), - RandomNumberHash: suite.randomNumberHashes[0], - ExpireHeight: 10, - Timestamp: 10, - Sender: suite.addrs[0], - Recipient: suite.addrs[5], - SenderOtherChain: "bnb1uky3me9ggqypmrsvxk7ur6hqkzq7zmv4ed4ng7", - RecipientOtherChain: "bnb1urfermcg92dwq36572cx4xg84wpk3lfpksr5g7", - ClosedBlock: 0, - Status: types.SWAP_STATUS_COMPLETED, - }, - false, - }, - { - "invalid status 0", - types.AtomicSwap{ - Amount: cs(c("bnb", 50000)), - RandomNumberHash: suite.randomNumberHashes[0], - ExpireHeight: 10, - Timestamp: 10, - Sender: suite.addrs[0], - Recipient: suite.addrs[5], - SenderOtherChain: "bnb1uky3me9ggqypmrsvxk7ur6hqkzq7zmv4ed4ng7", - RecipientOtherChain: "bnb1urfermcg92dwq36572cx4xg84wpk3lfpksr5g7", - ClosedBlock: 1, - Status: types.SWAP_STATUS_UNSPECIFIED, - }, - false, - }, - { - "invalid direction ", - types.AtomicSwap{ - Amount: cs(c("bnb", 50000)), - RandomNumberHash: suite.randomNumberHashes[0], - ExpireHeight: 10, - Timestamp: 10, - Sender: suite.addrs[0], - Recipient: suite.addrs[5], - SenderOtherChain: "bnb1uky3me9ggqypmrsvxk7ur6hqkzq7zmv4ed4ng7", - RecipientOtherChain: "bnb1urfermcg92dwq36572cx4xg84wpk3lfpksr5g7", - ClosedBlock: 1, - Status: types.SWAP_STATUS_OPEN, - Direction: types.SWAP_DIRECTION_UNSPECIFIED, - }, - false, - }, - } - - for _, tc := range testCases { - - err := tc.swap.Validate() - if tc.expectPass { - suite.Require().NoError(err, tc.msg) - suite.Require().Equal(tc.swap.Amount, tc.swap.GetCoins()) - - expectedSwapID := types.CalculateSwapID(tc.swap.RandomNumberHash, tc.swap.Sender, tc.swap.SenderOtherChain) - suite.Require().Equal(tmbytes.HexBytes(expectedSwapID), tc.swap.GetSwapID()) - } else { - suite.Require().Error(err) - } - - } -} - -func TestAtomicSwapTestSuite(t *testing.T) { - suite.Run(t, new(AtomicSwapTestSuite)) -} diff --git a/x/bep3/types/tx.pb.go b/x/bep3/types/tx.pb.go deleted file mode 100644 index 8929798a..00000000 --- a/x/bep3/types/tx.pb.go +++ /dev/null @@ -1,1606 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/bep3/v1beta1/tx.proto - -package types - -import ( - context "context" - 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" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - 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 - -// MsgCreateAtomicSwap defines the Msg/CreateAtomicSwap request type. -type MsgCreateAtomicSwap struct { - From string `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` - To string `protobuf:"bytes,2,opt,name=to,proto3" json:"to,omitempty"` - RecipientOtherChain string `protobuf:"bytes,3,opt,name=recipient_other_chain,json=recipientOtherChain,proto3" json:"recipient_other_chain,omitempty"` - SenderOtherChain string `protobuf:"bytes,4,opt,name=sender_other_chain,json=senderOtherChain,proto3" json:"sender_other_chain,omitempty"` - RandomNumberHash string `protobuf:"bytes,5,opt,name=random_number_hash,json=randomNumberHash,proto3" json:"random_number_hash,omitempty"` - Timestamp int64 `protobuf:"varint,6,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,7,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` - HeightSpan uint64 `protobuf:"varint,8,opt,name=height_span,json=heightSpan,proto3" json:"height_span,omitempty"` -} - -func (m *MsgCreateAtomicSwap) Reset() { *m = MsgCreateAtomicSwap{} } -func (*MsgCreateAtomicSwap) ProtoMessage() {} -func (*MsgCreateAtomicSwap) Descriptor() ([]byte, []int) { - return fileDescriptor_019a1c7100544f13, []int{0} -} -func (m *MsgCreateAtomicSwap) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgCreateAtomicSwap) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCreateAtomicSwap.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 *MsgCreateAtomicSwap) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCreateAtomicSwap.Merge(m, src) -} -func (m *MsgCreateAtomicSwap) XXX_Size() int { - return m.Size() -} -func (m *MsgCreateAtomicSwap) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCreateAtomicSwap.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCreateAtomicSwap proto.InternalMessageInfo - -// MsgCreateAtomicSwapResponse defines the Msg/CreateAtomicSwap response type. -type MsgCreateAtomicSwapResponse struct { -} - -func (m *MsgCreateAtomicSwapResponse) Reset() { *m = MsgCreateAtomicSwapResponse{} } -func (m *MsgCreateAtomicSwapResponse) String() string { return proto.CompactTextString(m) } -func (*MsgCreateAtomicSwapResponse) ProtoMessage() {} -func (*MsgCreateAtomicSwapResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_019a1c7100544f13, []int{1} -} -func (m *MsgCreateAtomicSwapResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgCreateAtomicSwapResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCreateAtomicSwapResponse.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 *MsgCreateAtomicSwapResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCreateAtomicSwapResponse.Merge(m, src) -} -func (m *MsgCreateAtomicSwapResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgCreateAtomicSwapResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCreateAtomicSwapResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCreateAtomicSwapResponse proto.InternalMessageInfo - -// MsgClaimAtomicSwap defines the Msg/ClaimAtomicSwap request type. -type MsgClaimAtomicSwap struct { - From string `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` - SwapID string `protobuf:"bytes,2,opt,name=swap_id,json=swapId,proto3" json:"swap_id,omitempty"` - RandomNumber string `protobuf:"bytes,3,opt,name=random_number,json=randomNumber,proto3" json:"random_number,omitempty"` -} - -func (m *MsgClaimAtomicSwap) Reset() { *m = MsgClaimAtomicSwap{} } -func (*MsgClaimAtomicSwap) ProtoMessage() {} -func (*MsgClaimAtomicSwap) Descriptor() ([]byte, []int) { - return fileDescriptor_019a1c7100544f13, []int{2} -} -func (m *MsgClaimAtomicSwap) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimAtomicSwap) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimAtomicSwap.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 *MsgClaimAtomicSwap) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimAtomicSwap.Merge(m, src) -} -func (m *MsgClaimAtomicSwap) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimAtomicSwap) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimAtomicSwap.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimAtomicSwap proto.InternalMessageInfo - -// MsgClaimAtomicSwapResponse defines the Msg/ClaimAtomicSwap response type. -type MsgClaimAtomicSwapResponse struct { -} - -func (m *MsgClaimAtomicSwapResponse) Reset() { *m = MsgClaimAtomicSwapResponse{} } -func (m *MsgClaimAtomicSwapResponse) String() string { return proto.CompactTextString(m) } -func (*MsgClaimAtomicSwapResponse) ProtoMessage() {} -func (*MsgClaimAtomicSwapResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_019a1c7100544f13, []int{3} -} -func (m *MsgClaimAtomicSwapResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimAtomicSwapResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimAtomicSwapResponse.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 *MsgClaimAtomicSwapResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimAtomicSwapResponse.Merge(m, src) -} -func (m *MsgClaimAtomicSwapResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimAtomicSwapResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimAtomicSwapResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimAtomicSwapResponse proto.InternalMessageInfo - -// MsgRefundAtomicSwap defines the Msg/RefundAtomicSwap request type. -type MsgRefundAtomicSwap struct { - From string `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` - SwapID string `protobuf:"bytes,2,opt,name=swap_id,json=swapId,proto3" json:"swap_id,omitempty"` -} - -func (m *MsgRefundAtomicSwap) Reset() { *m = MsgRefundAtomicSwap{} } -func (*MsgRefundAtomicSwap) ProtoMessage() {} -func (*MsgRefundAtomicSwap) Descriptor() ([]byte, []int) { - return fileDescriptor_019a1c7100544f13, []int{4} -} -func (m *MsgRefundAtomicSwap) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgRefundAtomicSwap) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgRefundAtomicSwap.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 *MsgRefundAtomicSwap) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgRefundAtomicSwap.Merge(m, src) -} -func (m *MsgRefundAtomicSwap) XXX_Size() int { - return m.Size() -} -func (m *MsgRefundAtomicSwap) XXX_DiscardUnknown() { - xxx_messageInfo_MsgRefundAtomicSwap.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgRefundAtomicSwap proto.InternalMessageInfo - -// MsgRefundAtomicSwapResponse defines the Msg/RefundAtomicSwap response type. -type MsgRefundAtomicSwapResponse struct { -} - -func (m *MsgRefundAtomicSwapResponse) Reset() { *m = MsgRefundAtomicSwapResponse{} } -func (m *MsgRefundAtomicSwapResponse) String() string { return proto.CompactTextString(m) } -func (*MsgRefundAtomicSwapResponse) ProtoMessage() {} -func (*MsgRefundAtomicSwapResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_019a1c7100544f13, []int{5} -} -func (m *MsgRefundAtomicSwapResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgRefundAtomicSwapResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgRefundAtomicSwapResponse.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 *MsgRefundAtomicSwapResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgRefundAtomicSwapResponse.Merge(m, src) -} -func (m *MsgRefundAtomicSwapResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgRefundAtomicSwapResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgRefundAtomicSwapResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgRefundAtomicSwapResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgCreateAtomicSwap)(nil), "kava.bep3.v1beta1.MsgCreateAtomicSwap") - proto.RegisterType((*MsgCreateAtomicSwapResponse)(nil), "kava.bep3.v1beta1.MsgCreateAtomicSwapResponse") - proto.RegisterType((*MsgClaimAtomicSwap)(nil), "kava.bep3.v1beta1.MsgClaimAtomicSwap") - proto.RegisterType((*MsgClaimAtomicSwapResponse)(nil), "kava.bep3.v1beta1.MsgClaimAtomicSwapResponse") - proto.RegisterType((*MsgRefundAtomicSwap)(nil), "kava.bep3.v1beta1.MsgRefundAtomicSwap") - proto.RegisterType((*MsgRefundAtomicSwapResponse)(nil), "kava.bep3.v1beta1.MsgRefundAtomicSwapResponse") -} - -func init() { proto.RegisterFile("kava/bep3/v1beta1/tx.proto", fileDescriptor_019a1c7100544f13) } - -var fileDescriptor_019a1c7100544f13 = []byte{ - // 592 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x54, 0xbf, 0x6f, 0xd3, 0x40, - 0x14, 0xb6, 0x93, 0x92, 0xd2, 0x6b, 0x11, 0xe1, 0x5a, 0x24, 0xd7, 0x14, 0x3b, 0x4a, 0x45, 0xe5, - 0xa1, 0xb1, 0x69, 0xba, 0x31, 0xd1, 0x84, 0x81, 0x0e, 0x05, 0xc9, 0xd9, 0x58, 0xac, 0xb3, 0x7d, - 0xb5, 0xaf, 0xad, 0xef, 0x2c, 0xdf, 0x25, 0x2d, 0xff, 0x01, 0x23, 0x23, 0x62, 0xca, 0xcc, 0xc2, - 0xc2, 0xdf, 0x80, 0x3a, 0x56, 0x4c, 0x4c, 0x05, 0x25, 0x0b, 0x7f, 0x06, 0xf2, 0x8f, 0x84, 0xe6, - 0x97, 0xa8, 0x90, 0x98, 0x7c, 0xf7, 0xbe, 0xef, 0xbd, 0x7b, 0xf7, 0x7d, 0x7e, 0x07, 0xd4, 0x53, - 0xd4, 0x43, 0x96, 0x8b, 0xe3, 0x7d, 0xab, 0xb7, 0xe7, 0x62, 0x81, 0xf6, 0x2c, 0x71, 0x61, 0xc6, - 0x09, 0x13, 0x0c, 0x3e, 0x48, 0x31, 0x33, 0xc5, 0xcc, 0x02, 0x53, 0x35, 0x8f, 0xf1, 0x88, 0x71, - 0xcb, 0x45, 0x1c, 0x8f, 0x13, 0x3c, 0x46, 0x68, 0x9e, 0xa2, 0x6e, 0xe6, 0xb8, 0x93, 0xed, 0xac, - 0x7c, 0x53, 0x40, 0x1b, 0x01, 0x0b, 0x58, 0x1e, 0x4f, 0x57, 0x79, 0xb4, 0xfe, 0xb9, 0x0c, 0xd6, - 0x8f, 0x78, 0xd0, 0x4e, 0x30, 0x12, 0xf8, 0x40, 0xb0, 0x88, 0x78, 0x9d, 0x73, 0x14, 0xc3, 0x5d, - 0xb0, 0x74, 0x9c, 0xb0, 0x48, 0x91, 0x6b, 0xb2, 0xb1, 0xd2, 0x52, 0xbe, 0x7d, 0x69, 0x6c, 0x14, - 0xd5, 0x0e, 0x7c, 0x3f, 0xc1, 0x9c, 0x77, 0x44, 0x42, 0x68, 0x60, 0x67, 0x2c, 0x68, 0x80, 0x92, - 0x60, 0x4a, 0xe9, 0x2f, 0xdc, 0x92, 0x60, 0xb0, 0x09, 0x1e, 0x26, 0xd8, 0x23, 0x31, 0xc1, 0x54, - 0x38, 0x4c, 0x84, 0x38, 0x71, 0xbc, 0x10, 0x11, 0xaa, 0x94, 0xd3, 0x64, 0x7b, 0x7d, 0x0c, 0xbe, - 0x4e, 0xb1, 0x76, 0x0a, 0xc1, 0x5d, 0x00, 0x39, 0xa6, 0x3e, 0x4e, 0x26, 0x12, 0x96, 0xb2, 0x84, - 0x6a, 0x8e, 0x4c, 0xb2, 0x13, 0x44, 0x7d, 0x16, 0x39, 0xb4, 0x1b, 0xb9, 0x38, 0x71, 0x42, 0xc4, - 0x43, 0xe5, 0x4e, 0xce, 0xce, 0x91, 0x57, 0x19, 0xf0, 0x12, 0xf1, 0x10, 0x6e, 0x81, 0x15, 0x41, - 0x22, 0xcc, 0x05, 0x8a, 0x62, 0xa5, 0x52, 0x93, 0x8d, 0xb2, 0xfd, 0x27, 0x00, 0x3d, 0x50, 0x41, - 0x11, 0xeb, 0x52, 0xa1, 0x2c, 0xd7, 0xca, 0xc6, 0x6a, 0x73, 0xd3, 0x2c, 0x2e, 0x96, 0xea, 0x3f, - 0x32, 0xc5, 0x6c, 0x33, 0x42, 0x5b, 0x4f, 0x2f, 0xaf, 0x75, 0xe9, 0xd3, 0x0f, 0xdd, 0x08, 0x88, - 0x08, 0xbb, 0xae, 0xe9, 0xb1, 0xa8, 0xd0, 0xbf, 0xf8, 0x34, 0xb8, 0x7f, 0x6a, 0x89, 0xb7, 0x31, - 0xe6, 0x59, 0x02, 0xb7, 0x8b, 0xd2, 0x50, 0x07, 0xab, 0x21, 0x26, 0x41, 0x28, 0x1c, 0x1e, 0x23, - 0xaa, 0xdc, 0xad, 0xc9, 0xc6, 0x92, 0x0d, 0xf2, 0x50, 0x27, 0x46, 0xf4, 0xd9, 0xda, 0xbb, 0xbe, - 0x2e, 0x7d, 0xe8, 0xeb, 0xd2, 0xaf, 0xbe, 0x2e, 0xd5, 0x1f, 0x83, 0x47, 0x73, 0x0c, 0xb3, 0x31, - 0x8f, 0x19, 0xe5, 0xb8, 0xfe, 0x51, 0x06, 0x30, 0xc5, 0xcf, 0x10, 0x89, 0xfe, 0xd9, 0xcf, 0x6d, - 0xb0, 0xcc, 0xcf, 0x51, 0xec, 0x10, 0xbf, 0x30, 0x15, 0x0c, 0xae, 0xf5, 0x4a, 0x5a, 0xe8, 0xf0, - 0x85, 0x5d, 0x49, 0xa1, 0x43, 0x1f, 0x6e, 0x83, 0x7b, 0x13, 0x42, 0x17, 0x16, 0xae, 0xdd, 0xd4, - 0x78, 0xaa, 0xf7, 0x2d, 0xa0, 0xce, 0xf6, 0x36, 0x6e, 0xbd, 0x97, 0xfd, 0x8a, 0x36, 0x3e, 0xee, - 0x52, 0xff, 0xbf, 0xb6, 0x3e, 0x57, 0xd1, 0xe9, 0x73, 0x47, 0x6d, 0x35, 0xbf, 0x96, 0x40, 0xf9, - 0x88, 0x07, 0xf0, 0x04, 0x54, 0x67, 0xc6, 0x64, 0xc7, 0x9c, 0x99, 0x51, 0x73, 0x8e, 0x3b, 0xaa, - 0x79, 0x3b, 0xde, 0xe8, 0x4c, 0x18, 0x80, 0xfb, 0xd3, 0x0e, 0x3e, 0x59, 0x50, 0x62, 0x92, 0xa6, - 0x36, 0x6e, 0x45, 0x1b, 0x1f, 0x74, 0x02, 0xaa, 0x33, 0x82, 0x2f, 0xb8, 0xd4, 0x34, 0x6f, 0xd1, - 0xa5, 0x16, 0x09, 0xd9, 0x7a, 0x7e, 0x39, 0xd0, 0xe4, 0xab, 0x81, 0x26, 0xff, 0x1c, 0x68, 0xf2, - 0xfb, 0xa1, 0x26, 0x5d, 0x0d, 0x35, 0xe9, 0xfb, 0x50, 0x93, 0xde, 0xec, 0xdc, 0x18, 0x9a, 0xb4, - 0x66, 0xe3, 0x0c, 0xb9, 0x3c, 0x5b, 0x59, 0x17, 0xf9, 0xe3, 0x98, 0x0d, 0x8e, 0x5b, 0xc9, 0x1e, - 0xad, 0xfd, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x94, 0xca, 0xe1, 0xe1, 0x36, 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 - -// 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 { - // CreateAtomicSwap defines a method for creating an atomic swap - CreateAtomicSwap(ctx context.Context, in *MsgCreateAtomicSwap, opts ...grpc.CallOption) (*MsgCreateAtomicSwapResponse, error) - // ClaimAtomicSwap defines a method for claiming an atomic swap - ClaimAtomicSwap(ctx context.Context, in *MsgClaimAtomicSwap, opts ...grpc.CallOption) (*MsgClaimAtomicSwapResponse, error) - // RefundAtomicSwap defines a method for refunding an atomic swap - RefundAtomicSwap(ctx context.Context, in *MsgRefundAtomicSwap, opts ...grpc.CallOption) (*MsgRefundAtomicSwapResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) CreateAtomicSwap(ctx context.Context, in *MsgCreateAtomicSwap, opts ...grpc.CallOption) (*MsgCreateAtomicSwapResponse, error) { - out := new(MsgCreateAtomicSwapResponse) - err := c.cc.Invoke(ctx, "/kava.bep3.v1beta1.Msg/CreateAtomicSwap", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ClaimAtomicSwap(ctx context.Context, in *MsgClaimAtomicSwap, opts ...grpc.CallOption) (*MsgClaimAtomicSwapResponse, error) { - out := new(MsgClaimAtomicSwapResponse) - err := c.cc.Invoke(ctx, "/kava.bep3.v1beta1.Msg/ClaimAtomicSwap", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) RefundAtomicSwap(ctx context.Context, in *MsgRefundAtomicSwap, opts ...grpc.CallOption) (*MsgRefundAtomicSwapResponse, error) { - out := new(MsgRefundAtomicSwapResponse) - err := c.cc.Invoke(ctx, "/kava.bep3.v1beta1.Msg/RefundAtomicSwap", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // CreateAtomicSwap defines a method for creating an atomic swap - CreateAtomicSwap(context.Context, *MsgCreateAtomicSwap) (*MsgCreateAtomicSwapResponse, error) - // ClaimAtomicSwap defines a method for claiming an atomic swap - ClaimAtomicSwap(context.Context, *MsgClaimAtomicSwap) (*MsgClaimAtomicSwapResponse, error) - // RefundAtomicSwap defines a method for refunding an atomic swap - RefundAtomicSwap(context.Context, *MsgRefundAtomicSwap) (*MsgRefundAtomicSwapResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) CreateAtomicSwap(ctx context.Context, req *MsgCreateAtomicSwap) (*MsgCreateAtomicSwapResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method CreateAtomicSwap not implemented") -} -func (*UnimplementedMsgServer) ClaimAtomicSwap(ctx context.Context, req *MsgClaimAtomicSwap) (*MsgClaimAtomicSwapResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ClaimAtomicSwap not implemented") -} -func (*UnimplementedMsgServer) RefundAtomicSwap(ctx context.Context, req *MsgRefundAtomicSwap) (*MsgRefundAtomicSwapResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RefundAtomicSwap not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_CreateAtomicSwap_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgCreateAtomicSwap) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).CreateAtomicSwap(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.bep3.v1beta1.Msg/CreateAtomicSwap", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).CreateAtomicSwap(ctx, req.(*MsgCreateAtomicSwap)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ClaimAtomicSwap_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgClaimAtomicSwap) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ClaimAtomicSwap(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.bep3.v1beta1.Msg/ClaimAtomicSwap", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ClaimAtomicSwap(ctx, req.(*MsgClaimAtomicSwap)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_RefundAtomicSwap_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgRefundAtomicSwap) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).RefundAtomicSwap(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.bep3.v1beta1.Msg/RefundAtomicSwap", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).RefundAtomicSwap(ctx, req.(*MsgRefundAtomicSwap)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.bep3.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "CreateAtomicSwap", - Handler: _Msg_CreateAtomicSwap_Handler, - }, - { - MethodName: "ClaimAtomicSwap", - Handler: _Msg_ClaimAtomicSwap_Handler, - }, - { - MethodName: "RefundAtomicSwap", - Handler: _Msg_RefundAtomicSwap_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/bep3/v1beta1/tx.proto", -} - -func (m *MsgCreateAtomicSwap) 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 *MsgCreateAtomicSwap) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCreateAtomicSwap) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.HeightSpan != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.HeightSpan)) - i-- - dAtA[i] = 0x40 - } - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - } - if m.Timestamp != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Timestamp)) - i-- - dAtA[i] = 0x30 - } - if len(m.RandomNumberHash) > 0 { - i -= len(m.RandomNumberHash) - copy(dAtA[i:], m.RandomNumberHash) - i = encodeVarintTx(dAtA, i, uint64(len(m.RandomNumberHash))) - i-- - dAtA[i] = 0x2a - } - if len(m.SenderOtherChain) > 0 { - i -= len(m.SenderOtherChain) - copy(dAtA[i:], m.SenderOtherChain) - i = encodeVarintTx(dAtA, i, uint64(len(m.SenderOtherChain))) - i-- - dAtA[i] = 0x22 - } - if len(m.RecipientOtherChain) > 0 { - i -= len(m.RecipientOtherChain) - copy(dAtA[i:], m.RecipientOtherChain) - i = encodeVarintTx(dAtA, i, uint64(len(m.RecipientOtherChain))) - i-- - dAtA[i] = 0x1a - } - if len(m.To) > 0 { - i -= len(m.To) - copy(dAtA[i:], m.To) - i = encodeVarintTx(dAtA, i, uint64(len(m.To))) - i-- - dAtA[i] = 0x12 - } - if len(m.From) > 0 { - i -= len(m.From) - copy(dAtA[i:], m.From) - i = encodeVarintTx(dAtA, i, uint64(len(m.From))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgCreateAtomicSwapResponse) 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 *MsgCreateAtomicSwapResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCreateAtomicSwapResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgClaimAtomicSwap) 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 *MsgClaimAtomicSwap) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimAtomicSwap) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RandomNumber) > 0 { - i -= len(m.RandomNumber) - copy(dAtA[i:], m.RandomNumber) - i = encodeVarintTx(dAtA, i, uint64(len(m.RandomNumber))) - i-- - dAtA[i] = 0x1a - } - if len(m.SwapID) > 0 { - i -= len(m.SwapID) - copy(dAtA[i:], m.SwapID) - i = encodeVarintTx(dAtA, i, uint64(len(m.SwapID))) - i-- - dAtA[i] = 0x12 - } - if len(m.From) > 0 { - i -= len(m.From) - copy(dAtA[i:], m.From) - i = encodeVarintTx(dAtA, i, uint64(len(m.From))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClaimAtomicSwapResponse) 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 *MsgClaimAtomicSwapResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimAtomicSwapResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgRefundAtomicSwap) 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 *MsgRefundAtomicSwap) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgRefundAtomicSwap) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.SwapID) > 0 { - i -= len(m.SwapID) - copy(dAtA[i:], m.SwapID) - i = encodeVarintTx(dAtA, i, uint64(len(m.SwapID))) - i-- - dAtA[i] = 0x12 - } - if len(m.From) > 0 { - i -= len(m.From) - copy(dAtA[i:], m.From) - i = encodeVarintTx(dAtA, i, uint64(len(m.From))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgRefundAtomicSwapResponse) 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 *MsgRefundAtomicSwapResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgRefundAtomicSwapResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgCreateAtomicSwap) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.From) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.To) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.RecipientOtherChain) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.SenderOtherChain) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.RandomNumberHash) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.Timestamp != 0 { - n += 1 + sovTx(uint64(m.Timestamp)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - if m.HeightSpan != 0 { - n += 1 + sovTx(uint64(m.HeightSpan)) - } - return n -} - -func (m *MsgCreateAtomicSwapResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgClaimAtomicSwap) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.From) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.SwapID) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.RandomNumber) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgClaimAtomicSwapResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgRefundAtomicSwap) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.From) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.SwapID) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgRefundAtomicSwapResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgCreateAtomicSwap) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgCreateAtomicSwap: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCreateAtomicSwap: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.From = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field To", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.To = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RecipientOtherChain", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RecipientOtherChain = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SenderOtherChain", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SenderOtherChain = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RandomNumberHash", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RandomNumberHash = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 6: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) - } - m.Timestamp = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Timestamp |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field HeightSpan", wireType) - } - m.HeightSpan = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.HeightSpan |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgCreateAtomicSwapResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgCreateAtomicSwapResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCreateAtomicSwapResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimAtomicSwap) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimAtomicSwap: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimAtomicSwap: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.From = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SwapID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SwapID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RandomNumber", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RandomNumber = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimAtomicSwapResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimAtomicSwapResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimAtomicSwapResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgRefundAtomicSwap) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgRefundAtomicSwap: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgRefundAtomicSwap: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.From = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SwapID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SwapID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgRefundAtomicSwapResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgRefundAtomicSwapResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgRefundAtomicSwapResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/cdp/abci.go b/x/cdp/abci.go deleted file mode 100644 index 9967bd51..00000000 --- a/x/cdp/abci.go +++ /dev/null @@ -1,65 +0,0 @@ -package cdp - -import ( - "errors" - "fmt" - "time" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/kava-labs/kava/x/cdp/keeper" - "github.com/kava-labs/kava/x/cdp/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -// BeginBlocker compounds the debt in outstanding cdps and liquidates cdps that are below the required collateralization ratio -func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, k keeper.Keeper) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - - params := k.GetParams(ctx) - - // only run CDP liquidations every `LiquidationBlockInterval` blocks - skipSyncronizeAndLiquidations := ctx.BlockHeight()%params.LiquidationBlockInterval != 0 - - for _, cp := range params.CollateralParams { - ok := k.UpdatePricefeedStatus(ctx, cp.SpotMarketID) - if !ok { - continue - } - - ok = k.UpdatePricefeedStatus(ctx, cp.LiquidationMarketID) - if !ok { - continue - } - - err := k.AccumulateInterest(ctx, cp.Type) - if err != nil { - panic(err) - } - - if skipSyncronizeAndLiquidations { - ctx.Logger().Debug(fmt.Sprintf("skipping x/cdp SynchronizeInterestForRiskyCDPs and LiquidateCdps for %s", cp.Type)) - continue - } - - ctx.Logger().Debug(fmt.Sprintf("running x/cdp SynchronizeInterestForRiskyCDPs and LiquidateCdps for %s", cp.Type)) - - err = k.SynchronizeInterestForRiskyCDPs(ctx, sdk.MaxSortableDec, cp) - if err != nil { - panic(err) - } - - err = k.LiquidateCdps(ctx, cp.LiquidationMarketID, cp.Type, cp.LiquidationRatio, cp.CheckCollateralizationIndexCount) - if err != nil && !errors.Is(err, pricefeedtypes.ErrNoValidPrice) { - panic(err) - } - } - - err := k.RunSurplusAndDebtAuctions(ctx) - if err != nil { - panic(err) - } -} diff --git a/x/cdp/abci_test.go b/x/cdp/abci_test.go deleted file mode 100644 index eaffaa96..00000000 --- a/x/cdp/abci_test.go +++ /dev/null @@ -1,375 +0,0 @@ -package cdp_test - -import ( - "math/rand" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" - - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - auctiontypes "github.com/kava-labs/kava/x/auction/types" - "github.com/kava-labs/kava/x/cdp" - "github.com/kava-labs/kava/x/cdp/keeper" - "github.com/kava-labs/kava/x/cdp/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -type ModuleTestSuite struct { - suite.Suite - - keeper keeper.Keeper - addrs []sdk.AccAddress - app app.TestApp - cdps types.CDPs - ctx sdk.Context - liquidations liquidationTracker -} - -type liquidationTracker struct { - xrp []uint64 - btc []uint64 - debt int64 -} - -func (suite *ModuleTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - tracker := liquidationTracker{} - - coins := cs(c("btc", 100000000), c("xrp", 10000000000), c("erc20/usdc", 10000000000)) - _, addrs := app.GeneratePrivKeyAddressPairs(100) - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(tApp.AppCodec()), - NewCDPGenStateMulti(tApp.AppCodec()), - ) - suite.ctx = ctx - suite.app = tApp - suite.keeper = tApp.GetCDPKeeper() - suite.cdps = types.CDPs{} - suite.addrs = addrs - suite.liquidations = tracker -} - -func (suite *ModuleTestSuite) createCdps() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - cdps := make(types.CDPs, 100) - tracker := liquidationTracker{} - - coins := cs(c("btc", 100000000), c("xrp", 10000000000), c("erc20/usdc", 10000000000)) - _, addrs := app.GeneratePrivKeyAddressPairs(100) - - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(tApp.AppCodec()), - NewCDPGenStateMulti(tApp.AppCodec()), - ) - - suite.ctx = ctx - suite.app = tApp - suite.keeper = tApp.GetCDPKeeper() - - // create 100 cdps - for j := 0; j < 100; j++ { - // 50 of the cdps will be collateralized with xrp - collateral := "xrp" - amount := 10000000000 - debt := simulation.RandIntBetween(rand.New(rand.NewSource(int64(j))), 750000000, 1249000000) - // the other half (50) will be collateralized with btc - if j%2 == 0 { - collateral = "btc" - amount = 100000000 - debt = simulation.RandIntBetween(rand.New(rand.NewSource(int64(j))), 2700000000, 5332000000) - if debt >= 4000000000 { - tracker.btc = append(tracker.btc, uint64(j+1)) - tracker.debt += int64(debt) - } - } else { - if debt >= 1000000000 { - tracker.xrp = append(tracker.xrp, uint64(j+1)) - tracker.debt += int64(debt) - } - } - suite.Nil(suite.keeper.AddCdp(suite.ctx, addrs[j], c(collateral, int64(amount)), c("usdx", int64(debt)), collateral+"-a")) - c, f := suite.keeper.GetCDP(suite.ctx, collateral+"-a", uint64(j+1)) - suite.True(f) - cdps[j] = c - } - - suite.cdps = cdps - suite.addrs = addrs - suite.liquidations = tracker -} - -func (suite *ModuleTestSuite) setPrice(price sdk.Dec, market string) { - pfKeeper := suite.app.GetPriceFeedKeeper() - - _, err := pfKeeper.SetPrice(suite.ctx, sdk.AccAddress{}, market, price, suite.ctx.BlockTime().Add(time.Hour*3)) - suite.NoError(err) - - err = pfKeeper.SetCurrentPrices(suite.ctx, market) - suite.NoError(err) - pp, err := pfKeeper.GetCurrentPrice(suite.ctx, market) - suite.NoError(err) - suite.Equal(price, pp.Price) -} - -func (suite *ModuleTestSuite) TestBeginBlockNewCdpTypeSetsGlobalInterest() { - suite.createCdps() - - // add a new collateral that does not have previous accumulation time or global interest factor set - params := suite.keeper.GetParams(suite.ctx) - usdcCollateral := types.CollateralParam{ - Denom: "erc20/usdc", - Type: "erc20-usdc", - LiquidationRatio: sdk.MustNewDecFromStr("1.01"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.OneDec(), - AuctionSize: sdkmath.NewIntFromUint64(10000000000), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - SpotMarketID: "usdc:usd", - LiquidationMarketID: "usdc:usd", - ConversionFactor: sdkmath.NewInt(6), - } - usdtCollateral := types.CollateralParam{ - Denom: "erc20/usdt", - Type: "erc20-usdt", - LiquidationRatio: sdk.MustNewDecFromStr("1.01"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.OneDec(), - AuctionSize: sdkmath.NewIntFromUint64(10000000000), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - SpotMarketID: "usdt:usd", - LiquidationMarketID: "usdt:usd", - ConversionFactor: sdkmath.NewInt(18), - } - newCollaterals := []types.CollateralParam{usdcCollateral, usdtCollateral} - params.CollateralParams = append(params.CollateralParams, newCollaterals...) - suite.keeper.SetParams(suite.ctx, params) - - // setup market for cdp collateral - priceFeedKeeper := suite.app.GetPriceFeedKeeper() - priceParams := priceFeedKeeper.GetParams(suite.ctx) - newMarkets := []pricefeedtypes.Market{ - {MarketID: "usdc:usd", BaseAsset: "usdc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "usdt:usd", BaseAsset: "usdt", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - } - priceParams.Markets = append(priceParams.Markets, newMarkets...) - priceFeedKeeper.SetParams(suite.ctx, priceParams) - suite.setPrice(d("1"), "usdc:usd") - suite.keeper.UpdatePricefeedStatus(suite.ctx, usdcCollateral.SpotMarketID) - suite.setPrice(d("1"), "usdt:usd") - suite.keeper.UpdatePricefeedStatus(suite.ctx, usdtCollateral.SpotMarketID) - - // create a CDP for USDC, no CDPS for USDT - err := suite.keeper.AddCdp(suite.ctx, suite.addrs[0], c(usdcCollateral.Denom, 100000000), c("usdx", 10000000), usdcCollateral.Type) - suite.Require().NoError(err) - - // ensure begin block does not panic due to no accumulation time or no global interest factor - suite.Require().NotPanics(func() { - cdp.BeginBlocker(suite.ctx, abci.RequestBeginBlock{Header: suite.ctx.BlockHeader()}, suite.keeper) - }, "expected begin blocker not to panic") - - // set by accumulate interest (or add cdp above) - // usdc has accural time set - previousAccrualTime, found := suite.keeper.GetPreviousAccrualTime(suite.ctx, usdcCollateral.Type) - suite.Require().True(found, "expected previous accrual time for new market to be set") - suite.Equal(suite.ctx.BlockTime(), previousAccrualTime, "expected previous accrual time to equal block time") - // usdt has accural time set - previousAccrualTime, found = suite.keeper.GetPreviousAccrualTime(suite.ctx, usdtCollateral.Type) - suite.Require().True(found, "expected previous accrual time for new market to be set") - suite.Equal(suite.ctx.BlockTime(), previousAccrualTime, "expected previous accrual time to equal block time") - - // set for USDC by AddCdp - globalInterestFactor, found := suite.keeper.GetInterestFactor(suite.ctx, usdcCollateral.Type) - suite.Require().True(found, "expected global interest factor for new collateral to be set") - suite.Equal(sdk.OneDec(), globalInterestFactor, "expected global interest factor to equal 1") - // not set for USDT since it has no cdps - globalInterestFactor, found = suite.keeper.GetInterestFactor(suite.ctx, usdtCollateral.Type) - suite.Require().False(found, "expected global interest factor for new collateral to not be set") - suite.Equal(sdk.ZeroDec(), globalInterestFactor, "expected global interest factor to equal 0") -} - -func (suite *ModuleTestSuite) TestBeginBlock() { - // test setup, creating - // 50 xrp cdps each with - // collateral: 10000000000 - // debt: between 750000000 - 1249000000 - // if debt above 10000000000, - // cdp added to tracker / liquidation list - // debt total added to trackers debt total - // 50 btc cdps each with - // collateral: 10000000000 - // debt: between 2700000000 - 5332000000 - // if debt above 4000000000, - // cdp added to tracker / liquidation list - // debt total added to trackers debt total - - // naively we expect roughly half of the cdps to be above the debt tracking floor, roughly 25 of them collaterallized with xrp, the other 25 with btcb - - // usdx is the principal for all cdps - suite.createCdps() - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - // test case 1 setup - acc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - // track how much xrp collateral exists in the cdp module - originalXrpCollateral := bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount - // set the trading price for xrp:usd pools - suite.setPrice(d("0.2"), "xrp:usd") - - // test case 1 execution - cdp.BeginBlocker(suite.ctx, abci.RequestBeginBlock{Header: suite.ctx.BlockHeader()}, suite.keeper) - - // test case 1 assert - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - // get the current amount of xrp held by the cdp module - finalXrpCollateral := bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount - seizedXrpCollateral := originalXrpCollateral.Sub(finalXrpCollateral) - // calculate the number of cdps that were liquidated based on the total - // seized collateral divided by the size of each cdp when it was created - xrpLiquidations := int(seizedXrpCollateral.Quo(i(10000000000)).Int64()) - // should be 10 because...? - suite.Equal(10, xrpLiquidations) - - // btc collateral test case setup - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - originalBtcCollateral := bk.GetBalance(suite.ctx, acc.GetAddress(), "btc").Amount - // set the trading price for btc:usd pools - suite.setPrice(d("6000"), "btc:usd") - - // btc collateral test case execution - cdp.BeginBlocker(suite.ctx, abci.RequestBeginBlock{Header: suite.ctx.BlockHeader()}, suite.keeper) - - // btc collateral test case assertion 1 - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - finalBtcCollateral := bk.GetBalance(suite.ctx, acc.GetAddress(), "btc").Amount - seizedBtcCollateral := originalBtcCollateral.Sub(finalBtcCollateral) - // calculate the number of btc cdps that were liquidated based on the - // total seized collateral divided by the fixed size of each cdp - // when it was created during test setup - btcLiquidations := int(seizedBtcCollateral.Quo(i(100000000)).Int64()) - suite.Equal(10, btcLiquidations) - - // btc collateral test case assertion 2 - // test that the auction module has a balance equal to the amount of collateral seized - acc = ak.GetModuleAccount(suite.ctx, auctiontypes.ModuleName) - // should be this exact value because...? - suite.Equal(int64(71955653865), bk.GetBalance(suite.ctx, acc.GetAddress(), "debt").Amount.Int64()) -} - -func (suite *ModuleTestSuite) TestSeizeSingleCdpWithFees() { - // test setup - // starting with zero cdps, add a single cdp of - // xrp backed 1:1 with usdx - err := suite.keeper.AddCdp(suite.ctx, suite.addrs[0], c("xrp", 10000000000), c("usdx", 1000000000), "xrp-a") - suite.NoError(err) - // verify the total value of all assets in cdps composed of xrp-a/usdx pair equals the amount of the single cdp we just added above - suite.Equal(i(1000000000), suite.keeper.GetTotalPrincipal(suite.ctx, "xrp-a", "usdx")) - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - cdpMacc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(i(1000000000), bk.GetBalance(suite.ctx, cdpMacc.GetAddress(), "debt").Amount) - for i := 0; i < 100; i++ { - suite.ctx = suite.ctx.WithBlockTime(suite.ctx.BlockTime().Add(time.Second * 6)) - cdp.BeginBlocker(suite.ctx, abci.RequestBeginBlock{Header: suite.ctx.BlockHeader()}, suite.keeper) - } - - cdpMacc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(i(1000000891), (bk.GetBalance(suite.ctx, cdpMacc.GetAddress(), "debt").Amount)) - cdp, _ := suite.keeper.GetCDP(suite.ctx, "xrp-a", 1) - - err = suite.keeper.SeizeCollateral(suite.ctx, cdp) - suite.NoError(err) - _, found := suite.keeper.GetCDP(suite.ctx, "xrp-a", 1) - suite.False(found) -} - -func (suite *ModuleTestSuite) TestCDPBeginBlockerRunsOnlyOnConfiguredInterval() { - // test setup, creating - // 50 xrp cdps each with - // collateral: 10000000000 - // debt: between 750000000 - 1249000000 - // if debt above 10000000000, - // cdp added to tracker / liquidation list - // debt total added to trackers debt total - // 50 btc cdps each with - // collateral: 10000000000 - // debt: between 2700000000 - 5332000000 - // if debt above 4000000000, - // cdp added to tracker / liquidation list - // debt total added to trackers debt total - - // naively we expect roughly half of the cdps to be above the debt tracking floor, roughly 25 of them collaterallized with xrp, the other 25 with btcb - - // usdx is the principal for all cdps - suite.createCdps() - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - // set the cdp begin blocker to run every other block - params := suite.keeper.GetParams(suite.ctx) - params.LiquidationBlockInterval = 2 - suite.keeper.SetParams(suite.ctx, params) - - // test case 1 setup - acc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - // track how much xrp collateral exists in the cdp module - originalXrpCollateral := bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount - // set the trading price for xrp:usd pools - suite.setPrice(d("0.2"), "xrp:usd") - - // test case 1 execution - cdp.BeginBlocker(suite.ctx, abci.RequestBeginBlock{Header: suite.ctx.BlockHeader()}, suite.keeper) - - // test case 1 assert - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - // get the current amount of xrp held by the cdp module - finalXrpCollateral := bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount - seizedXrpCollateral := originalXrpCollateral.Sub(finalXrpCollateral) - // calculate the number of cdps that were liquidated based on the total - // seized collateral divided by the size of each cdp when it was created - xrpLiquidations := int(seizedXrpCollateral.Quo(i(10000000000)).Int64()) - // should be 0 because the cdp begin blocker is configured to - // skip execution every odd numbered block - suite.Equal(0, xrpLiquidations, "expected cdp begin blocker not to run liqudations") - - // test case 2 setup - // simulate running the second block of the chain - suite.ctx = suite.ctx.WithBlockHeight(2) - - // test case 2 execution - cdp.BeginBlocker(suite.ctx, abci.RequestBeginBlock{Header: suite.ctx.BlockHeader()}, suite.keeper) - - // test case 2 assert - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - // get the current amount of xrp held by the cdp module - finalXrpCollateral = bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount - seizedXrpCollateral = originalXrpCollateral.Sub(finalXrpCollateral) - // calculate the number of cdps that were liquidated based on the total - // seized collateral divided by the size of each cdp when it was created - xrpLiquidations = int(seizedXrpCollateral.Quo(i(10000000000)).Int64()) - suite.Greater(xrpLiquidations, 0, "expected cdp begin blocker to run liquidations") -} - -func TestModuleTestSuite(t *testing.T) { - suite.Run(t, new(ModuleTestSuite)) -} diff --git a/x/cdp/client/cli/query.go b/x/cdp/client/cli/query.go deleted file mode 100644 index dcfe3623..00000000 --- a/x/cdp/client/cli/query.go +++ /dev/null @@ -1,272 +0,0 @@ -package cli - -import ( - "context" - "fmt" - "strconv" - "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/cosmos/cosmos-sdk/version" - - "github.com/kava-labs/kava/x/cdp/types" -) - -// Query CDP flags -const ( - flagCollateralType = "collateral-type" - flagOwner = "owner" - flagID = "id" - flagRatio = "ratio" // returns CDPs under the given collateralization ratio threshold -) - -// GetQueryCmd returns the cli query commands for this module -func GetQueryCmd() *cobra.Command { - // Group nameservice queries under a subcommand - cdpQueryCmd := &cobra.Command{ - Use: "cdp", - Short: "Querying commands for the cdp module", - } - - cmds := []*cobra.Command{ - QueryCdpCmd(), - QueryGetCdpsCmd(), - QueryCdpDepositsCmd(), - QueryParamsCmd(), - QueryGetAccounts(), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - cdpQueryCmd.AddCommand(cmds...) - - return cdpQueryCmd -} - -// QueryCdpCmd returns the command handler for querying a particular cdp -func QueryCdpCmd() *cobra.Command { - return &cobra.Command{ - Use: "cdp [owner-addr] [collateral-type]", - Short: "get info about a cdp", - Long: strings.TrimSpace( - fmt.Sprintf(`Get a CDP by the owner address and the collateral name. - -Example: -$ %s query %s cdp kava15qdefkmwswysgg4qxgqpqr35k3m49pkx2jdfnw atom-a -`, version.AppName, types.ModuleName)), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - _, err = sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - res, err := queryClient.Cdp(context.Background(), &types.QueryCdpRequest{ - Owner: args[0], - CollateralType: args[1], - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -// QueryGetCdpsCmd queries the cdps in the store -func QueryGetCdpsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "cdps", - Short: "query cdps with optional filters", - Long: strings.TrimSpace(`Query for all paginated cdps that match optional filters: -Example: -$ kvcli q cdp cdps --collateral-type=bnb -$ kvcli q cdp cdps --owner=kava1hatdq32u5x4wnxrtv5wzjzmq49sxgjgsj0mffm -$ kvcli q cdp cdps --id=21 -$ kvcli q cdp cdps --ratio=2.75 -$ kvcli q cdp cdps --page=2 --limit=100 -`, - ), - RunE: func(cmd *cobra.Command, args []string) error { - strCollateralType, err := cmd.Flags().GetString(flagCollateralType) - if err != nil { - return err - } - strOwner, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - strID, err := cmd.Flags().GetString(flagID) - if err != nil { - return err - } - strRatio, err := cmd.Flags().GetString(flagRatio) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - req := types.QueryCdpsRequest{ - Pagination: pageReq, - } - - if len(strCollateralType) != 0 { - req.CollateralType = strings.ToLower(strings.TrimSpace(strCollateralType)) - } - - if len(strOwner) != 0 { - cdpOwner, err := sdk.AccAddressFromBech32(strings.ToLower(strings.TrimSpace(strOwner))) - if err != nil { - return fmt.Errorf("cannot parse address from cdp owner %s", strOwner) - } - req.Owner = cdpOwner.String() - } - - if len(strID) != 0 { - cdpID, err := strconv.ParseUint(strID, 10, 64) - if err != nil { - return fmt.Errorf("cannot parse cdp ID %s", strID) - } - req.ID = cdpID - } - - if len(strRatio) != 0 { - cdpRatio, err := sdk.NewDecFromStr(strRatio) - if err != nil { - return fmt.Errorf("cannot parse cdp ratio %s", strRatio) - } - // ratio is also validated on server - req.Ratio = cdpRatio.String() - } - - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Cdps(context.Background(), &req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - cmd.Flags().String(flagCollateralType, "", "(optional) filter by CDP collateral type") - cmd.Flags().String(flagOwner, "", "(optional) filter by CDP owner") - cmd.Flags().String(flagID, "", "(optional) filter by CDP ID") - cmd.Flags().String(flagRatio, "", "(optional) filter by CDP collateralization ratio threshold") - - flags.AddPaginationFlagsToCmd(cmd, "cdps") - - return cmd -} - -// QueryCdpDepositsCmd returns the command handler for querying the deposits of a particular cdp -func QueryCdpDepositsCmd() *cobra.Command { - return &cobra.Command{ - Use: "deposits [owner-addr] [collateral-type]", - Short: "get deposits for a cdp", - Long: strings.TrimSpace( - fmt.Sprintf(`Get the deposits of a CDP. - -Example: -$ %s query %s deposits kava15qdefkmwswysgg4qxgqpqr35k3m49pkx2jdfnw atom-a -`, version.AppName, types.ModuleName)), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - _, err = sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - res, err := queryClient.Deposits(context.Background(), &types.QueryDepositsRequest{ - Owner: args[0], - CollateralType: args[1], - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -// QueryParamsCmd returns the command handler for cdp parameter querying -func QueryParamsCmd() *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: "get the cdp module parameters", - Long: "get the current global cdp module parameters.", - 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(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } -} - -// QueryGetAccounts queries CDP module accounts -func QueryGetAccounts() *cobra.Command { - return &cobra.Command{ - Use: "accounts", - Short: "get module accounts", - Long: "get cdp module account addresses", - 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.Accounts(context.Background(), &types.QueryAccountsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} diff --git a/x/cdp/client/cli/tx.go b/x/cdp/client/cli/tx.go deleted file mode 100644 index 69262375..00000000 --- a/x/cdp/client/cli/tx.go +++ /dev/null @@ -1,245 +0,0 @@ -package cli - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/kava-labs/kava/x/cdp/types" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - cdpTxCmd := &cobra.Command{ - Use: "cdp", - Short: "cdp transactions subcommands", - } - - cmds := []*cobra.Command{ - GetCmdCreateCdp(), - GetCmdDeposit(), - GetCmdWithdraw(), - GetCmdDraw(), - GetCmdRepay(), - GetCmdLiquidate(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - cdpTxCmd.AddCommand(cmds...) - - return cdpTxCmd -} - -// GetCmdCreateCdp returns the command handler for creating a cdp -func GetCmdCreateCdp() *cobra.Command { - return &cobra.Command{ - Use: "create [collateral] [debt] [collateral-type]", - Short: "create a new cdp", - Long: strings.TrimSpace( - fmt.Sprintf(`Create a new cdp, depositing some collateral and drawing some debt. - -Example: -$ %s tx %s create 10000000uatom 1000usdx atom-a --from myKeyName -`, version.AppName, types.ModuleName)), - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - collateral, err := sdk.ParseCoinNormalized(args[0]) - if err != nil { - return err - } - debt, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - msg := types.NewMsgCreateCDP(clientCtx.GetFromAddress(), collateral, debt, args[2]) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -// GetCmdDeposit cli command for depositing to a cdp. -func GetCmdDeposit() *cobra.Command { - return &cobra.Command{ - Use: "deposit [owner-addr] [collateral] [collateral-type]", - Short: "deposit collateral to an existing cdp", - Long: strings.TrimSpace( - fmt.Sprintf(`Add collateral to an existing cdp. - -Example: -$ %s tx %s deposit kava15qdefkmwswysgg4qxgqpqr35k3m49pkx2jdfnw 10000000uatom atom-a --from myKeyName -`, version.AppName, types.ModuleName)), - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - collateral, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - owner, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - msg := types.NewMsgDeposit(owner, clientCtx.GetFromAddress(), collateral, args[2]) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -// GetCmdWithdraw cli command for withdrawing from a cdp. -func GetCmdWithdraw() *cobra.Command { - return &cobra.Command{ - Use: "withdraw [owner-addr] [collateral] [collateral-type]", - Short: "withdraw collateral from an existing cdp", - Long: strings.TrimSpace( - fmt.Sprintf(`Remove collateral from an existing cdp. - -Example: -$ %s tx %s withdraw kava15qdefkmwswysgg4qxgqpqr35k3m49pkx2jdfnw 10000000uatom atom-a --from myKeyName -`, version.AppName, types.ModuleName)), - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - collateral, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - owner, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - msg := types.NewMsgWithdraw(owner, clientCtx.GetFromAddress(), collateral, args[2]) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -// GetCmdDraw cli command for depositing to a cdp. -func GetCmdDraw() *cobra.Command { - return &cobra.Command{ - Use: "draw [collateral-type] [debt]", - Short: "draw debt off an existing cdp", - Long: strings.TrimSpace( - fmt.Sprintf(`Create debt in an existing cdp and send the newly minted asset to your account. - -Example: -$ %s tx %s draw atom-a 1000usdx --from myKeyName -`, version.AppName, types.ModuleName)), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - debt, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - msg := types.NewMsgDrawDebt(clientCtx.GetFromAddress(), args[0], debt) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -// GetCmdRepay cli command for depositing to a cdp. -func GetCmdRepay() *cobra.Command { - return &cobra.Command{ - Use: "repay [collateral-name] [debt]", - Short: "repay debt to an existing cdp", - Long: strings.TrimSpace( - fmt.Sprintf(`Cancel out debt in an existing cdp. - -Example: -$ %s tx %s repay atom-a 1000usdx --from myKeyName -`, version.AppName, types.ModuleName)), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - payment, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - msg := types.NewMsgRepayDebt(clientCtx.GetFromAddress(), args[0], payment) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -// GetCmdLiquidate cli command for liquidating a cdp. -func GetCmdLiquidate() *cobra.Command { - return &cobra.Command{ - Use: "liquidate [cdp-owner-address] [collateral-type]", - Short: "liquidate a cdp", - Long: strings.TrimSpace( - fmt.Sprintf(`Liquidate a cdp if it is below the required liquidation ratio - -Example: -$ %s tx %s liquidate kava1y70y90wzmnf00e63efk2lycgqwepthdmyzsfzm btcb-a --from myKeyName -`, version.AppName, types.ModuleName)), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - addr, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - msg := types.NewMsgLiquidate(clientCtx.GetFromAddress(), addr, args[1]) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} diff --git a/x/cdp/genesis.go b/x/cdp/genesis.go deleted file mode 100644 index c3123b65..00000000 --- a/x/cdp/genesis.go +++ /dev/null @@ -1,133 +0,0 @@ -package cdp - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/cdp/keeper" - "github.com/kava-labs/kava/x/cdp/types" -) - -// InitGenesis sets initial genesis state for cdp module -func InitGenesis(ctx sdk.Context, k keeper.Keeper, pk types.PricefeedKeeper, ak types.AccountKeeper, gs types.GenesisState) { - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - // check if the module accounts exists - cdpModuleAcc := ak.GetModuleAccount(ctx, types.ModuleName) - if cdpModuleAcc == nil { - panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) - } - liqModuleAcc := ak.GetModuleAccount(ctx, types.LiquidatorMacc) - if liqModuleAcc == nil { - panic(fmt.Sprintf("%s module account has not been set", types.LiquidatorMacc)) - } - - // validate denoms - check that any collaterals in the params are in the pricefeed, - // pricefeed MUST call InitGenesis before cdp - collateralMap := make(map[string]int) - ap := pk.GetParams(ctx) - for _, a := range ap.Markets { - collateralMap[a.MarketID] = 1 - } - - for _, col := range gs.Params.CollateralParams { - _, found := collateralMap[col.SpotMarketID] - if !found { - panic(fmt.Sprintf("%s collateral market %v not found in pricefeed", col.Denom, col.SpotMarketID)) - } - // sets the status of the pricefeed in the store - // if pricefeed not active, debt operations are paused - _ = k.UpdatePricefeedStatus(ctx, col.SpotMarketID) - - _, found = collateralMap[col.LiquidationMarketID] - if !found { - panic(fmt.Sprintf("%s collateral market %v not found in pricefeed", col.Denom, col.LiquidationMarketID)) - } - // sets the status of the pricefeed in the store - // if pricefeed not active, debt operations are paused - _ = k.UpdatePricefeedStatus(ctx, col.LiquidationMarketID) - } - - k.SetParams(ctx, gs.Params) - - for _, gat := range gs.PreviousAccumulationTimes { - k.SetInterestFactor(ctx, gat.CollateralType, gat.InterestFactor) - if gat.PreviousAccumulationTime.Unix() > 0 { - k.SetPreviousAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - } - } - - for _, gtp := range gs.TotalPrincipals { - k.SetTotalPrincipal(ctx, gtp.CollateralType, types.DefaultStableDenom, gtp.TotalPrincipal) - } - // add cdps - for _, cdp := range gs.CDPs { - if cdp.ID == gs.StartingCdpID { - panic(fmt.Sprintf("starting cdp id is assigned to an existing cdp: %v", cdp)) - } - err := k.SetCDP(ctx, cdp) - if err != nil { - panic(fmt.Sprintf("error setting cdp: %v", err)) - } - k.IndexCdpByOwner(ctx, cdp) - ratio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal()) - k.IndexCdpByCollateralRatio(ctx, cdp.Type, cdp.ID, ratio) - } - - k.SetNextCdpID(ctx, gs.StartingCdpID) - k.SetDebtDenom(ctx, gs.DebtDenom) - k.SetGovDenom(ctx, gs.GovDenom) - - for _, d := range gs.Deposits { - k.SetDeposit(ctx, d) - } -} - -// ExportGenesis export genesis state for cdp module -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { - params := k.GetParams(ctx) - - cdps := types.CDPs{} - deposits := types.Deposits{} - k.IterateAllCdps(ctx, func(cdp types.CDP) (stop bool) { - syncedCdp := k.SynchronizeInterest(ctx, cdp) - cdps = append(cdps, syncedCdp) - k.IterateDeposits(ctx, cdp.ID, func(deposit types.Deposit) (stop bool) { - deposits = append(deposits, deposit) - return false - }) - return false - }) - - cdpID := k.GetNextCdpID(ctx) - debtDenom := k.GetDebtDenom(ctx) - govDenom := k.GetGovDenom(ctx) - - var previousAccumTimes types.GenesisAccumulationTimes - var totalPrincipals types.GenesisTotalPrincipals - - for _, cp := range params.CollateralParams { - interestFactor, found := k.GetInterestFactor(ctx, cp.Type) - if !found { - interestFactor = sdk.OneDec() - } - // Governance param changes happen in the end blocker. If a new collateral type is added and then the chain - // is exported before the BeginBlocker can run, previous accrual time won't be found. We can't set it to - // current block time because it is not available in the export ctx. We should panic instead of exporting - // bad state. - previousAccumTime, f := k.GetPreviousAccrualTime(ctx, cp.Type) - if !f { - panic(fmt.Sprintf("expected previous accrual time to be set in state for %s", cp.Type)) - } - previousAccumTimes = append(previousAccumTimes, types.NewGenesisAccumulationTime(cp.Type, previousAccumTime, interestFactor)) - - tp := k.GetTotalPrincipal(ctx, cp.Type, types.DefaultStableDenom) - genTotalPrincipal := types.NewGenesisTotalPrincipal(cp.Type, tp) - totalPrincipals = append(totalPrincipals, genTotalPrincipal) - } - - return types.NewGenesisState(params, cdps, deposits, cdpID, debtDenom, govDenom, previousAccumTimes, totalPrincipals) -} diff --git a/x/cdp/genesis_test.go b/x/cdp/genesis_test.go deleted file mode 100644 index ef9254f0..00000000 --- a/x/cdp/genesis_test.go +++ /dev/null @@ -1,331 +0,0 @@ -package cdp_test - -import ( - "fmt" - "sort" - "strings" - "testing" - "time" - - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/cdp" - "github.com/kava-labs/kava/x/cdp/keeper" - "github.com/kava-labs/kava/x/cdp/types" -) - -type GenesisTestSuite struct { - suite.Suite - - app app.TestApp - ctx sdk.Context - genTime time.Time - keeper keeper.Keeper - addrs []sdk.AccAddress -} - -func (suite *GenesisTestSuite) SetupTest() { - tApp := app.NewTestApp() - suite.genTime = tmtime.Canonical(time.Date(2021, 1, 1, 1, 1, 1, 1, time.UTC)) - suite.ctx = tApp.NewContext(true, tmproto.Header{Height: 1, Time: suite.genTime}) - suite.keeper = tApp.GetCDPKeeper() - suite.app = tApp - - _, addrs := app.GeneratePrivKeyAddressPairs(3) - suite.addrs = addrs -} - -func (suite *GenesisTestSuite) TestInvalidGenState() { - type args struct { - params types.Params - cdps types.CDPs - deposits types.Deposits - startingID uint64 - debtDenom string - govDenom string - genAccumTimes types.GenesisAccumulationTimes - genTotalPrincipals types.GenesisTotalPrincipals - } - type errArgs struct { - expectPass bool - contains string - } - - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - name: "empty debt denom", - args: args{ - params: types.DefaultParams(), - cdps: types.CDPs{}, - deposits: types.Deposits{}, - debtDenom: "", - govDenom: types.DefaultGovDenom, - genAccumTimes: types.DefaultGenesisState().PreviousAccumulationTimes, - genTotalPrincipals: types.DefaultGenesisState().TotalPrincipals, - }, - errArgs: errArgs{ - expectPass: false, - contains: "debt denom invalid", - }, - }, - { - name: "empty gov denom", - args: args{ - params: types.DefaultParams(), - cdps: types.CDPs{}, - deposits: types.Deposits{}, - debtDenom: types.DefaultDebtDenom, - govDenom: "", - genAccumTimes: types.DefaultGenesisState().PreviousAccumulationTimes, - genTotalPrincipals: types.DefaultGenesisState().TotalPrincipals, - }, - errArgs: errArgs{ - expectPass: false, - contains: "gov denom invalid", - }, - }, - { - name: "interest factor below one", - args: args{ - params: types.DefaultParams(), - cdps: types.CDPs{}, - deposits: types.Deposits{}, - debtDenom: types.DefaultDebtDenom, - govDenom: types.DefaultGovDenom, - genAccumTimes: types.GenesisAccumulationTimes{types.NewGenesisAccumulationTime("bnb-a", time.Time{}, sdk.OneDec().Sub(sdk.SmallestDec()))}, - genTotalPrincipals: types.DefaultGenesisState().TotalPrincipals, - }, - errArgs: errArgs{ - expectPass: false, - contains: "interest factor should be ≥ 1.0", - }, - }, - { - name: "negative total principal", - args: args{ - params: types.DefaultParams(), - cdps: types.CDPs{}, - deposits: types.Deposits{}, - debtDenom: types.DefaultDebtDenom, - govDenom: types.DefaultGovDenom, - genAccumTimes: types.DefaultGenesisState().PreviousAccumulationTimes, - genTotalPrincipals: types.GenesisTotalPrincipals{types.NewGenesisTotalPrincipal("bnb-a", sdkmath.NewInt(-1))}, - }, - errArgs: errArgs{ - expectPass: false, - contains: "total principal should be positive", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - gs := types.NewGenesisState(tc.args.params, tc.args.cdps, tc.args.deposits, tc.args.startingID, - tc.args.debtDenom, tc.args.govDenom, tc.args.genAccumTimes, tc.args.genTotalPrincipals) - err := gs.Validate() - if tc.errArgs.expectPass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *GenesisTestSuite) TestValidGenState() { - cdc := suite.app.AppCodec() - - suite.NotPanics(func() { - suite.app.InitializeFromGenesisStates( - NewPricefeedGenStateMulti(cdc), - NewCDPGenStateMulti(cdc), - ) - }) - - cdpGS := NewCDPGenStateMulti(cdc) - gs := types.GenesisState{} - suite.app.AppCodec().MustUnmarshalJSON(cdpGS["cdp"], &gs) - gs.CDPs = cdps() - gs.StartingCdpID = uint64(5) - appGS := app.GenesisState{"cdp": suite.app.AppCodec().MustMarshalJSON(&gs)} - suite.NotPanics(func() { - suite.SetupTest() - suite.app.InitializeFromGenesisStates( - NewPricefeedGenStateMulti(cdc), - appGS, - ) - }) -} - -func (suite *GenesisTestSuite) Test_InitExportGenesis() { - cdps := types.CDPs{ - { - ID: 2, - Owner: suite.addrs[0], - Type: "xrp-a", - Collateral: c("xrp", 200000000), - Principal: c("usdx", 10000000), - AccumulatedFees: c("usdx", 0), - FeesUpdated: suite.genTime, - InterestFactor: sdk.NewDec(1), - }, - } - - genTotalPrincipals := types.GenesisTotalPrincipals{ - types.NewGenesisTotalPrincipal("btc-a", sdk.ZeroInt()), - types.NewGenesisTotalPrincipal("xrp-a", sdk.ZeroInt()), - } - - var deposits types.Deposits - for _, c := range cdps { - deposit := types.Deposit{ - CdpID: c.ID, - Depositor: c.Owner, - Amount: c.Collateral, - } - deposits = append(deposits, deposit) - - for i, p := range genTotalPrincipals { - if p.CollateralType == c.Type { - genTotalPrincipals[i].TotalPrincipal = genTotalPrincipals[i].TotalPrincipal.Add(c.Principal.Amount) - } - } - } - - cdpGenesis := types.GenesisState{ - Params: types.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - SurplusAuctionThreshold: types.DefaultSurplusThreshold, - SurplusAuctionLot: types.DefaultSurplusLot, - DebtAuctionThreshold: types.DefaultDebtThreshold, - DebtAuctionLot: types.DefaultDebtLot, - LiquidationBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - CollateralParams: types.CollateralParams{ - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("2.0"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // 5% apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(7000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(6), - }, - { - Denom: "btc", - Type: "btc-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000000782997609"), // 2.5% apr - LiquidationPenalty: d("0.025"), - AuctionSize: i(10000000), - SpotMarketID: "btc:usd", - LiquidationMarketID: "btc:usd", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(8), - }, - }, - DebtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: i(6), - DebtFloor: i(10000000), - }, - }, - StartingCdpID: types.DefaultCdpStartingID, - DebtDenom: types.DefaultDebtDenom, - GovDenom: types.DefaultGovDenom, - CDPs: cdps, - Deposits: deposits, - PreviousAccumulationTimes: types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime("btc-a", suite.genTime, sdk.OneDec()), - types.NewGenesisAccumulationTime("xrp-a", suite.genTime, sdk.OneDec()), - }, - TotalPrincipals: genTotalPrincipals, - } - - suite.NotPanics(func() { - suite.app.InitializeFromGenesisStatesWithTime( - suite.genTime, - NewPricefeedGenStateMulti(suite.app.AppCodec()), - app.GenesisState{types.ModuleName: suite.app.AppCodec().MustMarshalJSON(&cdpGenesis)}, - ) - }) - - // We run the BeginBlocker at time.Now() to accumulate interest - suite.ctx = suite.ctx.WithBlockTime(time.Now()) - cdp.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}, suite.keeper) - - expectedGenesis := cdpGenesis - - // Update previous accrual times in expected genesis - var expectedPrevAccTimes types.GenesisAccumulationTimes - for _, prevAccTime := range cdpGenesis.PreviousAccumulationTimes { - time, found := suite.keeper.GetPreviousAccrualTime(suite.ctx, prevAccTime.CollateralType) - if !found { - panic(fmt.Sprintf("couldn't find previous accrual time for %s", prevAccTime.CollateralType)) - } - prevAccTime.PreviousAccumulationTime = time - - interestFactor, found := suite.keeper.GetInterestFactor(suite.ctx, prevAccTime.CollateralType) - if !found { - panic(fmt.Sprintf("couldn't find interest factor for %s", prevAccTime.CollateralType)) - } - prevAccTime.InterestFactor = interestFactor - - expectedPrevAccTimes = append(expectedPrevAccTimes, prevAccTime) - } - expectedGenesis.PreviousAccumulationTimes = expectedPrevAccTimes - - // Update total principals - var totalPrincipals types.GenesisTotalPrincipals - for _, p := range expectedGenesis.TotalPrincipals { - totalPrincipal := suite.keeper.GetTotalPrincipal(suite.ctx, p.CollateralType, "usdx") - p.TotalPrincipal = totalPrincipal - totalPrincipals = append(totalPrincipals, p) - } - expectedGenesis.TotalPrincipals = totalPrincipals - - // Update CDPs - expectedGenesis.CDPs = suite.keeper.GetAllCdps(suite.ctx) - - exportedGenesis := cdp.ExportGenesis(suite.ctx, suite.keeper) - - // Sort TotalPrincipals in both genesis files so slice order matches - sort.SliceStable(expectedGenesis.TotalPrincipals, func(i, j int) bool { - return expectedGenesis.TotalPrincipals[i].CollateralType < expectedGenesis.TotalPrincipals[j].CollateralType - }) - sort.SliceStable(exportedGenesis.TotalPrincipals, func(i, j int) bool { - return exportedGenesis.TotalPrincipals[i].CollateralType < exportedGenesis.TotalPrincipals[j].CollateralType - }) - - // Sort PreviousAccumulationTimes in both genesis files so slice order matches - sort.SliceStable(expectedGenesis.PreviousAccumulationTimes, func(i, j int) bool { - return expectedGenesis.PreviousAccumulationTimes[i].CollateralType < expectedGenesis.PreviousAccumulationTimes[j].CollateralType - }) - sort.SliceStable(exportedGenesis.PreviousAccumulationTimes, func(i, j int) bool { - return exportedGenesis.PreviousAccumulationTimes[i].CollateralType < exportedGenesis.PreviousAccumulationTimes[j].CollateralType - }) - - suite.Equal(expectedGenesis, exportedGenesis) -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(GenesisTestSuite)) -} diff --git a/x/cdp/integration_test.go b/x/cdp/integration_test.go deleted file mode 100644 index 84255c29..00000000 --- a/x/cdp/integration_test.go +++ /dev/null @@ -1,183 +0,0 @@ -package cdp_test - -import ( - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/cdp/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -// Avoid cluttering test cases with long function names -func i(in int64) sdkmath.Int { return sdkmath.NewInt(in) } -func d(str string) sdk.Dec { return sdk.MustNewDecFromStr(str) } -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } - -func NewPricefeedGenState(cdc codec.JSONCodec, asset string, price sdk.Dec) app.GenesisState { - pfGenesis := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: asset + ":usd", BaseAsset: asset, QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: asset + ":usd", - OracleAddress: sdk.AccAddress{}, - Price: price, - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - return app.GenesisState{pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pfGenesis)} -} - -func NewCDPGenState(cdc codec.JSONCodec, asset string, liquidationRatio sdk.Dec) app.GenesisState { - cdpGenesis := types.GenesisState{ - Params: types.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - SurplusAuctionThreshold: types.DefaultSurplusThreshold, - SurplusAuctionLot: types.DefaultSurplusLot, - DebtAuctionThreshold: types.DefaultDebtThreshold, - DebtAuctionLot: types.DefaultDebtLot, - CollateralParams: types.CollateralParams{ - { - Denom: asset, - Type: asset + "-a", - LiquidationRatio: liquidationRatio, - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(1000000000), - ConversionFactor: i(6), - SpotMarketID: asset + ":usd", - LiquidationMarketID: asset + ":usd", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - }, - }, - DebtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: i(6), - DebtFloor: i(10000000), - }, - }, - StartingCdpID: types.DefaultCdpStartingID, - DebtDenom: types.DefaultDebtDenom, - GovDenom: types.DefaultGovDenom, - CDPs: types.CDPs{}, - PreviousAccumulationTimes: types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime(asset+"-a", time.Time{}, sdk.OneDec()), - }, - TotalPrincipals: types.GenesisTotalPrincipals{ - types.NewGenesisTotalPrincipal(asset+"-a", sdk.ZeroInt()), - }, - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&cdpGenesis)} -} - -func NewPricefeedGenStateMulti(cdc codec.JSONCodec) app.GenesisState { - pfGenesis := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "btc:usd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "xrp:usd", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "btc:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("8000.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "xrp:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("0.25"), - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - return app.GenesisState{pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pfGenesis)} -} - -func NewCDPGenStateMulti(cdc codec.JSONCodec) app.GenesisState { - cdpGenesis := types.GenesisState{ - Params: types.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - SurplusAuctionThreshold: types.DefaultSurplusThreshold, - SurplusAuctionLot: types.DefaultSurplusLot, - DebtAuctionThreshold: types.DefaultDebtThreshold, - DebtAuctionLot: types.DefaultDebtLot, - LiquidationBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - CollateralParams: types.CollateralParams{ - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("2.0"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(7000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(6), - }, - { - Denom: "btc", - Type: "btc-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000000782997609"), // %2.5 apr - LiquidationPenalty: d("0.025"), - AuctionSize: i(10000000), - SpotMarketID: "btc:usd", - LiquidationMarketID: "btc:usd", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(8), - }, - }, - DebtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: i(6), - DebtFloor: i(10000000), - }, - }, - StartingCdpID: types.DefaultCdpStartingID, - DebtDenom: types.DefaultDebtDenom, - GovDenom: types.DefaultGovDenom, - CDPs: types.CDPs{}, - PreviousAccumulationTimes: types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime("btc-a", time.Time{}, sdk.OneDec()), - types.NewGenesisAccumulationTime("xrp-a", time.Time{}, sdk.OneDec()), - }, - TotalPrincipals: types.GenesisTotalPrincipals{ - types.NewGenesisTotalPrincipal("btc-a", sdk.ZeroInt()), - types.NewGenesisTotalPrincipal("xrp-a", sdk.ZeroInt()), - }, - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&cdpGenesis)} -} - -func cdps() (cdps types.CDPs) { - _, addrs := app.GeneratePrivKeyAddressPairs(3) - c1 := types.NewCDP(uint64(1), addrs[0], sdk.NewCoin("xrp", sdkmath.NewInt(100000000)), "xrp-a", sdk.NewCoin("usdx", sdkmath.NewInt(8000000)), tmtime.Canonical(time.Now()), sdk.OneDec()) - c2 := types.NewCDP(uint64(2), addrs[1], sdk.NewCoin("xrp", sdkmath.NewInt(100000000)), "xrp-a", sdk.NewCoin("usdx", sdkmath.NewInt(10000000)), tmtime.Canonical(time.Now()), sdk.OneDec()) - c3 := types.NewCDP(uint64(3), addrs[1], sdk.NewCoin("btc", sdkmath.NewInt(1000000000)), "btc-a", sdk.NewCoin("usdx", sdkmath.NewInt(10000000)), tmtime.Canonical(time.Now()), sdk.OneDec()) - c4 := types.NewCDP(uint64(4), addrs[2], sdk.NewCoin("xrp", sdkmath.NewInt(1000000000)), "xrp-a", sdk.NewCoin("usdx", sdkmath.NewInt(50000000)), tmtime.Canonical(time.Now()), sdk.OneDec()) - cdps = append(cdps, c1, c2, c3, c4) - return -} diff --git a/x/cdp/keeper/auctions.go b/x/cdp/keeper/auctions.go deleted file mode 100644 index 7ab0b600..00000000 --- a/x/cdp/keeper/auctions.go +++ /dev/null @@ -1,171 +0,0 @@ -package keeper - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/cdp/types" -) - -const ( - // factor for setting the initial value of gov tokens to sell at debt auctions -- assuming stable token is ~1 usd, this starts the auction with a price of $0.01 KAVA - dump = 100 -) - -// AuctionCollateral creates auctions from the input deposits which attempt to raise the corresponding amount of debt -func (k Keeper) AuctionCollateral(ctx sdk.Context, deposits types.Deposits, collateralType string, debt sdkmath.Int, bidDenom string) error { - auctionSize := k.getAuctionSize(ctx, collateralType) - totalCollateral := deposits.SumCollateral() - for _, deposit := range deposits { - debtCoveredByDeposit := (sdk.NewDecFromInt(deposit.Amount.Amount).Quo(sdk.NewDecFromInt(totalCollateral))).Mul(sdk.NewDecFromInt(debt)).RoundInt() - if err := k.CreateAuctionsFromDeposit(ctx, deposit.Amount, collateralType, deposit.Depositor, debtCoveredByDeposit, auctionSize, bidDenom); err != nil { - return err - } - } - return nil -} - -// CreateAuctionsFromDeposit creates auctions from the input deposit -func (k Keeper) CreateAuctionsFromDeposit( - ctx sdk.Context, collateral sdk.Coin, collateralType string, returnAddr sdk.AccAddress, debt, auctionSize sdkmath.Int, - principalDenom string, -) error { - // number of auctions of auctionSize - numberOfAuctions := collateral.Amount.Quo(auctionSize) - debtPerAuction := debt.Mul(auctionSize).Quo(collateral.Amount) - - // last auction for remaining collateral (collateral < auctionSize) - lastAuctionCollateral := collateral.Amount.Mod(auctionSize) - lastAuctionDebt := debt.Mul(lastAuctionCollateral).Quo(collateral.Amount) - - // amount of debt that has not been allocated due to - // rounding error (unallocated debt is less than numberOfAuctions + 1) - unallocatedDebt := debt.Sub(numberOfAuctions.Mul(debtPerAuction).Add(lastAuctionDebt)) - - // rounding error for whole and last auctions in units of collateral - // higher value means a larger truncation - wholeAuctionError := debt.Mul(auctionSize).Mod(collateral.Amount) - lastAuctionError := debt.Mul(lastAuctionCollateral).Mod(collateral.Amount) - - // if last auction has larger rounding error, then allocate one debt to last auction first - // follows the largest remainder method https://en.wikipedia.org/wiki/Largest_remainder_method - if lastAuctionError.GT(wholeAuctionError) { - lastAuctionDebt = lastAuctionDebt.Add(sdk.OneInt()) - unallocatedDebt = unallocatedDebt.Sub(sdk.OneInt()) - } - - debtDenom := k.GetDebtDenom(ctx) - numAuctions := numberOfAuctions.Int64() - - // create whole auctions - for i := int64(0); i < numAuctions; i++ { - debtAmount := debtPerAuction - - // distribute unallocated debt left over starting with first auction created - if unallocatedDebt.IsPositive() { - debtAmount = debtAmount.Add(sdk.OneInt()) - unallocatedDebt = unallocatedDebt.Sub(sdk.OneInt()) - } - - penalty := k.ApplyLiquidationPenalty(ctx, collateralType, debtAmount) - - _, err := k.auctionKeeper.StartCollateralAuction( - ctx, types.LiquidatorMacc, sdk.NewCoin(collateral.Denom, auctionSize), - sdk.NewCoin(principalDenom, debtAmount.Add(penalty)), []sdk.AccAddress{returnAddr}, - []sdkmath.Int{auctionSize}, sdk.NewCoin(debtDenom, debtAmount), - ) - if err != nil { - return err - } - } - - // skip last auction if there is no collateral left to auction - if !lastAuctionCollateral.IsPositive() { - return nil - } - - // if the last auction had a larger rounding error than whole auctions, - // then unallocatedDebt will be zero since we will have already distributed - // all of the unallocated debt - if unallocatedDebt.IsPositive() { - lastAuctionDebt = lastAuctionDebt.Add(sdk.OneInt()) - unallocatedDebt = unallocatedDebt.Sub(sdk.OneInt()) - } - - penalty := k.ApplyLiquidationPenalty(ctx, collateralType, lastAuctionDebt) - - _, err := k.auctionKeeper.StartCollateralAuction( - ctx, types.LiquidatorMacc, sdk.NewCoin(collateral.Denom, lastAuctionCollateral), - sdk.NewCoin(principalDenom, lastAuctionDebt.Add(penalty)), []sdk.AccAddress{returnAddr}, - []sdkmath.Int{lastAuctionCollateral}, sdk.NewCoin(debtDenom, lastAuctionDebt), - ) - - return err -} - -// NetSurplusAndDebt burns surplus and debt coins equal to the minimum of surplus and debt balances held by the liquidator module account -// for example, if there is 1000 debt and 100 surplus, 100 surplus and 100 debt are burned, netting to 900 debt -func (k Keeper) NetSurplusAndDebt(ctx sdk.Context) error { - totalSurplus := k.GetTotalSurplus(ctx, types.LiquidatorMacc) - debt := k.GetTotalDebt(ctx, types.LiquidatorMacc) - netAmount := sdk.MinInt(totalSurplus, debt) - if netAmount.IsZero() { - return nil - } - - // burn debt coins equal to netAmount - err := k.bankKeeper.BurnCoins(ctx, types.LiquidatorMacc, sdk.NewCoins(sdk.NewCoin(k.GetDebtDenom(ctx), netAmount))) - if err != nil { - return err - } - - // burn stable coins equal to min(balance, netAmount) - dp := k.GetParams(ctx).DebtParam - liquidatorAcc := k.accountKeeper.GetModuleAccount(ctx, types.LiquidatorMacc) - balance := k.bankKeeper.GetBalance(ctx, liquidatorAcc.GetAddress(), dp.Denom).Amount - burnAmount := sdk.MinInt(balance, netAmount) - return k.bankKeeper.BurnCoins(ctx, types.LiquidatorMacc, sdk.NewCoins(sdk.NewCoin(dp.Denom, burnAmount))) -} - -// GetTotalSurplus returns the total amount of surplus tokens held by the liquidator module account -func (k Keeper) GetTotalSurplus(ctx sdk.Context, accountName string) sdkmath.Int { - acc := k.accountKeeper.GetModuleAccount(ctx, accountName) - dp := k.GetParams(ctx).DebtParam - return k.bankKeeper.GetBalance(ctx, acc.GetAddress(), dp.Denom).Amount -} - -// GetTotalDebt returns the total amount of debt tokens held by the liquidator module account -func (k Keeper) GetTotalDebt(ctx sdk.Context, accountName string) sdkmath.Int { - acc := k.accountKeeper.GetModuleAccount(ctx, accountName) - return k.bankKeeper.GetBalance(ctx, acc.GetAddress(), k.GetDebtDenom(ctx)).Amount -} - -// RunSurplusAndDebtAuctions nets the surplus and debt balances and then creates surplus or debt auctions if the remaining balance is above the auction threshold parameter -func (k Keeper) RunSurplusAndDebtAuctions(ctx sdk.Context) error { - if err := k.NetSurplusAndDebt(ctx); err != nil { - return err - } - remainingDebt := k.GetTotalDebt(ctx, types.LiquidatorMacc) - params := k.GetParams(ctx) - - if remainingDebt.GTE(params.DebtAuctionThreshold) { - debtLot := sdk.NewCoin(k.GetDebtDenom(ctx), params.DebtAuctionLot) - bidCoin := sdk.NewCoin(params.DebtParam.Denom, debtLot.Amount) - initialLot := sdk.NewCoin(k.GetGovDenom(ctx), debtLot.Amount.Mul(sdkmath.NewInt(dump))) - - _, err := k.auctionKeeper.StartDebtAuction(ctx, types.LiquidatorMacc, bidCoin, initialLot, debtLot) - if err != nil { - return err - } - } - - liquidatorAcc := k.accountKeeper.GetModuleAccount(ctx, types.LiquidatorMacc) - surplus := k.bankKeeper.GetBalance(ctx, liquidatorAcc.GetAddress(), params.DebtParam.Denom).Amount - if !surplus.GTE(params.SurplusAuctionThreshold) { - return nil - } - - surplusLot := sdk.NewCoin(params.DebtParam.Denom, sdk.MinInt(params.SurplusAuctionLot, surplus)) - _, err := k.auctionKeeper.StartSurplusAuction(ctx, types.LiquidatorMacc, surplusLot, k.GetGovDenom(ctx)) - return err -} diff --git a/x/cdp/keeper/auctions_test.go b/x/cdp/keeper/auctions_test.go deleted file mode 100644 index ba230542..00000000 --- a/x/cdp/keeper/auctions_test.go +++ /dev/null @@ -1,168 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - auctiontypes "github.com/kava-labs/kava/x/auction/types" - "github.com/kava-labs/kava/x/cdp/keeper" - "github.com/kava-labs/kava/x/cdp/types" - - "github.com/stretchr/testify/suite" - - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" -) - -type AuctionTestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context - addrs []sdk.AccAddress -} - -func (suite *AuctionTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - tApp := app.NewTestApp() - taddr := sdk.AccAddress(crypto.AddressHash([]byte("KavaTestUser1"))) - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), cs(c("usdx", 21000000000)), []sdk.AccAddress{taddr}) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(tApp.AppCodec()), - NewCDPGenStateMulti(tApp.AppCodec()), - ) - keeper := tApp.GetCDPKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - suite.addrs = []sdk.AccAddress{taddr} -} - -func (suite *AuctionTestSuite) TestNetDebtSurplus() { - bk := suite.app.GetBankKeeper() - ak := suite.app.GetAccountKeeper() - - err := bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("debt", 100))) - suite.NoError(err) - err = bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("usdx", 10))) - suite.NoError(err) - suite.NotPanics(func() { - err := suite.keeper.NetSurplusAndDebt(suite.ctx) - suite.NoError(err) - }) - acc := ak.GetModuleAccount(suite.ctx, types.LiquidatorMacc) - suite.Equal(cs(c("debt", 90)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) -} - -func (suite *AuctionTestSuite) TestCollateralAuction() { - bk := suite.app.GetBankKeeper() - err := bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("debt", 21000000000), c("bnb", 190000000000))) - suite.Require().NoError(err) - testDeposit := types.NewDeposit(1, suite.addrs[0], c("bnb", 190000000000)) - err = suite.keeper.AuctionCollateral(suite.ctx, types.Deposits{testDeposit}, "bnb-a", i(21000000000), "usdx") - suite.Require().NoError(err) -} - -func (suite *AuctionTestSuite) TestSurplusAuction() { - bk := suite.app.GetBankKeeper() - ak := suite.app.GetAccountKeeper() - - err := bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("usdx", 600000000000))) - suite.NoError(err) - err = bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("debt", 100000000000))) - suite.NoError(err) - err = suite.keeper.RunSurplusAndDebtAuctions(suite.ctx) - suite.NoError(err) - acc := ak.GetModuleAccount(suite.ctx, auctiontypes.ModuleName) - suite.Equal(cs(c("usdx", 10000000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) - acc = ak.GetModuleAccount(suite.ctx, types.LiquidatorMacc) - suite.Equal(cs(c("usdx", 490000000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) -} - -func (suite *AuctionTestSuite) TestDebtAuction() { - bk := suite.app.GetBankKeeper() - ak := suite.app.GetAccountKeeper() - - err := bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("usdx", 100000000000))) - suite.NoError(err) - err = bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("debt", 200000000000))) - suite.NoError(err) - err = suite.keeper.RunSurplusAndDebtAuctions(suite.ctx) - suite.NoError(err) - acc := ak.GetModuleAccount(suite.ctx, auctiontypes.ModuleName) - suite.Equal(cs(c("debt", 10000000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) - acc = ak.GetModuleAccount(suite.ctx, types.LiquidatorMacc) - suite.Equal(cs(c("debt", 90000000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) -} - -func (suite *AuctionTestSuite) TestGetTotalSurplus() { - bk := suite.app.GetBankKeeper() - - // liquidator account has zero coins - suite.Require().Equal(sdkmath.NewInt(0), suite.keeper.GetTotalSurplus(suite.ctx, types.LiquidatorMacc)) - - // mint some coins - err := bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("usdx", 100e6))) - suite.Require().NoError(err) - err = bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("usdx", 200e6))) - suite.Require().NoError(err) - - // liquidator account has 300e6 total usdx - suite.Require().Equal(sdkmath.NewInt(300e6), suite.keeper.GetTotalSurplus(suite.ctx, types.LiquidatorMacc)) - - // mint some debt - err = bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("debt", 500e6))) - suite.Require().NoError(err) - - // liquidator account still has 300e6 total usdx -- debt balance is ignored - suite.Require().Equal(sdkmath.NewInt(300e6), suite.keeper.GetTotalSurplus(suite.ctx, types.LiquidatorMacc)) - - // burn some usdx - err = bk.BurnCoins(suite.ctx, types.LiquidatorMacc, cs(c("usdx", 50e6))) - suite.Require().NoError(err) - - // liquidator usdx decreases - suite.Require().Equal(sdkmath.NewInt(250e6), suite.keeper.GetTotalSurplus(suite.ctx, types.LiquidatorMacc)) -} - -func (suite *AuctionTestSuite) TestGetTotalDebt() { - bk := suite.app.GetBankKeeper() - - // liquidator account has zero debt - suite.Require().Equal(sdkmath.NewInt(0), suite.keeper.GetTotalSurplus(suite.ctx, types.LiquidatorMacc)) - - // mint some debt - err := bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("debt", 100e6))) - suite.Require().NoError(err) - err = bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("debt", 200e6))) - suite.Require().NoError(err) - - // liquidator account has 300e6 total debt - suite.Require().Equal(sdkmath.NewInt(300e6), suite.keeper.GetTotalDebt(suite.ctx, types.LiquidatorMacc)) - - // mint some usdx - err = bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("usdx", 500e6))) - suite.Require().NoError(err) - - // liquidator account still has 300e6 total debt -- usdx balance is ignored - suite.Require().Equal(sdkmath.NewInt(300e6), suite.keeper.GetTotalDebt(suite.ctx, types.LiquidatorMacc)) - - // burn some debt - err = bk.BurnCoins(suite.ctx, types.LiquidatorMacc, cs(c("debt", 50e6))) - suite.Require().NoError(err) - - // liquidator debt decreases - suite.Require().Equal(sdkmath.NewInt(250e6), suite.keeper.GetTotalDebt(suite.ctx, types.LiquidatorMacc)) -} - -func TestAuctionTestSuite(t *testing.T) { - suite.Run(t, new(AuctionTestSuite)) -} diff --git a/x/cdp/keeper/cdp.go b/x/cdp/keeper/cdp.go deleted file mode 100644 index ddd78bf2..00000000 --- a/x/cdp/keeper/cdp.go +++ /dev/null @@ -1,667 +0,0 @@ -package keeper - -import ( - "fmt" - "sort" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/cdp/types" -) - -// AddCdp adds a cdp for a specific owner and collateral type -func (k Keeper) AddCdp(ctx sdk.Context, owner sdk.AccAddress, collateral sdk.Coin, principal sdk.Coin, collateralType string) error { - // validation - err := k.ValidateCollateral(ctx, collateral, collateralType) - if err != nil { - return err - } - err = k.ValidateBalance(ctx, collateral, owner) - if err != nil { - return err - } - _, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType) - if found { - return errorsmod.Wrapf(types.ErrCdpAlreadyExists, "owner %s, denom %s", owner, collateral.Denom) - } - err = k.ValidatePrincipalAdd(ctx, principal) - if err != nil { - return err - } - - err = k.ValidateDebtLimit(ctx, collateralType, principal) - if err != nil { - return err - } - err = k.ValidateCollateralizationRatio(ctx, collateral, collateralType, principal, sdk.NewCoin(principal.Denom, sdk.ZeroInt())) - if err != nil { - return err - } - - // send coins from the owners account to the cdp module - id := k.GetNextCdpID(ctx) - interestFactor, found := k.GetInterestFactor(ctx, collateralType) - if !found { - interestFactor = sdk.OneDec() - k.SetInterestFactor(ctx, collateralType, interestFactor) - - } - cdp := types.NewCDP(id, owner, collateral, collateralType, principal, ctx.BlockHeader().Time, interestFactor) - deposit := types.NewDeposit(cdp.ID, owner, collateral) - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, owner, types.ModuleName, sdk.NewCoins(collateral)) - if err != nil { - return err - } - - // mint the principal and send to the owners account - err = k.bankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(principal)) - if err != nil { - panic(err) - } - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, owner, sdk.NewCoins(principal)) - if err != nil { - panic(err) - } - - // mint the corresponding amount of debt coins - err = k.MintDebtCoins(ctx, types.ModuleName, k.GetDebtDenom(ctx), principal) - if err != nil { - panic(err) - } - - // update total principal for input collateral type - k.IncrementTotalPrincipal(ctx, collateralType, principal) - - // set the cdp, deposit, and indexes in the store - collateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, collateral, cdp.Type, principal) - err = k.SetCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio) - if err != nil { - return err - } - k.IndexCdpByOwner(ctx, cdp) - k.SetDeposit(ctx, deposit) - k.SetNextCdpID(ctx, id+1) - - k.hooks.AfterCDPCreated(ctx, cdp) - - // emit events for cdp creation, deposit, and draw - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCreateCdp, - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - ), - ) - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCdpDeposit, - sdk.NewAttribute(sdk.AttributeKeyAmount, collateral.String()), - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - ), - ) - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCdpDraw, - sdk.NewAttribute(sdk.AttributeKeyAmount, principal.String()), - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - ), - ) - - return nil -} - -// UpdateCdpAndCollateralRatioIndex updates the state of an existing cdp in the store by replacing the old index values and updating the store to the latest cdp object values -func (k Keeper) UpdateCdpAndCollateralRatioIndex(ctx sdk.Context, cdp types.CDP, ratio sdk.Dec) error { - err := k.removeOldCollateralRatioIndex(ctx, cdp.Type, cdp.ID) - if err != nil { - return err - } - - err = k.SetCDP(ctx, cdp) - if err != nil { - return err - } - k.IndexCdpByCollateralRatio(ctx, cdp.Type, cdp.ID, ratio) - return nil -} - -// DeleteCdpAndCollateralRatioIndex deletes an existing cdp in the store by removing the old index value and deleting the cdp object from the store -func (k Keeper) DeleteCdpAndCollateralRatioIndex(ctx sdk.Context, cdp types.CDP) error { - err := k.removeOldCollateralRatioIndex(ctx, cdp.Type, cdp.ID) - if err != nil { - return err - } - - return k.DeleteCDP(ctx, cdp) -} - -// SetCdpAndCollateralRatioIndex sets the cdp and collateral ratio index in the store -func (k Keeper) SetCdpAndCollateralRatioIndex(ctx sdk.Context, cdp types.CDP, ratio sdk.Dec) error { - err := k.SetCDP(ctx, cdp) - if err != nil { - return err - } - k.IndexCdpByCollateralRatio(ctx, cdp.Type, cdp.ID, ratio) - return nil -} - -func (k Keeper) removeOldCollateralRatioIndex(ctx sdk.Context, ctype string, id uint64) error { - storedCDP, found := k.GetCDP(ctx, ctype, id) - if !found { - return errorsmod.Wrapf(types.ErrCdpNotFound, "%d", storedCDP.ID) - } - oldCollateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, storedCDP.Collateral, storedCDP.Type, storedCDP.GetTotalPrincipal()) - k.RemoveCdpCollateralRatioIndex(ctx, storedCDP.Type, storedCDP.ID, oldCollateralToDebtRatio) - return nil -} - -// MintDebtCoins mints debt coins in the cdp module account -func (k Keeper) MintDebtCoins(ctx sdk.Context, moduleAccount string, denom string, principalCoins sdk.Coin) error { - debtCoins := sdk.NewCoins(sdk.NewCoin(denom, principalCoins.Amount)) - return k.bankKeeper.MintCoins(ctx, moduleAccount, debtCoins) -} - -// BurnDebtCoins burns debt coins from the cdp module account -func (k Keeper) BurnDebtCoins(ctx sdk.Context, moduleAccount string, denom string, paymentCoins sdk.Coin) error { - macc := k.accountKeeper.GetModuleAccount(ctx, moduleAccount) - maxBurnableAmount := k.bankKeeper.GetBalance(ctx, macc.GetAddress(), denom).Amount - // check that the requested burn is not greater than the mod account balance - debtCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.MinInt(paymentCoins.Amount, maxBurnableAmount))) - return k.bankKeeper.BurnCoins(ctx, moduleAccount, debtCoins) -} - -// GetCdpID returns the id of the cdp corresponding to a specific owner and collateral denom -func (k Keeper) GetCdpID(ctx sdk.Context, owner sdk.AccAddress, collateralType string) (uint64, bool) { - cdpIDs, found := k.GetCdpIdsByOwner(ctx, owner) - if !found { - return 0, false - } - for _, id := range cdpIDs { - _, found = k.GetCDP(ctx, collateralType, id) - if found { - return id, true - } - } - return 0, false -} - -// GetCdpIdsByOwner returns all the ids of cdps corresponding to a particular owner -func (k Keeper) GetCdpIdsByOwner(ctx sdk.Context, owner sdk.AccAddress) ([]uint64, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpIDKeyPrefix) - bz := store.Get(owner) - if bz == nil { - return []uint64{}, false - } - - var index types.OwnerCDPIndex - k.cdc.MustUnmarshal(bz, &index) - return index.CdpIDs, true -} - -// GetCdpByOwnerAndCollateralType queries cdps owned by owner and returns the cdp with matching denom -func (k Keeper) GetCdpByOwnerAndCollateralType(ctx sdk.Context, owner sdk.AccAddress, collateralType string) (types.CDP, bool) { - cdpIDs, found := k.GetCdpIdsByOwner(ctx, owner) - if !found { - return types.CDP{}, false - } - for _, id := range cdpIDs { - cdp, found := k.GetCDP(ctx, collateralType, id) - if found { - return cdp, true - } - } - return types.CDP{}, false -} - -// GetCDP returns the cdp associated with a particular collateral denom and id -func (k Keeper) GetCDP(ctx sdk.Context, collateralType string, cdpID uint64) (types.CDP, bool) { - // get store - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpKeyPrefix) - _, found := k.GetCollateral(ctx, collateralType) - if !found { - return types.CDP{}, false - } - // get CDP - bz := store.Get(types.CdpKey(collateralType, cdpID)) - // unmarshal - if bz == nil { - return types.CDP{}, false - } - var cdp types.CDP - k.cdc.MustUnmarshal(bz, &cdp) - return cdp, true -} - -// SetCDP sets a cdp in the store -func (k Keeper) SetCDP(ctx sdk.Context, cdp types.CDP) error { - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpKeyPrefix) - _, found := k.GetCollateral(ctx, cdp.Type) - if !found { - return errorsmod.Wrapf(types.ErrDenomPrefixNotFound, "%s", cdp.Collateral.Denom) - } - bz := k.cdc.MustMarshal(&cdp) - store.Set(types.CdpKey(cdp.Type, cdp.ID), bz) - return nil -} - -// DeleteCDP deletes a cdp from the store -func (k Keeper) DeleteCDP(ctx sdk.Context, cdp types.CDP) error { - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpKeyPrefix) - _, found := k.GetCollateral(ctx, cdp.Type) - if !found { - return errorsmod.Wrapf(types.ErrDenomPrefixNotFound, "%s", cdp.Collateral.Denom) - } - store.Delete(types.CdpKey(cdp.Type, cdp.ID)) - return nil -} - -// GetAllCdps returns all cdps from the store -func (k Keeper) GetAllCdps(ctx sdk.Context) (cdps types.CDPs) { - k.IterateAllCdps(ctx, func(cdp types.CDP) bool { - cdps = append(cdps, cdp) - return false - }) - return -} - -// GetAllCdpsByCollateralType returns all cdps of a particular collateral type from the store -func (k Keeper) GetAllCdpsByCollateralType(ctx sdk.Context, collateralType string) (cdps types.CDPs) { - k.IterateCdpsByCollateralType(ctx, collateralType, func(cdp types.CDP) bool { - cdps = append(cdps, cdp) - return false - }) - return -} - -// GetAllCdpsByCollateralTypeAndRatio returns all cdps of a particular collateral type and below a certain collateralization ratio -func (k Keeper) GetAllCdpsByCollateralTypeAndRatio(ctx sdk.Context, collateralType string, targetRatio sdk.Dec) (cdps types.CDPs) { - k.IterateCdpsByCollateralRatio(ctx, collateralType, targetRatio, func(cdp types.CDP) bool { - cdps = append(cdps, cdp) - return false - }) - return -} - -// SetNextCdpID sets the highest cdp id in the store -func (k Keeper) SetNextCdpID(ctx sdk.Context, id uint64) { - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpIDKey) - store.Set(types.CdpIDKey, types.GetCdpIDBytes(id)) -} - -// GetNextCdpID returns the highest cdp id from the store -func (k Keeper) GetNextCdpID(ctx sdk.Context) (id uint64) { - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpIDKey) - bz := store.Get(types.CdpIDKey) - if bz == nil { - panic("starting cdp id not set in genesis") - } - id = types.GetCdpIDFromBytes(bz) - return -} - -// IndexCdpByOwner sets the cdp id in the store, indexed by the owner -func (k Keeper) IndexCdpByOwner(ctx sdk.Context, cdp types.CDP) { - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpIDKeyPrefix) - - cdpIDs, found := k.GetCdpIdsByOwner(ctx, cdp.Owner) - - if found { - cdpIDs = append(cdpIDs, cdp.ID) - sort.Slice(cdpIDs, func(i, j int) bool { return cdpIDs[i] < cdpIDs[j] }) - } else { - cdpIDs = []uint64{cdp.ID} - } - - newIndex := types.OwnerCDPIndex{CdpIDs: cdpIDs} - store.Set(cdp.Owner, k.cdc.MustMarshal(&newIndex)) -} - -// RemoveCdpOwnerIndex deletes the cdp id from the store's index of cdps by owner -func (k Keeper) RemoveCdpOwnerIndex(ctx sdk.Context, cdp types.CDP) { - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpIDKeyPrefix) - - cdpIDs, found := k.GetCdpIdsByOwner(ctx, cdp.Owner) - if !found { - return - } - updatedCdpIds := []uint64{} - for _, id := range cdpIDs { - if id != cdp.ID { - updatedCdpIds = append(updatedCdpIds, id) - } - } - if len(updatedCdpIds) == 0 { - store.Delete(cdp.Owner) - return - } - - updatedIndex := types.OwnerCDPIndex{CdpIDs: updatedCdpIds} - updatedBytes := k.cdc.MustMarshal(&updatedIndex) - store.Set(cdp.Owner, updatedBytes) -} - -// IndexCdpByCollateralRatio sets the cdp id in the store, indexed by the collateral type and collateral to debt ratio -func (k Keeper) IndexCdpByCollateralRatio(ctx sdk.Context, collateralType string, id uint64, collateralRatio sdk.Dec) { - store := prefix.NewStore(ctx.KVStore(k.key), types.CollateralRatioIndexPrefix) - _, found := k.GetCollateral(ctx, collateralType) - if !found { - panic(fmt.Sprintf("denom %s prefix not found", collateralType)) - } - store.Set(types.CollateralRatioKey(collateralType, id, collateralRatio), types.GetCdpIDBytes(id)) -} - -// RemoveCdpCollateralRatioIndex deletes the cdp id from the store's index of cdps by collateral type and collateral to debt ratio -func (k Keeper) RemoveCdpCollateralRatioIndex(ctx sdk.Context, collateralType string, id uint64, collateralRatio sdk.Dec) { - store := prefix.NewStore(ctx.KVStore(k.key), types.CollateralRatioIndexPrefix) - _, found := k.GetCollateral(ctx, collateralType) - if !found { - panic(fmt.Sprintf("denom %s prefix not found", collateralType)) - } - store.Delete(types.CollateralRatioKey(collateralType, id, collateralRatio)) -} - -// GetDebtDenom returns the denom of debt in the system -func (k Keeper) GetDebtDenom(ctx sdk.Context) string { - store := prefix.NewStore(ctx.KVStore(k.key), types.DebtDenomKey) - bz := store.Get(types.DebtDenomKey) - return string(bz) -} - -// GetGovDenom returns the denom of the governance token -func (k Keeper) GetGovDenom(ctx sdk.Context) string { - store := prefix.NewStore(ctx.KVStore(k.key), types.GovDenomKey) - bz := store.Get(types.GovDenomKey) - return string(bz) -} - -// SetDebtDenom set the denom of debt in the system -func (k Keeper) SetDebtDenom(ctx sdk.Context, denom string) { - if denom == "" { - panic("debt denom not set in genesis") - } - store := prefix.NewStore(ctx.KVStore(k.key), types.DebtDenomKey) - store.Set(types.DebtDenomKey, []byte(denom)) -} - -// SetGovDenom set the denom of the governance token in the system -func (k Keeper) SetGovDenom(ctx sdk.Context, denom string) { - if denom == "" { - panic("gov denom not set in genesis") - } - store := prefix.NewStore(ctx.KVStore(k.key), types.GovDenomKey) - store.Set(types.GovDenomKey, []byte(denom)) -} - -// ValidateCollateral validates that a collateral is valid for use in cdps -func (k Keeper) ValidateCollateral(ctx sdk.Context, collateral sdk.Coin, collateralType string) error { - cp, found := k.GetCollateral(ctx, collateralType) - if !found { - return errorsmod.Wrap(types.ErrCollateralNotSupported, collateral.Denom) - } - if cp.Denom != collateral.Denom { - return errorsmod.Wrapf(types.ErrInvalidCollateral, "collateral type: %s expected denom: %s got: %s", collateralType, cp.Denom, collateral.Denom) - } - ok := k.GetMarketStatus(ctx, cp.SpotMarketID) - if !ok { - return errorsmod.Wrap(types.ErrPricefeedDown, collateral.Denom) - } - ok = k.GetMarketStatus(ctx, cp.LiquidationMarketID) - if !ok { - return errorsmod.Wrap(types.ErrPricefeedDown, collateral.Denom) - } - return nil -} - -// ValidatePrincipalAdd validates that an asset is valid for use as debt when creating a new cdp -func (k Keeper) ValidatePrincipalAdd(ctx sdk.Context, principal sdk.Coin) error { - dp, found := k.GetDebtParam(ctx, principal.Denom) - if !found { - return errorsmod.Wrap(types.ErrDebtNotSupported, principal.Denom) - } - if principal.Amount.LT(dp.DebtFloor) { - return errorsmod.Wrapf(types.ErrBelowDebtFloor, "proposed %s < minimum %s", principal, dp.DebtFloor) - } - return nil -} - -// ValidatePrincipalDraw validates that an asset is valid for use as debt when drawing debt off an existing cdp -func (k Keeper) ValidatePrincipalDraw(ctx sdk.Context, principal sdk.Coin, expectedDenom string) error { - if principal.Denom != expectedDenom { - return errorsmod.Wrapf(types.ErrInvalidDebtRequest, "proposed %s, expected %s", principal.Denom, expectedDenom) - } - _, found := k.GetDebtParam(ctx, principal.Denom) - if !found { - return errorsmod.Wrap(types.ErrDebtNotSupported, principal.Denom) - } - return nil -} - -// ValidateDebtLimit validates that the input debt amount does not exceed the global debt limit or the debt limit for that collateral -func (k Keeper) ValidateDebtLimit(ctx sdk.Context, collateralType string, principal sdk.Coin) error { - cp, found := k.GetCollateral(ctx, collateralType) - if !found { - return errorsmod.Wrap(types.ErrCollateralNotSupported, collateralType) - } - totalPrincipal := k.GetTotalPrincipal(ctx, collateralType, principal.Denom).Add(principal.Amount) - collateralLimit := cp.DebtLimit.Amount - if totalPrincipal.GT(collateralLimit) { - return errorsmod.Wrapf(types.ErrExceedsDebtLimit, "debt increase %s > collateral debt limit %s", sdk.NewCoins(sdk.NewCoin(principal.Denom, totalPrincipal)), sdk.NewCoins(sdk.NewCoin(principal.Denom, collateralLimit))) - } - globalLimit := k.GetParams(ctx).GlobalDebtLimit.Amount - if totalPrincipal.GT(globalLimit) { - return errorsmod.Wrapf(types.ErrExceedsDebtLimit, "debt increase %s > global debt limit %s", sdk.NewCoin(principal.Denom, totalPrincipal), sdk.NewCoin(principal.Denom, globalLimit)) - } - return nil -} - -// ValidateCollateralizationRatio validate that adding the input principal doesn't put the cdp below the liquidation ratio -func (k Keeper) ValidateCollateralizationRatio(ctx sdk.Context, collateral sdk.Coin, collateralType string, principal sdk.Coin, fees sdk.Coin) error { - collateralizationRatio, err := k.CalculateCollateralizationRatio(ctx, collateral, collateralType, principal, fees, spot) - if err != nil { - return err - } - liquidationRatio := k.getLiquidationRatio(ctx, collateralType) - if collateralizationRatio.LT(liquidationRatio) { - return errorsmod.Wrapf(types.ErrInvalidCollateralRatio, "collateral %s, collateral ratio %s, liquidation ratio %s", collateral.Denom, collateralizationRatio, liquidationRatio) - } - return nil -} - -// ValidateBalance validates that the input account has sufficient spendable funds -func (k Keeper) ValidateBalance(ctx sdk.Context, amount sdk.Coin, sender sdk.AccAddress) error { - acc := k.accountKeeper.GetAccount(ctx, sender) - if acc == nil { - return errorsmod.Wrapf(types.ErrAccountNotFound, "address: %s", sender) - } - spendableBalance := k.bankKeeper.SpendableCoins(ctx, acc.GetAddress()).AmountOf(amount.Denom) - if spendableBalance.LT(amount.Amount) { - return errorsmod.Wrapf(types.ErrInsufficientBalance, "%s < %s", sdk.NewCoin(amount.Denom, spendableBalance), amount) - } - - return nil -} - -// CalculateCollateralToDebtRatio returns the collateral to debt ratio of the input collateral and debt amounts -func (k Keeper) CalculateCollateralToDebtRatio(ctx sdk.Context, collateral sdk.Coin, collateralType string, debt sdk.Coin) sdk.Dec { - debtTotal := k.convertDebtToBaseUnits(ctx, debt) - - if debtTotal.IsZero() || debtTotal.GTE(types.MaxSortableDec) { - return types.MaxSortableDec.Sub(sdk.SmallestDec()) - } - - collateralBaseUnits := k.convertCollateralToBaseUnits(ctx, collateral, collateralType) - return collateralBaseUnits.Quo(debtTotal) -} - -// LoadAugmentedCDP creates a new augmented CDP from an existing CDP -func (k Keeper) LoadAugmentedCDP(ctx sdk.Context, cdp types.CDP) types.AugmentedCDP { - // sync the latest interest of the cdp - interestAccumulated := k.CalculateNewInterest(ctx, cdp) - cdp.AccumulatedFees = cdp.AccumulatedFees.Add(interestAccumulated) - // update cdp fields to match synced accumulated fees - prevAccrualTime, found := k.GetPreviousAccrualTime(ctx, cdp.Type) - if found { - cdp.FeesUpdated = prevAccrualTime - } - globalInterestFactor, found := k.GetInterestFactor(ctx, cdp.Type) - if found { - cdp.InterestFactor = globalInterestFactor - } - // calculate collateralization ratio - collateralizationRatio, err := k.CalculateCollateralizationRatio(ctx, cdp.Collateral, cdp.Type, cdp.Principal, cdp.AccumulatedFees, liquidation) - if err != nil { - return types.AugmentedCDP{CDP: cdp} - } - // convert collateral value to debt coin - totalDebt := cdp.GetTotalPrincipal().Amount - collateralValueInDebtDenom := sdk.NewDecFromInt(totalDebt).Mul(collateralizationRatio) - collateralValueInDebt := sdk.NewCoin(cdp.Principal.Denom, collateralValueInDebtDenom.RoundInt()) - // create new augmuented cdp - augmentedCDP := types.NewAugmentedCDP(cdp, collateralValueInDebt, collateralizationRatio) - return augmentedCDP -} - -// LoadCDPResponse creates a new CDPResponse from an existing CDP -func (k Keeper) LoadCDPResponse(ctx sdk.Context, cdp types.CDP) types.CDPResponse { - // sync the latest interest of the cdp - interestAccumulated := k.CalculateNewInterest(ctx, cdp) - cdp.AccumulatedFees = cdp.AccumulatedFees.Add(interestAccumulated) - // update cdp fields to match synced accumulated fees - prevAccrualTime, found := k.GetPreviousAccrualTime(ctx, cdp.Type) - if found { - cdp.FeesUpdated = prevAccrualTime - } - globalInterestFactor, found := k.GetInterestFactor(ctx, cdp.Type) - if found { - cdp.InterestFactor = globalInterestFactor - } - // calculate collateralization ratio - collateralizationRatio, err := k.CalculateCollateralizationRatio(ctx, cdp.Collateral, cdp.Type, cdp.Principal, cdp.AccumulatedFees, liquidation) - if err != nil { - return types.CDPResponse{ - ID: cdp.ID, - Owner: cdp.Owner.String(), - Type: cdp.Type, - Collateral: cdp.Collateral, - Principal: cdp.Principal, - AccumulatedFees: cdp.AccumulatedFees, - FeesUpdated: cdp.FeesUpdated, - InterestFactor: cdp.InterestFactor.String(), - } - } - // convert collateral value to debt coin - totalDebt := cdp.GetTotalPrincipal().Amount - collateralValueInDebtDenom := sdk.NewDecFromInt(totalDebt).Mul(collateralizationRatio) - collateralValueInDebt := sdk.NewCoin(cdp.Principal.Denom, collateralValueInDebtDenom.RoundInt()) - // create new cdp response - return types.NewCDPResponse(cdp, collateralValueInDebt, collateralizationRatio) -} - -// CalculateCollateralizationRatio returns the collateralization ratio of the input collateral to the input debt plus fees -func (k Keeper) CalculateCollateralizationRatio(ctx sdk.Context, collateral sdk.Coin, collateralType string, principal sdk.Coin, fees sdk.Coin, pfType pricefeedType) (sdk.Dec, error) { - if collateral.IsZero() { - return sdk.ZeroDec(), nil - } - var marketID string - switch pfType { - case spot: - marketID = k.getSpotMarketID(ctx, collateralType) - case liquidation: - marketID = k.getliquidationMarketID(ctx, collateralType) - default: - return sdk.Dec{}, pfType.IsValid() - } - - price, err := k.pricefeedKeeper.GetCurrentPrice(ctx, marketID) - if err != nil { - return sdk.Dec{}, err - } - collateralBaseUnits := k.convertCollateralToBaseUnits(ctx, collateral, collateralType) - collateralValue := collateralBaseUnits.Mul(price.Price) - - prinicpalBaseUnits := k.convertDebtToBaseUnits(ctx, principal) - principalTotal := prinicpalBaseUnits - feeBaseUnits := k.convertDebtToBaseUnits(ctx, fees) - principalTotal = principalTotal.Add(feeBaseUnits) - - collateralRatio := collateralValue.Quo(principalTotal) - return collateralRatio, nil -} - -// CalculateCollateralizationRatioFromAbsoluteRatio takes a coin's denom and an absolute ratio and returns the respective collateralization ratio -func (k Keeper) CalculateCollateralizationRatioFromAbsoluteRatio(ctx sdk.Context, collateralType string, absoluteRatio sdk.Dec, pfType pricefeedType) (sdk.Dec, error) { - // get price of collateral - var marketID string - switch pfType { - case spot: - marketID = k.getSpotMarketID(ctx, collateralType) - case liquidation: - marketID = k.getliquidationMarketID(ctx, collateralType) - default: - return sdk.Dec{}, pfType.IsValid() - } - - price, err := k.pricefeedKeeper.GetCurrentPrice(ctx, marketID) - if err != nil { - return sdk.Dec{}, err - } - // convert absolute ratio to collateralization ratio - respectiveCollateralRatio := absoluteRatio.Quo(price.Price) - return respectiveCollateralRatio, nil -} - -// SetMarketStatus sets the status of the input market, true means the market is up and running, false means it is down -func (k Keeper) SetMarketStatus(ctx sdk.Context, marketID string, up bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PricefeedStatusKeyPrefix) - if up { - store.Set([]byte(marketID), []byte{}) - } else { - store.Delete([]byte(marketID)) - } -} - -// GetMarketStatus returns true if the market has a price, otherwise false -func (k Keeper) GetMarketStatus(ctx sdk.Context, marketID string) bool { - store := prefix.NewStore(ctx.KVStore(k.key), types.PricefeedStatusKeyPrefix) - bz := store.Get([]byte(marketID)) - return bz != nil -} - -// UpdatePricefeedStatus determines if the price of an asset is available and updates the global status of the market -func (k Keeper) UpdatePricefeedStatus(ctx sdk.Context, marketID string) (ok bool) { - _, err := k.pricefeedKeeper.GetCurrentPrice(ctx, marketID) - if err != nil { - k.SetMarketStatus(ctx, marketID, false) - return false - } - k.SetMarketStatus(ctx, marketID, true) - return true -} - -// converts the input collateral to base units (ie multiplies the input by 10^(-ConversionFactor)) -func (k Keeper) convertCollateralToBaseUnits(ctx sdk.Context, collateral sdk.Coin, collateralType string) (baseUnits sdk.Dec) { - cp, _ := k.GetCollateral(ctx, collateralType) - return sdk.NewDecFromInt(collateral.Amount).Mul(sdk.NewDecFromIntWithPrec(sdk.OneInt(), cp.ConversionFactor.Int64())) -} - -// converts the input debt to base units (ie multiplies the input by 10^(-ConversionFactor)) -func (k Keeper) convertDebtToBaseUnits(ctx sdk.Context, debt sdk.Coin) (baseUnits sdk.Dec) { - dp, _ := k.GetDebtParam(ctx, debt.Denom) - return sdk.NewDecFromInt(debt.Amount).Mul(sdk.NewDecFromIntWithPrec(sdk.OneInt(), dp.ConversionFactor.Int64())) -} - -type pricefeedType string - -const ( - spot pricefeedType = "spot" - liquidation pricefeedType = "liquidation" -) - -func (pft pricefeedType) IsValid() error { - switch pft { - case spot, liquidation: - return nil - } - return fmt.Errorf("invalid pricefeed type: %s", pft) -} diff --git a/x/cdp/keeper/cdp_test.go b/x/cdp/keeper/cdp_test.go deleted file mode 100644 index 9c4b5203..00000000 --- a/x/cdp/keeper/cdp_test.go +++ /dev/null @@ -1,396 +0,0 @@ -package keeper_test - -import ( - "errors" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/cdp/keeper" - "github.com/kava-labs/kava/x/cdp/types" -) - -type CdpTestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context -} - -func (suite *CdpTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - tApp.InitializeFromGenesisStates( - NewPricefeedGenStateMulti(tApp.AppCodec()), - NewCDPGenStateMulti(tApp.AppCodec()), - ) - keeper := tApp.GetCDPKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper -} - -func (suite *CdpTestSuite) TestAddCdp() { - _, addrs := app.GeneratePrivKeyAddressPairs(2) - ak := suite.app.GetAccountKeeper() - acc := ak.NewAccountWithAddress(suite.ctx, addrs[0]) - err := suite.app.FundAccount(suite.ctx, acc.GetAddress(), cs(c("xrp", 200000000), c("btc", 500000000))) - suite.Require().NoError(err) - - ak.SetAccount(suite.ctx, acc) - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("xrp", 200000000), c("usdx", 10000000), "btc-a") - suite.Require().True(errors.Is(err, types.ErrInvalidCollateral)) - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("xrp", 200000000), c("usdx", 26000000), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrInvalidCollateralRatio)) - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("xrp", 500000000), c("usdx", 26000000), "xrp-a") - suite.Error(err) // insufficient balance - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("xrp", 200000000), c("xusd", 10000000), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrDebtNotSupported)) - - acc2 := ak.NewAccountWithAddress(suite.ctx, addrs[1]) - err = suite.app.FundAccount(suite.ctx, acc2.GetAddress(), cs(c("btc", 500000000000))) - suite.Require().NoError(err) - - ak.SetAccount(suite.ctx, acc2) - err = suite.keeper.AddCdp(suite.ctx, addrs[1], c("btc", 500000000000), c("usdx", 500000000001), "btc-a") - suite.Require().True(errors.Is(err, types.ErrExceedsDebtLimit)) - - ctx := suite.ctx.WithBlockTime(suite.ctx.BlockTime().Add(time.Hour * 2)) - pk := suite.app.GetPriceFeedKeeper() - err = pk.SetCurrentPrices(ctx, "xrp:usd") - suite.Error(err) - ok := suite.keeper.UpdatePricefeedStatus(ctx, "xrp:usd") - suite.False(ok) - err = suite.keeper.AddCdp(ctx, addrs[0], c("xrp", 100000000), c("usdx", 10000000), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrPricefeedDown)) - - err = pk.SetCurrentPrices(suite.ctx, "xrp:usd") - ok = suite.keeper.UpdatePricefeedStatus(suite.ctx, "xrp:usd") - suite.True(ok) - suite.NoError(err) - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("xrp", 100000000), c("usdx", 10000000), "xrp-a") - suite.NoError(err) - id := suite.keeper.GetNextCdpID(suite.ctx) - suite.Equal(uint64(2), id) - tp := suite.keeper.GetTotalPrincipal(suite.ctx, "xrp-a", "usdx") - suite.Equal(i(10000000), tp) - - bk := suite.app.GetBankKeeper() - - macc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(cs(c("debt", 10000000), c("xrp", 100000000)), bk.GetAllBalances(suite.ctx, macc.GetAddress())) - acc = ak.GetAccount(suite.ctx, addrs[0]) - suite.Equal(cs(c("usdx", 10000000), c("xrp", 100000000), c("btc", 500000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) - - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("btc", 500000000), c("usdx", 26667000000), "btc-a") - suite.Require().True(errors.Is(err, types.ErrInvalidCollateralRatio)) - - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("btc", 500000000), c("usdx", 100000000), "btc-a") - suite.NoError(err) - id = suite.keeper.GetNextCdpID(suite.ctx) - suite.Equal(uint64(3), id) - tp = suite.keeper.GetTotalPrincipal(suite.ctx, "btc-a", "usdx") - suite.Equal(i(100000000), tp) - macc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(cs(c("debt", 110000000), c("xrp", 100000000), c("btc", 500000000)), bk.GetAllBalances(suite.ctx, macc.GetAddress())) - acc = ak.GetAccount(suite.ctx, addrs[0]) - suite.Equal(cs(c("usdx", 110000000), c("xrp", 100000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) - - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("lol", 100), c("usdx", 10), "lol-a") - suite.Require().True(errors.Is(err, types.ErrCollateralNotSupported)) - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("xrp", 100), c("usdx", 10), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrCdpAlreadyExists)) -} - -func (suite *CdpTestSuite) TestGetCollateral() { - _, found := suite.keeper.GetCollateral(suite.ctx, "lol-a") - suite.False(found) - _, found = suite.keeper.GetCollateral(suite.ctx, "xrp-a") - suite.True(found) -} - -func (suite *CdpTestSuite) TestGetDebtDenom() { - suite.Panics(func() { suite.keeper.SetDebtDenom(suite.ctx, "") }) - t := suite.keeper.GetDebtDenom(suite.ctx) - suite.Equal("debt", t) - suite.keeper.SetDebtDenom(suite.ctx, "lol") - t = suite.keeper.GetDebtDenom(suite.ctx) - suite.Equal("lol", t) -} - -func (suite *CdpTestSuite) TestGetNextCdpID() { - id := suite.keeper.GetNextCdpID(suite.ctx) - suite.Equal(types.DefaultCdpStartingID, id) -} - -func (suite *CdpTestSuite) TestGetSetCdp() { - _, addrs := app.GeneratePrivKeyAddressPairs(1) - cdp := types.NewCDP(types.DefaultCdpStartingID, addrs[0], c("xrp", 1), "xrp-a", c("usdx", 1), tmtime.Canonical(time.Now()), sdk.OneDec()) - err := suite.keeper.SetCDP(suite.ctx, cdp) - suite.NoError(err) - - t, found := suite.keeper.GetCDP(suite.ctx, "xrp-a", types.DefaultCdpStartingID) - suite.True(found) - suite.Equal(cdp, t) - _, found = suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(2)) - suite.False(found) - suite.NoError(suite.keeper.DeleteCDP(suite.ctx, cdp)) - _, found = suite.keeper.GetCDP(suite.ctx, "btc-a", types.DefaultCdpStartingID) - suite.False(found) -} - -func (suite *CdpTestSuite) TestGetSetCdpId() { - _, addrs := app.GeneratePrivKeyAddressPairs(2) - cdp := types.NewCDP(types.DefaultCdpStartingID, addrs[0], c("xrp", 1), "xrp-a", c("usdx", 1), tmtime.Canonical(time.Now()), sdk.OneDec()) - err := suite.keeper.SetCDP(suite.ctx, cdp) - suite.NoError(err) - suite.keeper.IndexCdpByOwner(suite.ctx, cdp) - id, found := suite.keeper.GetCdpID(suite.ctx, addrs[0], "xrp-a") - suite.True(found) - suite.Equal(types.DefaultCdpStartingID, id) - _, found = suite.keeper.GetCdpID(suite.ctx, addrs[0], "lol-a") - suite.False(found) - _, found = suite.keeper.GetCdpID(suite.ctx, addrs[1], "xrp-a") - suite.False(found) -} - -func (suite *CdpTestSuite) TestGetSetCdpByOwnerAndCollateralType() { - _, addrs := app.GeneratePrivKeyAddressPairs(2) - cdp := types.NewCDP(types.DefaultCdpStartingID, addrs[0], c("xrp", 1), "xrp-a", c("usdx", 1), tmtime.Canonical(time.Now()), sdk.OneDec()) - err := suite.keeper.SetCDP(suite.ctx, cdp) - suite.NoError(err) - suite.keeper.IndexCdpByOwner(suite.ctx, cdp) - t, found := suite.keeper.GetCdpByOwnerAndCollateralType(suite.ctx, addrs[0], "xrp-a") - suite.True(found) - suite.Equal(cdp, t) - _, found = suite.keeper.GetCdpByOwnerAndCollateralType(suite.ctx, addrs[0], "lol-a") - suite.False(found) - _, found = suite.keeper.GetCdpByOwnerAndCollateralType(suite.ctx, addrs[1], "xrp-a") - suite.False(found) - suite.NotPanics(func() { suite.keeper.IndexCdpByOwner(suite.ctx, cdp) }) -} - -func (suite *CdpTestSuite) TestCalculateCollateralToDebtRatio() { - _, addrs := app.GeneratePrivKeyAddressPairs(1) - cdp := types.NewCDP(types.DefaultCdpStartingID, addrs[0], c("xrp", 3), "xrp-a", c("usdx", 1), tmtime.Canonical(time.Now()), sdk.OneDec()) - cr := suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, cdp.Collateral, cdp.Type, cdp.Principal) - suite.Equal(sdk.MustNewDecFromStr("3.0"), cr) - cdp = types.NewCDP(types.DefaultCdpStartingID, addrs[0], c("xrp", 1), "xrp-a", c("usdx", 2), tmtime.Canonical(time.Now()), sdk.OneDec()) - cr = suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, cdp.Collateral, cdp.Type, cdp.Principal) - suite.Equal(sdk.MustNewDecFromStr("0.5"), cr) -} - -func (suite *CdpTestSuite) TestSetCdpByCollateralRatio() { - _, addrs := app.GeneratePrivKeyAddressPairs(1) - cdp := types.NewCDP(types.DefaultCdpStartingID, addrs[0], c("xrp", 3), "xrp-a", c("usdx", 1), tmtime.Canonical(time.Now()), sdk.OneDec()) - cr := suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, cdp.Collateral, cdp.Type, cdp.Principal) - suite.NotPanics(func() { suite.keeper.IndexCdpByCollateralRatio(suite.ctx, cdp.Type, cdp.ID, cr) }) -} - -func (suite *CdpTestSuite) TestIterateCdps() { - cdps := cdps() - for _, c := range cdps { - err := suite.keeper.SetCDP(suite.ctx, c) - suite.NoError(err) - suite.keeper.IndexCdpByOwner(suite.ctx, c) - cr := suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, c.Collateral, c.Type, c.Principal) - suite.keeper.IndexCdpByCollateralRatio(suite.ctx, c.Type, c.ID, cr) - } - t := suite.keeper.GetAllCdps(suite.ctx) - suite.Equal(4, len(t)) -} - -func (suite *CdpTestSuite) TestIterateCdpsByCollateralType() { - cdps := cdps() - for _, c := range cdps { - err := suite.keeper.SetCDP(suite.ctx, c) - suite.NoError(err) - suite.keeper.IndexCdpByOwner(suite.ctx, c) - cr := suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, c.Collateral, c.Type, c.Principal) - suite.keeper.IndexCdpByCollateralRatio(suite.ctx, c.Type, c.ID, cr) - } - xrpCdps := suite.keeper.GetAllCdpsByCollateralType(suite.ctx, "xrp-a") - suite.Equal(3, len(xrpCdps)) - btcCdps := suite.keeper.GetAllCdpsByCollateralType(suite.ctx, "btc-a") - suite.Equal(1, len(btcCdps)) - suite.NoError(suite.keeper.DeleteCDP(suite.ctx, cdps[0])) - suite.keeper.RemoveCdpOwnerIndex(suite.ctx, cdps[0]) - xrpCdps = suite.keeper.GetAllCdpsByCollateralType(suite.ctx, "xrp-a") - suite.Equal(2, len(xrpCdps)) - suite.NoError(suite.keeper.DeleteCDP(suite.ctx, cdps[1])) - suite.keeper.RemoveCdpOwnerIndex(suite.ctx, cdps[1]) - ids, found := suite.keeper.GetCdpIdsByOwner(suite.ctx, cdps[1].Owner) - suite.True(found) - suite.Equal(1, len(ids)) - suite.Equal(uint64(3), ids[0]) -} - -func (suite *CdpTestSuite) TestIterateCdpsByCollateralRatio() { - cdps := cdps() - for _, c := range cdps { - err := suite.keeper.SetCDP(suite.ctx, c) - suite.NoError(err) - suite.keeper.IndexCdpByOwner(suite.ctx, c) - cr := suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, c.Collateral, c.Type, c.Principal) - suite.keeper.IndexCdpByCollateralRatio(suite.ctx, c.Type, c.ID, cr) - } - xrpCdps := suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("1.25")) - suite.Equal(0, len(xrpCdps)) - xrpCdps = suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("1.25").Add(sdk.SmallestDec())) - suite.Equal(1, len(xrpCdps)) - xrpCdps = suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("2.0").Add(sdk.SmallestDec())) - suite.Equal(2, len(xrpCdps)) - xrpCdps = suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("100.0").Add(sdk.SmallestDec())) - suite.Equal(3, len(xrpCdps)) - - suite.NoError(suite.keeper.DeleteCDP(suite.ctx, cdps[0])) - - suite.keeper.RemoveCdpOwnerIndex(suite.ctx, cdps[0]) - cr := suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, cdps[0].Collateral, cdps[0].Type, cdps[0].Principal) - suite.keeper.RemoveCdpCollateralRatioIndex(suite.ctx, cdps[0].Type, cdps[0].ID, cr) - xrpCdps = suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("2.0").Add(sdk.SmallestDec())) - suite.Equal(1, len(xrpCdps)) -} - -func (suite *CdpTestSuite) TestValidateCollateral() { - c := sdk.NewCoin("xrp", sdkmath.NewInt(1)) - err := suite.keeper.ValidateCollateral(suite.ctx, c, "xrp-a") - suite.NoError(err) - c = sdk.NewCoin("lol", sdkmath.NewInt(1)) - err = suite.keeper.ValidateCollateral(suite.ctx, c, "lol-a") - suite.Require().True(errors.Is(err, types.ErrCollateralNotSupported)) -} - -func (suite *CdpTestSuite) TestValidatePrincipal() { - d := sdk.NewCoin("usdx", sdkmath.NewInt(10000000)) - err := suite.keeper.ValidatePrincipalAdd(suite.ctx, d) - suite.NoError(err) - d = sdk.NewCoin("xusd", sdkmath.NewInt(1)) - err = suite.keeper.ValidatePrincipalAdd(suite.ctx, d) - suite.Require().True(errors.Is(err, types.ErrDebtNotSupported)) - d = sdk.NewCoin("usdx", sdkmath.NewInt(1000000000001)) - err = suite.keeper.ValidateDebtLimit(suite.ctx, "xrp-a", d) - suite.Require().True(errors.Is(err, types.ErrExceedsDebtLimit)) - d = sdk.NewCoin("usdx", sdkmath.NewInt(100000000)) - err = suite.keeper.ValidateDebtLimit(suite.ctx, "xrp-a", d) - suite.NoError(err) -} - -func (suite *CdpTestSuite) TestCalculateCollateralizationRatio() { - c := cdps()[1] - err := suite.keeper.SetCDP(suite.ctx, c) - suite.NoError(err) - suite.keeper.IndexCdpByOwner(suite.ctx, c) - cr := suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, c.Collateral, c.Type, c.Principal) - suite.keeper.IndexCdpByCollateralRatio(suite.ctx, c.Type, c.ID, cr) - cr, err = suite.keeper.CalculateCollateralizationRatio(suite.ctx, c.Collateral, c.Type, c.Principal, c.AccumulatedFees, "spot") - suite.NoError(err) - suite.Equal(d("2.5"), cr) - c.AccumulatedFees = sdk.NewCoin("usdx", i(10000000)) - cr, err = suite.keeper.CalculateCollateralizationRatio(suite.ctx, c.Collateral, c.Type, c.Principal, c.AccumulatedFees, "spot") - suite.NoError(err) - suite.Equal(d("1.25"), cr) -} - -func (suite *CdpTestSuite) TestMintBurnDebtCoins() { - cd := cdps()[1] - err := suite.keeper.MintDebtCoins(suite.ctx, types.ModuleName, suite.keeper.GetDebtDenom(suite.ctx), cd.Principal) - suite.NoError(err) - suite.Require().Panics(func() { - _ = suite.keeper.MintDebtCoins(suite.ctx, "notamodule", suite.keeper.GetDebtDenom(suite.ctx), cd.Principal) - }) - - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - acc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(cs(c("debt", 10000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) - - err = suite.keeper.BurnDebtCoins(suite.ctx, types.ModuleName, suite.keeper.GetDebtDenom(suite.ctx), cd.Principal) - suite.NoError(err) - suite.Require().Panics(func() { - _ = suite.keeper.BurnDebtCoins(suite.ctx, "notamodule", suite.keeper.GetDebtDenom(suite.ctx), cd.Principal) - }) - - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(sdk.Coins{}, bk.GetAllBalances(suite.ctx, acc.GetAddress())) -} - -func (suite *CdpTestSuite) TestCdpOwnerIndex() { - cdps := cdps() - - owner_1 := cdps[0].Owner - owner_2 := cdps[1].Owner - - cdpIds_1, found := suite.keeper.GetCdpIdsByOwner(suite.ctx, owner_1) - suite.Require().False(found) - cdpIds_2, found := suite.keeper.GetCdpIdsByOwner(suite.ctx, owner_2) - suite.Require().False(found) - - suite.Require().Equal(0, len(cdpIds_1)) - suite.Require().Equal(0, len(cdpIds_2)) - - suite.keeper.IndexCdpByOwner(suite.ctx, cdps[2]) - suite.keeper.IndexCdpByOwner(suite.ctx, cdps[1]) - suite.keeper.IndexCdpByOwner(suite.ctx, cdps[0]) - - expectedCdpIds, found := suite.keeper.GetCdpIdsByOwner(suite.ctx, owner_1) - suite.Require().True(found) - suite.Require().Equal([]uint64{cdps[0].ID}, expectedCdpIds) - - expectedCdpIds, found = suite.keeper.GetCdpIdsByOwner(suite.ctx, owner_2) - suite.Require().True(found) - suite.Require().Equal([]uint64{cdps[1].ID, cdps[2].ID}, expectedCdpIds) - - suite.keeper.RemoveCdpOwnerIndex(suite.ctx, cdps[0]) - expectedCdpIds, found = suite.keeper.GetCdpIdsByOwner(suite.ctx, owner_1) - suite.Require().False(found) - suite.Require().Equal([]uint64{}, expectedCdpIds) - - suite.keeper.RemoveCdpOwnerIndex(suite.ctx, cdps[1]) - expectedCdpIds, found = suite.keeper.GetCdpIdsByOwner(suite.ctx, owner_2) - suite.Require().True(found) - suite.Require().Equal([]uint64{cdps[2].ID}, expectedCdpIds) - - suite.keeper.RemoveCdpOwnerIndex(suite.ctx, cdps[2]) - expectedCdpIds, found = suite.keeper.GetCdpIdsByOwner(suite.ctx, owner_2) - suite.Require().False(found) - suite.Require().Equal([]uint64{}, expectedCdpIds) -} - -func (suite *CdpTestSuite) TestMarketStatus() { - suite.keeper.SetMarketStatus(suite.ctx, "ukava:usd", true) - status := suite.keeper.GetMarketStatus(suite.ctx, "ukava:usd") - suite.Require().True(status) - suite.keeper.SetMarketStatus(suite.ctx, "ukava:usd", false) - status = suite.keeper.GetMarketStatus(suite.ctx, "ukava:usd") - suite.Require().False(status) - suite.keeper.SetMarketStatus(suite.ctx, "ukava:usd", true) - status = suite.keeper.GetMarketStatus(suite.ctx, "ukava:usd") - suite.Require().True(status) - - status = suite.keeper.GetMarketStatus(suite.ctx, "unknown:usd") - suite.Require().False(status) - - suite.keeper.SetMarketStatus(suite.ctx, "btc:usd", false) - status = suite.keeper.GetMarketStatus(suite.ctx, "btc:usd") - suite.Require().False(status) - suite.keeper.SetMarketStatus(suite.ctx, "btc:usd", true) - status = suite.keeper.GetMarketStatus(suite.ctx, "btc:usd") - suite.Require().True(status) - suite.keeper.SetMarketStatus(suite.ctx, "btc:usd", false) - status = suite.keeper.GetMarketStatus(suite.ctx, "btc:usd") - suite.Require().False(status) -} - -func TestCdpTestSuite(t *testing.T) { - suite.Run(t, new(CdpTestSuite)) -} diff --git a/x/cdp/keeper/deposit.go b/x/cdp/keeper/deposit.go deleted file mode 100644 index a2edf65d..00000000 --- a/x/cdp/keeper/deposit.go +++ /dev/null @@ -1,166 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/cdp/types" -) - -// DepositCollateral adds collateral to a cdp -func (k Keeper) DepositCollateral(ctx sdk.Context, owner, depositor sdk.AccAddress, collateral sdk.Coin, collateralType string) error { - // check that collateral exists and has a functioning pricefeed - err := k.ValidateCollateral(ctx, collateral, collateralType) - if err != nil { - return err - } - cdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType) - if !found { - return errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, collateral %s", owner, collateralType) - } - err = k.ValidateBalance(ctx, collateral, depositor) - if err != nil { - return err - } - k.hooks.BeforeCDPModified(ctx, cdp) - cdp = k.SynchronizeInterest(ctx, cdp) - - deposit, found := k.GetDeposit(ctx, cdp.ID, depositor) - if found { - deposit.Amount = deposit.Amount.Add(collateral) - } else { - deposit = types.NewDeposit(cdp.ID, depositor, collateral) - } - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, depositor, types.ModuleName, sdk.NewCoins(collateral)) - if err != nil { - return err - } - - k.SetDeposit(ctx, deposit) - - cdp.Collateral = cdp.Collateral.Add(collateral) - collateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal()) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCdpDeposit, - sdk.NewAttribute(sdk.AttributeKeyAmount, collateral.String()), - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - ), - ) - - return k.UpdateCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio) -} - -// WithdrawCollateral removes collateral from a cdp if it does not put the cdp below the liquidation ratio -func (k Keeper) WithdrawCollateral(ctx sdk.Context, owner, depositor sdk.AccAddress, collateral sdk.Coin, collateralType string) error { - err := k.ValidateCollateral(ctx, collateral, collateralType) - if err != nil { - return err - } - cdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType) - if !found { - return errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, collateral %s", owner, collateral.Denom) - } - deposit, found := k.GetDeposit(ctx, cdp.ID, depositor) - if !found { - return errorsmod.Wrapf(types.ErrDepositNotFound, "depositor %s, collateral %s %s", depositor, collateral.Denom, collateralType) - } - if collateral.Amount.GT(deposit.Amount.Amount) { - return errorsmod.Wrapf(types.ErrInvalidWithdrawAmount, "collateral %s, deposit %s", collateral, deposit.Amount) - } - k.hooks.BeforeCDPModified(ctx, cdp) - cdp = k.SynchronizeInterest(ctx, cdp) - - collateralizationRatio, err := k.CalculateCollateralizationRatio(ctx, cdp.Collateral.Sub(collateral), cdp.Type, cdp.Principal, cdp.AccumulatedFees, spot) - if err != nil { - return err - } - liquidationRatio := k.getLiquidationRatio(ctx, cdp.Type) - if collateralizationRatio.LT(liquidationRatio) { - return errorsmod.Wrapf(types.ErrInvalidCollateralRatio, "collateral %s, collateral ratio %s, liquidation ration %s", collateral.Denom, collateralizationRatio, liquidationRatio) - } - - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, depositor, sdk.NewCoins(collateral)) - if err != nil { - panic(err) - } - - cdp.Collateral = cdp.Collateral.Sub(collateral) - collateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal()) - err = k.UpdateCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio) - if err != nil { - return err - } - - deposit.Amount = deposit.Amount.Sub(collateral) - // delete deposits if amount is 0 - if deposit.Amount.IsZero() { - k.DeleteDeposit(ctx, deposit.CdpID, deposit.Depositor) - } else { - k.SetDeposit(ctx, deposit) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCdpWithdrawal, - sdk.NewAttribute(sdk.AttributeKeyAmount, collateral.String()), - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - ), - ) - - return nil -} - -// GetDeposit returns the deposit of a depositor on a particular cdp from the store -func (k Keeper) GetDeposit(ctx sdk.Context, cdpID uint64, depositor sdk.AccAddress) (deposit types.Deposit, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositKeyPrefix) - bz := store.Get(types.DepositKey(cdpID, depositor)) - if bz == nil { - return deposit, false - } - k.cdc.MustUnmarshal(bz, &deposit) - return deposit, true -} - -// SetDeposit sets the deposit in the store -func (k Keeper) SetDeposit(ctx sdk.Context, deposit types.Deposit) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositKeyPrefix) - bz := k.cdc.MustMarshal(&deposit) - - store.Set(types.DepositKey(deposit.CdpID, deposit.Depositor), bz) -} - -// DeleteDeposit deletes a deposit from the store -func (k Keeper) DeleteDeposit(ctx sdk.Context, cdpID uint64, depositor sdk.AccAddress) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositKeyPrefix) - store.Delete(types.DepositKey(cdpID, depositor)) -} - -// IterateDeposits iterates over the all the deposits of a cdp and performs a callback function -func (k Keeper) IterateDeposits(ctx sdk.Context, cdpID uint64, cb func(deposit types.Deposit) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, types.GetCdpIDBytes(cdpID)) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var deposit types.Deposit - k.cdc.MustUnmarshal(iterator.Value(), &deposit) - - if cb(deposit) { - break - } - } -} - -// GetDeposits returns all the deposits to a cdp -func (k Keeper) GetDeposits(ctx sdk.Context, cdpID uint64) (deposits types.Deposits) { - k.IterateDeposits(ctx, cdpID, func(deposit types.Deposit) bool { - deposits = append(deposits, deposit) - return false - }) - return -} diff --git a/x/cdp/keeper/deposit_test.go b/x/cdp/keeper/deposit_test.go deleted file mode 100644 index 070c50b1..00000000 --- a/x/cdp/keeper/deposit_test.go +++ /dev/null @@ -1,139 +0,0 @@ -package keeper_test - -import ( - "errors" - "testing" - - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/cdp/keeper" - "github.com/kava-labs/kava/x/cdp/types" -) - -type DepositTestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context - addrs []sdk.AccAddress -} - -func (suite *DepositTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - cdc := tApp.AppCodec() - - _, addrs := app.GeneratePrivKeyAddressPairs(10) - authGS := app.NewFundedGenStateWithCoins( - cdc, - []sdk.Coins{ - cs(c("xrp", 500000000), c("btc", 500000000)), - cs(c("xrp", 200000000)), - }, - addrs[0:2], - ) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(cdc), - NewCDPGenStateMulti(cdc), - ) - keeper := tApp.GetCDPKeeper() - suite.app = tApp - suite.keeper = keeper - suite.ctx = ctx - suite.addrs = addrs - err := suite.keeper.AddCdp(suite.ctx, addrs[0], c("xrp", 400000000), c("usdx", 10000000), "xrp-a") - suite.NoError(err) -} - -func (suite *DepositTestSuite) TestGetSetDeposit() { - d, found := suite.keeper.GetDeposit(suite.ctx, uint64(1), suite.addrs[0]) - suite.True(found) - td := types.NewDeposit(uint64(1), suite.addrs[0], c("xrp", 400000000)) - suite.True(d.Equals(td)) - ds := suite.keeper.GetDeposits(suite.ctx, uint64(1)) - suite.Equal(1, len(ds)) - suite.True(ds[0].Equals(td)) - suite.keeper.DeleteDeposit(suite.ctx, uint64(1), suite.addrs[0]) - _, found = suite.keeper.GetDeposit(suite.ctx, uint64(1), suite.addrs[0]) - suite.False(found) - ds = suite.keeper.GetDeposits(suite.ctx, uint64(1)) - suite.Equal(0, len(ds)) -} - -func (suite *DepositTestSuite) TestDepositCollateral() { - err := suite.keeper.DepositCollateral(suite.ctx, suite.addrs[0], suite.addrs[0], c("xrp", 10000000), "xrp-a") - suite.NoError(err) - d, found := suite.keeper.GetDeposit(suite.ctx, uint64(1), suite.addrs[0]) - suite.True(found) - td := types.NewDeposit(uint64(1), suite.addrs[0], c("xrp", 410000000)) - suite.True(d.Equals(td)) - ds := suite.keeper.GetDeposits(suite.ctx, uint64(1)) - suite.Equal(1, len(ds)) - suite.True(ds[0].Equals(td)) - cd, _ := suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(1)) - suite.Equal(c("xrp", 410000000), cd.Collateral) - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - acc := ak.GetAccount(suite.ctx, suite.addrs[0]) - suite.Equal(i(90000000), bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount) - - err = suite.keeper.DepositCollateral(suite.ctx, suite.addrs[0], suite.addrs[0], c("btc", 1), "btc-a") - suite.Require().True(errors.Is(err, types.ErrCdpNotFound)) - - err = suite.keeper.DepositCollateral(suite.ctx, suite.addrs[1], suite.addrs[0], c("xrp", 1), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrCdpNotFound)) - - err = suite.keeper.DepositCollateral(suite.ctx, suite.addrs[0], suite.addrs[1], c("xrp", 10000000), "xrp-a") - suite.NoError(err) - d, found = suite.keeper.GetDeposit(suite.ctx, uint64(1), suite.addrs[1]) - suite.True(found) - td = types.NewDeposit(uint64(1), suite.addrs[1], c("xrp", 10000000)) - suite.True(d.Equals(td)) - ds = suite.keeper.GetDeposits(suite.ctx, uint64(1)) - suite.Equal(2, len(ds)) - suite.True(ds[1].Equals(td)) -} - -func (suite *DepositTestSuite) TestWithdrawCollateral() { - err := suite.keeper.WithdrawCollateral(suite.ctx, suite.addrs[0], suite.addrs[0], c("xrp", 400000000), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrInvalidCollateralRatio)) - err = suite.keeper.WithdrawCollateral(suite.ctx, suite.addrs[0], suite.addrs[0], c("xrp", 321000000), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrInvalidCollateralRatio)) - err = suite.keeper.WithdrawCollateral(suite.ctx, suite.addrs[1], suite.addrs[0], c("xrp", 10000000), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrCdpNotFound)) - - cd, _ := suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(1)) - cd.AccumulatedFees = c("usdx", 1) - err = suite.keeper.SetCDP(suite.ctx, cd) - suite.NoError(err) - err = suite.keeper.WithdrawCollateral(suite.ctx, suite.addrs[0], suite.addrs[0], c("xrp", 320000000), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrInvalidCollateralRatio)) - - err = suite.keeper.WithdrawCollateral(suite.ctx, suite.addrs[0], suite.addrs[0], c("xrp", 10000000), "xrp-a") - suite.NoError(err) - dep, _ := suite.keeper.GetDeposit(suite.ctx, uint64(1), suite.addrs[0]) - td := types.NewDeposit(uint64(1), suite.addrs[0], c("xrp", 390000000)) - suite.True(dep.Equals(td)) - - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - acc := ak.GetAccount(suite.ctx, suite.addrs[0]) - suite.Equal(i(110000000), bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount) - - err = suite.keeper.WithdrawCollateral(suite.ctx, suite.addrs[0], suite.addrs[1], c("xrp", 10000000), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrDepositNotFound)) -} - -func TestDepositTestSuite(t *testing.T) { - suite.Run(t, new(DepositTestSuite)) -} diff --git a/x/cdp/keeper/draw.go b/x/cdp/keeper/draw.go deleted file mode 100644 index 3b09f470..00000000 --- a/x/cdp/keeper/draw.go +++ /dev/null @@ -1,243 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/cdp/types" -) - -// AddPrincipal adds debt to a cdp if the additional debt does not put the cdp below the liquidation ratio -func (k Keeper) AddPrincipal(ctx sdk.Context, owner sdk.AccAddress, collateralType string, principal sdk.Coin) error { - // validation - cdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType) - if !found { - return errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", owner, collateralType) - } - err := k.ValidatePrincipalDraw(ctx, principal, cdp.Principal.Denom) - if err != nil { - return err - } - - err = k.ValidateDebtLimit(ctx, cdp.Type, principal) - if err != nil { - return err - } - k.hooks.BeforeCDPModified(ctx, cdp) - cdp = k.SynchronizeInterest(ctx, cdp) - - err = k.ValidateCollateralizationRatio(ctx, cdp.Collateral, cdp.Type, cdp.Principal.Add(principal), cdp.AccumulatedFees) - if err != nil { - return err - } - - // mint the principal and send it to the cdp owner - err = k.bankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(principal)) - if err != nil { - panic(err) - } - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, owner, sdk.NewCoins(principal)) - if err != nil { - panic(err) - } - - // mint the corresponding amount of debt coins in the cdp module account - err = k.MintDebtCoins(ctx, types.ModuleName, k.GetDebtDenom(ctx), principal) - if err != nil { - panic(err) - } - - // emit cdp draw event - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCdpDraw, - sdk.NewAttribute(sdk.AttributeKeyAmount, principal.String()), - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - ), - ) - - // update cdp state - cdp.Principal = cdp.Principal.Add(principal) - - // increment total principal for the input collateral type - k.IncrementTotalPrincipal(ctx, cdp.Type, principal) - - // set cdp state and indexes in the store - collateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal()) - return k.UpdateCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio) -} - -// RepayPrincipal removes debt from the cdp -// If all debt is repaid, the collateral is returned to depositors and the cdp is removed from the store -func (k Keeper) RepayPrincipal(ctx sdk.Context, owner sdk.AccAddress, collateralType string, payment sdk.Coin) error { - // validation - cdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType) - if !found { - return errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", owner, collateralType) - } - - err := k.ValidatePaymentCoins(ctx, cdp, payment) - if err != nil { - return err - } - - err = k.ValidateBalance(ctx, payment, owner) - if err != nil { - return err - } - k.hooks.BeforeCDPModified(ctx, cdp) - cdp = k.SynchronizeInterest(ctx, cdp) - - // Note: assumes cdp.Principal and cdp.AccumulatedFees don't change during calculations - totalPrincipal := cdp.GetTotalPrincipal() - - // calculate fee and principal payment - feePayment, principalPayment := k.calculatePayment(ctx, totalPrincipal, cdp.AccumulatedFees, payment) - - err = k.validatePrincipalPayment(ctx, cdp, principalPayment) - if err != nil { - return err - } - // send the payment from the sender to the cpd module - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, owner, types.ModuleName, sdk.NewCoins(feePayment.Add(principalPayment))) - if err != nil { - return err - } - - // burn the payment coins - err = k.bankKeeper.BurnCoins(ctx, types.ModuleName, sdk.NewCoins(feePayment.Add(principalPayment))) - if err != nil { - panic(err) - } - - // burn the corresponding amount of debt coins - cdpDebt := k.getModAccountDebt(ctx, types.ModuleName) - paymentAmount := feePayment.Add(principalPayment).Amount - - debtDenom := k.GetDebtDenom(ctx) - coinsToBurn := sdk.NewCoin(debtDenom, paymentAmount) - - if paymentAmount.GT(cdpDebt) { - coinsToBurn = sdk.NewCoin(debtDenom, cdpDebt) - } - - err = k.BurnDebtCoins(ctx, types.ModuleName, debtDenom, coinsToBurn) - - if err != nil { - panic(err) - } - - // emit repayment event - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCdpRepay, - sdk.NewAttribute(sdk.AttributeKeyAmount, feePayment.Add(principalPayment).String()), - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - ), - ) - - // remove the old collateral:debt ratio index - - // update cdp state - if !principalPayment.IsZero() { - cdp.Principal = cdp.Principal.Sub(principalPayment) - } - cdp.AccumulatedFees = cdp.AccumulatedFees.Sub(feePayment) - - // decrement the total principal for the input collateral type - k.DecrementTotalPrincipal(ctx, cdp.Type, feePayment.Add(principalPayment)) - - // if the debt is fully paid, return collateral to depositors, - // and remove the cdp and indexes from the store - if cdp.Principal.IsZero() && cdp.AccumulatedFees.IsZero() { - k.ReturnCollateral(ctx, cdp) - k.RemoveCdpOwnerIndex(ctx, cdp) - err := k.DeleteCdpAndCollateralRatioIndex(ctx, cdp) - if err != nil { - return err - } - - // emit cdp close event - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCdpClose, - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - ), - ) - return nil - } - - // set cdp state and update indexes - collateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal()) - return k.UpdateCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio) -} - -// ValidatePaymentCoins validates that the input coins are valid for repaying debt -func (k Keeper) ValidatePaymentCoins(ctx sdk.Context, cdp types.CDP, payment sdk.Coin) error { - debt := cdp.GetTotalPrincipal() - if payment.Denom != debt.Denom { - return errorsmod.Wrapf(types.ErrInvalidPayment, "cdp %d: expected %s, got %s", cdp.ID, debt.Denom, payment.Denom) - } - _, found := k.GetDebtParam(ctx, payment.Denom) - if !found { - return errorsmod.Wrapf(types.ErrInvalidPayment, "payment denom %s not found", payment.Denom) - } - return nil -} - -// ReturnCollateral returns collateral to depositors on a cdp and removes deposits from the store -func (k Keeper) ReturnCollateral(ctx sdk.Context, cdp types.CDP) { - deposits := k.GetDeposits(ctx, cdp.ID) - for _, deposit := range deposits { - if err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, deposit.Depositor, sdk.NewCoins(deposit.Amount)); err != nil { - panic(err) - } - k.DeleteDeposit(ctx, cdp.ID, deposit.Depositor) - } -} - -// calculatePayment divides the input payment into the portions that will be used to repay fees and principal -// owed - Principal + AccumulatedFees -// fees - AccumulatedFees -// CONTRACT: owned and payment denoms must be checked before calling this function. -func (k Keeper) calculatePayment(ctx sdk.Context, owed, fees, payment sdk.Coin) (sdk.Coin, sdk.Coin) { - // divides repayment into principal and fee components, with fee payment applied first. - - feePayment := sdk.NewCoin(payment.Denom, sdk.ZeroInt()) - principalPayment := sdk.NewCoin(payment.Denom, sdk.ZeroInt()) - var overpayment sdk.Coin - // return zero value coins if payment amount is invalid - if !payment.Amount.IsPositive() { - return feePayment, principalPayment - } - // check for over payment - if payment.Amount.GT(owed.Amount) { - overpayment = payment.Sub(owed) - payment = payment.Sub(overpayment) - } - // if no fees, 100% of payment is principal payment - if fees.IsZero() { - return feePayment, payment - } - // pay fees before repaying principal - if payment.Amount.GT(fees.Amount) { - feePayment = fees - principalPayment = payment.Sub(fees) - } else { - feePayment = payment - } - return feePayment, principalPayment -} - -// validatePrincipalPayment checks that the payment is either full or does not put the cdp below the debt floor -// CONTRACT: payment denom must be checked before calling this function. -func (k Keeper) validatePrincipalPayment(ctx sdk.Context, cdp types.CDP, payment sdk.Coin) error { - proposedBalance := cdp.Principal.Amount.Sub(payment.Amount) - dp, _ := k.GetDebtParam(ctx, payment.Denom) - if proposedBalance.GT(sdk.ZeroInt()) && proposedBalance.LT(dp.DebtFloor) { - return errorsmod.Wrapf(types.ErrBelowDebtFloor, "proposed %s < minimum %s", sdk.NewCoin(payment.Denom, proposedBalance), dp.DebtFloor) - } - return nil -} diff --git a/x/cdp/keeper/draw_test.go b/x/cdp/keeper/draw_test.go deleted file mode 100644 index e3d6f979..00000000 --- a/x/cdp/keeper/draw_test.go +++ /dev/null @@ -1,173 +0,0 @@ -package keeper_test - -import ( - "errors" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/cdp/keeper" - "github.com/kava-labs/kava/x/cdp/types" -) - -type DrawTestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context - addrs []sdk.AccAddress -} - -func (suite *DrawTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - cdc := tApp.AppCodec() - _, addrs := app.GeneratePrivKeyAddressPairs(3) - coins := []sdk.Coins{ - cs(c("xrp", 500000000), c("btc", 500000000), c("usdx", 10000000000)), - cs(c("xrp", 200000000)), - cs(c("xrp", 10000000000000), c("usdx", 100000000000)), - } - - authGS := app.NewFundedGenStateWithCoins(cdc, coins, addrs) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(cdc), - NewCDPGenStateMulti(cdc), - ) - keeper := tApp.GetCDPKeeper() - suite.app = tApp - suite.keeper = keeper - suite.ctx = ctx - suite.addrs = addrs - err := suite.keeper.AddCdp(suite.ctx, addrs[0], c("xrp", 400000000), c("usdx", 10000000), "xrp-a") - suite.NoError(err) -} - -func (suite *DrawTestSuite) TestAddRepayPrincipal() { - err := suite.keeper.AddPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("usdx", 10000000)) - suite.NoError(err) - - t, found := suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(1)) - suite.True(found) - suite.Equal(c("usdx", 20000000), t.Principal) - ctd := suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, t.Collateral, "xrp-a", t.Principal.Add(t.AccumulatedFees)) - suite.Equal(d("20.0"), ctd) - ts := suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("20.0")) - suite.Equal(0, len(ts)) - ts = suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("20.0").Add(sdk.SmallestDec())) - suite.Equal(ts[0], t) - tp := suite.keeper.GetTotalPrincipal(suite.ctx, "xrp-a", "usdx") - suite.Equal(i(20000000), tp) - - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - acc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(cs(c("xrp", 400000000), c("debt", 20000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) - - err = suite.keeper.AddPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("susd", 10000000)) - suite.Require().True(errors.Is(err, types.ErrInvalidDebtRequest)) - - err = suite.keeper.AddPrincipal(suite.ctx, suite.addrs[1], "xrp-a", c("usdx", 10000000)) - suite.Require().True(errors.Is(err, types.ErrCdpNotFound)) - err = suite.keeper.AddPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("xusd", 10000000)) - suite.Require().True(errors.Is(err, types.ErrInvalidDebtRequest)) - err = suite.keeper.AddPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("usdx", 311000000)) - suite.Require().True(errors.Is(err, types.ErrInvalidCollateralRatio)) - - err = suite.keeper.RepayPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("usdx", 10000000)) - suite.NoError(err) - - t, found = suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(1)) - suite.True(found) - suite.Equal(c("usdx", 10000000), t.Principal) - - ctd = suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, t.Collateral, "xrp-a", t.Principal.Add(t.AccumulatedFees)) - suite.Equal(d("40.0"), ctd) - ts = suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("40.0")) - suite.Equal(0, len(ts)) - ts = suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("40.0").Add(sdk.SmallestDec())) - suite.Equal(ts[0], t) - - ak = suite.app.GetAccountKeeper() - bk = suite.app.GetBankKeeper() - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(cs(c("xrp", 400000000), c("debt", 10000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) - - err = suite.keeper.RepayPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("xusd", 10000000)) - suite.Require().True(errors.Is(err, types.ErrInvalidPayment)) - err = suite.keeper.RepayPrincipal(suite.ctx, suite.addrs[1], "xrp-a", c("xusd", 10000000)) - suite.Require().True(errors.Is(err, types.ErrCdpNotFound)) - - err = suite.keeper.RepayPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("usdx", 9000000)) - suite.Require().True(errors.Is(err, types.ErrBelowDebtFloor)) - err = suite.keeper.RepayPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("usdx", 10000000)) - suite.NoError(err) - - _, found = suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(1)) - suite.False(found) - ts = suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", types.MaxSortableDec) - suite.Equal(0, len(ts)) - ts = suite.keeper.GetAllCdpsByCollateralType(suite.ctx, "xrp-a") - suite.Equal(0, len(ts)) - - ak = suite.app.GetAccountKeeper() - bk = suite.app.GetBankKeeper() - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(sdk.Coins{}, bk.GetAllBalances(suite.ctx, acc.GetAddress())) -} - -func (suite *DrawTestSuite) TestRepayPrincipalOverpay() { - err := suite.keeper.RepayPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("usdx", 20000000)) - suite.NoError(err) - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - acc := ak.GetAccount(suite.ctx, suite.addrs[0]) - suite.Equal(i(10000000000), (bk.GetBalance(suite.ctx, acc.GetAddress(), "usdx")).Amount) - _, found := suite.keeper.GetCDP(suite.ctx, "xrp-a", 1) - suite.False(found) -} - -func (suite *DrawTestSuite) TestPricefeedFailure() { - ctx := suite.ctx.WithBlockTime(suite.ctx.BlockTime().Add(time.Hour * 2)) - pfk := suite.app.GetPriceFeedKeeper() - err := pfk.SetCurrentPrices(ctx, "xrp:usd") - suite.Error(err) - - err = suite.keeper.AddPrincipal(ctx, suite.addrs[0], "xrp-a", c("usdx", 10000000)) - suite.Error(err) - err = suite.keeper.RepayPrincipal(ctx, suite.addrs[0], "xrp-a", c("usdx", 10000000)) - suite.NoError(err) -} - -func (suite *DrawTestSuite) TestModuleAccountFailure() { - ctx := suite.ctx.WithBlockHeader(suite.ctx.BlockHeader()) - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - acc := ak.GetModuleAccount(ctx, types.ModuleName) - - // Remove module account balance - ak.RemoveAccount(ctx, acc) - // Also need to burn coins as account keeper no longer stores balances - err := bk.BurnCoins(ctx, types.ModuleName, bk.GetAllBalances(ctx, acc.GetAddress())) - suite.Require().NoError(err) - - suite.Panics(func() { - // Error ignored here since this should panic - _ = suite.keeper.RepayPrincipal(ctx, suite.addrs[0], "xrp-a", c("usdx", 10000000)) - }) -} - -func TestDrawTestSuite(t *testing.T) { - suite.Run(t, new(DrawTestSuite)) -} diff --git a/x/cdp/keeper/grpc_query.go b/x/cdp/keeper/grpc_query.go deleted file mode 100644 index c81ac912..00000000 --- a/x/cdp/keeper/grpc_query.go +++ /dev/null @@ -1,297 +0,0 @@ -package keeper - -import ( - "context" - "sort" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/kava-labs/kava/x/cdp/types" -) - -type QueryServer struct { - keeper Keeper -} - -// NewQueryServer returns an implementation of the pricefeed MsgServer interface -// for the provided Keeper. -func NewQueryServerImpl(keeper Keeper) types.QueryServer { - return &QueryServer{keeper: keeper} -} - -var _ types.QueryServer = QueryServer{} - -// Params queries all parameters of the cdp module. -func (s QueryServer) Params(c context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(c) - params := s.keeper.GetParams(sdkCtx) - - return &types.QueryParamsResponse{Params: params}, nil -} - -// Accounts queries the CDP module accounts. -func (s QueryServer) Accounts(c context.Context, req *types.QueryAccountsRequest) (*types.QueryAccountsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - cdpAccAccount := s.keeper.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - liquidatorAccAccount := s.keeper.accountKeeper.GetModuleAccount(ctx, types.LiquidatorMacc) - - accounts := []authtypes.ModuleAccount{ - *cdpAccAccount.(*authtypes.ModuleAccount), - *liquidatorAccAccount.(*authtypes.ModuleAccount), - } - - return &types.QueryAccountsResponse{Accounts: accounts}, nil -} - -// TotalPrincipal queries the total principal of a given collateral type. -func (s QueryServer) TotalPrincipal(c context.Context, req *types.QueryTotalPrincipalRequest) (*types.QueryTotalPrincipalResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - var queryCollateralTypes []string - - if req.CollateralType != "" { - // Single collateralType provided - queryCollateralTypes = append(queryCollateralTypes, req.CollateralType) - } else { - // No collateralType provided, respond with all of them - keeperParams := s.keeper.GetParams(ctx) - - for _, collateral := range keeperParams.CollateralParams { - queryCollateralTypes = append(queryCollateralTypes, collateral.Type) - } - } - - var collateralPrincipals types.TotalPrincipals - - for _, queryType := range queryCollateralTypes { - // Hardcoded to default USDX - principalAmount := s.keeper.GetTotalPrincipal(ctx, queryType, types.DefaultStableDenom) - // Wrap it in an sdk.Coin - totalAmountCoin := sdk.NewCoin(types.DefaultStableDenom, principalAmount) - - totalPrincipal := types.NewTotalPrincipal(queryType, totalAmountCoin) - collateralPrincipals = append(collateralPrincipals, totalPrincipal) - } - - return &types.QueryTotalPrincipalResponse{ - TotalPrincipal: collateralPrincipals, - }, nil -} - -// TotalCollateral queries the total collateral of a given collateral type. -func (s QueryServer) TotalCollateral(c context.Context, req *types.QueryTotalCollateralRequest) (*types.QueryTotalCollateralResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - params := s.keeper.GetParams(ctx) - denomCollateralTypes := make(map[string][]string) - - // collect collateral types for each denom - for _, collateralParam := range params.CollateralParams { - denomCollateralTypes[collateralParam.Denom] = append(denomCollateralTypes[collateralParam.Denom], collateralParam.Type) - } - - // sort collateral types alphabetically - for _, collateralTypes := range denomCollateralTypes { - sort.Slice(collateralTypes, func(i int, j int) bool { - return collateralTypes[i] < collateralTypes[j] - }) - } - - // get total collateral in all cdps - cdpAccount := s.keeper.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - totalCdpCollateral := s.keeper.bankKeeper.GetAllBalances(ctx, cdpAccount.GetAddress()) - - var totalCollaterals types.TotalCollaterals - - for denom, collateralTypes := range denomCollateralTypes { - // skip any denoms that do not match the requested collateral type - if req.CollateralType != "" { - match := false - for _, ctype := range collateralTypes { - if ctype == req.CollateralType { - match = true - } - } - - if !match { - continue - } - } - - totalCollateral := totalCdpCollateral.AmountOf(denom) - - // we need to query individual cdps for denoms with more than one collateral type - for i := len(collateralTypes) - 1; i > 0; i-- { - cdps := s.keeper.GetAllCdpsByCollateralType(ctx, collateralTypes[i]) - - collateral := sdk.ZeroInt() - - for _, cdp := range cdps { - collateral = collateral.Add(cdp.Collateral.Amount) - } - - totalCollateral = totalCollateral.Sub(collateral) - - // if we have no collateralType filter, or the filter matches, include it in the response - if req.CollateralType == "" || collateralTypes[i] == req.CollateralType { - totalCollaterals = append(totalCollaterals, types.NewTotalCollateral(collateralTypes[i], sdk.NewCoin(denom, collateral))) - } - - // skip the rest of the cdp queries if we have a matching filter - if collateralTypes[i] == req.CollateralType { - break - } - } - - if req.CollateralType == "" || collateralTypes[0] == req.CollateralType { - // all leftover total collateral belongs to the first collateral type - totalCollaterals = append(totalCollaterals, types.NewTotalCollateral(collateralTypes[0], sdk.NewCoin(denom, totalCollateral))) - } - } - - // sort to ensure deterministic response - sort.Slice(totalCollaterals, func(i int, j int) bool { - return totalCollaterals[i].CollateralType < totalCollaterals[j].CollateralType - }) - - return &types.QueryTotalCollateralResponse{ - TotalCollateral: totalCollaterals, - }, nil -} - -// Cdps queries all active CDPs. -func (s QueryServer) Cdps(c context.Context, req *types.QueryCdpsRequest) (*types.QueryCdpsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - // Filter CDPs - filteredCDPs, err := GrpcFilterCDPs(ctx, s.keeper, *req) - if err != nil { - return nil, err - } - - return &types.QueryCdpsResponse{ - Cdps: filteredCDPs, - // TODO: Use built in pagination and respond - Pagination: nil, - }, nil -} - -// Cdp queries a CDP with the input owner address and collateral type. -func (s QueryServer) Cdp(c context.Context, req *types.QueryCdpRequest) (*types.QueryCdpResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - owner, err := sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid address") - } - - _, valid := s.keeper.GetCollateral(ctx, req.CollateralType) - if !valid { - return nil, errorsmod.Wrap(types.ErrInvalidCollateral, req.CollateralType) - } - - cdp, found := s.keeper.GetCdpByOwnerAndCollateralType(ctx, owner, req.CollateralType) - if !found { - return nil, errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", req.Owner, req.CollateralType) - } - - cdpResponse := s.keeper.LoadCDPResponse(ctx, cdp) - - return &types.QueryCdpResponse{ - Cdp: cdpResponse, - }, nil -} - -// Deposits queries deposits associated with the CDP owned by an address for a collateral type. -func (s QueryServer) Deposits(c context.Context, req *types.QueryDepositsRequest) (*types.QueryDepositsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - owner, err := sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid address") - } - - _, valid := s.keeper.GetCollateral(ctx, req.CollateralType) - if !valid { - return nil, errorsmod.Wrap(types.ErrInvalidCollateral, req.CollateralType) - } - - cdp, found := s.keeper.GetCdpByOwnerAndCollateralType(ctx, owner, req.CollateralType) - if !found { - return nil, errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", req.Owner, req.CollateralType) - } - - deposits := s.keeper.GetDeposits(ctx, cdp.ID) - - return &types.QueryDepositsResponse{ - Deposits: deposits, - }, nil -} - -// FilterCDPs queries the store for all CDPs that match query req -func GrpcFilterCDPs(ctx sdk.Context, k Keeper, req types.QueryCdpsRequest) (types.CDPResponses, error) { - // TODO: Ideally use query.Paginate() here over existing FilterCDPs. However - // This is difficult to use different CDP indices and specific keeper - // methods without iterating over all CDPs. - page, limit, err := query.ParsePagination(req.Pagination) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, err.Error()) - } - - // Owner address is optional, only parse if it's provided otherwise it will - // respond with an error - var owner sdk.AccAddress - if req.Owner != "" { - owner, err = sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid owner address") - } - } - - ratio := sdk.ZeroDec() - - if req.Ratio != "" { - ratio, err = sdk.NewDecFromStr(req.Ratio) - if err != nil { - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid ratio") - } - } - } - - legacyParams := types.NewQueryCdpsParams(page, limit, req.CollateralType, owner, req.ID, ratio) - - cdps, err := FilterCDPs(ctx, k, legacyParams) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, err.Error()) - } - - var cdpResponses types.CDPResponses - for _, cdp := range cdps { - cdpResponse := types.CDPResponse{ - ID: cdp.ID, - Owner: cdp.Owner.String(), - Type: cdp.Type, - Collateral: cdp.Collateral, - Principal: cdp.Principal, - AccumulatedFees: cdp.AccumulatedFees, - FeesUpdated: cdp.FeesUpdated, - InterestFactor: cdp.InterestFactor.String(), - CollateralValue: cdp.CollateralValue, - CollateralizationRatio: cdp.CollateralizationRatio.String(), - } - cdpResponses = append(cdpResponses, cdpResponse) - } - - return cdpResponses, nil -} diff --git a/x/cdp/keeper/grpc_query_test.go b/x/cdp/keeper/grpc_query_test.go deleted file mode 100644 index 3c1e06d0..00000000 --- a/x/cdp/keeper/grpc_query_test.go +++ /dev/null @@ -1,284 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/cdp/keeper" - "github.com/kava-labs/kava/x/cdp/types" - "github.com/stretchr/testify/suite" -) - -type grpcQueryTestSuite struct { - suite.Suite - - tApp app.TestApp - ctx sdk.Context - keeper keeper.Keeper - queryServer types.QueryServer - addrs []sdk.AccAddress - now time.Time -} - -func (suite *grpcQueryTestSuite) SetupTest() { - suite.tApp = app.NewTestApp() - suite.tApp.InitializeFromGenesisStates( - NewPricefeedGenStateMulti(suite.tApp.AppCodec()), - NewCDPGenStateMulti(suite.tApp.AppCodec()), - ) - suite.ctx = suite.tApp.NewContext(true, tmprototypes.Header{}). - WithBlockTime(time.Now().UTC()) - suite.keeper = suite.tApp.GetCDPKeeper() - suite.queryServer = keeper.NewQueryServerImpl(suite.keeper) - - _, addrs := app.GeneratePrivKeyAddressPairs(5) - suite.addrs = addrs - - suite.now = time.Now().UTC() -} - -func (suite *grpcQueryTestSuite) addCdp() { - ak := suite.tApp.GetAccountKeeper() - pk := suite.tApp.GetPriceFeedKeeper() - - acc := ak.NewAccountWithAddress(suite.ctx, suite.addrs[0]) - err := suite.tApp.FundAccount(suite.ctx, acc.GetAddress(), cs(c("xrp", 200000000), c("btc", 500000000))) - suite.NoError(err) - - ak.SetAccount(suite.ctx, acc) - - err = pk.SetCurrentPrices(suite.ctx, "xrp:usd") - suite.NoError(err) - - ok := suite.keeper.UpdatePricefeedStatus(suite.ctx, "xrp:usd") - suite.True(ok) - - err = suite.keeper.AddCdp(suite.ctx, suite.addrs[0], c("xrp", 100000000), c("usdx", 10000000), "xrp-a") - suite.NoError(err) - - id := suite.keeper.GetNextCdpID(suite.ctx) - suite.Equal(uint64(2), id) - - tp := suite.keeper.GetTotalPrincipal(suite.ctx, "xrp-a", "usdx") - suite.Equal(i(10000000), tp) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryParams() { - res, err := suite.queryServer.Params(sdk.WrapSDKContext(suite.ctx), &types.QueryParamsRequest{}) - suite.Require().NoError(err) - - var expected types.GenesisState - defaultCdpState := NewCDPGenStateMulti(suite.tApp.AppCodec()) - suite.tApp.AppCodec().MustUnmarshalJSON(defaultCdpState[types.ModuleName], &expected) - - suite.Equal(expected.Params, res.Params, "params should equal test genesis state") -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryParams_Default() { - suite.keeper.SetParams(suite.ctx, types.DefaultParams()) - - res, err := suite.queryServer.Params(sdk.WrapSDKContext(suite.ctx), &types.QueryParamsRequest{}) - suite.Require().NoError(err) - suite.Empty(res.Params.CollateralParams) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryAccounts() { - res, err := suite.queryServer.Accounts(sdk.WrapSDKContext(suite.ctx), &types.QueryAccountsRequest{}) - suite.Require().NoError(err) - - ak := suite.tApp.GetAccountKeeper() - acc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - liquidator := ak.GetModuleAccount(suite.ctx, types.LiquidatorMacc) - - suite.Len(res.Accounts, 2) - suite.Equal(acc, &res.Accounts[0], "accounts should include module account") - suite.Equal(liquidator, &res.Accounts[1], "accounts should include liquidator account") -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalPrincipal() { - suite.addCdp() - - res, err := suite.queryServer.TotalPrincipal(sdk.WrapSDKContext(suite.ctx), &types.QueryTotalPrincipalRequest{}) - suite.Require().NoError(err) - - suite.Len(res.TotalPrincipal, 4, "total principal should include all collateral params") - - suite.Contains(res.TotalPrincipal, types.TotalPrincipal{ - CollateralType: "xrp-a", - Amount: sdk.NewCoin("usdx", sdkmath.NewInt(10000000)), - }, "total principals should include added cdp") - suite.Contains(res.TotalPrincipal, types.TotalPrincipal{ - CollateralType: "busd-a", - Amount: sdk.NewCoin("usdx", sdkmath.NewInt(0)), - }, "total busd principal should be 0") -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalCollateral() { - suite.addCdp() - - res, err := suite.queryServer.TotalCollateral(sdk.WrapSDKContext(suite.ctx), &types.QueryTotalCollateralRequest{}) - suite.Require().NoError(err) - - suite.Len(res.TotalCollateral, 4, "total collateral should include all collateral params") - suite.Contains(res.TotalCollateral, types.TotalCollateral{ - CollateralType: "xrp-a", - Amount: sdk.NewCoin("xrp", sdkmath.NewInt(100000000)), - }, "total collaterals should include added cdp") - suite.Contains(res.TotalCollateral, types.TotalCollateral{ - CollateralType: "busd-a", - Amount: sdk.NewCoin("busd", sdkmath.NewInt(0)), - }, "busd total collateral should be 0") -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryCdps() { - suite.addCdp() - - res, err := suite.queryServer.Cdps(sdk.WrapSDKContext(suite.ctx), &types.QueryCdpsRequest{ - CollateralType: "xrp-a", - Pagination: &query.PageRequest{ - Limit: 100, - }, - }) - suite.Require().NoError(err) - - suite.Len(res.Cdps, 1) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryCdps_InvalidCollateralType() { - suite.addCdp() - - _, err := suite.queryServer.Cdps(sdk.WrapSDKContext(suite.ctx), &types.QueryCdpsRequest{ - CollateralType: "kava-a", - }) - suite.Require().Error(err) - suite.Require().Equal("rpc error: code = InvalidArgument desc = invalid collateral type", err.Error()) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryCdp() { - suite.addCdp() - - tests := []struct { - giveName string - giveRequest types.QueryCdpRequest - wantAccepted bool - wantErr string - }{ - { - "valid", - types.QueryCdpRequest{ - CollateralType: "xrp-a", - Owner: suite.addrs[0].String(), - }, - true, - "", - }, - { - "invalid collateral", - types.QueryCdpRequest{ - CollateralType: "kava-a", - Owner: suite.addrs[0].String(), - }, - false, - "kava-a: invalid collateral for input collateral type", - }, - { - "missing owner", - types.QueryCdpRequest{ - CollateralType: "xrp-a", - }, - false, - "rpc error: code = InvalidArgument desc = invalid address", - }, - { - "invalid owner", - types.QueryCdpRequest{ - CollateralType: "xrp-a", - Owner: "invalid addr", - }, - false, - "rpc error: code = InvalidArgument desc = invalid address", - }, - } - - for _, tt := range tests { - suite.Run(tt.giveName, func() { - _, err := suite.queryServer.Cdp(sdk.WrapSDKContext(suite.ctx), &tt.giveRequest) - - if tt.wantAccepted { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Require().Equal(tt.wantErr, err.Error()) - } - }) - } -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryDeposits() { - suite.addCdp() - - tests := []struct { - giveName string - giveRequest *types.QueryDepositsRequest - wantContainsDeposit *types.Deposit - wantShouldErr bool - wantErr string - }{ - { - "valid", - &types.QueryDepositsRequest{ - CollateralType: "xrp-a", - Owner: suite.addrs[0].String(), - }, - &types.Deposit{ - CdpID: 1, - Depositor: suite.addrs[0], - Amount: sdk.NewCoin("xrp", sdkmath.NewInt(100000000)), - }, - false, - "", - }, - { - "invalid collateral type", - &types.QueryDepositsRequest{ - CollateralType: "kava-a", - Owner: suite.addrs[0].String(), - }, - nil, - true, - "kava-a: invalid collateral for input collateral type", - }, - { - "missing owner", - &types.QueryDepositsRequest{ - CollateralType: "xrp-a", - }, - nil, - true, - "rpc error: code = InvalidArgument desc = invalid address", - }, - } - - for _, tt := range tests { - suite.Run(tt.giveName, func() { - res, err := suite.queryServer.Deposits(sdk.WrapSDKContext(suite.ctx), tt.giveRequest) - - if tt.wantShouldErr { - suite.Error(err) - suite.Equal(tt.wantErr, err.Error()) - } else { - suite.NoError(err) - suite.Contains(res.Deposits, *tt.wantContainsDeposit) - } - }) - } -} - -func TestGrpcQueryTestSuite(t *testing.T) { - suite.Run(t, new(grpcQueryTestSuite)) -} diff --git a/x/cdp/keeper/hooks.go b/x/cdp/keeper/hooks.go deleted file mode 100644 index 7768bc08..00000000 --- a/x/cdp/keeper/hooks.go +++ /dev/null @@ -1,23 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/cdp/types" -) - -// Implements StakingHooks interface -var _ types.CDPHooks = Keeper{} - -// AfterCDPCreated - call hook if registered -func (k Keeper) AfterCDPCreated(ctx sdk.Context, cdp types.CDP) { - if k.hooks != nil { - k.hooks.AfterCDPCreated(ctx, cdp) - } -} - -// BeforeCDPModified - call hook if registered -func (k Keeper) BeforeCDPModified(ctx sdk.Context, cdp types.CDP) { - if k.hooks != nil { - k.hooks.BeforeCDPModified(ctx, cdp) - } -} diff --git a/x/cdp/keeper/integration_test.go b/x/cdp/keeper/integration_test.go deleted file mode 100644 index 8f64e3f1..00000000 --- a/x/cdp/keeper/integration_test.go +++ /dev/null @@ -1,320 +0,0 @@ -package keeper_test - -import ( - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/cdp/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -// Avoid cluttering test cases with long function names -func i(in int64) sdkmath.Int { return sdkmath.NewInt(in) } -func d(str string) sdk.Dec { return sdk.MustNewDecFromStr(str) } -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } - -func NewPricefeedGenState(cdc codec.JSONCodec, asset string, price sdk.Dec) app.GenesisState { - pfGenesis := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: asset + ":usd", BaseAsset: asset, QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: asset + ":usd", - OracleAddress: sdk.AccAddress{}, - Price: price, - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - return app.GenesisState{pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pfGenesis)} -} - -func NewCDPGenState(cdc codec.JSONCodec, asset string, liquidationRatio sdk.Dec) app.GenesisState { - cdpGenesis := types.GenesisState{ - Params: types.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - SurplusAuctionThreshold: types.DefaultSurplusThreshold, - SurplusAuctionLot: types.DefaultSurplusLot, - DebtAuctionThreshold: types.DefaultDebtThreshold, - DebtAuctionLot: types.DefaultDebtLot, - LiquidationBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - CollateralParams: types.CollateralParams{ - { - Denom: asset, - Type: asset + "-a", - LiquidationRatio: liquidationRatio, - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(100), - SpotMarketID: asset + ":usd", - LiquidationMarketID: asset + ":usd", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(6), - }, - }, - DebtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: i(6), - DebtFloor: i(10000000), - }, - }, - StartingCdpID: types.DefaultCdpStartingID, - DebtDenom: types.DefaultDebtDenom, - GovDenom: types.DefaultGovDenom, - CDPs: types.CDPs{}, - PreviousAccumulationTimes: types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime(asset+"-a", time.Time{}, sdk.OneDec()), - }, - TotalPrincipals: types.GenesisTotalPrincipals{ - types.NewGenesisTotalPrincipal(asset+"-a", sdk.ZeroInt()), - }, - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&cdpGenesis)} -} - -func NewPricefeedGenStateMulti(cdc codec.JSONCodec) app.GenesisState { - pfGenesis := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "btc:usd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "btc:usd:30", BaseAsset: "btc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "xrp:usd", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "xrp:usd:30", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd:30", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "busd:usd", BaseAsset: "busd", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "busd:usd:30", BaseAsset: "busd", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "btc:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("8000.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "btc:usd:30", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("8000.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "xrp:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("0.25"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "xrp:usd:30", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("0.25"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("17.25"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "bnb:usd:30", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("17.25"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "busd:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.OneDec(), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "busd:usd:30", - OracleAddress: sdk.AccAddress{}, - Price: sdk.OneDec(), - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - return app.GenesisState{pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pfGenesis)} -} - -func NewCDPGenStateMulti(cdc codec.JSONCodec) app.GenesisState { - cdpGenesis := types.GenesisState{ - Params: types.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - SurplusAuctionThreshold: types.DefaultSurplusThreshold, - SurplusAuctionLot: types.DefaultSurplusLot, - DebtAuctionThreshold: types.DefaultDebtThreshold, - DebtAuctionLot: types.DefaultDebtLot, - LiquidationBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - CollateralParams: types.CollateralParams{ - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("2.0"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(7000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd:30", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(6), - }, - { - Denom: "btc", - Type: "btc-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000000782997609"), // %2.5 apr - LiquidationPenalty: d("0.025"), - AuctionSize: i(10000000), - SpotMarketID: "btc:usd", - LiquidationMarketID: "btc:usd:30", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(8), - }, - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd:30", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(8), - }, - { - Denom: "busd", - Type: "busd-a", - LiquidationRatio: d("1.01"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.OneDec(), // %0 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(10000000000), - SpotMarketID: "busd:usd", - LiquidationMarketID: "busd:usd:30", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(8), - }, - }, - DebtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: i(6), - DebtFloor: i(10000000), - }, - }, - StartingCdpID: types.DefaultCdpStartingID, - DebtDenom: types.DefaultDebtDenom, - GovDenom: types.DefaultGovDenom, - CDPs: types.CDPs{}, - PreviousAccumulationTimes: types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime("btc-a", time.Time{}, sdk.OneDec()), - types.NewGenesisAccumulationTime("xrp-a", time.Time{}, sdk.OneDec()), - types.NewGenesisAccumulationTime("busd-a", time.Time{}, sdk.OneDec()), - types.NewGenesisAccumulationTime("bnb-a", time.Time{}, sdk.OneDec()), - }, - TotalPrincipals: types.GenesisTotalPrincipals{ - types.NewGenesisTotalPrincipal("btc-a", sdk.ZeroInt()), - types.NewGenesisTotalPrincipal("xrp-a", sdk.ZeroInt()), - types.NewGenesisTotalPrincipal("busd-a", sdk.ZeroInt()), - types.NewGenesisTotalPrincipal("bnb-a", sdk.ZeroInt()), - }, - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&cdpGenesis)} -} - -func NewCDPGenStateHighDebtLimit(cdc codec.JSONCodec) app.GenesisState { - cdpGenesis := types.GenesisState{ - Params: types.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 100000000000000), - SurplusAuctionThreshold: types.DefaultSurplusThreshold, - SurplusAuctionLot: types.DefaultSurplusLot, - DebtAuctionThreshold: types.DefaultDebtThreshold, - DebtAuctionLot: types.DefaultDebtLot, - LiquidationBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - CollateralParams: types.CollateralParams{ - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("2.0"), - DebtLimit: sdk.NewInt64Coin("usdx", 50000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(7000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(6), - }, - { - Denom: "btc", - Type: "btc-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 50000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000000782997609"), // %2.5 apr - LiquidationPenalty: d("0.025"), - AuctionSize: i(10000000), - SpotMarketID: "btc:usd", - LiquidationMarketID: "btc:usd", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(8), - }, - }, - DebtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: i(6), - DebtFloor: i(10000000), - }, - }, - StartingCdpID: types.DefaultCdpStartingID, - DebtDenom: types.DefaultDebtDenom, - GovDenom: types.DefaultGovDenom, - CDPs: types.CDPs{}, - PreviousAccumulationTimes: types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime("btc-a", time.Time{}, sdk.OneDec()), - types.NewGenesisAccumulationTime("xrp-a", time.Time{}, sdk.OneDec()), - }, - TotalPrincipals: types.GenesisTotalPrincipals{ - types.NewGenesisTotalPrincipal("btc-a", sdk.ZeroInt()), - types.NewGenesisTotalPrincipal("xrp-a", sdk.ZeroInt()), - }, - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&cdpGenesis)} -} - -func cdps() (cdps types.CDPs) { - _, addrs := app.GeneratePrivKeyAddressPairs(3) - c1 := types.NewCDP(uint64(1), addrs[0], sdk.NewCoin("xrp", sdkmath.NewInt(10000000)), "xrp-a", sdk.NewCoin("usdx", sdkmath.NewInt(8000000)), tmtime.Canonical(time.Now()), sdk.OneDec()) - c2 := types.NewCDP(uint64(2), addrs[1], sdk.NewCoin("xrp", sdkmath.NewInt(100000000)), "xrp-a", sdk.NewCoin("usdx", sdkmath.NewInt(10000000)), tmtime.Canonical(time.Now()), sdk.OneDec()) - c3 := types.NewCDP(uint64(3), addrs[1], sdk.NewCoin("btc", sdkmath.NewInt(1000000000)), "btc-a", sdk.NewCoin("usdx", sdkmath.NewInt(10000000)), tmtime.Canonical(time.Now()), sdk.OneDec()) - c4 := types.NewCDP(uint64(4), addrs[2], sdk.NewCoin("xrp", sdkmath.NewInt(1000000000)), "xrp-a", sdk.NewCoin("usdx", sdkmath.NewInt(500000000)), tmtime.Canonical(time.Now()), sdk.OneDec()) - cdps = append(cdps, c1, c2, c3, c4) - return -} diff --git a/x/cdp/keeper/interest.go b/x/cdp/keeper/interest.go deleted file mode 100644 index 36a566ef..00000000 --- a/x/cdp/keeper/interest.go +++ /dev/null @@ -1,271 +0,0 @@ -package keeper - -import ( - "fmt" - "math" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/cdp/types" -) - -var scalingFactor = 1e18 - -// AccumulateInterest calculates the new interest that has accrued for the input collateral type based on the total amount of principal -// that has been created with that collateral type and the amount of time that has passed since interest was last accumulated -func (k Keeper) AccumulateInterest(ctx sdk.Context, ctype string) error { - previousAccrualTime, found := k.GetPreviousAccrualTime(ctx, ctype) - if !found { - k.SetPreviousAccrualTime(ctx, ctype, ctx.BlockTime()) - return nil - } - - timeElapsed := int64(math.RoundToEven( - ctx.BlockTime().Sub(previousAccrualTime).Seconds(), - )) - if timeElapsed == 0 { - return nil - } - - totalPrincipalPrior := k.GetTotalPrincipal(ctx, ctype, types.DefaultStableDenom) - if totalPrincipalPrior.IsZero() || totalPrincipalPrior.IsNegative() { - k.SetPreviousAccrualTime(ctx, ctype, ctx.BlockTime()) - return nil - } - - interestFactorPrior, foundInterestFactorPrior := k.GetInterestFactor(ctx, ctype) - if !foundInterestFactorPrior { - k.SetInterestFactor(ctx, ctype, sdk.OneDec()) - // set previous accrual time exit early because interest accumulated will be zero - k.SetPreviousAccrualTime(ctx, ctype, ctx.BlockTime()) - return nil - } - - borrowRateSpy := k.getFeeRate(ctx, ctype) - if borrowRateSpy.Equal(sdk.OneDec()) { - k.SetPreviousAccrualTime(ctx, ctype, ctx.BlockTime()) - return nil - } - interestFactor := CalculateInterestFactor(borrowRateSpy, sdkmath.NewInt(timeElapsed)) - interestAccumulated := (interestFactor.Mul(sdk.NewDecFromInt(totalPrincipalPrior))).RoundInt().Sub(totalPrincipalPrior) - if interestAccumulated.IsZero() { - // in the case accumulated interest rounds to zero, exit early without updating accrual time - return nil - } - err := k.MintDebtCoins(ctx, types.ModuleName, k.GetDebtDenom(ctx), sdk.NewCoin(types.DefaultStableDenom, interestAccumulated)) - if err != nil { - return err - } - - dp, found := k.GetDebtParam(ctx, types.DefaultStableDenom) - if !found { - panic(fmt.Sprintf("Debt parameters for %s not found", types.DefaultStableDenom)) - } - - newFeesSurplus := interestAccumulated - - // mint surplus coins to the liquidator module account. - if newFeesSurplus.IsPositive() { - err := k.bankKeeper.MintCoins(ctx, types.LiquidatorMacc, sdk.NewCoins(sdk.NewCoin(dp.Denom, newFeesSurplus))) - if err != nil { - return err - } - } - - interestFactorNew := interestFactorPrior.Mul(interestFactor) - totalPrincipalNew := totalPrincipalPrior.Add(interestAccumulated) - - k.SetTotalPrincipal(ctx, ctype, types.DefaultStableDenom, totalPrincipalNew) - k.SetInterestFactor(ctx, ctype, interestFactorNew) - k.SetPreviousAccrualTime(ctx, ctype, ctx.BlockTime()) - - return nil -} - -// CalculateInterestFactor calculates the simple interest scaling factor, -// which is equal to: (per-second interest rate ** number of seconds elapsed) -// Will return 1.000x, multiply by principal to get new principal with added interest -func CalculateInterestFactor(perSecondInterestRate sdk.Dec, secondsElapsed sdkmath.Int) sdk.Dec { - scalingFactorUint := sdk.NewUint(uint64(scalingFactor)) - scalingFactorInt := sdkmath.NewInt(int64(scalingFactor)) - - // Convert per-second interest rate to a uint scaled by 1e18 - interestMantissa := sdkmath.NewUintFromBigInt(perSecondInterestRate.MulInt(scalingFactorInt).RoundInt().BigInt()) - - // Convert seconds elapsed to uint (*not scaled*) - secondsElapsedUint := sdkmath.NewUintFromBigInt(secondsElapsed.BigInt()) - - // Calculate the interest factor as a uint scaled by 1e18 - interestFactorMantissa := sdkmath.RelativePow(interestMantissa, secondsElapsedUint, scalingFactorUint) - - // Convert interest factor to an unscaled sdk.Dec - return sdk.NewDecFromBigInt(interestFactorMantissa.BigInt()).QuoInt(scalingFactorInt) -} - -// SynchronizeInterest updates the input cdp object to reflect the current accumulated interest, updates the cdp state in the store, -// and returns the updated cdp object -func (k Keeper) SynchronizeInterest(ctx sdk.Context, cdp types.CDP) types.CDP { - globalInterestFactor, found := k.GetInterestFactor(ctx, cdp.Type) - if !found { - k.SetInterestFactor(ctx, cdp.Type, sdk.OneDec()) - cdp.InterestFactor = sdk.OneDec() - cdp.FeesUpdated = ctx.BlockTime() - if err := k.SetCDP(ctx, cdp); err != nil { - panic(err) - } - return cdp - } - - accumulatedInterest := k.CalculateNewInterest(ctx, cdp) - prevAccrualTime, found := k.GetPreviousAccrualTime(ctx, cdp.Type) - if !found { - return cdp - } - if accumulatedInterest.IsZero() { - // accumulated interest is zero if apy is zero or are if the total fees for all cdps round to zero - if cdp.FeesUpdated.Equal(prevAccrualTime) { - // if all fees are rounding to zero, don't update FeesUpdated - return cdp - } - // if apy is zero, we need to update FeesUpdated - cdp.FeesUpdated = prevAccrualTime - if err := k.SetCDP(ctx, cdp); err != nil { - panic(err) - } - } - - cdp.AccumulatedFees = cdp.AccumulatedFees.Add(accumulatedInterest) - cdp.FeesUpdated = prevAccrualTime - cdp.InterestFactor = globalInterestFactor - collateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal()) - if err := k.UpdateCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio); err != nil { - panic(err) - } - - return cdp -} - -// CalculateNewInterest returns the amount of interest that has accrued to the cdp since its interest was last synchronized -func (k Keeper) CalculateNewInterest(ctx sdk.Context, cdp types.CDP) sdk.Coin { - globalInterestFactor, found := k.GetInterestFactor(ctx, cdp.Type) - if !found { - return sdk.NewCoin(cdp.AccumulatedFees.Denom, sdk.ZeroInt()) - } - cdpInterestFactor := globalInterestFactor.Quo(cdp.InterestFactor) - if cdpInterestFactor.Equal(sdk.OneDec()) { - return sdk.NewCoin(cdp.AccumulatedFees.Denom, sdk.ZeroInt()) - } - accumulatedInterest := sdk.NewDecFromInt(cdp.GetTotalPrincipal().Amount).Mul(cdpInterestFactor).RoundInt().Sub(cdp.GetTotalPrincipal().Amount) - return sdk.NewCoin(cdp.AccumulatedFees.Denom, accumulatedInterest) -} - -// SynchronizeInterestForRiskyCDPs synchronizes the interest for the slice of cdps with the lowest collateral:debt ratio -func (k Keeper) SynchronizeInterestForRiskyCDPs(ctx sdk.Context, targetRatio sdk.Dec, cp types.CollateralParam) error { - debtParam := k.GetParams(ctx).DebtParam - - cdpStore := prefix.NewStore(ctx.KVStore(k.key), types.CdpKeyPrefix) - collateralRatioStore := prefix.NewStore(ctx.KVStore(k.key), types.CollateralRatioIndexPrefix) - - cdpIDs := make([]uint64, 0, cp.CheckCollateralizationIndexCount.Int64()) - - iterator := collateralRatioStore.Iterator(types.CollateralRatioIterKey(cp.Type, sdk.ZeroDec()), types.CollateralRatioIterKey(cp.Type, targetRatio)) - for ; iterator.Valid(); iterator.Next() { - _, id, _ := types.SplitCollateralRatioKey(iterator.Key()) - cdpIDs = append(cdpIDs, id) - if int64(len(cdpIDs)) >= cp.CheckCollateralizationIndexCount.Int64() { - break - } - } - iterator.Close() - - globalInterestFactor, found := k.GetInterestFactor(ctx, cp.Type) - if !found && len(cdpIDs) > 0 { - panic(fmt.Sprintf("global interest factor not found for type %s", cp.Type)) - } - prevAccrualTime, found := k.GetPreviousAccrualTime(ctx, cp.Type) - if !found { - panic(fmt.Sprintf("previous accrual time not found for type %s", cp.Type)) - } - - for _, cdpID := range cdpIDs { - // - // GET CDP - // - bz := cdpStore.Get(types.CdpKey(cp.Type, cdpID)) - if bz == nil { - panic(fmt.Sprintf("cdp %d does not exist", cdpID)) - } - var cdp types.CDP - k.cdc.MustUnmarshal(bz, &cdp) - - if debtParam.Denom != cdp.GetTotalPrincipal().Denom { - panic(fmt.Sprintf("unkown debt param %s", cdp.GetTotalPrincipal().Denom)) - } - - // - // HOOK - // - k.hooks.BeforeCDPModified(ctx, cdp) - - // - // CALC INTEREST - // - accumulatedInterest := sdk.ZeroInt() - cdpInterestFactor := globalInterestFactor.Quo(cdp.InterestFactor) - if !cdpInterestFactor.Equal(sdk.OneDec()) { - accumulatedInterest = sdk.NewDecFromInt(cdp.GetTotalPrincipal().Amount).Mul(cdpInterestFactor).RoundInt().Sub(cdp.GetTotalPrincipal().Amount) - } - - if accumulatedInterest.IsZero() { - // accumulated interest is zero if apy is zero or are if the total fees for all cdps round to zero - if cdp.FeesUpdated.Equal(prevAccrualTime) { - // if all fees are rounding to zero, don't update FeesUpdated - continue - } - // if apy is zero, we need to update FeesUpdated - cdp.FeesUpdated = prevAccrualTime - bz = k.cdc.MustMarshal(&cdp) - cdpStore.Set(types.CdpKey(cdp.Type, cdp.ID), bz) - } - - // - // GET OLD RATIO - // - previousCollateralRatio := calculateCollateralRatio(debtParam, cp, cdp) - - // - // UPDATE CDP - // - cdp.AccumulatedFees = cdp.AccumulatedFees.Add(sdk.NewCoin(cdp.AccumulatedFees.Denom, accumulatedInterest)) - cdp.FeesUpdated = prevAccrualTime - cdp.InterestFactor = globalInterestFactor - - // - // CALC NEW RATIO - // - updatedCollateralRatio := calculateCollateralRatio(debtParam, cp, cdp) - - // - // UPDATE STORE - // - collateralRatioStore.Delete(types.CollateralRatioKey(cdp.Type, cdp.ID, previousCollateralRatio)) - bz = k.cdc.MustMarshal(&cdp) - cdpStore.Set(types.CdpKey(cdp.Type, cdp.ID), bz) - collateralRatioStore.Set(types.CollateralRatioKey(cdp.Type, cdp.ID, updatedCollateralRatio), types.GetCdpIDBytes(cdp.ID)) - } - - return nil -} - -func calculateCollateralRatio(debtParam types.DebtParam, collateralParam types.CollateralParam, cdp types.CDP) sdk.Dec { - debtTotal := sdk.NewDecFromInt(cdp.GetTotalPrincipal().Amount).Mul(sdk.NewDecFromIntWithPrec(sdk.OneInt(), debtParam.ConversionFactor.Int64())) - - if debtTotal.IsZero() || debtTotal.GTE(types.MaxSortableDec) { - return types.MaxSortableDec.Sub(sdk.SmallestDec()) - } else { - collateralBaseUnits := sdk.NewDecFromInt(cdp.Collateral.Amount).Mul(sdk.NewDecFromIntWithPrec(sdk.OneInt(), collateralParam.ConversionFactor.Int64())) - return collateralBaseUnits.Quo(debtTotal) - } -} diff --git a/x/cdp/keeper/interest_test.go b/x/cdp/keeper/interest_test.go deleted file mode 100644 index 622283f4..00000000 --- a/x/cdp/keeper/interest_test.go +++ /dev/null @@ -1,747 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/stretchr/testify/suite" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/cdp/keeper" - "github.com/kava-labs/kava/x/cdp/types" -) - -type InterestTestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context -} - -func (suite *InterestTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - cdc := tApp.AppCodec() - tApp.InitializeFromGenesisStates( - NewPricefeedGenStateMulti(cdc), - NewCDPGenStateMulti(cdc), - ) - keeper := tApp.GetCDPKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper -} - -func (suite *InterestTestSuite) TestCalculateInterestFactor() { - type args struct { - perSecondInterestRate sdk.Dec - timeElapsed sdkmath.Int - expectedValue sdk.Dec - } - - type test struct { - name string - args args - } - - oneYearInSeconds := int64(31536000) - - testCases := []test{ - { - "1 year", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("1.191463614477847370"), - }, - }, - { - "10 year", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds * 10), - expectedValue: sdk.MustNewDecFromStr("5.765113233897391189"), - }, - }, - { - "1 month", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds / 12), - expectedValue: sdk.MustNewDecFromStr("1.014705619075717373"), - }, - }, - { - "1 day", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds / 365), - expectedValue: sdk.MustNewDecFromStr("1.000480067194057924"), - }, - }, - { - "1 year: low interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000000555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("1.017656545925063632"), - }, - }, - { - "1 year, lower interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000000055"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("1.001735985079841390"), - }, - }, - { - "1 year, lowest interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000000005"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("1.000157692432076670"), - }, - }, - { - "1 year: high interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000055555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("5.766022095987868825"), - }, - }, - { - "1 year: higher interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000555555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("40628388.864535408465693310"), - }, - }, - // If we raise the per second interest rate too much we'll cause an integer overflow. - // For example, perSecondInterestRate: '1.000005555555' will cause a panic. - { - "1 year: highest interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000001555555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("2017093013158200407564.613502861572552603"), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - interestFactor := keeper.CalculateInterestFactor(tc.args.perSecondInterestRate, tc.args.timeElapsed) - suite.Require().Equal(tc.args.expectedValue, interestFactor) - }) - } -} - -func (suite *InterestTestSuite) TestAccumulateInterest() { - type args struct { - ctype string - initialTime time.Time - totalPrincipal sdkmath.Int - timeElapsed int - expectedTotalPrincipal sdkmath.Int - expectedLastAccrualTime time.Time - } - - type test struct { - name string - args args - } - oneYearInSeconds := 31536000 - - testCases := []test{ - { - "1 year", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - totalPrincipal: sdkmath.NewInt(100000000000000), - timeElapsed: oneYearInSeconds, - expectedTotalPrincipal: sdkmath.NewInt(105000000000012), - expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * oneYearInSeconds)), - }, - }, - { - "1 year - zero principal", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - totalPrincipal: sdk.ZeroInt(), - timeElapsed: oneYearInSeconds, - expectedTotalPrincipal: sdk.ZeroInt(), - expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * oneYearInSeconds)), - }, - }, - { - "1 month", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - totalPrincipal: sdkmath.NewInt(100000000000000), - timeElapsed: 86400 * 30, - expectedTotalPrincipal: sdkmath.NewInt(100401820189198), - expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 86400 * 30)), - }, - }, - { - "1 month - interest rounds to zero", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - totalPrincipal: sdkmath.NewInt(10), - timeElapsed: 86400 * 30, - expectedTotalPrincipal: sdkmath.NewInt(10), - expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - }, - }, - { - "7 seconds", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - totalPrincipal: sdkmath.NewInt(100000000000000), - timeElapsed: 7, - expectedTotalPrincipal: sdkmath.NewInt(100000001082988), - expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7)), - }, - }, - { - "7 seconds - interest rounds to zero", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - totalPrincipal: sdkmath.NewInt(30000000), - timeElapsed: 7, - expectedTotalPrincipal: sdkmath.NewInt(30000000), - expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - }, - }, - { - "7 seconds - zero interest", - args{ - ctype: "busd-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - totalPrincipal: sdkmath.NewInt(100000000000000), - timeElapsed: 7, - expectedTotalPrincipal: sdkmath.NewInt(100000000000000), - expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7)), - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.ctx = suite.ctx.WithBlockTime(tc.args.initialTime) - suite.keeper.SetTotalPrincipal(suite.ctx, tc.args.ctype, types.DefaultStableDenom, tc.args.totalPrincipal) - suite.keeper.SetPreviousAccrualTime(suite.ctx, tc.args.ctype, suite.ctx.BlockTime()) - suite.keeper.SetInterestFactor(suite.ctx, tc.args.ctype, sdk.OneDec()) - - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - err := suite.keeper.AccumulateInterest(suite.ctx, tc.args.ctype) - suite.Require().NoError(err) - - actualTotalPrincipal := suite.keeper.GetTotalPrincipal(suite.ctx, tc.args.ctype, types.DefaultStableDenom) - suite.Require().Equal(tc.args.expectedTotalPrincipal, actualTotalPrincipal) - actualAccrualTime, _ := suite.keeper.GetPreviousAccrualTime(suite.ctx, tc.args.ctype) - suite.Require().Equal(tc.args.expectedLastAccrualTime, actualAccrualTime) - }) - } -} - -// TestSynchronizeInterest tests the functionality of synchronizing the accumulated interest for CDPs -func (suite *InterestTestSuite) TestSynchronizeInterest() { - type args struct { - ctype string - initialTime time.Time - initialCollateral sdk.Coin - initialPrincipal sdk.Coin - timeElapsed int - expectedFees sdk.Coin - expectedFeesUpdatedTime time.Time - } - - type test struct { - name string - args args - } - - oneYearInSeconds := 31536000 - testCases := []test{ - { - "1 year", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 100000000000), - timeElapsed: oneYearInSeconds, - expectedFees: c("usdx", 5000000000), - expectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * oneYearInSeconds)), - }, - }, - { - "1 month", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 100000000000), - timeElapsed: 86400 * 30, - expectedFees: c("usdx", 401820189), - expectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 86400 * 30)), - }, - }, - { - "7 seconds", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 100000000000), - timeElapsed: 7, - expectedFees: c("usdx", 1083), - expectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7)), - }, - }, - { - "7 seconds - zero apy", - args{ - ctype: "busd-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("busd", 10000000000000), - initialPrincipal: c("usdx", 10000000000), - timeElapsed: 7, - expectedFees: c("usdx", 0), - expectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7)), - }, - }, - { - "7 seconds - fees round to zero", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("bnb", 1000000000), - initialPrincipal: c("usdx", 10000000), - timeElapsed: 7, - expectedFees: c("usdx", 0), - expectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - suite.ctx = suite.ctx.WithBlockTime(tc.args.initialTime) - - // setup account state - _, addrs := app.GeneratePrivKeyAddressPairs(1) - ak := suite.app.GetAccountKeeper() - // setup the first account - acc := ak.NewAccountWithAddress(suite.ctx, addrs[0]) - ak.SetAccount(suite.ctx, acc) - bk := suite.app.GetBankKeeper() - - err := bk.MintCoins(suite.ctx, types.ModuleName, cs(tc.args.initialCollateral)) - suite.Require().NoError(err) - err = bk.SendCoinsFromModuleToAccount(suite.ctx, types.ModuleName, addrs[0], cs(tc.args.initialCollateral)) - suite.Require().NoError(err) - - // setup pricefeed - pk := suite.app.GetPriceFeedKeeper() - _, err = pk.SetPrice(suite.ctx, sdk.AccAddress{}, "bnb:usd", d("17.25"), tc.args.expectedFeesUpdatedTime.Add(time.Second)) - suite.NoError(err) - _, err = pk.SetPrice(suite.ctx, sdk.AccAddress{}, "busd:usd", d("1"), tc.args.expectedFeesUpdatedTime.Add(time.Second)) - suite.NoError(err) - - // setup cdp state - suite.keeper.SetPreviousAccrualTime(suite.ctx, tc.args.ctype, suite.ctx.BlockTime()) - suite.keeper.SetInterestFactor(suite.ctx, tc.args.ctype, sdk.OneDec()) - err = suite.keeper.AddCdp(suite.ctx, addrs[0], tc.args.initialCollateral, tc.args.initialPrincipal, tc.args.ctype) - suite.Require().NoError(err) - - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - err = suite.keeper.AccumulateInterest(suite.ctx, tc.args.ctype) - suite.Require().NoError(err) - - cdp, found := suite.keeper.GetCDP(suite.ctx, tc.args.ctype, 1) - suite.Require().True(found) - - cdp = suite.keeper.SynchronizeInterest(suite.ctx, cdp) - - suite.Require().Equal(tc.args.expectedFees, cdp.AccumulatedFees) - suite.Require().Equal(tc.args.expectedFeesUpdatedTime, cdp.FeesUpdated) - }) - } -} - -func (suite *InterestTestSuite) TestMultipleCDPInterest() { - type args struct { - ctype string - initialTime time.Time - blockInterval int - numberOfBlocks int - initialCDPCollateral sdk.Coin - initialCDPPrincipal sdk.Coin - numberOfCdps int - expectedFeesPerCDP sdk.Coin - expectedTotalPrincipalPerCDP sdk.Coin - expectedFeesUpdatedTime time.Time - expectedTotalPrincipal sdkmath.Int - expectedDebtBalance sdkmath.Int - expectedStableBalance sdkmath.Int - expectedSumOfCDPPrincipal sdkmath.Int - } - - type test struct { - name string - args args - } - - testCases := []test{ - { - "1 block", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - blockInterval: 7, - numberOfBlocks: 1, - initialCDPCollateral: c("bnb", 10000000000), - initialCDPPrincipal: c("usdx", 500000000), - numberOfCdps: 100, - expectedFeesPerCDP: c("usdx", 5), - expectedTotalPrincipalPerCDP: c("usdx", 500000005), - expectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7)), - expectedTotalPrincipal: i(50000000541), - expectedDebtBalance: i(50000000541), - expectedStableBalance: i(50000000541), - expectedSumOfCDPPrincipal: i(50000000500), - }, - }, - { - "100 blocks", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - blockInterval: 7, - numberOfBlocks: 100, - initialCDPCollateral: c("bnb", 10000000000), - initialCDPPrincipal: c("usdx", 500000000), - numberOfCdps: 100, - expectedFeesPerCDP: c("usdx", 541), - expectedTotalPrincipalPerCDP: c("usdx", 500000541), - expectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7 * 100)), - expectedTotalPrincipal: i(50000054100), - expectedDebtBalance: i(50000054100), - expectedStableBalance: i(50000054100), - expectedSumOfCDPPrincipal: i(50000054100), - }, - }, - { - "10000 blocks", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - blockInterval: 7, - numberOfBlocks: 10000, - initialCDPCollateral: c("bnb", 10000000000), - initialCDPPrincipal: c("usdx", 500000000), - numberOfCdps: 100, - expectedFeesPerCDP: c("usdx", 54152), - expectedTotalPrincipalPerCDP: c("usdx", 500054152), - expectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7 * 10000)), - expectedTotalPrincipal: i(50005418990), - expectedDebtBalance: i(50005418990), - expectedStableBalance: i(50005418990), - expectedSumOfCDPPrincipal: i(50005415200), - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - suite.ctx = suite.ctx.WithBlockTime(tc.args.initialTime) - - // setup pricefeed - pk := suite.app.GetPriceFeedKeeper() - _, err := pk.SetPrice(suite.ctx, sdk.AccAddress{}, "bnb:usd", d("17.25"), tc.args.expectedFeesUpdatedTime.Add(time.Second)) - suite.NoError(err) - - // setup cdp state - suite.keeper.SetPreviousAccrualTime(suite.ctx, tc.args.ctype, suite.ctx.BlockTime()) - suite.keeper.SetInterestFactor(suite.ctx, tc.args.ctype, sdk.OneDec()) - - // setup account state - _, addrs := app.GeneratePrivKeyAddressPairs(tc.args.numberOfCdps) - for j := 0; j < tc.args.numberOfCdps; j++ { - ak := suite.app.GetAccountKeeper() - // setup the first account - acc := ak.NewAccountWithAddress(suite.ctx, addrs[j]) - ak.SetAccount(suite.ctx, acc) - bk := suite.app.GetBankKeeper() - err := bk.MintCoins(suite.ctx, types.ModuleName, cs(tc.args.initialCDPCollateral)) - suite.Require().NoError(err) - err = bk.SendCoinsFromModuleToAccount(suite.ctx, types.ModuleName, addrs[j], cs(tc.args.initialCDPCollateral)) - suite.Require().NoError(err) - err = suite.keeper.AddCdp(suite.ctx, addrs[j], tc.args.initialCDPCollateral, tc.args.initialCDPPrincipal, tc.args.ctype) - suite.Require().NoError(err) - } - - // run a number of blocks where CDPs are not synchronized - for j := 0; j < tc.args.numberOfBlocks; j++ { - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.blockInterval)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - err := suite.keeper.AccumulateInterest(suite.ctx, tc.args.ctype) - suite.Require().NoError(err) - } - - bk := suite.app.GetBankKeeper() - debtSupply := bk.GetSupply(suite.ctx, types.DefaultDebtDenom) - usdxSupply := bk.GetSupply(suite.ctx, types.DefaultStableDenom) - totalPrincipal := suite.keeper.GetTotalPrincipal(suite.ctx, tc.args.ctype, types.DefaultStableDenom) - - suite.Require().Equal(tc.args.expectedDebtBalance, debtSupply.Amount) - suite.Require().Equal(tc.args.expectedStableBalance, usdxSupply.Amount) - suite.Require().Equal(tc.args.expectedTotalPrincipal, totalPrincipal) - - sumOfCDPPrincipal := sdk.ZeroInt() - - for j := 0; j < tc.args.numberOfCdps; j++ { - cdp, found := suite.keeper.GetCDP(suite.ctx, tc.args.ctype, uint64(j+1)) - suite.Require().True(found) - cdp = suite.keeper.SynchronizeInterest(suite.ctx, cdp) - suite.Require().Equal(tc.args.expectedFeesPerCDP, cdp.AccumulatedFees) - suite.Require().Equal(tc.args.expectedTotalPrincipalPerCDP, cdp.GetTotalPrincipal()) - suite.Require().Equal(tc.args.expectedFeesUpdatedTime, cdp.FeesUpdated) - sumOfCDPPrincipal = sumOfCDPPrincipal.Add(cdp.GetTotalPrincipal().Amount) - } - - suite.Require().Equal(tc.args.expectedSumOfCDPPrincipal, sumOfCDPPrincipal) - }) - } -} - -// TestSynchronizeInterest tests the functionality of synchronizing the accumulated interest for CDPs -func (suite *InterestTestSuite) TestCalculateCDPInterest() { - type args struct { - ctype string - initialTime time.Time - initialCollateral sdk.Coin - initialPrincipal sdk.Coin - timeElapsed int - expectedFees sdk.Coin - } - - type test struct { - name string - args args - } - - oneYearInSeconds := 31536000 - testCases := []test{ - { - "1 year", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 100000000000), - timeElapsed: oneYearInSeconds, - expectedFees: c("usdx", 5000000000), - }, - }, - { - "1 month", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 100000000000), - timeElapsed: 86400 * 30, - expectedFees: c("usdx", 401820189), - }, - }, - { - "7 seconds", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 100000000000), - timeElapsed: 7, - expectedFees: c("usdx", 1083), - }, - }, - { - "7 seconds - fees round to zero", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("bnb", 1000000000), - initialPrincipal: c("usdx", 10000000), - timeElapsed: 7, - expectedFees: c("usdx", 0), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - suite.ctx = suite.ctx.WithBlockTime(tc.args.initialTime) - - // setup account state - _, addrs := app.GeneratePrivKeyAddressPairs(1) - ak := suite.app.GetAccountKeeper() - // setup the first account - acc := ak.NewAccountWithAddress(suite.ctx, addrs[0]) - ak.SetAccount(suite.ctx, acc) - bk := suite.app.GetBankKeeper() - err := bk.MintCoins(suite.ctx, types.ModuleName, cs(tc.args.initialCollateral)) - suite.Require().NoError(err) - err = bk.SendCoinsFromModuleToAccount(suite.ctx, types.ModuleName, addrs[0], cs(tc.args.initialCollateral)) - suite.Require().NoError(err) - - // setup pricefeed - pk := suite.app.GetPriceFeedKeeper() - _, err = pk.SetPrice(suite.ctx, sdk.AccAddress{}, "bnb:usd", d("17.25"), tc.args.initialTime.Add(time.Duration(int(time.Second)*tc.args.timeElapsed))) - suite.Require().NoError(err) - - // setup cdp state - suite.keeper.SetPreviousAccrualTime(suite.ctx, tc.args.ctype, suite.ctx.BlockTime()) - suite.keeper.SetInterestFactor(suite.ctx, tc.args.ctype, sdk.OneDec()) - err = suite.keeper.AddCdp(suite.ctx, addrs[0], tc.args.initialCollateral, tc.args.initialPrincipal, tc.args.ctype) - suite.Require().NoError(err) - - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - err = suite.keeper.AccumulateInterest(suite.ctx, tc.args.ctype) - suite.Require().NoError(err) - - cdp, found := suite.keeper.GetCDP(suite.ctx, tc.args.ctype, 1) - suite.Require().True(found) - - newInterest := suite.keeper.CalculateNewInterest(suite.ctx, cdp) - - suite.Require().Equal(tc.args.expectedFees, newInterest) - }) - } -} - -func (suite *InterestTestSuite) TestSyncInterestForRiskyCDPs() { - type args struct { - ctype string - numberCdps int - slice int - initialCollateral sdk.Coin - minPrincipal sdk.Coin - principalIncrement sdk.Coin - initialTime time.Time - timeElapsed int - expectedCDPs int - } - - type test struct { - name string - args args - } - - oneYearInSeconds := 31536000 - testCases := []test{ - { - "1 year", - args{ - ctype: "bnb-a", - numberCdps: 20, - slice: 10, - initialCollateral: c("bnb", 100000000000), - minPrincipal: c("usdx", 100000000), - principalIncrement: c("usdx", 10000000), - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - timeElapsed: oneYearInSeconds, - expectedCDPs: 10, - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - suite.ctx = suite.ctx.WithBlockTime(tc.args.initialTime) - // setup account state - _, addrs := app.GeneratePrivKeyAddressPairs(tc.args.numberCdps) - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - for _, addr := range addrs { - acc := ak.NewAccountWithAddress(suite.ctx, addr) - ak.SetAccount(suite.ctx, acc) - err := bk.MintCoins(suite.ctx, types.ModuleName, cs(tc.args.initialCollateral)) - suite.Require().NoError(err) - err = bk.SendCoinsFromModuleToAccount(suite.ctx, types.ModuleName, addr, cs(tc.args.initialCollateral)) - suite.Require().NoError(err) - } - // setup pricefeed - pk := suite.app.GetPriceFeedKeeper() - _, err := pk.SetPrice(suite.ctx, sdk.AccAddress{}, "bnb:usd", d("20.0"), tc.args.initialTime.Add(time.Duration(int(time.Second)*tc.args.timeElapsed))) - suite.Require().NoError(err) - - // setup cdp state - suite.keeper.SetPreviousAccrualTime(suite.ctx, tc.args.ctype, suite.ctx.BlockTime()) - suite.keeper.SetInterestFactor(suite.ctx, tc.args.ctype, sdk.OneDec()) - for j, addr := range addrs { - initialPrincipal := tc.args.minPrincipal.Add(c("usdx", int64(j)*tc.args.principalIncrement.Amount.Int64())) - err := suite.keeper.AddCdp(suite.ctx, addr, tc.args.initialCollateral, initialPrincipal, tc.args.ctype) - suite.Require().NoError(err) - } - - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - err = suite.keeper.AccumulateInterest(suite.ctx, tc.args.ctype) - suite.Require().NoError(err) - - params := suite.keeper.GetParams(suite.ctx) - var ctype types.CollateralParam - - for _, cp := range params.CollateralParams { - if cp.Type == tc.args.ctype { - ctype = cp - - cp.CheckCollateralizationIndexCount = sdk.NewInt(int64(tc.args.slice)) - break - } - } - - err = suite.keeper.SynchronizeInterestForRiskyCDPs(suite.ctx, sdk.MaxSortableDec, ctype) - suite.Require().NoError(err) - - cdpsUpdatedCount := 0 - - for _, addr := range addrs { - cdp, found := suite.keeper.GetCdpByOwnerAndCollateralType(suite.ctx, addr, tc.args.ctype) - suite.Require().True(found) - if cdp.FeesUpdated.Equal(suite.ctx.BlockTime()) { - cdpsUpdatedCount += 1 - } - } - suite.Require().Equal(tc.args.expectedCDPs, cdpsUpdatedCount) - }) - } -} - -func TestInterestTestSuite(t *testing.T) { - suite.Run(t, new(InterestTestSuite)) -} diff --git a/x/cdp/keeper/keeper.go b/x/cdp/keeper/keeper.go deleted file mode 100644 index 2ab77c3c..00000000 --- a/x/cdp/keeper/keeper.go +++ /dev/null @@ -1,223 +0,0 @@ -package keeper - -import ( - "fmt" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store/prefix" - 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/kava-labs/kava/x/cdp/types" -) - -// Keeper keeper for the cdp module -type Keeper struct { - key storetypes.StoreKey - cdc codec.Codec - paramSubspace paramtypes.Subspace - pricefeedKeeper types.PricefeedKeeper - auctionKeeper types.AuctionKeeper - bankKeeper types.BankKeeper - accountKeeper types.AccountKeeper - hooks types.CDPHooks - maccPerms map[string][]string -} - -// NewKeeper creates a new keeper -func NewKeeper(cdc codec.Codec, key storetypes.StoreKey, paramstore paramtypes.Subspace, pfk types.PricefeedKeeper, - ak types.AuctionKeeper, bk types.BankKeeper, ack types.AccountKeeper, maccs map[string][]string, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - key: key, - cdc: cdc, - paramSubspace: paramstore, - pricefeedKeeper: pfk, - auctionKeeper: ak, - bankKeeper: bk, - accountKeeper: ack, - hooks: nil, - maccPerms: maccs, - } -} - -// SetHooks adds hooks to the keeper. -func (k *Keeper) SetHooks(hooks types.CDPHooks) *Keeper { - if k.hooks != nil { - panic("cannot set cdp hooks twice") - } - k.hooks = hooks - return k -} - -// CdpDenomIndexIterator returns an sdk.Iterator for all cdps with matching collateral denom -func (k Keeper) CdpDenomIndexIterator(ctx sdk.Context, collateralType string) sdk.Iterator { - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpKeyPrefix) - return sdk.KVStorePrefixIterator(store, types.DenomIterKey(collateralType)) -} - -// CdpCollateralRatioIndexIterator returns an sdk.Iterator for all cdps that have collateral denom -// matching denom and collateral:debt ratio LESS THAN targetRatio -func (k Keeper) CdpCollateralRatioIndexIterator(ctx sdk.Context, collateralType string, targetRatio sdk.Dec) sdk.Iterator { - store := prefix.NewStore(ctx.KVStore(k.key), types.CollateralRatioIndexPrefix) - return store.Iterator(types.CollateralRatioIterKey(collateralType, sdk.ZeroDec()), types.CollateralRatioIterKey(collateralType, targetRatio)) -} - -// IterateAllCdps iterates over all cdps and performs a callback function -func (k Keeper) IterateAllCdps(ctx sdk.Context, cb func(cdp types.CDP) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var cdp types.CDP - k.cdc.MustUnmarshal(iterator.Value(), &cdp) - - if cb(cdp) { - break - } - } -} - -// IterateCdpsByCollateralType iterates over cdps with matching denom and performs a callback function -func (k Keeper) IterateCdpsByCollateralType(ctx sdk.Context, collateralType string, cb func(cdp types.CDP) (stop bool)) { - iterator := k.CdpDenomIndexIterator(ctx, collateralType) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var cdp types.CDP - k.cdc.MustUnmarshal(iterator.Value(), &cdp) - if cb(cdp) { - break - } - } -} - -// IterateCdpsByCollateralRatio iterate over cdps with collateral denom equal to denom and -// collateral:debt ratio LESS THAN targetRatio and performs a callback function. -func (k Keeper) IterateCdpsByCollateralRatio(ctx sdk.Context, collateralType string, targetRatio sdk.Dec, cb func(cdp types.CDP) (stop bool)) { - iterator := k.CdpCollateralRatioIndexIterator(ctx, collateralType, targetRatio) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - _, id, _ := types.SplitCollateralRatioKey(iterator.Key()) - cdp, found := k.GetCDP(ctx, collateralType, id) - if !found { - panic(fmt.Sprintf("cdp %d does not exist", id)) - } - if cb(cdp) { - break - } - - } -} - -// GetSliceOfCDPsByRatioAndType returns a slice of cdps of size equal to the input cutoffCount -// sorted by target ratio in ascending order (ie, the lowest collateral:debt ratio cdps are returned first) -func (k Keeper) GetSliceOfCDPsByRatioAndType(ctx sdk.Context, cutoffCount sdkmath.Int, targetRatio sdk.Dec, collateralType string) (cdps types.CDPs) { - count := sdk.ZeroInt() - k.IterateCdpsByCollateralRatio(ctx, collateralType, targetRatio, func(cdp types.CDP) bool { - cdps = append(cdps, cdp) - count = count.Add(sdk.OneInt()) - return count.GTE(cutoffCount) - }) - return cdps -} - -// GetPreviousAccrualTime returns the last time an individual market accrued interest -func (k Keeper) GetPreviousAccrualTime(ctx sdk.Context, ctype string) (time.Time, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousAccrualTimePrefix) - bz := store.Get([]byte(ctype)) - if bz == nil { - return time.Time{}, false - } - var previousAccrualTime time.Time - if err := previousAccrualTime.UnmarshalBinary(bz); err != nil { - panic(err) - } - return previousAccrualTime, true -} - -// SetPreviousAccrualTime sets the most recent accrual time for a particular market -func (k Keeper) SetPreviousAccrualTime(ctx sdk.Context, ctype string, previousAccrualTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousAccrualTimePrefix) - bz, err := previousAccrualTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(ctype), bz) -} - -// GetInterestFactor returns the current interest factor for an individual collateral type -func (k Keeper) GetInterestFactor(ctx sdk.Context, ctype string) (sdk.Dec, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.InterestFactorPrefix) - bz := store.Get([]byte(ctype)) - if bz == nil { - return sdk.ZeroDec(), false - } - var interestFactor sdk.Dec - if err := interestFactor.Unmarshal(bz); err != nil { - panic(err) - } - return interestFactor, true -} - -// SetInterestFactor sets the current interest factor for an individual collateral type -func (k Keeper) SetInterestFactor(ctx sdk.Context, ctype string, interestFactor sdk.Dec) { - store := prefix.NewStore(ctx.KVStore(k.key), types.InterestFactorPrefix) - bz, err := interestFactor.Marshal() - if err != nil { - panic(err) - } - store.Set([]byte(ctype), bz) -} - -// IncrementTotalPrincipal increments the total amount of debt that has been drawn with that collateral type -func (k Keeper) IncrementTotalPrincipal(ctx sdk.Context, collateralType string, principal sdk.Coin) { - total := k.GetTotalPrincipal(ctx, collateralType, principal.Denom) - total = total.Add(principal.Amount) - k.SetTotalPrincipal(ctx, collateralType, principal.Denom, total) -} - -// DecrementTotalPrincipal decrements the total amount of debt that has been drawn for a particular collateral type -func (k Keeper) DecrementTotalPrincipal(ctx sdk.Context, collateralType string, principal sdk.Coin) { - total := k.GetTotalPrincipal(ctx, collateralType, principal.Denom) - // NOTE: negative total principal can happen in tests due to rounding errors - // in fee calculation - total = sdk.MaxInt(total.Sub(principal.Amount), sdk.ZeroInt()) - k.SetTotalPrincipal(ctx, collateralType, principal.Denom, total) -} - -// GetTotalPrincipal returns the total amount of principal that has been drawn for a particular collateral -func (k Keeper) GetTotalPrincipal(ctx sdk.Context, collateralType, principalDenom string) (total sdkmath.Int) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PrincipalKeyPrefix) - bz := store.Get([]byte(collateralType + principalDenom)) - if bz == nil { - k.SetTotalPrincipal(ctx, collateralType, principalDenom, sdk.ZeroInt()) - return sdk.ZeroInt() - } - if err := total.Unmarshal(bz); err != nil { - panic(err) - } - return total -} - -// SetTotalPrincipal sets the total amount of principal that has been drawn for the input collateral -func (k Keeper) SetTotalPrincipal(ctx sdk.Context, collateralType, principalDenom string, total sdkmath.Int) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PrincipalKeyPrefix) - _, found := k.GetCollateral(ctx, collateralType) - if !found { - panic(fmt.Sprintf("collateral not found: %s", collateralType)) - } - bz, err := total.Marshal() - if err != nil { - panic(err) - } - store.Set([]byte(collateralType+principalDenom), bz) -} diff --git a/x/cdp/keeper/keeper_bench_test.go b/x/cdp/keeper/keeper_bench_test.go deleted file mode 100644 index 974451fd..00000000 --- a/x/cdp/keeper/keeper_bench_test.go +++ /dev/null @@ -1,147 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/cdp/keeper" - "github.com/kava-labs/kava/x/cdp/types" -) - -// saving the result to a module level variable ensures the compiler doesn't optimize the test away -var coinsResult sdk.Coins -var coinResult sdk.Coin - -// Note - the iteration benchmarks take a long time to stabilize, to get stable results use: -// go test -benchmem -bench ^(BenchmarkAccountIteration)$ -benchtime 60s -timeout 2h -// go test -benchmem -bench ^(BenchmarkCdpIteration)$ -benchtime 60s -timeout 2h - -func BenchmarkAccountIteration(b *testing.B) { - benchmarks := []struct { - name string - numberAccounts int - coins bool - }{ - {name: "10000 Accounts, No Coins", numberAccounts: 10000, coins: false}, - {name: "100000 Accounts, No Coins", numberAccounts: 100000, coins: false}, - {name: "1000000 Accounts, No Coins", numberAccounts: 1000000, coins: false}, - {name: "10000 Accounts, With Coins", numberAccounts: 10000, coins: true}, - {name: "100000 Accounts, With Coins", numberAccounts: 100000, coins: true}, - {name: "1000000 Accounts, With Coins", numberAccounts: 1000000, coins: true}, - } - coins := sdk.Coins{ - sdk.NewCoin("xrp", sdkmath.NewInt(1000000000)), - sdk.NewCoin("usdx", sdkmath.NewInt(1000000000)), - } - - for _, bm := range benchmarks { - b.Run(bm.name, func(b *testing.B) { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - ak := tApp.GetAccountKeeper() - bk := tApp.GetBankKeeper() - - tApp.InitializeFromGenesisStates() - for i := 0; i < bm.numberAccounts; i++ { - arr := []byte{byte((i & 0xFF0000) >> 16), byte((i & 0xFF00) >> 8), byte(i & 0xFF)} - addr := sdk.AccAddress(arr) - acc := ak.NewAccountWithAddress(ctx, addr) - if bm.coins { - if err := tApp.FundAccount(ctx, acc.GetAddress(), coins); err != nil { - panic(err) - } - } - ak.SetAccount(ctx, acc) - } - // reset timer ensures we don't count setup time - b.ResetTimer() - for i := 0; i < b.N; i++ { - ak.IterateAccounts(ctx, - func(acc authtypes.AccountI) (stop bool) { - coins := bk.GetAllBalances(ctx, acc.GetAddress()) - coinsResult = coins - return false - }) - } - }) - } -} - -func createCdps(n int) (app.TestApp, sdk.Context, keeper.Keeper) { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - cdc := tApp.AppCodec() - - _, addrs := app.GeneratePrivKeyAddressPairs(n) - coins := cs(c("btc", 100000000)) - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(cdc), - NewCDPGenStateMulti(cdc), - ) - cdpKeeper := tApp.GetCDPKeeper() - for i := 0; i < n; i++ { - err := cdpKeeper.AddCdp(ctx, addrs[i], coins[0], c("usdx", 100000000), "btc-a") - if err != nil { - panic("failed to create cdp") - } - } - return tApp, ctx, cdpKeeper -} - -func BenchmarkCdpIteration(b *testing.B) { - benchmarks := []struct { - name string - numberCdps int - }{ - {"1000 Cdps", 1000}, - {"10000 Cdps", 10000}, - {"100000 Cdps", 100000}, - } - for _, bm := range benchmarks { - b.Run(bm.name, func(b *testing.B) { - _, ctx, cdpKeeper := createCdps(bm.numberCdps) - b.ResetTimer() - for i := 0; i < b.N; i++ { - cdpKeeper.IterateAllCdps(ctx, func(c types.CDP) (stop bool) { - coinResult = c.Principal - return false - }) - } - }) - } -} - -var errResult error - -func BenchmarkCdpCreation(b *testing.B) { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - cdc := tApp.AppCodec() - - _, addrs := app.GeneratePrivKeyAddressPairs(b.N) - coins := cs(c("btc", 100000000)) - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(cdc), - NewCDPGenStateMulti(cdc), - ) - cdpKeeper := tApp.GetCDPKeeper() - b.ResetTimer() - for i := 0; i < b.N; i++ { - err := cdpKeeper.AddCdp(ctx, addrs[i], coins[0], c("usdx", 100000000), "btc-a") - if err != nil { - b.Error("unexpected error") - } - errResult = err - } -} diff --git a/x/cdp/keeper/keeper_test.go b/x/cdp/keeper/keeper_test.go deleted file mode 100644 index dff4095d..00000000 --- a/x/cdp/keeper/keeper_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package keeper_test - -import ( - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/cdp/keeper" -) - -type KeeperTestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context -} - -func (suite *KeeperTestSuite) SetupTest() { - suite.ResetChain() -} - -func (suite *KeeperTestSuite) ResetChain() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - keeper := tApp.GetCDPKeeper() - - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper -} diff --git a/x/cdp/keeper/migrations.go b/x/cdp/keeper/migrations.go deleted file mode 100644 index 7b8a0c18..00000000 --- a/x/cdp/keeper/migrations.go +++ /dev/null @@ -1,23 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - v2 "github.com/kava-labs/kava/x/cdp/migrations/v2" -) - -// Migrator is a struct for handling in-place store migrations. -type Migrator struct { - keeper Keeper -} - -// NewMigrator returns a new Migrator. -func NewMigrator(keeper Keeper) Migrator { - return Migrator{ - keeper: keeper, - } -} - -// Migrate1to2 migrates from version 1 to 2. -func (m Migrator) Migrate1to2(ctx sdk.Context) error { - return v2.MigrateStore(ctx, m.keeper.paramSubspace) -} diff --git a/x/cdp/keeper/msg_server.go b/x/cdp/keeper/msg_server.go deleted file mode 100644 index 8f078b43..00000000 --- a/x/cdp/keeper/msg_server.go +++ /dev/null @@ -1,175 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/cdp/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the cdp MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -func (k msgServer) CreateCDP(goCtx context.Context, msg *types.MsgCreateCDP) (*types.MsgCreateCDPResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - err = k.keeper.AddCdp(ctx, sender, msg.Collateral, msg.Principal, msg.CollateralType) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - ), - ) - - id, _ := k.keeper.GetCdpID(ctx, sender, msg.CollateralType) - return &types.MsgCreateCDPResponse{CdpID: id}, nil -} - -func (k msgServer) Deposit(goCtx context.Context, msg *types.MsgDeposit) (*types.MsgDepositResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - owner, err := sdk.AccAddressFromBech32(msg.Owner) - if err != nil { - return nil, err - } - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - - err = k.keeper.DepositCollateral(ctx, owner, depositor, msg.Collateral, msg.CollateralType) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Depositor), - ), - ) - return &types.MsgDepositResponse{}, nil -} - -func (k msgServer) Withdraw(goCtx context.Context, msg *types.MsgWithdraw) (*types.MsgWithdrawResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - owner, err := sdk.AccAddressFromBech32(msg.Owner) - if err != nil { - return nil, err - } - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - - err = k.keeper.WithdrawCollateral(ctx, owner, depositor, msg.Collateral, msg.CollateralType) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Depositor), - ), - ) - return &types.MsgWithdrawResponse{}, nil -} - -func (k msgServer) DrawDebt(goCtx context.Context, msg *types.MsgDrawDebt) (*types.MsgDrawDebtResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - err = k.keeper.AddPrincipal(ctx, sender, msg.CollateralType, msg.Principal) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - ), - ) - return &types.MsgDrawDebtResponse{}, nil -} - -func (k msgServer) RepayDebt(goCtx context.Context, msg *types.MsgRepayDebt) (*types.MsgRepayDebtResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - err = k.keeper.RepayPrincipal(ctx, sender, msg.CollateralType, msg.Payment) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - ), - ) - return &types.MsgRepayDebtResponse{}, nil -} - -func (k msgServer) Liquidate(goCtx context.Context, msg *types.MsgLiquidate) (*types.MsgLiquidateResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - keeper, err := sdk.AccAddressFromBech32(msg.Keeper) - if err != nil { - return nil, err - } - - borrower, err := sdk.AccAddressFromBech32(msg.Borrower) - if err != nil { - return nil, err - } - - err = k.keeper.AttemptKeeperLiquidation(ctx, keeper, borrower, msg.CollateralType) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Keeper), - ), - ) - return &types.MsgLiquidateResponse{}, nil -} diff --git a/x/cdp/keeper/params.go b/x/cdp/keeper/params.go deleted file mode 100644 index 62b3a4a6..00000000 --- a/x/cdp/keeper/params.go +++ /dev/null @@ -1,101 +0,0 @@ -package keeper - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/cdp/types" -) - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - var p types.Params - k.paramSubspace.GetParamSetIfExists(ctx, &p) - return p -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} - -// GetCollateral returns the collateral param with corresponding denom -func (k Keeper) GetCollateral(ctx sdk.Context, collateralType string) (types.CollateralParam, bool) { - params := k.GetParams(ctx) - for _, cp := range params.CollateralParams { - if cp.Type == collateralType { - return cp, true - } - } - return types.CollateralParam{}, false -} - -// GetCollateralTypes returns an array of collateral types -func (k Keeper) GetCollateralTypes(ctx sdk.Context) []string { - params := k.GetParams(ctx) - var denoms []string - for _, cp := range params.CollateralParams { - denoms = append(denoms, cp.Type) - } - return denoms -} - -// GetDebtParam returns the debt param with matching denom -func (k Keeper) GetDebtParam(ctx sdk.Context, denom string) (types.DebtParam, bool) { - dp := k.GetParams(ctx).DebtParam - if dp.Denom == denom { - return dp, true - } - return types.DebtParam{}, false -} - -func (k Keeper) getSpotMarketID(ctx sdk.Context, collateralType string) string { - cp, found := k.GetCollateral(ctx, collateralType) - if !found { - panic(fmt.Sprintf("collateral not found: %s", collateralType)) - } - return cp.SpotMarketID -} - -func (k Keeper) getliquidationMarketID(ctx sdk.Context, collateralType string) string { - cp, found := k.GetCollateral(ctx, collateralType) - if !found { - panic(fmt.Sprintf("collateral not found: %s", collateralType)) - } - return cp.LiquidationMarketID -} - -func (k Keeper) getLiquidationRatio(ctx sdk.Context, collateralType string) sdk.Dec { - cp, found := k.GetCollateral(ctx, collateralType) - if !found { - panic(fmt.Sprintf("collateral not found: %s", collateralType)) - } - return cp.LiquidationRatio -} - -func (k Keeper) getLiquidationPenalty(ctx sdk.Context, collateralType string) sdk.Dec { - cp, found := k.GetCollateral(ctx, collateralType) - if !found { - panic(fmt.Sprintf("collateral not found: %s", collateralType)) - } - return cp.LiquidationPenalty -} - -func (k Keeper) getAuctionSize(ctx sdk.Context, collateralType string) sdkmath.Int { - cp, found := k.GetCollateral(ctx, collateralType) - if !found { - panic(fmt.Sprintf("collateral not found: %s", collateralType)) - } - return cp.AuctionSize -} - -// GetFeeRate returns the per second fee rate for the input denom -func (k Keeper) getFeeRate(ctx sdk.Context, collateralType string) (fee sdk.Dec) { - collalateralParam, found := k.GetCollateral(ctx, collateralType) - if !found { - panic(fmt.Sprintf("could not get fee rate for %s, collateral not found", collateralType)) - } - return collalateralParam.StabilityFee -} diff --git a/x/cdp/keeper/querier.go b/x/cdp/keeper/querier.go deleted file mode 100644 index 143dbff0..00000000 --- a/x/cdp/keeper/querier.go +++ /dev/null @@ -1,154 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/cdp/types" -) - -// FilterCDPs queries the store for all CDPs that match query params -func FilterCDPs(ctx sdk.Context, k Keeper, params types.QueryCdpsParams) (types.AugmentedCDPs, error) { - var matchCollateralType, matchOwner, matchID, matchRatio types.CDPs - - // match cdp owner (if supplied) - if len(params.Owner) > 0 { - denoms := k.GetCollateralTypes(ctx) - for _, denom := range denoms { - cdp, found := k.GetCdpByOwnerAndCollateralType(ctx, params.Owner, denom) - if found { - matchOwner = append(matchOwner, cdp) - } - } - } - - // match cdp collateral denom (if supplied) - if len(params.CollateralType) > 0 { - // if owner is specified only iterate over already matched cdps for efficiency - if len(params.Owner) > 0 { - for _, cdp := range matchOwner { - if cdp.Type == params.CollateralType { - matchCollateralType = append(matchCollateralType, cdp) - } - } - } else { - _, found := k.GetCollateral(ctx, params.CollateralType) - if !found { - return nil, fmt.Errorf("invalid collateral type") - } - matchCollateralType = k.GetAllCdpsByCollateralType(ctx, params.CollateralType) - } - } - - // match cdp ID (if supplied) - if params.ID != 0 { - denoms := k.GetCollateralTypes(ctx) - for _, denom := range denoms { - cdp, found := k.GetCDP(ctx, denom, params.ID) - if found { - matchID = append(matchID, cdp) - } - } - } - - // match cdp ratio (if supplied) - if !params.Ratio.IsNil() && params.Ratio.GT(sdk.ZeroDec()) { - denoms := k.GetCollateralTypes(ctx) - for _, denom := range denoms { - ratio, err := k.CalculateCollateralizationRatioFromAbsoluteRatio(ctx, denom, params.Ratio, "liquidation") - if err != nil { - continue - } - cdpsUnderRatio := k.GetAllCdpsByCollateralTypeAndRatio(ctx, denom, ratio) - matchRatio = append(matchRatio, cdpsUnderRatio...) - } - } - - var commonCDPs types.CDPs - // If no params specified, fetch all CDPs - if params.CollateralType == "" && len(params.Owner) == 0 && params.ID == 0 && params.Ratio.Equal(sdk.ZeroDec()) { - commonCDPs = k.GetAllCdps(ctx) - } - - // Find the intersection of any matched CDPs - if params.CollateralType != "" { - if len(matchCollateralType) == 0 { - return nil, nil - } - - commonCDPs = matchCollateralType - } - - if len(params.Owner) > 0 { - if len(matchCollateralType) > 0 { - if len(commonCDPs) > 0 { - commonCDPs = FindIntersection(commonCDPs, matchOwner) - } else { - commonCDPs = matchOwner - } - } else { - commonCDPs = matchOwner - } - } - - if params.ID != 0 { - if len(matchID) == 0 { - return nil, nil - } - - if len(commonCDPs) > 0 { - commonCDPs = FindIntersection(commonCDPs, matchID) - } else { - commonCDPs = matchID - } - } - - if !params.Ratio.IsNil() && params.Ratio.GT(sdk.ZeroDec()) { - if len(matchRatio) == 0 { - return nil, nil - } - - if len(commonCDPs) > 0 { - commonCDPs = FindIntersection(commonCDPs, matchRatio) - } else { - commonCDPs = matchRatio - } - } - - // Load augmented CDPs - var augmentedCDPs types.AugmentedCDPs - for _, cdp := range commonCDPs { - augmentedCDP := k.LoadAugmentedCDP(ctx, cdp) - augmentedCDPs = append(augmentedCDPs, augmentedCDP) - } - - // Apply page and limit params - start, end := client.Paginate(len(augmentedCDPs), params.Page, params.Limit, 100) - if start < 0 || end < 0 { - return nil, nil - } - - return augmentedCDPs[start:end], nil -} - -// FindIntersection finds the intersection of two CDP arrays in linear time complexity O(n + n) -func FindIntersection(x types.CDPs, y types.CDPs) types.CDPs { - cdpSet := make(types.CDPs, 0) - cdpMap := make(map[uint64]bool) - - for i := 0; i < len(x); i++ { - cdp := x[i] - cdpMap[cdp.ID] = true - } - - for i := 0; i < len(y); i++ { - cdp := y[i] - if _, found := cdpMap[cdp.ID]; found { - cdpSet = append(cdpSet, cdp) - } - } - - return cdpSet -} diff --git a/x/cdp/keeper/seize.go b/x/cdp/keeper/seize.go deleted file mode 100644 index 77529a60..00000000 --- a/x/cdp/keeper/seize.go +++ /dev/null @@ -1,170 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/cdp/types" -) - -// AttemptKeeperLiquidation liquidates the cdp with the input collateral type and owner if it is below the required collateralization ratio -// if the cdp is liquidated, the keeper that sent the transaction is rewarded a percentage of the collateral according to that collateral types' -// keeper reward percentage. -func (k Keeper) AttemptKeeperLiquidation(ctx sdk.Context, keeper, owner sdk.AccAddress, collateralType string) error { - cdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType) - if !found { - return errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", owner, collateralType) - } - k.hooks.BeforeCDPModified(ctx, cdp) - cdp = k.SynchronizeInterest(ctx, cdp) - - err := k.ValidateLiquidation(ctx, cdp.Collateral, cdp.Type, cdp.Principal, cdp.AccumulatedFees) - if err != nil { - return err - } - cdp, err = k.payoutKeeperLiquidationReward(ctx, keeper, cdp) - if err != nil { - return err - } - return k.SeizeCollateral(ctx, cdp) -} - -// SeizeCollateral liquidates the collateral in the input cdp. -// the following operations are performed: -// 1. Collateral for all deposits is sent from the cdp module to the liquidator module account -// 2. The liquidation penalty is applied -// 3. Debt coins are sent from the cdp module to the liquidator module account -// 4. The total amount of principal outstanding for that collateral type is decremented -// (this is the equivalent of saying that fees are no longer accumulated by a cdp once it gets liquidated) -func (k Keeper) SeizeCollateral(ctx sdk.Context, cdp types.CDP) error { - // Calculate the previous collateral ratio - oldCollateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal()) - - // Move debt coins from cdp to liquidator account - deposits := k.GetDeposits(ctx, cdp.ID) - debt := cdp.GetTotalPrincipal().Amount - modAccountDebt := k.getModAccountDebt(ctx, types.ModuleName) - debt = sdk.MinInt(debt, modAccountDebt) - debtCoin := sdk.NewCoin(k.GetDebtDenom(ctx), debt) - err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, types.LiquidatorMacc, sdk.NewCoins(debtCoin)) - if err != nil { - return err - } - - // liquidate deposits and send collateral from cdp to liquidator - for _, dep := range deposits { - if err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, types.LiquidatorMacc, sdk.NewCoins(dep.Amount)); err != nil { - return err - } - - k.DeleteDeposit(ctx, dep.CdpID, dep.Depositor) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCdpLiquidation, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - sdk.NewAttribute(types.AttributeKeyDeposit, dep.String()), - ), - ) - } - - err = k.AuctionCollateral(ctx, deposits, cdp.Type, debt, cdp.Principal.Denom) - if err != nil { - return err - } - - // Decrement total principal for this collateral type - coinsToDecrement := cdp.GetTotalPrincipal() - k.DecrementTotalPrincipal(ctx, cdp.Type, coinsToDecrement) - - // Delete CDP from state - k.RemoveCdpOwnerIndex(ctx, cdp) - k.RemoveCdpCollateralRatioIndex(ctx, cdp.Type, cdp.ID, oldCollateralToDebtRatio) - return k.DeleteCDP(ctx, cdp) -} - -// LiquidateCdps seizes collateral from all CDPs below the input liquidation ratio -func (k Keeper) LiquidateCdps(ctx sdk.Context, marketID string, collateralType string, liquidationRatio sdk.Dec, count sdkmath.Int) error { - price, err := k.pricefeedKeeper.GetCurrentPrice(ctx, marketID) - if err != nil { - return err - } - priceDivLiqRatio := price.Price.Quo(liquidationRatio) - if priceDivLiqRatio.IsZero() { - priceDivLiqRatio = sdk.SmallestDec() - } - // price = $0.5 - // liquidation ratio = 1.5 - // normalizedRatio = (1/(0.5/1.5)) = 3 - normalizedRatio := sdk.OneDec().Quo(priceDivLiqRatio) - cdpsToLiquidate := k.GetSliceOfCDPsByRatioAndType(ctx, count, normalizedRatio, collateralType) - for _, c := range cdpsToLiquidate { - k.hooks.BeforeCDPModified(ctx, c) - err := k.SeizeCollateral(ctx, c) - if err != nil { - return err - } - } - return nil -} - -// ApplyLiquidationPenalty multiplies the input debt amount by the liquidation penalty -func (k Keeper) ApplyLiquidationPenalty(ctx sdk.Context, collateralType string, debt sdkmath.Int) sdkmath.Int { - penalty := k.getLiquidationPenalty(ctx, collateralType) - return sdk.NewDecFromInt(debt).Mul(penalty).RoundInt() -} - -// ValidateLiquidation validate that adding the input principal puts the cdp below the liquidation ratio -func (k Keeper) ValidateLiquidation(ctx sdk.Context, collateral sdk.Coin, collateralType string, principal sdk.Coin, fees sdk.Coin) error { - collateralizationRatio, err := k.CalculateCollateralizationRatio(ctx, collateral, collateralType, principal, fees, liquidation) - if err != nil { - return err - } - liquidationRatio := k.getLiquidationRatio(ctx, collateralType) - if collateralizationRatio.GTE(liquidationRatio) { - return errorsmod.Wrapf(types.ErrNotLiquidatable, "collateral %s, collateral ratio %s, liquidation ratio %s", collateral.Denom, collateralizationRatio, liquidationRatio) - } - return nil -} - -func (k Keeper) getModAccountDebt(ctx sdk.Context, accountName string) sdkmath.Int { - macc := k.accountKeeper.GetModuleAccount(ctx, accountName) - return k.bankKeeper.GetBalance(ctx, macc.GetAddress(), k.GetDebtDenom(ctx)).Amount -} - -func (k Keeper) payoutKeeperLiquidationReward(ctx sdk.Context, keeper sdk.AccAddress, cdp types.CDP) (types.CDP, error) { - collateralParam, found := k.GetCollateral(ctx, cdp.Type) - if !found { - return types.CDP{}, errorsmod.Wrapf(types.ErrInvalidCollateral, "%s", cdp.Type) - } - reward := sdk.NewDecFromInt(cdp.Collateral.Amount).Mul(collateralParam.KeeperRewardPercentage).RoundInt() - rewardCoin := sdk.NewCoin(cdp.Collateral.Denom, reward) - paidReward := false - deposits := k.GetDeposits(ctx, cdp.ID) - for _, dep := range deposits { - if dep.Amount.IsGTE(rewardCoin) { - dep.Amount = dep.Amount.Sub(rewardCoin) - k.SetDeposit(ctx, dep) - paidReward = true - break - } - } - if !paidReward { - return cdp, nil - } - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, keeper, sdk.NewCoins(rewardCoin)) - if err != nil { - return types.CDP{}, err - } - cdp.Collateral = cdp.Collateral.Sub(rewardCoin) - ratio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal()) - err = k.UpdateCdpAndCollateralRatioIndex(ctx, cdp, ratio) - if err != nil { - return types.CDP{}, err - } - return cdp, nil -} diff --git a/x/cdp/keeper/seize_test.go b/x/cdp/keeper/seize_test.go deleted file mode 100644 index 37c8428a..00000000 --- a/x/cdp/keeper/seize_test.go +++ /dev/null @@ -1,576 +0,0 @@ -package keeper_test - -import ( - "errors" - "fmt" - "math/rand" - "strings" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" - - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - auctiontypes "github.com/kava-labs/kava/x/auction/types" - "github.com/kava-labs/kava/x/cdp/keeper" - "github.com/kava-labs/kava/x/cdp/types" -) - -type SeizeTestSuite struct { - suite.Suite - - keeper keeper.Keeper - addrs []sdk.AccAddress - app app.TestApp - cdps types.CDPs - ctx sdk.Context - liquidations liquidationTracker -} - -type liquidationTracker struct { - xrp []uint64 - btc []uint64 - debt int64 -} - -func (suite *SeizeTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now(), ChainID: app.TestChainId}) - tracker := liquidationTracker{} - coins := cs(c("btc", 100000000), c("xrp", 10000000000)) - _, addrs := app.GeneratePrivKeyAddressPairs(100) - - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(tApp.AppCodec()), - NewCDPGenStateMulti(tApp.AppCodec()), - ) - suite.ctx = ctx - suite.app = tApp - suite.keeper = tApp.GetCDPKeeper() - suite.cdps = types.CDPs{} - suite.addrs = addrs - suite.liquidations = tracker -} - -func (suite *SeizeTestSuite) createCdps() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - cdps := make(types.CDPs, 100) - _, addrs := app.GeneratePrivKeyAddressPairs(100) - tracker := liquidationTracker{} - coins := cs(c("btc", 100000000), c("xrp", 10000000000)) - - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(tApp.AppCodec()), - NewCDPGenStateMulti(tApp.AppCodec()), - ) - - suite.ctx = ctx - suite.app = tApp - suite.keeper = tApp.GetCDPKeeper() - randSource := rand.New(rand.NewSource(int64(777))) - for j := 0; j < 100; j++ { - collateral := "xrp" - amount := 10000000000 - debt := simulation.RandIntBetween(randSource, 750000000, 1249000000) - if j%2 == 0 { - collateral = "btc" - amount = 100000000 - debt = simulation.RandIntBetween(randSource, 2700000000, 5332000000) - if debt >= 4000000000 { - tracker.btc = append(tracker.btc, uint64(j+1)) - tracker.debt += int64(debt) - } - } else { - if debt >= 1000000000 { - tracker.xrp = append(tracker.xrp, uint64(j+1)) - tracker.debt += int64(debt) - } - } - err := suite.keeper.AddCdp(suite.ctx, addrs[j], c(collateral, int64(amount)), c("usdx", int64(debt)), collateral+"-a") - suite.NoError(err) - c, f := suite.keeper.GetCDP(suite.ctx, collateral+"-a", uint64(j+1)) - suite.True(f) - cdps[j] = c - } - - suite.cdps = cdps - suite.addrs = addrs - suite.liquidations = tracker -} - -func (suite *SeizeTestSuite) setPrice(price sdk.Dec, market string) { - pfKeeper := suite.app.GetPriceFeedKeeper() - - _, err := pfKeeper.SetPrice(suite.ctx, sdk.AccAddress{}, market, price, suite.ctx.BlockTime().Add(time.Hour*3)) - suite.NoError(err) - err = pfKeeper.SetCurrentPrices(suite.ctx, market) - suite.NoError(err) - pp, err := pfKeeper.GetCurrentPrice(suite.ctx, market) - suite.NoError(err) - suite.Equal(price, pp.Price) -} - -func (suite *SeizeTestSuite) TestSeizeCollateral() { - suite.createCdps() - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - cdp, found := suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(2)) - suite.True(found) - - p := cdp.Principal.Amount - cl := cdp.Collateral.Amount - - tpb := suite.keeper.GetTotalPrincipal(suite.ctx, "xrp-a", "usdx") - err := suite.keeper.SeizeCollateral(suite.ctx, cdp) - suite.NoError(err) - - tpa := suite.keeper.GetTotalPrincipal(suite.ctx, "xrp-a", "usdx") - suite.Equal(tpb.Sub(tpa), p) - - auctionKeeper := suite.app.GetAuctionKeeper() - - _, found = auctionKeeper.GetAuction(suite.ctx, auctiontypes.DefaultNextAuctionID) - suite.True(found) - - auctionMacc := ak.GetModuleAccount(suite.ctx, auctiontypes.ModuleName) - suite.Equal(cs(c("debt", p.Int64()), c("xrp", cl.Int64())), bk.GetAllBalances(suite.ctx, auctionMacc.GetAddress())) - - acc := ak.GetAccount(suite.ctx, suite.addrs[1]) - suite.Equal(p.Int64(), bk.GetBalance(suite.ctx, acc.GetAddress(), "usdx").Amount.Int64()) - err = suite.keeper.WithdrawCollateral(suite.ctx, suite.addrs[1], suite.addrs[1], c("xrp", 10), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrCdpNotFound)) -} - -func (suite *SeizeTestSuite) TestSeizeCollateralMultiDeposit() { - suite.createCdps() - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - _, found := suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(2)) - suite.True(found) - - err := suite.keeper.DepositCollateral(suite.ctx, suite.addrs[1], suite.addrs[0], c("xrp", 6999000000), "xrp-a") - suite.NoError(err) - - cdp, found := suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(2)) - suite.True(found) - - deposits := suite.keeper.GetDeposits(suite.ctx, cdp.ID) - suite.Equal(2, len(deposits)) - - p := cdp.Principal.Amount - cl := cdp.Collateral.Amount - tpb := suite.keeper.GetTotalPrincipal(suite.ctx, "xrp-a", "usdx") - err = suite.keeper.SeizeCollateral(suite.ctx, cdp) - suite.NoError(err) - - tpa := suite.keeper.GetTotalPrincipal(suite.ctx, "xrp-a", "usdx") - suite.Equal(tpb.Sub(tpa), p) - - auctionMacc := ak.GetModuleAccount(suite.ctx, auctiontypes.ModuleName) - suite.Equal(cs(c("debt", p.Int64()), c("xrp", cl.Int64())), bk.GetAllBalances(suite.ctx, auctionMacc.GetAddress())) - - acc := ak.GetAccount(suite.ctx, suite.addrs[1]) - suite.Equal(p.Int64(), bk.GetBalance(suite.ctx, acc.GetAddress(), "usdx").Amount.Int64()) - err = suite.keeper.WithdrawCollateral(suite.ctx, suite.addrs[1], suite.addrs[1], c("xrp", 10), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrCdpNotFound)) -} - -func (suite *SeizeTestSuite) TestLiquidateCdps() { - suite.createCdps() - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - acc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - - originalXrpCollateral := bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount - suite.setPrice(d("0.2"), "xrp:usd") - p, found := suite.keeper.GetCollateral(suite.ctx, "xrp-a") - suite.True(found) - - err := suite.keeper.LiquidateCdps(suite.ctx, "xrp:usd", "xrp-a", p.LiquidationRatio, p.CheckCollateralizationIndexCount) - suite.NoError(err) - - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - finalXrpCollateral := bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount - seizedXrpCollateral := originalXrpCollateral.Sub(finalXrpCollateral) - xrpLiquidations := int(seizedXrpCollateral.Quo(i(10000000000)).Int64()) - suite.Equal(10, xrpLiquidations) -} - -func (suite *SeizeTestSuite) TestApplyLiquidationPenalty() { - penalty := suite.keeper.ApplyLiquidationPenalty(suite.ctx, "xrp-a", i(1000)) - suite.Equal(i(50), penalty) - penalty = suite.keeper.ApplyLiquidationPenalty(suite.ctx, "btc-a", i(1000)) - suite.Equal(i(25), penalty) - penalty = suite.keeper.ApplyLiquidationPenalty(suite.ctx, "xrp-a", i(675760172)) - suite.Equal(i(33788009), penalty) - suite.Panics(func() { suite.keeper.ApplyLiquidationPenalty(suite.ctx, "lol-a", i(1000)) }) -} - -func (suite *SeizeTestSuite) TestKeeperLiquidation() { - type args struct { - ctype string - blockTime time.Time - initialPrice sdk.Dec - finalPrice sdk.Dec - finalTwapPrice sdk.Dec - collateral sdk.Coin - principal sdk.Coin - expectedKeeperCoins sdk.Coins // additional coins (if any) the borrower address should have after successfully liquidating position - expectedAuctions []auctiontypes.Auction // the auctions we should expect to find have been started - } - - type errArgs struct { - expectLiquidate bool - contains string - } - - type test struct { - name string - args args - errArgs errArgs - } - - // Set up auction constants - layout := "2006-01-02T15:04:05.000Z" - endTimeStr := "9000-01-01T00:00:00.000Z" - endTime, _ := time.Parse(layout, endTimeStr) - addr, _ := sdk.AccAddressFromBech32("kava1ze7y9qwdddejmy7jlw4cymqqlt2wh05yhwmrv2") - - testCases := []test{ - { - "valid liquidation", - args{ - ctype: "btc-a", - blockTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialPrice: d("20000.00"), - finalPrice: d("19000.0"), - finalTwapPrice: d("19000.0"), - collateral: c("btc", 10000000), - principal: c("usdx", 1333330000), - expectedKeeperCoins: cs(c("btc", 100100000), c("xrp", 10000000000)), - expectedAuctions: []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "liquidator", - Lot: c("btc", 9900000), - Bidder: nil, - Bid: c("usdx", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: c("debt", 1333330000), - MaxBid: c("usdx", 1366663250), - LotReturns: auctiontypes.WeightedAddresses{ - Addresses: []sdk.AccAddress{addr}, - Weights: []sdkmath.Int{sdkmath.NewInt(9900000)}, - }, - }, - }, - }, - errArgs{ - true, - "", - }, - }, - { - "valid liquidation - twap market liquidateable but not spot", - args{ - ctype: "btc-a", - blockTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialPrice: d("20000.00"), - // spot price does not liquidates - finalPrice: d("21000.0"), - // twap / liquidation price does liquidate - finalTwapPrice: d("19000.0"), - collateral: c("btc", 10000000), - principal: c("usdx", 1333330000), - expectedKeeperCoins: cs(c("btc", 100100000), c("xrp", 10000000000)), - expectedAuctions: []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "liquidator", - Lot: c("btc", 9900000), - Bidder: nil, - Bid: c("usdx", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: c("debt", 1333330000), - MaxBid: c("usdx", 1366663250), - LotReturns: auctiontypes.WeightedAddresses{ - Addresses: []sdk.AccAddress{addr}, - Weights: []sdkmath.Int{sdkmath.NewInt(9900000)}, - }, - }, - }, - }, - errArgs{ - true, - "", - }, - }, - { - "invalid - not below collateralization ratio", - args{ - ctype: "btc-a", - blockTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialPrice: d("20000.00"), - finalPrice: d("21000.0"), - finalTwapPrice: d("21000.0"), - collateral: c("btc", 10000000), - principal: c("usdx", 1333330000), - expectedKeeperCoins: cs(), - expectedAuctions: []auctiontypes.Auction{}, - }, - errArgs{ - false, - "collateral ratio not below liquidation ratio", - }, - }, - { - "invalid - spot market liquidateable but not twap", - args{ - ctype: "btc-a", - blockTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialPrice: d("20000.00"), - // spot price liquidates - finalPrice: d("19000.0"), - // twap / liquidation price does not liquidate - finalTwapPrice: d("21000.0"), - collateral: c("btc", 10000000), - principal: c("usdx", 1333330000), - expectedKeeperCoins: cs(), - expectedAuctions: []auctiontypes.Auction{}, - }, - errArgs{ - false, - "collateral ratio not below liquidation ratio", - }, - }, - { - "invalid - collateralization ratio equal to liquidation ratio", - args{ - ctype: "xrp-a", - blockTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialPrice: d("1.00"), // we are allowed to create a cdp with an exact ratio - finalPrice: d("1.00"), - finalTwapPrice: d("1.00"), // and it should not be able to be liquidated - collateral: c("xrp", 100000000), - principal: c("usdx", 50000000), - expectedKeeperCoins: cs(), - expectedAuctions: []auctiontypes.Auction{}, - }, - errArgs{ - false, - "collateral ratio not below liquidation ratio", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - spotMarket := fmt.Sprintf("%s:usd", tc.args.collateral.Denom) - liquidationMarket := fmt.Sprintf("%s:30", spotMarket) - - // setup pricefeed - pk := suite.app.GetPriceFeedKeeper() - _, err := pk.SetPrice(suite.ctx, sdk.AccAddress{}, spotMarket, tc.args.initialPrice, suite.ctx.BlockTime().Add(time.Hour*24)) - suite.Require().NoError(err) - err = pk.SetCurrentPrices(suite.ctx, spotMarket) - suite.Require().NoError(err) - - // setup cdp state - suite.keeper.SetPreviousAccrualTime(suite.ctx, tc.args.ctype, suite.ctx.BlockTime()) - suite.keeper.SetInterestFactor(suite.ctx, tc.args.ctype, sdk.OneDec()) - err = suite.keeper.AddCdp(suite.ctx, suite.addrs[0], tc.args.collateral, tc.args.principal, tc.args.ctype) - suite.Require().NoError(err) - - // update pricefeed - // spot market - _, err = pk.SetPrice(suite.ctx, sdk.AccAddress{}, spotMarket, tc.args.finalPrice, suite.ctx.BlockTime().Add(time.Hour*24)) - suite.Require().NoError(err) - // liquidate market - _, err = pk.SetPrice(suite.ctx, sdk.AccAddress{}, liquidationMarket, tc.args.finalTwapPrice, suite.ctx.BlockTime().Add(time.Hour*24)) - suite.Require().NoError(err) - - err = pk.SetCurrentPrices(suite.ctx, spotMarket) - suite.Require().NoError(err) - err = pk.SetCurrentPrices(suite.ctx, liquidationMarket) - suite.Require().NoError(err) - - _, found := suite.keeper.GetCdpByOwnerAndCollateralType(suite.ctx, suite.addrs[0], tc.args.ctype) - suite.Require().True(found) - - err = suite.keeper.AttemptKeeperLiquidation(suite.ctx, suite.addrs[1], suite.addrs[0], tc.args.ctype) - - if tc.errArgs.expectLiquidate { - suite.Require().NoError(err) - - _, found = suite.keeper.GetCdpByOwnerAndCollateralType(suite.ctx, suite.addrs[0], tc.args.ctype) - suite.Require().False(found) - - ak := suite.app.GetAuctionKeeper() - auctions := ak.GetAllAuctions(suite.ctx) - suite.Require().Equal(tc.args.expectedAuctions, auctions) - - ack := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - keeper := ack.GetAccount(suite.ctx, suite.addrs[1]) - suite.Require().Equal(tc.args.expectedKeeperCoins, bk.GetAllBalances(suite.ctx, keeper.GetAddress())) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *SeizeTestSuite) TestBeginBlockerLiquidation() { - type args struct { - ctype string - blockTime time.Time - initialPrice sdk.Dec - finalPrice sdk.Dec - collaterals sdk.Coins - principals sdk.Coins - expectedAuctions []auctiontypes.Auction // the auctions we should expect to find have been started - } - type errArgs struct { - expectLiquidate bool - contains string - } - type test struct { - name string - args args - errArgs errArgs - } - // Set up auction constants - layout := "2006-01-02T15:04:05.000Z" - endTimeStr := "9000-01-01T00:00:00.000Z" - endTime, _ := time.Parse(layout, endTimeStr) - addr, _ := sdk.AccAddressFromBech32("kava1ze7y9qwdddejmy7jlw4cymqqlt2wh05yhwmrv2") - - testCases := []test{ - { - "1 liquidation", - args{ - "btc-a", - time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - d("20000.00"), - d("10000.00"), - sdk.Coins{c("btc", 10000000), c("btc", 10000000)}, - sdk.Coins{c("usdx", 1000000000), c("usdx", 500000000)}, - []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "liquidator", - Lot: c("btc", 10000000), - Bidder: nil, - Bid: c("usdx", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: c("debt", 1000000000), - MaxBid: c("usdx", 1025000000), - LotReturns: auctiontypes.WeightedAddresses{ - Addresses: []sdk.AccAddress{addr}, - Weights: []sdkmath.Int{sdkmath.NewInt(10000000)}, - }, - }, - }, - }, - errArgs{ - true, - "", - }, - }, - { - "no liquidation", - args{ - "btc-a", - time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - d("20000.00"), - d("10000.00"), - sdk.Coins{c("btc", 10000000), c("btc", 10000000)}, - sdk.Coins{c("usdx", 500000000), c("usdx", 500000000)}, - []auctiontypes.Auction{}, - }, - errArgs{ - false, - "collateral ratio not below liquidation ratio", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - // setup pricefeed - pk := suite.app.GetPriceFeedKeeper() - _, err := pk.SetPrice(suite.ctx, sdk.AccAddress{}, "btc:usd", tc.args.initialPrice, suite.ctx.BlockTime().Add(time.Hour*24)) - suite.Require().NoError(err) - err = pk.SetCurrentPrices(suite.ctx, "btc:usd") - suite.Require().NoError(err) - - // setup cdp state - suite.keeper.SetPreviousAccrualTime(suite.ctx, tc.args.ctype, suite.ctx.BlockTime()) - suite.keeper.SetInterestFactor(suite.ctx, tc.args.ctype, sdk.OneDec()) - - for idx, col := range tc.args.collaterals { - err := suite.keeper.AddCdp(suite.ctx, suite.addrs[idx], col, tc.args.principals[idx], tc.args.ctype) - suite.Require().NoError(err) - } - - // update pricefeed - _, err = pk.SetPrice(suite.ctx, sdk.AccAddress{}, "btc:usd", tc.args.finalPrice, suite.ctx.BlockTime().Add(time.Hour*24)) - suite.Require().NoError(err) - err = pk.SetCurrentPrices(suite.ctx, "btc:usd") - suite.Require().NoError(err) - - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{Header: suite.ctx.BlockHeader()}) - ak := suite.app.GetAuctionKeeper() - auctions := ak.GetAllAuctions(suite.ctx) - if tc.errArgs.expectLiquidate { - suite.Require().Equal(tc.args.expectedAuctions, auctions) - for _, a := range auctions { - ca := a.(*auctiontypes.CollateralAuction) - _, found := suite.keeper.GetCdpByOwnerAndCollateralType(suite.ctx, ca.LotReturns.Addresses[0], tc.args.ctype) - suite.Require().False(found) - } - } else { - suite.Require().Equal(0, len(auctions)) - for idx := range tc.args.collaterals { - _, found := suite.keeper.GetCdpByOwnerAndCollateralType(suite.ctx, suite.addrs[idx], tc.args.ctype) - suite.Require().True(found) - } - } - }) - } -} - -func TestSeizeTestSuite(t *testing.T) { - suite.Run(t, new(SeizeTestSuite)) -} diff --git a/x/cdp/migrations/v2/store.go b/x/cdp/migrations/v2/store.go deleted file mode 100644 index f457c174..00000000 --- a/x/cdp/migrations/v2/store.go +++ /dev/null @@ -1,22 +0,0 @@ -package v2 - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/kava-labs/kava/x/cdp/types" -) - -// MigrateStore performs in-place store migrations for consensus version 2 -// V2 adds the begin_blocker_execution_block_interval param to parameters. -func MigrateStore(ctx sdk.Context, paramstore paramtypes.Subspace) error { - migrateParamsStore(ctx, paramstore) - return nil -} - -// migrateParamsStore ensures the param key table exists and has the begin_blocker_execution_block_interval property -func migrateParamsStore(ctx sdk.Context, paramstore paramtypes.Subspace) { - if !paramstore.HasKeyTable() { - paramstore.WithKeyTable(types.ParamKeyTable()) - } - paramstore.Set(ctx, types.KeyBeginBlockerExecutionBlockInterval, types.DefaultBeginBlockerExecutionBlockInterval) -} diff --git a/x/cdp/migrations/v2/store_test.go b/x/cdp/migrations/v2/store_test.go deleted file mode 100644 index 13da0382..00000000 --- a/x/cdp/migrations/v2/store_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package v2_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - - v2cdp "github.com/kava-labs/kava/x/cdp/migrations/v2" - "github.com/kava-labs/kava/x/cdp/types" -) - -func TestStoreMigrationAddsKeyTableIncludingNewParam(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig() - cdpKey := sdk.NewKVStoreKey(types.ModuleName) - tcdpKey := sdk.NewTransientStoreKey("transient_test") - ctx := testutil.DefaultContext(cdpKey, tcdpKey) - paramstore := paramtypes.NewSubspace(encCfg.Codec, encCfg.Amino, cdpKey, tcdpKey, types.ModuleName) - - // Check param doesn't exist before - require.False(t, paramstore.Has(ctx, types.KeyBeginBlockerExecutionBlockInterval)) - - // Run migrations. - err := v2cdp.MigrateStore(ctx, paramstore) - require.NoError(t, err) - - // Make sure the new params are set. - require.True(t, paramstore.Has(ctx, types.KeyBeginBlockerExecutionBlockInterval)) - // Assert the value is what we expect - result := types.DefaultBeginBlockerExecutionBlockInterval - paramstore.Get(ctx, types.KeyBeginBlockerExecutionBlockInterval, &result) - require.Equal(t, result, types.DefaultBeginBlockerExecutionBlockInterval) -} - -func TestStoreMigrationSetsNewParamOnExistingKeyTable(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig() - cdpKey := sdk.NewKVStoreKey(types.ModuleName) - tcdpKey := sdk.NewTransientStoreKey("transient_test") - ctx := testutil.DefaultContext(cdpKey, tcdpKey) - paramstore := paramtypes.NewSubspace(encCfg.Codec, encCfg.Amino, cdpKey, tcdpKey, types.ModuleName) - paramstore.WithKeyTable(types.ParamKeyTable()) - - // expect it to have key table - require.True(t, paramstore.HasKeyTable()) - // expect it to not have new param - require.False(t, paramstore.Has(ctx, types.KeyBeginBlockerExecutionBlockInterval)) - - // Run migrations. - err := v2cdp.MigrateStore(ctx, paramstore) - require.NoError(t, err) - - // Make sure the new params are set. - require.True(t, paramstore.Has(ctx, types.KeyBeginBlockerExecutionBlockInterval)) - - // Assert the value is what we expect - result := types.DefaultBeginBlockerExecutionBlockInterval - paramstore.Get(ctx, types.KeyBeginBlockerExecutionBlockInterval, &result) - require.Equal(t, result, types.DefaultBeginBlockerExecutionBlockInterval) -} diff --git a/x/cdp/module.go b/x/cdp/module.go deleted file mode 100644 index 32d07d1c..00000000 --- a/x/cdp/module.go +++ /dev/null @@ -1,155 +0,0 @@ -package cdp - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/kava-labs/kava/x/cdp/client/cli" - "github.com/kava-labs/kava/x/cdp/keeper" - "github.com/kava-labs/kava/x/cdp/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// ConsensusVersion defines the current module consensus version. -const ConsensusVersion = 2 - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis returns default genesis state as raw bytes for the cdp -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - gs := types.DefaultGenesisState() - return cdc.MustMarshalJSON(&gs) -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) - if err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the gov module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return ConsensusVersion -} - -// GetTxCmd returns the root tx command for the cdp module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns the root query command for the auction module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper - pricefeedKeeper types.PricefeedKeeper - bankKeeper types.BankKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper types.AccountKeeper, pricefeedKeeper types.PricefeedKeeper, bankKeeper types.BankKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: accountKeeper, - pricefeedKeeper: pricefeedKeeper, - bankKeeper: bankKeeper, - } -} - -// Name module name -func (AppModule) Name() string { - return types.ModuleName -} - -// RegisterInvariants register module invariants -func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) - - m := keeper.NewMigrator(am.keeper) - if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil { - panic(fmt.Sprintf("failed to migrate x/cdp from version 1 to 2: %v", err)) - } -} - -// InitGenesis module init-genesis -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, am.pricefeedKeeper, am.accountKeeper, genState) - return []abci.ValidatorUpdate{} -} - -// ExportGenesis module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(&gs) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { - BeginBlocker(ctx, req, am.keeper) -} - -// EndBlock module end-block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/cdp/spec/01_concepts.md b/x/cdp/spec/01_concepts.md deleted file mode 100644 index 7e8876f9..00000000 --- a/x/cdp/spec/01_concepts.md +++ /dev/null @@ -1,86 +0,0 @@ - - -# Concepts - -## Collateralized Debt Positions - -CDPs enable the creation of a stable asset by collateralization with another on chain asset. - -A CDP is scoped to one collateral type. It has one primary owner, and a set of "depositors". The depositors can deposit and withdraw collateral to the CDP. The owner can draw stable assets (creating debt), deposit and withdraw collateral, and repay stable assets to cancel the debt. - -Once created, stable assets are free to be transferred between users, but a CDP owner must repay their debt to get their collateral back. - -User interactions with this module: - -- create a new CDP by depositing a supported coin as collateral and minting debt -- deposit to a CDP controlled by a different owner address -- withdraw deposited collateral, if it doesn't put the CDP below the liquidation ratio -- issue stable coins from this CDP (up to a fraction of the value of the collateral) -- repay debt by paying back stable coins (including paying any fees accrued) -- remove collateral and close CDP - -Module interactions: - -- fees for all CDPs are updated each block -- the value of fees (surplus) is divded between users, via the savings rate, and owners of the governance token, via burning governance tokens proportional to surplus -- the value of an asset that is supported for CDPs is determined by querying an external pricefeed -- if the price of an asset puts a CDP below the liquidation ratio, the CDP is liquidated -- liquidated collateral is divided into lots and sent to an external auction module -- collateral that is returned from the auction module is returned to the account that deposited that collateral -- if auctions do not recover the desired amount of debt, debt auctions are triggered after a certain threshold of global debt is reached -- surplus auctions are triggered after a certain threshold of surplus is triggered - -## Liquidation & Stability System - -In the event of a decrease in the price of the collateral, the total value of all collateral in CDPs may drop below the value of all the issued stable assets. This undesirable event is countered through two mechanisms: - -**CDP Liquidations** The ratio of collateral value to debt value in each CDP is monitored. When this drops too low the collateral and debt is automatically seized by the system. The collateral is sold off through an auction to bring in stable asset which is burned against the seized debt. The price used to determine liquidation is controlled by the `LiquidationMarketID` parameter, which can be the same as the `SpotMarketID` or use a different calculation of price, such as a time-weighted average. - -**Debt Auctions** In extreme cases where liquidations fail to raise enough to cover the seized debt, another mechanism kicks in: Debt Auctions. System governance tokens are minted and sold through auction to raise enough stable asset to cover the remaining debt. The governors of the system represent the lenders of last resort. - -The system monitors the state of CDPs and debt and triggers these auctions as needed. - -## Internal Debt Tracking - -Users incur debt when they draw new stable assets from their CDP. Within the system this debt is tracked in the form of a "debt coin" stored internally in the module's accounts. Every time a stable coin is created a corresponding debt coin is created. Likewise when debt is repaid stable coin and internal debt coin are burned. - -The cdp module uses two module accounts - one to hold debt coins associated with active CDPs, and another (the "liquidator" account) to hold debt from CDPS that have been seized by the system. - -## Fees - -When a user repays stable asset withdrawn from a CDP, they must also pay a fee. - -This is calculated according to the amount of stable asset withdrawn and the time withdrawn for. Like interest on a loan, fees grow at a compounding percentage of original debt. - -Fees create incentives to open or close CDPs and can be changed by governance to help keep the system functioning through changing market conditions. - -A further fee is applied on liquidation of a CDP. Normally when the collateral is sold to cover the debt, any excess not sold is returned to the CDP holder. The liquidation fee reduces the amount of excess collateral returned, representing a cut that the system takes. - -Fees accumulate to the system and are split between the savings rate and surplus. Fees accumulated by the savings rate are distributed directly to holders of stable coins at a specified frequency. Savings rate distributions are proportional to tokens held. For example, if an account holds 1% of all stable coins, they will receive 1% of the savings rate distribution. Fees accumulated as surplus are automatically sold at auction for governance token once a certain threshold is reached. The governance tokens raised at auction are then burned, acting as incentive for safe governance of the system. - -## Governance - -The cdp module's behavior is controlled through several parameters which are updated through a governance mechanism. These parameters are listed in [Parameters](04_params.md). - -Governance is important for actions such as: - -- enabling CDPs to be created with new collateral assets -- changing fee rates to incentivize behavior -- increasing the debt ceiling to allow more stable asset to be created -- increasing/decreasing the savings rate to promote stability of the debt asset - -## Dependency: supply - -The CDP module relies on a supply keeper to move assets between its module accounts and user accounts. - -## Dependency: pricefeed - -The CDP module needs to know the current price of collateral assets in order to determine if CDPs are under collateralized. This is provided by a "pricefeed" module that returns a price for a given collateral in units (usually US Dollars) which are the target for the stable asset. The status of the pricefeed for each collateral is checked at the beginning of each block. In the event that the pricefeed does not return a price for a collateral asset: - -1. Liquidation of CDPs is suspended until a price is reported -2. Accumulation of fees is suspended until a price is reported -3. Deposits and withdrawals of collateral are suspended until a price is reported -4. Creation of new CDPs is suspended until a price is reported -5. Drawing of additional debt off of existing CDPs is suspended until a price is reported diff --git a/x/cdp/spec/02_state.md b/x/cdp/spec/02_state.md deleted file mode 100644 index bdf36744..00000000 --- a/x/cdp/spec/02_state.md +++ /dev/null @@ -1,78 +0,0 @@ - - -# State - -For detail on the state tracked by the cdp module see the types package. In particular [keys.go](../types/keys.go) describes how state is stored in the key-value store. - -## Module Accounts - -The cdp module account controls two module accounts: - -**CDP Account:** Stores the deposited cdp collateral, and the debt coins for the debt in all the cdps. - -**Liquidator Account:** Stores debt coins that have been seized by the system, and any stable asset that has been raised through auctions. - -## CDP - -A CDP is a struct representing a debt position owned by one address. It has one collateral type and records the debt that has been drawn and how much fees should be repaid. - -Only an owner is authorized to draw or repay debt, but anyone can deposit collateral to a CDP. Deposits are scoped per address and are recorded separately in `Deposit` types. Depositors are free to withdraw their collateral provided it does not put the CDP below the liquidation ratio. - -The CDP's collateral always equal to the total of the deposits. - -```go -type CDP struct { - ID uint64 - Owner sdk.AccAddress - Type string - Collateral sdk.Coin - Principal sdk.Coin - AccumulatedFees sdk.Coin - FeesUpdated time.Time - InterestFactor sdk.Dec -} -``` - -CDPs are stored with three database indexes for faster lookup: - -- by collateral ratio - to look up cdps that are close to the liquidation ratio -- by collateral denom - to look up cdps with a particular collateral asset -- by owner index - to look up cdps that an address is the owner of - -## Deposit - -A Deposit is a struct recording collateral added to a CDP by one address. The address only has authorization to change their deposited amount (provided it does not put the CDP below the liquidation ratio). - -```go -type Deposit struct { - CdpID uint64 - Depositor sdk.AccAddress - Amount sdk.Coin -} -``` - -## Params - -Module parameters controlled by governance. See [Parameters](04_params.md) for details. - -## NextCDPID - -A global counter used to create unique CDP ids. - -## DebtDenom - -The name of the internal debt coin. Its value can be configured at genesis. - -## GovDenom - -The name of the internal governance coin. Its value can be configured at genesis. - -## Total Principle - -Sum of all non seized debt plus accumulated fees. - -## Previous Savings Distribution Time - -A record of the last block time when the savings rate was distributed diff --git a/x/cdp/spec/03_messages.md b/x/cdp/spec/03_messages.md deleted file mode 100644 index 1fe7fd02..00000000 --- a/x/cdp/spec/03_messages.md +++ /dev/null @@ -1,145 +0,0 @@ - - -# Messages - -Users can submit various messages to the cdp module which trigger state changes detailed below. - -## CreateCDP - -CreateCDP sets up and stores a new CDP, adding collateral from the sender, and drawing `Principle` debt. - -```go -type MsgCreateCDP struct { - Sender sdk.AccAddress - Collateral sdk.Coin - Principal sdk.Coin -} -``` - -State changes: - -- a new CDP is created, `Sender` becomes CDP owner -- collateral taken from `Sender` and sent to cdp module account, new `Deposit` created -- `Principal` stable coins are minted and sent to `Sender` -- equal amount of internal debt coins created and stored in cdp module account - -## Deposit - -Deposit adds collateral to a CDP in the form of a deposit. Collateral is taken from `Depositor`. - -```go -type MsgDeposit struct { - Owner sdk.AccAddress - Depositor sdk.AccAddress - Collateral sdk.Coin -} -``` - -State Changes: - -- `Collateral` taken from depositor and sent to cdp module account -- the depositor's `Deposit` struct is updated or a new one created -- cdp fees are updated (see below) - -## Withdraw - -Withdraw removes collateral from a CDP, provided it would not put the CDP under the liquidation ratio. Collateral is removed from one deposit only. - -```go -type MsgWithdraw struct { - Owner sdk.AccAddress - Depositor sdk.AccAddress - Collateral sdk.Coin -} -``` - -State Changes: - -- `Collateral` coins are sent from the cdp module account to `Depositor` -- `Collateral` amount of coins subtracted from the `Deposit` struct. If the amount is now zero, the struct is deleted - -## DrawDebt - -DrawDebt creates debt in a CDP, minting new stable asset which is sent to the sender. - -```go -type MsgDrawDebt struct { - Sender sdk.AccAddress - CdpDenom string - Principal sdk.Coin -} -``` - -State Changes: - -- mint `Principal` coins and send them to `Sender`, updating the CDP's `Principal` field -- mint equal amount of internal debt coins and store in the module account -- increment total principal for principal denom - -## RepayDebt - -RepayDebt removes some debt from a CDP and burns the corresponding amount of stable asset from the sender. If all debt is repaid, the collateral is returned to depositors and the cdp is removed from the store - -```go -type MsgRepayDebt struct { - Sender sdk.AccAddress - CdpDenom string - Payment sdk.Coin -} -``` - -State Changes: - -- burn `Payment` coins taken from `Sender`, updating the CDP by reducing `Principal` field by `Paymment` -- burn an equal amount of internal debt coins -- decrement total principal for payment denom -- if fees and principal are zero, return collateral to depositors and delete the CDP struct: - - For each deposit, send coins from the cdp module account to the depositor, and delete the deposit struct from store. - -## Liquidate - -Liquidate enables Keepers to liquidate a Borrower's CDP. If the CDP is below its Loan-to-Value obligations, the CDP's deposits are seized: a small percentage of the seized funds are sent to the Keeper with the rest auctioned off to recover the CDP's outstanding borrowed amount. Any deposited funds leftover that weren't needed to cover the Borrower's debts are returned to the Borrower. - -Note: In kava v0.21.x and below, CDP's that have a collateral ratio exactly equal to the liquidation ratio can be liquidated through this method. - -```go -// MsgLiquidate attempts to liquidate a borrower's cdp -type MsgLiquidate struct { - Keeper sdk.AccAddress `json:"keeper" yaml:"keeper"` - Borrower sdk.AccAddress `json:"borrower" yaml:"borrower"` - CollateralType string `json:"collateral_type" yaml:"collateral_type"` -} -``` - -State Changes: - -- the CDP's outstanding interest is synchronized so that the deposit and borrow amount are accurate -- the liquidation attempt is validated by comparing the CDP's current collateralization ratio to its liquidation ratio -- the `Keeper` is paid out a percentage of the liquidated position; the exact percentage is specified in the module's params -- the CDP's deposits are seized and used to start an `Auction` to recover the CDP's outstanding borrowed funds -- the module's `TotalPrincipal` for the CDP's collateral type is decremented by the CDP's `Principal` -- the CDP is deleted from the store and removed from the liquidation index - -## Fees - -At the beginning of each block, fees accumulated since the last update are calculated and added on. - -``` -feesAccumulated = (outstandingDebt * (feeRate^periods)) - outstandingDebt -``` - -where: - -- `outstandingDebt` is the CDP's `Principal` plus `AccumulatedFees` -- `periods` is the number of seconds since last fee update -- `feeRate` is the per second debt interest rate - -Fees are divided between surplus and savings rate. For example, if the savings rate is 0.95, 95% of all fees go towards the savings rate and 5% go to surplus. - -In the event that the rounded value of `feesAccumulated` is zero, fees are not updated, and the `FeesUpdated` value on the CDP struct is not updated. When a sufficient number of periods have passed such that the rounded value is no longer zero, fees will be updated. - -## Database Indexes - -When CDPs are update by the above messages the database indexes are also updated. diff --git a/x/cdp/spec/04_params.md b/x/cdp/spec/04_params.md deleted file mode 100644 index 70e4b16c..00000000 --- a/x/cdp/spec/04_params.md +++ /dev/null @@ -1,42 +0,0 @@ - - -# Parameters - -The cdp module contains the following parameters: - -| Key | Type | Example | Description | -|------------------------------|-------------------------|------------------------------------|------------------------------------------------------------------| -| CollateralParams | array (CollateralParam) | [{see below}] | array of params for each enabled collateral type | -| DebtParams | DebtParam | `{see below}` | array of params for each enabled pegged asset | -| GlobalDebtLimit | coin | `{"denom":"usdx","amount":"1000"}` | maximum pegged assets that can be minted across the whole system | -| SavingsDistributionFrequency | string (int) | "84600" | number of seconds between distribution of the savings rate | -| GlobalDebtLimit | coin | `{"denom":"usdx","amount":"1000"}` | maximum pegged assets that can be minted across the whole system | -| DebtAuctionThreshold | string (int) | "100000000000" | amount of system debt before a debt auction is triggered | -| SurplusAuctionThreshold | string (int) | "100000000000" | amount of system surplus before a surplus auction is triggered | -| DebtAuctionLot | string (int) | "10000000000" | amount of debt that each debt auction will attempt to recoup | -| SurplusAuctionLot | string (int) | "10000000000" | amount of surplus that will be sold at each surplus auction | - -Each CollateralParam has the following parameters: - -| Key | Type | Example | Description | -|---------------------|---------------|--------------------------------------------|-------------------------------------------------------------------------------| -| Denom | string | "bnb" | collateral coin denom | -| LiquidationRatio | string (dec) | "1.500000000000000000" | the ratio under which a cdp with this collateral type will be liquidated | -| DebtLimit | coin | `{"denom":"bnb","amount":"1000000000000"}` | maximum pegged asset that can be minted backed by this collateral type | -| StabilityFee | string (dec) | "1.000000001547126" | per second fee | -| Prefix | number (byte) | "34" | identifier used in store keys - **must** be unique across collateral types | -| SpotMarketID | string | "bnb:usd" | price feed identifier for the spot price of this collateral type | -| LiquidationMarketID | string | "bnb:usd:30" | price feed identifier for the liquidation price of this collateral type | -| ConversionFactor | string (int) | "6" | 10^_ multiplier for external (BTC1.50) to internal (150000000) representation | - -DebtParam has the following parameters: - -| Key | Type | Example | Description | -|------------------|--------------|------------|------------------------------------------------------------------------------------------------------------| -| Denom | string | "usdx" | pegged asset coin denom | -| ReferenceAsset | string | "USD" | asset this asset is pegged to, informational purposes only | -| ConversionFactor | string (int) | "6" | 10^_ multiplier to go from external amount (say $1.50) to internal representation of that amount (1500000) | -| DebtFloor | string (int) | "10000000" | minimum amount of debt that a CDP can contain | -| SavingsRate | string (dec) | "0.95" | the percentage of accumulated fees that go towards the savings rate | diff --git a/x/cdp/spec/05_events.md b/x/cdp/spec/05_events.md deleted file mode 100644 index d001d496..00000000 --- a/x/cdp/spec/05_events.md +++ /dev/null @@ -1,68 +0,0 @@ - - -# Events - -The cdp module emits the following events: - -## Handlers - -### MsgCreateCDP - -| Type | Attribute Key | Attribute Value | -|-------------|---------------|--------------------| -| message | module | cdp | -| message | sender | `{sender address}' | -| create_cdp | cdp_id | `{cdp id}' | -| cdp_deposit | cdp_id | `{cdp id}' | -| cdp_deposit | amount | `{deposit amount}' | -| cdp_draw | cdp_id | `{cdp id}' | -| cdp_draw | amount | `{draw amount}' | - -### MsgWithdraw - -| Type | Attribute Key | Attribute Value | -|---------|--------------- |-----------------------| -| message | cdp_withdrawal | `{collateral amount}' | -| message | cdp_id | `{cdp_id}' | -| message | module | cdp | -| message | sender | `{sender address}' | - -### MsgDeposit - -| Type | Attribute Key | Attribute Value | -|-------------|---------------|--------------------| -| message | module | cdp | -| message | sender | `{sender address}' | -| cdp_deposit | cdp_id | `{cdp id}' | -| cdp_deposit | amount | `{deposit amount}' | - -### MsgDrawDebt - -| Type | Attribute Key | Attribute Value | -|----------|---------------|--------------------| -| message | module | cdp | -| message | sender | `{sender address}' | -| cdp_draw | cdp_id | `{cdp id}' | -| cdp_draw | amount | `{draw amount}' | - -### MsgRepayDebt - -| Type | Attribute Key | Attribute Value | -|---------------|---------------|----------------------| -| cdp_repayment | amount | `{repayment amount}' | -| cdp_repayment | cdp_id | `{cdp id}' | -| cdp_close | cdp_id | `{cdp id}' | -| message | module | cdp | -| message | sender | `{sender address}' | - -## BeginBlock - -| Type | Attribute Key | Attribute Value | -|-------------------------|---------------|---------------------| -| cdp_liquidation | module | cdp | -| cdp_liquidation | cdp_id | `{cdp id}' | -| cdp_liquidation | deposit | `{deposit}' | -| cdp_begin_blocker_error | module | cdp | -| cdp_begin_blocker_error | error_message | `{error}' | diff --git a/x/cdp/spec/06_begin_block.md b/x/cdp/spec/06_begin_block.md deleted file mode 100644 index cae98e21..00000000 --- a/x/cdp/spec/06_begin_block.md +++ /dev/null @@ -1,46 +0,0 @@ - - -# Begin Block - -At the start of every block the BeginBlock of the cdp module: - -- updates the status of the pricefeed for each collateral asset -- If the pricefeed is active (reporting a price): - - updates fees for CDPs - - liquidates CDPs under the collateral ratio -- nets out system debt and, if necessary, starts auctions to re-balance it -- pays out the savings rate if sufficient time has past -- records the last savings rate distribution, if one occurred - -## Update Fees - -- The total fees accumulated since the last block for each CDP are calculated. -- If the fee amount is non-zero: - - Set the updated value for fees - - Set the fees updated time for the CDP to the current block time - - An equal amount of debt coins are minted and sent to the system's CDP module account. - - An equal amount of stable asset coins are minted and sent to the system's liquidator module account - - Increment total principal. - -## Liquidate CDP - -- Get every cdp that is under the liquidation ratio for its collateral type. -- For each cdp: - - Remove all collateral and internal debt coins from cdp and deposits and delete it. Send the coins to the liquidator module account. - - Start auctions of a fixed size from this collateral (with any remainder in a smaller sized auction), sending collateral and debt coins to the auction module account. - - Decrement total principal. - -## Net Out System Debt, Re-Balance - -- Burn the maximum possible equal amount of debt and stable asset from the liquidator module account. -- If there is enough debt remaining for an auction, start one. -- If there is enough surplus stable asset, minus surplus reserved for the savings rate, remaining for an auction, start one. -- Otherwise do nothing, leave debt/surplus to accumulate over subsequent blocks. - -## Distribute Surplus Stable Asset According to the Savings Rate - -- If `SavingsDistributionFrequency` seconds have elapsed since the previous distribution, the savings rate is applied to all accounts that hold stable asset. -- Each account that holds stable asset is distributed a ratable portion of the surplus that is apportioned to the savings rate. -- If distribution occurred, the time of the distribution is recorded. diff --git a/x/cdp/spec/README.md b/x/cdp/spec/README.md deleted file mode 100644 index 225f2d01..00000000 --- a/x/cdp/spec/README.md +++ /dev/null @@ -1,25 +0,0 @@ - - -# `cdp` - -## Table of Contents - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Parameters](04_params.md)** -5. **[Events](05_events.md)** -6. **[BeginBlock](06_begin_block.md)** - -## Overview - -The `x/cdp` module stores and manages Collateralized Debt Positions (or CDPs). - -A CDP enables the creation of a stable asset pegged to an external price (usually US Dollar) by collateralization with another asset. Collateral is locked in a CDP and new stable asset can be minted up to some fraction of the value of the collateral. To unlock the collateral, the debt must be repaid by returning some stable asset to the CDP at which point it will be burned and the collateral unlocked. - -Pegged assets remain fully collateralized by the value locked in CDPs. In the event of price changes, this collateral can be seized and sold off in auctions by the system to reclaim and reduce the supply of stable assets. diff --git a/x/cdp/types/cdp.go b/x/cdp/types/cdp.go deleted file mode 100644 index df38a9b3..00000000 --- a/x/cdp/types/cdp.go +++ /dev/null @@ -1,205 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "strings" - "time" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// NewCDP creates a new CDP object -func NewCDP(id uint64, owner sdk.AccAddress, collateral sdk.Coin, collateralType string, principal sdk.Coin, time time.Time, interestFactor sdk.Dec) CDP { - fees := sdk.NewCoin(principal.Denom, sdk.ZeroInt()) - return CDP{ - ID: id, - Owner: owner, - Type: collateralType, - Collateral: collateral, - Principal: principal, - AccumulatedFees: fees, - FeesUpdated: time, - InterestFactor: interestFactor, - } -} - -// NewCDPWithFees creates a new CDP object, for use during migration -func NewCDPWithFees(id uint64, owner sdk.AccAddress, collateral sdk.Coin, collateralType string, principal, fees sdk.Coin, time time.Time, interestFactor sdk.Dec) CDP { - return CDP{ - ID: id, - Owner: owner, - Type: collateralType, - Collateral: collateral, - Principal: principal, - AccumulatedFees: fees, - FeesUpdated: time, - InterestFactor: interestFactor, - } -} - -// Validate performs a basic validation of the CDP fields. -func (cdp CDP) Validate() error { - if cdp.ID == 0 { - return errors.New("cdp id cannot be 0") - } - if cdp.Owner.Empty() { - return errors.New("cdp owner cannot be empty") - } - if !cdp.Collateral.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "collateral %s", cdp.Collateral) - } - if !cdp.Principal.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "principal %s", cdp.Principal) - } - if !cdp.AccumulatedFees.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "accumulated fees %s", cdp.AccumulatedFees) - } - if cdp.FeesUpdated.Unix() <= 0 { - return errors.New("cdp updated fee time cannot be zero") - } - if strings.TrimSpace(cdp.Type) == "" { - return fmt.Errorf("cdp type cannot be empty") - } - return nil -} - -// GetTotalPrincipal returns the total principle for the cdp -func (cdp CDP) GetTotalPrincipal() sdk.Coin { - return cdp.Principal.Add(cdp.AccumulatedFees) -} - -// GetNormalizedPrincipal returns the total cdp principal divided by the interest factor. -// -// Multiplying the normalized principal by the current global factor gives the current debt (ie including all interest, ie a synced cdp). -// The normalized principal is effectively how big the principal would have been if it had been borrowed at time 0 and not touched since. -// -// An error is returned if the cdp interest factor is in an invalid state. -func (cdp CDP) GetNormalizedPrincipal() (sdk.Dec, error) { - unsyncedDebt := cdp.GetTotalPrincipal().Amount - if cdp.InterestFactor.LT(sdk.OneDec()) { - return sdk.Dec{}, fmt.Errorf("interest factor '%s' must be ≥ 1", cdp.InterestFactor) - } - return sdk.NewDecFromInt(unsyncedDebt).Quo(cdp.InterestFactor), nil -} - -// CDPs a collection of CDP objects -type CDPs []CDP - -// Validate validates each CDP -func (cdps CDPs) Validate() error { - for _, cdp := range cdps { - if err := cdp.Validate(); err != nil { - return err - } - } - return nil -} - -// AugmentedCDP provides additional information about an active CDP. -// This is only used for the legacy querier and legacy rest endpoints. -type AugmentedCDP struct { - CDP `json:"cdp" yaml:"cdp"` - CollateralValue sdk.Coin `json:"collateral_value" yaml:"collateral_value"` // collateral's market value in debt coin - CollateralizationRatio sdk.Dec `json:"collateralization_ratio" yaml:"collateralization_ratio"` // current collateralization ratio -} - -// NewAugmentedCDP creates a new AugmentedCDP object -func NewAugmentedCDP(cdp CDP, collateralValue sdk.Coin, collateralizationRatio sdk.Dec) AugmentedCDP { - augmentedCDP := AugmentedCDP{ - CDP: CDP{ - ID: cdp.ID, - Owner: cdp.Owner, - Type: cdp.Type, - Collateral: cdp.Collateral, - Principal: cdp.Principal, - AccumulatedFees: cdp.AccumulatedFees, - FeesUpdated: cdp.FeesUpdated, - InterestFactor: cdp.InterestFactor, - }, - CollateralValue: collateralValue, - CollateralizationRatio: collateralizationRatio, - } - return augmentedCDP -} - -// String implements fmt.stringer -func (augCDP AugmentedCDP) String() string { - return strings.TrimSpace(fmt.Sprintf(`AugmentedCDP: - Owner: %s - ID: %d - Collateral Type: %s - Collateral: %s - Collateral Value: %s - Principal: %s - Fees: %s - Fees Last Updated: %s - Interest Factor: %s - Collateralization ratio: %s`, - augCDP.Owner, - augCDP.ID, - augCDP.Type, - augCDP.Collateral, - augCDP.CollateralValue, - augCDP.Principal, - augCDP.AccumulatedFees, - augCDP.FeesUpdated, - augCDP.InterestFactor, - augCDP.CollateralizationRatio, - )) -} - -// AugmentedCDPs a collection of AugmentedCDP objects -type AugmentedCDPs []AugmentedCDP - -// String implements stringer -func (augcdps AugmentedCDPs) String() string { - out := "" - for _, augcdp := range augcdps { - out += augcdp.String() + "\n" - } - return out -} - -// NewCDPResponse creates a new CDPResponse object -func NewCDPResponse(cdp CDP, collateralValue sdk.Coin, collateralizationRatio sdk.Dec) CDPResponse { - return CDPResponse{ - ID: cdp.ID, - Owner: cdp.Owner.String(), - Type: cdp.Type, - Collateral: cdp.Collateral, - Principal: cdp.Principal, - AccumulatedFees: cdp.AccumulatedFees, - FeesUpdated: cdp.FeesUpdated, - InterestFactor: cdp.InterestFactor.String(), - CollateralValue: collateralValue, - CollateralizationRatio: collateralizationRatio.String(), - } -} - -// CDPResponses a collection of CDPResponse objects -type CDPResponses []CDPResponse - -// TotalPrincipals a collection of TotalPrincipal objects -type TotalPrincipals []TotalPrincipal - -// TotalPrincipal returns a new TotalPrincipal -func NewTotalPrincipal(collateralType string, amount sdk.Coin) TotalPrincipal { - return TotalPrincipal{ - CollateralType: collateralType, - Amount: amount, - } -} - -// TotalCollaterals a collection of TotalCollateral objects -type TotalCollaterals []TotalCollateral - -// TotalCollateral returns a new TotalCollateral -func NewTotalCollateral(collateralType string, amount sdk.Coin) TotalCollateral { - return TotalCollateral{ - CollateralType: collateralType, - Amount: amount, - } -} diff --git a/x/cdp/types/cdp.pb.go b/x/cdp/types/cdp.pb.go deleted file mode 100644 index a59e9caf..00000000 --- a/x/cdp/types/cdp.pb.go +++ /dev/null @@ -1,1528 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/cdp/v1beta1/cdp.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" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 - -// CDP defines the state of a single collateralized debt position. -type CDP struct { - ID uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` - Owner github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,2,opt,name=owner,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"owner,omitempty"` - Type string `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"` - Collateral types.Coin `protobuf:"bytes,4,opt,name=collateral,proto3" json:"collateral"` - Principal types.Coin `protobuf:"bytes,5,opt,name=principal,proto3" json:"principal"` - AccumulatedFees types.Coin `protobuf:"bytes,6,opt,name=accumulated_fees,json=accumulatedFees,proto3" json:"accumulated_fees"` - FeesUpdated time.Time `protobuf:"bytes,7,opt,name=fees_updated,json=feesUpdated,proto3,stdtime" json:"fees_updated"` - InterestFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,8,opt,name=interest_factor,json=interestFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"interest_factor"` -} - -func (m *CDP) Reset() { *m = CDP{} } -func (m *CDP) String() string { return proto.CompactTextString(m) } -func (*CDP) ProtoMessage() {} -func (*CDP) Descriptor() ([]byte, []int) { - return fileDescriptor_68a9ab097fb7be40, []int{0} -} -func (m *CDP) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CDP) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CDP.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 *CDP) XXX_Merge(src proto.Message) { - xxx_messageInfo_CDP.Merge(m, src) -} -func (m *CDP) XXX_Size() int { - return m.Size() -} -func (m *CDP) XXX_DiscardUnknown() { - xxx_messageInfo_CDP.DiscardUnknown(m) -} - -var xxx_messageInfo_CDP proto.InternalMessageInfo - -// Deposit defines an amount of coins deposited by an account to a cdp -type Deposit struct { - CdpID uint64 `protobuf:"varint,1,opt,name=cdp_id,json=cdpId,proto3" json:"cdp_id,omitempty"` - Depositor github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,2,opt,name=depositor,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"depositor,omitempty"` - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *Deposit) Reset() { *m = Deposit{} } -func (m *Deposit) String() string { return proto.CompactTextString(m) } -func (*Deposit) ProtoMessage() {} -func (*Deposit) Descriptor() ([]byte, []int) { - return fileDescriptor_68a9ab097fb7be40, []int{1} -} -func (m *Deposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Deposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Deposit.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 *Deposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_Deposit.Merge(m, src) -} -func (m *Deposit) XXX_Size() int { - return m.Size() -} -func (m *Deposit) XXX_DiscardUnknown() { - xxx_messageInfo_Deposit.DiscardUnknown(m) -} - -var xxx_messageInfo_Deposit proto.InternalMessageInfo - -// TotalPrincipal defines the total principal of a given collateral type -type TotalPrincipal struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Amount types.Coin `protobuf:"bytes,2,opt,name=amount,proto3" json:"amount"` -} - -func (m *TotalPrincipal) Reset() { *m = TotalPrincipal{} } -func (m *TotalPrincipal) String() string { return proto.CompactTextString(m) } -func (*TotalPrincipal) ProtoMessage() {} -func (*TotalPrincipal) Descriptor() ([]byte, []int) { - return fileDescriptor_68a9ab097fb7be40, []int{2} -} -func (m *TotalPrincipal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TotalPrincipal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TotalPrincipal.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 *TotalPrincipal) XXX_Merge(src proto.Message) { - xxx_messageInfo_TotalPrincipal.Merge(m, src) -} -func (m *TotalPrincipal) XXX_Size() int { - return m.Size() -} -func (m *TotalPrincipal) XXX_DiscardUnknown() { - xxx_messageInfo_TotalPrincipal.DiscardUnknown(m) -} - -var xxx_messageInfo_TotalPrincipal proto.InternalMessageInfo - -// TotalCollateral defines the total collateral of a given collateral type -type TotalCollateral struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Amount types.Coin `protobuf:"bytes,2,opt,name=amount,proto3" json:"amount"` -} - -func (m *TotalCollateral) Reset() { *m = TotalCollateral{} } -func (m *TotalCollateral) String() string { return proto.CompactTextString(m) } -func (*TotalCollateral) ProtoMessage() {} -func (*TotalCollateral) Descriptor() ([]byte, []int) { - return fileDescriptor_68a9ab097fb7be40, []int{3} -} -func (m *TotalCollateral) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TotalCollateral) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TotalCollateral.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 *TotalCollateral) XXX_Merge(src proto.Message) { - xxx_messageInfo_TotalCollateral.Merge(m, src) -} -func (m *TotalCollateral) XXX_Size() int { - return m.Size() -} -func (m *TotalCollateral) XXX_DiscardUnknown() { - xxx_messageInfo_TotalCollateral.DiscardUnknown(m) -} - -var xxx_messageInfo_TotalCollateral proto.InternalMessageInfo - -// OwnerCDPIndex defines the cdp ids for a single cdp owner -type OwnerCDPIndex struct { - CdpIDs []uint64 `protobuf:"varint,1,rep,packed,name=cdp_ids,json=cdpIds,proto3" json:"cdp_ids,omitempty"` -} - -func (m *OwnerCDPIndex) Reset() { *m = OwnerCDPIndex{} } -func (m *OwnerCDPIndex) String() string { return proto.CompactTextString(m) } -func (*OwnerCDPIndex) ProtoMessage() {} -func (*OwnerCDPIndex) Descriptor() ([]byte, []int) { - return fileDescriptor_68a9ab097fb7be40, []int{4} -} -func (m *OwnerCDPIndex) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *OwnerCDPIndex) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_OwnerCDPIndex.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 *OwnerCDPIndex) XXX_Merge(src proto.Message) { - xxx_messageInfo_OwnerCDPIndex.Merge(m, src) -} -func (m *OwnerCDPIndex) XXX_Size() int { - return m.Size() -} -func (m *OwnerCDPIndex) XXX_DiscardUnknown() { - xxx_messageInfo_OwnerCDPIndex.DiscardUnknown(m) -} - -var xxx_messageInfo_OwnerCDPIndex proto.InternalMessageInfo - -func init() { - proto.RegisterType((*CDP)(nil), "kava.cdp.v1beta1.CDP") - proto.RegisterType((*Deposit)(nil), "kava.cdp.v1beta1.Deposit") - proto.RegisterType((*TotalPrincipal)(nil), "kava.cdp.v1beta1.TotalPrincipal") - proto.RegisterType((*TotalCollateral)(nil), "kava.cdp.v1beta1.TotalCollateral") - proto.RegisterType((*OwnerCDPIndex)(nil), "kava.cdp.v1beta1.OwnerCDPIndex") -} - -func init() { proto.RegisterFile("kava/cdp/v1beta1/cdp.proto", fileDescriptor_68a9ab097fb7be40) } - -var fileDescriptor_68a9ab097fb7be40 = []byte{ - // 613 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x54, 0xcf, 0x6e, 0xd3, 0x30, - 0x1c, 0xae, 0xbb, 0x36, 0x5b, 0xbd, 0xb1, 0x4e, 0x06, 0xa1, 0xac, 0x87, 0xa4, 0x1a, 0x02, 0x7a, - 0x69, 0xa2, 0x01, 0x12, 0x17, 0x10, 0x5a, 0x1a, 0x0d, 0xca, 0x85, 0x29, 0x1a, 0x17, 0x0e, 0x54, - 0xae, 0xed, 0x96, 0x68, 0x69, 0x1c, 0xc5, 0xee, 0xd8, 0x1e, 0x02, 0x69, 0x0f, 0xb3, 0x87, 0xd8, - 0x81, 0xc3, 0xb4, 0x13, 0xe2, 0x10, 0x20, 0x7b, 0x0b, 0x4e, 0xc8, 0x4e, 0xba, 0xec, 0x58, 0x24, - 0x38, 0xf5, 0xf7, 0xc7, 0xdf, 0xf7, 0x73, 0x7f, 0xdf, 0x17, 0xc3, 0xce, 0x11, 0x3e, 0xc6, 0x2e, - 0xa1, 0x89, 0x7b, 0xbc, 0x3b, 0x66, 0x12, 0xef, 0xaa, 0xd8, 0x49, 0x52, 0x2e, 0x39, 0xda, 0x52, - 0x3d, 0x47, 0xe5, 0x65, 0xaf, 0x63, 0x11, 0x2e, 0x66, 0x5c, 0xb8, 0x63, 0x2c, 0x58, 0x05, 0xe0, - 0x61, 0x5c, 0x20, 0x3a, 0xdb, 0x45, 0x7f, 0xa4, 0x33, 0xb7, 0x48, 0xca, 0xd6, 0xbd, 0x29, 0x9f, - 0xf2, 0xa2, 0xae, 0xa2, 0xb2, 0x6a, 0x4f, 0x39, 0x9f, 0x46, 0xcc, 0xd5, 0xd9, 0x78, 0x3e, 0x71, - 0x65, 0x38, 0x63, 0x42, 0xe2, 0x59, 0x79, 0x87, 0x9d, 0x2f, 0x0d, 0xb8, 0x32, 0xf0, 0x0f, 0xd0, - 0x7d, 0x58, 0x0f, 0xa9, 0x09, 0xba, 0xa0, 0xd7, 0xf0, 0x8c, 0x3c, 0xb3, 0xeb, 0x43, 0x3f, 0xa8, - 0x87, 0x14, 0x7d, 0x84, 0x4d, 0xfe, 0x39, 0x66, 0xa9, 0x59, 0xef, 0x82, 0xde, 0x86, 0xf7, 0xe6, - 0x77, 0x66, 0xf7, 0xa7, 0xa1, 0xfc, 0x34, 0x1f, 0x3b, 0x84, 0xcf, 0xca, 0x2b, 0x94, 0x3f, 0x7d, - 0x41, 0x8f, 0x5c, 0x79, 0x9a, 0x30, 0xe1, 0xec, 0x11, 0xb2, 0x47, 0x69, 0xca, 0x84, 0xb8, 0x3a, - 0xef, 0xdf, 0x2d, 0x2f, 0x5a, 0x56, 0xbc, 0x53, 0xc9, 0x44, 0x50, 0xd0, 0x22, 0x04, 0x1b, 0x0a, - 0x61, 0xae, 0x74, 0x41, 0xaf, 0x15, 0xe8, 0x18, 0xbd, 0x82, 0x90, 0xf0, 0x28, 0xc2, 0x92, 0xa5, - 0x38, 0x32, 0x1b, 0x5d, 0xd0, 0x5b, 0x7f, 0xb2, 0xed, 0x94, 0x24, 0x6a, 0x35, 0x8b, 0x7d, 0x39, - 0x03, 0x1e, 0xc6, 0x5e, 0xe3, 0x22, 0xb3, 0x6b, 0xc1, 0x2d, 0x08, 0x7a, 0x09, 0x5b, 0x49, 0x1a, - 0xc6, 0x24, 0x4c, 0x70, 0x64, 0x36, 0x97, 0xc3, 0x57, 0x08, 0xf4, 0x16, 0x6e, 0x61, 0x42, 0xe6, - 0xb3, 0xb9, 0xe2, 0xa3, 0xa3, 0x09, 0x63, 0xc2, 0x34, 0x96, 0x63, 0x69, 0xdf, 0x02, 0xee, 0x33, - 0x26, 0xd0, 0x6b, 0xb8, 0xa1, 0xf0, 0xa3, 0x79, 0x42, 0x55, 0xcd, 0x5c, 0xd5, 0x3c, 0x1d, 0xa7, - 0xd0, 0xc5, 0x59, 0xe8, 0xe2, 0x1c, 0x2e, 0x74, 0xf1, 0xd6, 0x14, 0xd1, 0xd9, 0x0f, 0x1b, 0x04, - 0xeb, 0x0a, 0xf9, 0xbe, 0x00, 0x22, 0x06, 0xdb, 0x61, 0x2c, 0x59, 0xca, 0x84, 0x1c, 0x4d, 0x30, - 0x91, 0x3c, 0x35, 0xd7, 0xd4, 0xce, 0xbc, 0x17, 0xea, 0xfc, 0xf7, 0xcc, 0x7e, 0xb4, 0x84, 0x2c, - 0x3e, 0x23, 0x57, 0xe7, 0x7d, 0x58, 0xfe, 0x09, 0x9f, 0x91, 0x60, 0x73, 0x41, 0xba, 0xaf, 0x39, - 0x77, 0xbe, 0x02, 0xb8, 0xea, 0xb3, 0x84, 0x8b, 0x50, 0xa2, 0x2e, 0x34, 0x08, 0x4d, 0x46, 0x37, - 0xbe, 0x68, 0xe5, 0x99, 0xdd, 0x1c, 0xd0, 0x64, 0xe8, 0x07, 0x4d, 0x42, 0x93, 0x21, 0x45, 0x13, - 0xd8, 0xa2, 0xc5, 0x61, 0x5e, 0x38, 0xa4, 0xf5, 0x0f, 0x1d, 0x52, 0x51, 0xa3, 0xe7, 0xd0, 0xc0, - 0x33, 0x3e, 0x8f, 0xa5, 0xf6, 0xc9, 0x12, 0x3a, 0x94, 0xc7, 0x77, 0x52, 0xb8, 0x79, 0xc8, 0x25, - 0x8e, 0x0e, 0x6e, 0xc4, 0x7d, 0x0c, 0xdb, 0x95, 0x53, 0x46, 0xda, 0x7b, 0x40, 0x7b, 0x6f, 0xb3, - 0x2a, 0x1f, 0x2a, 0x17, 0x56, 0x33, 0xeb, 0x7f, 0x37, 0x53, 0xc0, 0xb6, 0x9e, 0x39, 0xa8, 0x0c, - 0xf9, 0xff, 0x87, 0x3e, 0x83, 0x77, 0xde, 0xa9, 0x0f, 0x6a, 0xe0, 0x1f, 0x0c, 0x63, 0xca, 0x4e, - 0xd0, 0x03, 0xb8, 0x5a, 0x88, 0x27, 0x4c, 0xd0, 0x5d, 0xe9, 0x35, 0x3c, 0x98, 0x67, 0xb6, 0xa1, - 0xd5, 0x13, 0x81, 0xa1, 0xe5, 0x13, 0xde, 0xe0, 0xe2, 0x97, 0x55, 0xbb, 0xc8, 0x2d, 0x70, 0x99, - 0x5b, 0xe0, 0x67, 0x6e, 0x81, 0xb3, 0x6b, 0xab, 0x76, 0x79, 0x6d, 0xd5, 0xbe, 0x5d, 0x5b, 0xb5, - 0x0f, 0x0f, 0x6f, 0xc9, 0xa8, 0x9e, 0xaa, 0x7e, 0x84, 0xc7, 0x42, 0x47, 0xee, 0x89, 0x7e, 0xd2, - 0xb4, 0x92, 0x63, 0x43, 0x9b, 0xf8, 0xe9, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x95, 0xe3, 0x65, - 0xc4, 0xeb, 0x04, 0x00, 0x00, -} - -func (m *CDP) 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 *CDP) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CDP) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.InterestFactor.Size() - i -= size - if _, err := m.InterestFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintCdp(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.FeesUpdated, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.FeesUpdated):]) - if err1 != nil { - return 0, err1 - } - i -= n1 - i = encodeVarintCdp(dAtA, i, uint64(n1)) - i-- - dAtA[i] = 0x3a - { - size, err := m.AccumulatedFees.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintCdp(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.Principal.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintCdp(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.Collateral.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintCdp(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - if len(m.Type) > 0 { - i -= len(m.Type) - copy(dAtA[i:], m.Type) - i = encodeVarintCdp(dAtA, i, uint64(len(m.Type))) - i-- - dAtA[i] = 0x1a - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintCdp(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if m.ID != 0 { - i = encodeVarintCdp(dAtA, i, uint64(m.ID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *Deposit) 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 *Deposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Deposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintCdp(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintCdp(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0x12 - } - if m.CdpID != 0 { - i = encodeVarintCdp(dAtA, i, uint64(m.CdpID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *TotalPrincipal) 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 *TotalPrincipal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TotalPrincipal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintCdp(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintCdp(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *TotalCollateral) 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 *TotalCollateral) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TotalCollateral) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintCdp(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintCdp(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *OwnerCDPIndex) 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 *OwnerCDPIndex) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *OwnerCDPIndex) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CdpIDs) > 0 { - dAtA9 := make([]byte, len(m.CdpIDs)*10) - var j8 int - for _, num := range m.CdpIDs { - for num >= 1<<7 { - dAtA9[j8] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j8++ - } - dAtA9[j8] = uint8(num) - j8++ - } - i -= j8 - copy(dAtA[i:], dAtA9[:j8]) - i = encodeVarintCdp(dAtA, i, uint64(j8)) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintCdp(dAtA []byte, offset int, v uint64) int { - offset -= sovCdp(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *CDP) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.ID != 0 { - n += 1 + sovCdp(uint64(m.ID)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovCdp(uint64(l)) - } - l = len(m.Type) - if l > 0 { - n += 1 + l + sovCdp(uint64(l)) - } - l = m.Collateral.Size() - n += 1 + l + sovCdp(uint64(l)) - l = m.Principal.Size() - n += 1 + l + sovCdp(uint64(l)) - l = m.AccumulatedFees.Size() - n += 1 + l + sovCdp(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.FeesUpdated) - n += 1 + l + sovCdp(uint64(l)) - l = m.InterestFactor.Size() - n += 1 + l + sovCdp(uint64(l)) - return n -} - -func (m *Deposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CdpID != 0 { - n += 1 + sovCdp(uint64(m.CdpID)) - } - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovCdp(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovCdp(uint64(l)) - return n -} - -func (m *TotalPrincipal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovCdp(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovCdp(uint64(l)) - return n -} - -func (m *TotalCollateral) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovCdp(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovCdp(uint64(l)) - return n -} - -func (m *OwnerCDPIndex) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.CdpIDs) > 0 { - l = 0 - for _, e := range m.CdpIDs { - l += sovCdp(uint64(e)) - } - n += 1 + sovCdp(uint64(l)) + l - } - return n -} - -func sovCdp(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozCdp(x uint64) (n int) { - return sovCdp(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *CDP) 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 ErrIntOverflowCdp - } - 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: CDP: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CDP: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - m.ID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = append(m.Owner[:0], dAtA[iNdEx:postIndex]...) - if m.Owner == nil { - m.Owner = []byte{} - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - 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 ErrInvalidLengthCdp - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Type = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Collateral", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Collateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Principal", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Principal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AccumulatedFees", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.AccumulatedFees.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FeesUpdated", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.FeesUpdated, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InterestFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - 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 ErrInvalidLengthCdp - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.InterestFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipCdp(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthCdp - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Deposit) 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 ErrIntOverflowCdp - } - 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: Deposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Deposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CdpID", wireType) - } - m.CdpID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CdpID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - 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 ErrInvalidLengthCdp - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = github_com_cosmos_cosmos_sdk_types.AccAddress(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipCdp(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthCdp - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TotalPrincipal) 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 ErrIntOverflowCdp - } - 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: TotalPrincipal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TotalPrincipal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - 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 ErrInvalidLengthCdp - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipCdp(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthCdp - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TotalCollateral) 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 ErrIntOverflowCdp - } - 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: TotalCollateral: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TotalCollateral: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - 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 ErrInvalidLengthCdp - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipCdp(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthCdp - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *OwnerCDPIndex) 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 ErrIntOverflowCdp - } - 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: OwnerCDPIndex: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: OwnerCDPIndex: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType == 0 { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CdpIDs = append(m.CdpIDs, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - var count int - for _, integer := range dAtA[iNdEx:postIndex] { - if integer < 128 { - count++ - } - } - elementCount = count - if elementCount != 0 && len(m.CdpIDs) == 0 { - m.CdpIDs = make([]uint64, 0, elementCount) - } - for iNdEx < postIndex { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CdpIDs = append(m.CdpIDs, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field CdpIDs", wireType) - } - default: - iNdEx = preIndex - skippy, err := skipCdp(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthCdp - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipCdp(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, ErrIntOverflowCdp - } - 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, ErrIntOverflowCdp - } - 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, ErrIntOverflowCdp - } - 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, ErrInvalidLengthCdp - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupCdp - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthCdp - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthCdp = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowCdp = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupCdp = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/cdp/types/cdp_test.go b/x/cdp/types/cdp_test.go deleted file mode 100644 index 424899b6..00000000 --- a/x/cdp/types/cdp_test.go +++ /dev/null @@ -1,243 +0,0 @@ -package types_test - -import ( - "math/rand" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/cometbft/cometbft/crypto/secp256k1" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/x/cdp/types" -) - -type CdpValidationSuite struct { - suite.Suite - - addrs []sdk.AccAddress -} - -func (suite *CdpValidationSuite) SetupTest() { - r := rand.New(rand.NewSource(12345)) - privkeySeed := make([]byte, 15) - r.Read(privkeySeed) - addr := sdk.AccAddress(secp256k1.GenPrivKeySecp256k1(privkeySeed).PubKey().Address()) - suite.addrs = []sdk.AccAddress{addr} -} - -func (suite *CdpValidationSuite) TestCdpValidation() { - type errArgs struct { - expectPass bool - msg string - } - testCases := []struct { - name string - cdp types.CDP - errArgs errArgs - }{ - { - name: "valid cdp", - cdp: types.NewCDP(1, suite.addrs[0], sdk.NewInt64Coin("bnb", 100000), "bnb-a", sdk.NewInt64Coin("usdx", 100000), tmtime.Now(), sdk.OneDec()), - errArgs: errArgs{ - expectPass: true, - msg: "", - }, - }, - { - name: "invalid cdp id", - cdp: types.NewCDP(0, suite.addrs[0], sdk.NewInt64Coin("bnb", 100000), "bnb-a", sdk.NewInt64Coin("usdx", 100000), tmtime.Now(), sdk.OneDec()), - errArgs: errArgs{ - expectPass: false, - msg: "cdp id cannot be 0", - }, - }, - { - name: "invalid collateral", - cdp: types.CDP{1, suite.addrs[0], "bnb-a", sdk.Coin{"", sdkmath.NewInt(100)}, sdk.Coin{"usdx", sdkmath.NewInt(100)}, sdk.Coin{"usdx", sdkmath.NewInt(0)}, tmtime.Now(), sdk.OneDec()}, - errArgs: errArgs{ - expectPass: false, - msg: "collateral 100: invalid coins", - }, - }, - { - name: "invalid principal", - cdp: types.CDP{1, suite.addrs[0], "xrp-a", sdk.Coin{"xrp", sdkmath.NewInt(100)}, sdk.Coin{"", sdkmath.NewInt(100)}, sdk.Coin{"usdx", sdkmath.NewInt(0)}, tmtime.Now(), sdk.OneDec()}, - errArgs: errArgs{ - expectPass: false, - msg: "principal 100: invalid coins", - }, - }, - { - name: "invalid fees", - cdp: types.CDP{1, suite.addrs[0], "xrp-a", sdk.Coin{"xrp", sdkmath.NewInt(100)}, sdk.Coin{"usdx", sdkmath.NewInt(100)}, sdk.Coin{"", sdkmath.NewInt(0)}, tmtime.Now(), sdk.OneDec()}, - errArgs: errArgs{ - expectPass: false, - msg: "accumulated fees 0: invalid coins", - }, - }, - { - name: "invalid fees updated", - cdp: types.CDP{1, suite.addrs[0], "xrp-a", sdk.Coin{"xrp", sdkmath.NewInt(100)}, sdk.Coin{"usdx", sdkmath.NewInt(100)}, sdk.Coin{"usdx", sdkmath.NewInt(0)}, time.Time{}, sdk.OneDec()}, - errArgs: errArgs{ - expectPass: false, - msg: "cdp updated fee time cannot be zero", - }, - }, - { - name: "invalid type", - cdp: types.CDP{1, suite.addrs[0], "", sdk.Coin{"xrp", sdkmath.NewInt(100)}, sdk.Coin{"usdx", sdkmath.NewInt(100)}, sdk.Coin{"usdx", sdkmath.NewInt(0)}, tmtime.Now(), sdk.OneDec()}, - errArgs: errArgs{ - expectPass: false, - msg: "cdp type cannot be empty", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - err := tc.cdp.Validate() - if tc.errArgs.expectPass { - suite.Require().NoError(err, tc.name) - } else { - suite.Require().Error(err, tc.name) - suite.Require().Equal(err.Error(), tc.errArgs.msg) - } - }) - } -} - -func (suite *CdpValidationSuite) TestDepositValidation() { - type errArgs struct { - expectPass bool - msg string - } - testCases := []struct { - name string - deposit types.Deposit - errArgs errArgs - }{ - { - name: "valid deposit", - deposit: types.NewDeposit(1, suite.addrs[0], sdk.NewInt64Coin("bnb", 1000000)), - errArgs: errArgs{ - expectPass: true, - msg: "", - }, - }, - { - name: "invalid cdp id", - deposit: types.NewDeposit(0, suite.addrs[0], sdk.NewInt64Coin("bnb", 1000000)), - errArgs: errArgs{ - expectPass: false, - msg: "deposit's cdp id cannot be 0", - }, - }, - { - name: "empty depositor", - deposit: types.NewDeposit(1, sdk.AccAddress{}, sdk.NewInt64Coin("bnb", 1000000)), - errArgs: errArgs{ - expectPass: false, - msg: "depositor cannot be empty", - }, - }, - { - name: "invalid deposit coins", - deposit: types.NewDeposit(1, suite.addrs[0], sdk.Coin{Denom: "Invalid Denom", Amount: sdkmath.NewInt(1000000)}), - errArgs: errArgs{ - expectPass: false, - msg: "deposit 1000000Invalid Denom: invalid coins", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - err := tc.deposit.Validate() - if tc.errArgs.expectPass { - suite.Require().NoError(err, tc.name) - } else { - suite.Require().Error(err, tc.name) - suite.Require().Equal(err.Error(), tc.errArgs.msg) - } - }) - } -} - -func (suite *CdpValidationSuite) TestCdpGetTotalPrinciple() { - principal := sdk.Coin{"usdx", sdkmath.NewInt(100500)} - accumulatedFees := sdk.Coin{"usdx", sdkmath.NewInt(25000)} - - cdp := types.CDP{Principal: principal, AccumulatedFees: accumulatedFees} - - suite.Require().Equal(cdp.GetTotalPrincipal(), principal.Add(accumulatedFees)) -} - -func (suite *CdpValidationSuite) TestCDPGetNormalizedPrincipal() { - type expectedErr struct { - expectPass bool - contains string - } - testCases := []struct { - name string - cdp types.CDP - expected sdk.Dec - expectedErr expectedErr - }{ - { - name: "principal + fees is divided by factor correctly", - cdp: types.CDP{ - Principal: sdk.NewInt64Coin("usdx", 1e9), - AccumulatedFees: sdk.NewInt64Coin("usdx", 1e6), - InterestFactor: sdk.MustNewDecFromStr("2"), - }, - expected: sdk.MustNewDecFromStr("500500000"), - expectedErr: expectedErr{ - expectPass: true, - }, - }, - { - name: "factor < 1 returns error", - cdp: types.CDP{ - Principal: sdk.NewInt64Coin("usdx", 1e9), - AccumulatedFees: sdk.NewInt64Coin("usdx", 1e6), - InterestFactor: sdk.MustNewDecFromStr("0.999999999999999999"), - }, - expectedErr: expectedErr{ - contains: "must be ≥ 1", - }, - }, - { - name: "0 factor returns error rather than div by 0 panic", - cdp: types.CDP{ - Principal: sdk.NewInt64Coin("usdx", 1e9), - AccumulatedFees: sdk.NewInt64Coin("usdx", 1e6), - InterestFactor: sdk.MustNewDecFromStr("0"), - }, - expectedErr: expectedErr{ - contains: "must be ≥ 1", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - np, err := tc.cdp.GetNormalizedPrincipal() - - if tc.expectedErr.expectPass { - suite.Require().NoError(err, tc.name) - suite.Equal(tc.expected, np) - } else { - suite.Require().Error(err, tc.name) - suite.Contains(err.Error(), tc.expectedErr.contains) - } - }) - } -} - -func TestCdpValidationSuite(t *testing.T) { - suite.Run(t, new(CdpValidationSuite)) -} diff --git a/x/cdp/types/codec.go b/x/cdp/types/codec.go deleted file mode 100644 index 08066e63..00000000 --- a/x/cdp/types/codec.go +++ /dev/null @@ -1,48 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the -// governance module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgCreateCDP{}, "cdp/MsgCreateCDP", nil) - cdc.RegisterConcrete(&MsgDeposit{}, "cdp/MsgDeposit", nil) - cdc.RegisterConcrete(&MsgWithdraw{}, "cdp/MsgWithdraw", nil) - cdc.RegisterConcrete(&MsgDrawDebt{}, "cdp/MsgDrawDebt", nil) - cdc.RegisterConcrete(&MsgRepayDebt{}, "cdp/MsgRepayDebt", nil) - cdc.RegisterConcrete(&MsgLiquidate{}, "cdp/MsgLiquidate", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgCreateCDP{}, - &MsgDeposit{}, - &MsgWithdraw{}, - &MsgDrawDebt{}, - &MsgRepayDebt{}, - &MsgLiquidate{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/cdp/types/deposit.go b/x/cdp/types/deposit.go deleted file mode 100644 index 5104ffcc..00000000 --- a/x/cdp/types/deposit.go +++ /dev/null @@ -1,63 +0,0 @@ -package types - -import ( - "errors" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// NewDeposit creates a new Deposit object -func NewDeposit(cdpID uint64, depositor sdk.AccAddress, amount sdk.Coin) Deposit { - return Deposit{cdpID, depositor, amount} -} - -// Validate performs a basic validation of the deposit fields. -func (d Deposit) Validate() error { - if d.CdpID == 0 { - return errors.New("deposit's cdp id cannot be 0") - } - if d.Depositor.Empty() { - return errors.New("depositor cannot be empty") - } - if !d.Amount.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "deposit %s", d.Amount) - } - return nil -} - -// Deposits a collection of Deposit objects -type Deposits []Deposit - -// Validate validates each deposit -func (ds Deposits) Validate() error { - for _, d := range ds { - if err := d.Validate(); err != nil { - return err - } - } - return nil -} - -// Equals returns whether two deposits are equal. -func (d Deposit) Equals(comp Deposit) bool { - return d.Depositor.Equals(comp.Depositor) && d.CdpID == comp.CdpID && d.Amount.IsEqual(comp.Amount) -} - -// Empty returns whether a deposit is empty. -func (d Deposit) Empty() bool { - return d.Equals(Deposit{}) -} - -// SumCollateral returns the total amount of collateral in the input deposits -func (ds Deposits) SumCollateral() (sum sdkmath.Int) { - sum = sdk.ZeroInt() - for _, d := range ds { - if !d.Amount.IsZero() { - sum = sum.Add(d.Amount.Amount) - } - } - return -} diff --git a/x/cdp/types/errors.go b/x/cdp/types/errors.go deleted file mode 100644 index da31d130..00000000 --- a/x/cdp/types/errors.go +++ /dev/null @@ -1,52 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// DONTCOVER - -var ( - // ErrCdpAlreadyExists error for duplicate cdps - ErrCdpAlreadyExists = errorsmod.Register(ModuleName, 2, "cdp already exists") - // ErrInvalidCollateralLength error for invalid collateral input length - ErrInvalidCollateralLength = errorsmod.Register(ModuleName, 3, "only one collateral type per cdp") - // ErrCollateralNotSupported error for unsupported collateral - ErrCollateralNotSupported = errorsmod.Register(ModuleName, 4, "collateral not supported") - // ErrDebtNotSupported error for unsupported debt - ErrDebtNotSupported = errorsmod.Register(ModuleName, 5, "debt not supported") - // ErrExceedsDebtLimit error for attempted draws that exceed debt limit - ErrExceedsDebtLimit = errorsmod.Register(ModuleName, 6, "proposed debt increase would exceed debt limit") - // ErrInvalidCollateralRatio error for attempted draws that are below liquidation ratio - ErrInvalidCollateralRatio = errorsmod.Register(ModuleName, 7, "proposed collateral ratio is below liquidation ratio") - // ErrCdpNotFound error cdp not found - ErrCdpNotFound = errorsmod.Register(ModuleName, 8, "cdp not found") - // ErrDepositNotFound error for deposit not found - ErrDepositNotFound = errorsmod.Register(ModuleName, 9, "deposit not found") - // ErrInvalidDeposit error for invalid deposit - ErrInvalidDeposit = errorsmod.Register(ModuleName, 10, "invalid deposit") - // ErrInvalidPayment error for invalid payment - ErrInvalidPayment = errorsmod.Register(ModuleName, 11, "invalid payment") - // ErrDepositNotAvailable error for withdrawing deposits in liquidation - ErrDepositNotAvailable = errorsmod.Register(ModuleName, 12, "deposit in liquidation") - // ErrInvalidWithdrawAmount error for invalid withdrawal amount - ErrInvalidWithdrawAmount = errorsmod.Register(ModuleName, 13, "withdrawal amount exceeds deposit") - // ErrCdpNotAvailable error for depositing to a CDP in liquidation - ErrCdpNotAvailable = errorsmod.Register(ModuleName, 14, "cannot modify cdp in liquidation") - // ErrBelowDebtFloor error for creating a cdp with debt below the minimum - ErrBelowDebtFloor = errorsmod.Register(ModuleName, 15, "proposed cdp debt is below minimum") - // ErrLoadingAugmentedCDP error loading augmented cdp - ErrLoadingAugmentedCDP = errorsmod.Register(ModuleName, 16, "augmented cdp could not be loaded from cdp") - // ErrInvalidDebtRequest error for invalid principal input length - ErrInvalidDebtRequest = errorsmod.Register(ModuleName, 17, "only one principal type per cdp") - // ErrDenomPrefixNotFound error for denom prefix not found - ErrDenomPrefixNotFound = errorsmod.Register(ModuleName, 18, "denom prefix not found") - // ErrPricefeedDown error for when a price for the input denom is not found - ErrPricefeedDown = errorsmod.Register(ModuleName, 19, "no price found for collateral") - // ErrInvalidCollateral error for when the input collateral denom does not match the expected collateral denom - ErrInvalidCollateral = errorsmod.Register(ModuleName, 20, "invalid collateral for input collateral type") - // ErrAccountNotFound error for when no account is found for an input address - ErrAccountNotFound = errorsmod.Register(ModuleName, 21, "account not found") - // ErrInsufficientBalance error for when an account does not have enough funds - ErrInsufficientBalance = errorsmod.Register(ModuleName, 22, "insufficient balance") - // ErrNotLiquidatable error for when an cdp is not liquidatable - ErrNotLiquidatable = errorsmod.Register(ModuleName, 23, "cdp collateral ratio not below liquidation ratio") -) diff --git a/x/cdp/types/events.go b/x/cdp/types/events.go deleted file mode 100644 index 793fe55a..00000000 --- a/x/cdp/types/events.go +++ /dev/null @@ -1,18 +0,0 @@ -package types - -// Event types for cdp module -const ( - EventTypeCreateCdp = "create_cdp" - EventTypeCdpDeposit = "cdp_deposit" - EventTypeCdpDraw = "cdp_draw" - EventTypeCdpRepay = "cdp_repayment" - EventTypeCdpClose = "cdp_close" - EventTypeCdpWithdrawal = "cdp_withdrawal" - EventTypeCdpLiquidation = "cdp_liquidation" - EventTypeBeginBlockerFatal = "cdp_begin_block_error" - - AttributeKeyCdpID = "cdp_id" - AttributeKeyDeposit = "deposit" - AttributeValueCategory = "cdp" - AttributeKeyError = "error_message" -) diff --git a/x/cdp/types/expected_keepers.go b/x/cdp/types/expected_keepers.go deleted file mode 100644 index d956ee3e..00000000 --- a/x/cdp/types/expected_keepers.go +++ /dev/null @@ -1,62 +0,0 @@ -package types - -import ( - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - pftypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -// BankKeeper defines the expected bank keeper for module accounts -type BankKeeper interface { - 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 - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error - MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - - GetSupply(ctx sdk.Context, denom string) sdk.Coin - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins -} - -var _ BankKeeper = (bankkeeper.Keeper)(nil) - -// PricefeedKeeper defines the expected interface for the pricefeed -type PricefeedKeeper interface { - GetCurrentPrice(sdk.Context, string) (pftypes.CurrentPrice, error) - GetParams(sdk.Context) pftypes.Params - // These are used for testing TODO replace mockApp with keeper in tests to remove these - SetParams(sdk.Context, pftypes.Params) - SetPrice(sdk.Context, sdk.AccAddress, string, sdk.Dec, time.Time) (pftypes.PostedPrice, error) - SetCurrentPrices(sdk.Context, string) error -} - -// AuctionKeeper expected interface for the auction keeper -type AuctionKeeper interface { - StartSurplusAuction(ctx sdk.Context, seller string, lot sdk.Coin, bidDenom string) (uint64, error) - StartDebtAuction(ctx sdk.Context, buyer string, bid sdk.Coin, initialLot sdk.Coin, debt sdk.Coin) (uint64, error) - StartCollateralAuction(ctx sdk.Context, seller string, lot sdk.Coin, maxBid sdk.Coin, lotReturnAddrs []sdk.AccAddress, lotReturnWeights []sdkmath.Int, debt sdk.Coin) (uint64, error) -} - -// AccountKeeper expected interface for the account keeper -type AccountKeeper interface { - GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, name string) authtypes.ModuleAccountI - // TODO remove with genesis 2-phases refactor https://github.com/cosmos/cosmos-sdk/issues/2862 - SetModuleAccount(sdk.Context, authtypes.ModuleAccountI) - - IterateAccounts(ctx sdk.Context, cb func(account authtypes.AccountI) (stop bool)) - GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI -} - -// CDPHooks event hooks for other keepers to run code in response to CDP modifications -type CDPHooks interface { - AfterCDPCreated(ctx sdk.Context, cdp CDP) - BeforeCDPModified(ctx sdk.Context, cdp CDP) -} diff --git a/x/cdp/types/genesis.go b/x/cdp/types/genesis.go deleted file mode 100644 index cf51b7a2..00000000 --- a/x/cdp/types/genesis.go +++ /dev/null @@ -1,138 +0,0 @@ -package types - -import ( - "fmt" - "strings" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewGenesisState returns a new genesis state -func NewGenesisState(params Params, cdps CDPs, deposits Deposits, startingCdpID uint64, - debtDenom, govDenom string, prevAccumTimes GenesisAccumulationTimes, - totalPrincipals GenesisTotalPrincipals, -) GenesisState { - return GenesisState{ - Params: params, - CDPs: cdps, - Deposits: deposits, - StartingCdpID: startingCdpID, - DebtDenom: debtDenom, - GovDenom: govDenom, - PreviousAccumulationTimes: prevAccumTimes, - TotalPrincipals: totalPrincipals, - } -} - -// DefaultGenesisState returns a default genesis state -func DefaultGenesisState() GenesisState { - return NewGenesisState( - DefaultParams(), - CDPs{}, - Deposits{}, - DefaultCdpStartingID, - DefaultDebtDenom, - DefaultGovDenom, - GenesisAccumulationTimes{}, - GenesisTotalPrincipals{}, - ) -} - -// Validate performs basic validation of genesis data returning an -// error for any failed validation criteria. -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - - if err := gs.CDPs.Validate(); err != nil { - return err - } - - if err := gs.Deposits.Validate(); err != nil { - return err - } - - if err := gs.PreviousAccumulationTimes.Validate(); err != nil { - return err - } - - if err := gs.TotalPrincipals.Validate(); err != nil { - return err - } - - if err := sdk.ValidateDenom(gs.DebtDenom); err != nil { - return fmt.Errorf(fmt.Sprintf("debt denom invalid: %v", err)) - } - - if err := sdk.ValidateDenom(gs.GovDenom); err != nil { - return fmt.Errorf(fmt.Sprintf("gov denom invalid: %v", err)) - } - - return nil -} - -// NewGenesisTotalPrincipal returns a new GenesisTotalPrincipal -func NewGenesisTotalPrincipal(ctype string, principal sdkmath.Int) GenesisTotalPrincipal { - return GenesisTotalPrincipal{ - CollateralType: ctype, - TotalPrincipal: principal, - } -} - -// GenesisTotalPrincipals slice of GenesisTotalPrincipal -type GenesisTotalPrincipals []GenesisTotalPrincipal - -// Validate performs validation of GenesisTotalPrincipal -func (gtp GenesisTotalPrincipal) Validate() error { - if strings.TrimSpace(gtp.CollateralType) == "" { - return fmt.Errorf("collateral type cannot be empty") - } - - if gtp.TotalPrincipal.IsNegative() { - return fmt.Errorf("total principal should be positive, is %s for %s", gtp.TotalPrincipal, gtp.CollateralType) - } - return nil -} - -// Validate performs validation of GenesisTotalPrincipals -func (gtps GenesisTotalPrincipals) Validate() error { - for _, gtp := range gtps { - if err := gtp.Validate(); err != nil { - return err - } - } - return nil -} - -// NewGenesisAccumulationTime returns a new GenesisAccumulationTime -func NewGenesisAccumulationTime(ctype string, prevTime time.Time, factor sdk.Dec) GenesisAccumulationTime { - return GenesisAccumulationTime{ - CollateralType: ctype, - PreviousAccumulationTime: prevTime, - InterestFactor: factor, - } -} - -// Validate performs validation of GenesisAccumulationTime -func (gat GenesisAccumulationTime) Validate() error { - if gat.InterestFactor.LT(sdk.OneDec()) { - return fmt.Errorf("interest factor should be ≥ 1.0, is %s for %s", gat.InterestFactor, gat.CollateralType) - } - return nil -} - -// GenesisAccumulationTimes slice of GenesisAccumulationTime -type GenesisAccumulationTimes []GenesisAccumulationTime - -// Validate performs validation of GenesisAccumulationTimes -func (gats GenesisAccumulationTimes) Validate() error { - for _, gat := range gats { - if err := gat.Validate(); err != nil { - return err - } - } - return nil -} diff --git a/x/cdp/types/genesis.pb.go b/x/cdp/types/genesis.pb.go deleted file mode 100644 index 49ba9a75..00000000 --- a/x/cdp/types/genesis.pb.go +++ /dev/null @@ -1,2838 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/cdp/v1beta1/genesis.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" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 cdp module's genesis state. -type GenesisState struct { - // params defines all the parameters of the module. - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - CDPs CDPs `protobuf:"bytes,2,rep,name=cdps,proto3,castrepeated=CDPs" json:"cdps"` - Deposits Deposits `protobuf:"bytes,3,rep,name=deposits,proto3,castrepeated=Deposits" json:"deposits"` - StartingCdpID uint64 `protobuf:"varint,4,opt,name=starting_cdp_id,json=startingCdpId,proto3" json:"starting_cdp_id,omitempty"` - DebtDenom string `protobuf:"bytes,5,opt,name=debt_denom,json=debtDenom,proto3" json:"debt_denom,omitempty"` - GovDenom string `protobuf:"bytes,6,opt,name=gov_denom,json=govDenom,proto3" json:"gov_denom,omitempty"` - PreviousAccumulationTimes GenesisAccumulationTimes `protobuf:"bytes,7,rep,name=previous_accumulation_times,json=previousAccumulationTimes,proto3,castrepeated=GenesisAccumulationTimes" json:"previous_accumulation_times"` - TotalPrincipals GenesisTotalPrincipals `protobuf:"bytes,8,rep,name=total_principals,json=totalPrincipals,proto3,castrepeated=GenesisTotalPrincipals" json:"total_principals"` -} - -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_e4494a90aaab0034, []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) GetCDPs() CDPs { - if m != nil { - return m.CDPs - } - return nil -} - -func (m *GenesisState) GetDeposits() Deposits { - if m != nil { - return m.Deposits - } - return nil -} - -func (m *GenesisState) GetStartingCdpID() uint64 { - if m != nil { - return m.StartingCdpID - } - return 0 -} - -func (m *GenesisState) GetDebtDenom() string { - if m != nil { - return m.DebtDenom - } - return "" -} - -func (m *GenesisState) GetGovDenom() string { - if m != nil { - return m.GovDenom - } - return "" -} - -func (m *GenesisState) GetPreviousAccumulationTimes() GenesisAccumulationTimes { - if m != nil { - return m.PreviousAccumulationTimes - } - return nil -} - -func (m *GenesisState) GetTotalPrincipals() GenesisTotalPrincipals { - if m != nil { - return m.TotalPrincipals - } - return nil -} - -// Params defines the parameters for the cdp module. -type Params struct { - CollateralParams CollateralParams `protobuf:"bytes,1,rep,name=collateral_params,json=collateralParams,proto3,castrepeated=CollateralParams" json:"collateral_params"` - DebtParam DebtParam `protobuf:"bytes,2,opt,name=debt_param,json=debtParam,proto3" json:"debt_param"` - GlobalDebtLimit types.Coin `protobuf:"bytes,3,opt,name=global_debt_limit,json=globalDebtLimit,proto3" json:"global_debt_limit"` - SurplusAuctionThreshold github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,4,opt,name=surplus_auction_threshold,json=surplusAuctionThreshold,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"surplus_auction_threshold"` - SurplusAuctionLot github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,5,opt,name=surplus_auction_lot,json=surplusAuctionLot,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"surplus_auction_lot"` - DebtAuctionThreshold github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,6,opt,name=debt_auction_threshold,json=debtAuctionThreshold,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"debt_auction_threshold"` - DebtAuctionLot github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,7,opt,name=debt_auction_lot,json=debtAuctionLot,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"debt_auction_lot"` - CircuitBreaker bool `protobuf:"varint,8,opt,name=circuit_breaker,json=circuitBreaker,proto3" json:"circuit_breaker,omitempty"` - LiquidationBlockInterval int64 `protobuf:"varint,9,opt,name=liquidation_block_interval,json=liquidationBlockInterval,proto3" json:"liquidation_block_interval,omitempty"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_e4494a90aaab0034, []int{1} -} -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 (m *Params) GetCollateralParams() CollateralParams { - if m != nil { - return m.CollateralParams - } - return nil -} - -func (m *Params) GetDebtParam() DebtParam { - if m != nil { - return m.DebtParam - } - return DebtParam{} -} - -func (m *Params) GetGlobalDebtLimit() types.Coin { - if m != nil { - return m.GlobalDebtLimit - } - return types.Coin{} -} - -func (m *Params) GetCircuitBreaker() bool { - if m != nil { - return m.CircuitBreaker - } - return false -} - -func (m *Params) GetLiquidationBlockInterval() int64 { - if m != nil { - return m.LiquidationBlockInterval - } - return 0 -} - -// DebtParam defines governance params for debt assets -type DebtParam struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - ReferenceAsset string `protobuf:"bytes,2,opt,name=reference_asset,json=referenceAsset,proto3" json:"reference_asset,omitempty"` - ConversionFactor github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=conversion_factor,json=conversionFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"conversion_factor"` - DebtFloor github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,4,opt,name=debt_floor,json=debtFloor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"debt_floor"` -} - -func (m *DebtParam) Reset() { *m = DebtParam{} } -func (m *DebtParam) String() string { return proto.CompactTextString(m) } -func (*DebtParam) ProtoMessage() {} -func (*DebtParam) Descriptor() ([]byte, []int) { - return fileDescriptor_e4494a90aaab0034, []int{2} -} -func (m *DebtParam) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DebtParam) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DebtParam.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 *DebtParam) XXX_Merge(src proto.Message) { - xxx_messageInfo_DebtParam.Merge(m, src) -} -func (m *DebtParam) XXX_Size() int { - return m.Size() -} -func (m *DebtParam) XXX_DiscardUnknown() { - xxx_messageInfo_DebtParam.DiscardUnknown(m) -} - -var xxx_messageInfo_DebtParam proto.InternalMessageInfo - -func (m *DebtParam) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *DebtParam) GetReferenceAsset() string { - if m != nil { - return m.ReferenceAsset - } - return "" -} - -// CollateralParam defines governance parameters for each collateral type within the cdp module -type CollateralParam struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Type string `protobuf:"bytes,2,opt,name=type,proto3" json:"type,omitempty"` - LiquidationRatio github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=liquidation_ratio,json=liquidationRatio,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"liquidation_ratio"` - DebtLimit types.Coin `protobuf:"bytes,4,opt,name=debt_limit,json=debtLimit,proto3" json:"debt_limit"` - StabilityFee github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=stability_fee,json=stabilityFee,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"stability_fee"` - AuctionSize github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,6,opt,name=auction_size,json=auctionSize,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"auction_size"` - LiquidationPenalty github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,7,opt,name=liquidation_penalty,json=liquidationPenalty,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"liquidation_penalty"` - SpotMarketID string `protobuf:"bytes,8,opt,name=spot_market_id,json=spotMarketId,proto3" json:"spot_market_id,omitempty"` - LiquidationMarketID string `protobuf:"bytes,9,opt,name=liquidation_market_id,json=liquidationMarketId,proto3" json:"liquidation_market_id,omitempty"` - KeeperRewardPercentage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,10,opt,name=keeper_reward_percentage,json=keeperRewardPercentage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"keeper_reward_percentage"` - CheckCollateralizationIndexCount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,11,opt,name=check_collateralization_index_count,json=checkCollateralizationIndexCount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"check_collateralization_index_count"` - ConversionFactor github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,12,opt,name=conversion_factor,json=conversionFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"conversion_factor"` -} - -func (m *CollateralParam) Reset() { *m = CollateralParam{} } -func (m *CollateralParam) String() string { return proto.CompactTextString(m) } -func (*CollateralParam) ProtoMessage() {} -func (*CollateralParam) Descriptor() ([]byte, []int) { - return fileDescriptor_e4494a90aaab0034, []int{3} -} -func (m *CollateralParam) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CollateralParam) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CollateralParam.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 *CollateralParam) XXX_Merge(src proto.Message) { - xxx_messageInfo_CollateralParam.Merge(m, src) -} -func (m *CollateralParam) XXX_Size() int { - return m.Size() -} -func (m *CollateralParam) XXX_DiscardUnknown() { - xxx_messageInfo_CollateralParam.DiscardUnknown(m) -} - -var xxx_messageInfo_CollateralParam proto.InternalMessageInfo - -func (m *CollateralParam) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *CollateralParam) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -func (m *CollateralParam) GetDebtLimit() types.Coin { - if m != nil { - return m.DebtLimit - } - return types.Coin{} -} - -func (m *CollateralParam) GetSpotMarketID() string { - if m != nil { - return m.SpotMarketID - } - return "" -} - -func (m *CollateralParam) GetLiquidationMarketID() string { - if m != nil { - return m.LiquidationMarketID - } - return "" -} - -// GenesisAccumulationTime defines the previous distribution time and its corresponding denom -type GenesisAccumulationTime struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - PreviousAccumulationTime time.Time `protobuf:"bytes,2,opt,name=previous_accumulation_time,json=previousAccumulationTime,proto3,stdtime" json:"previous_accumulation_time"` - InterestFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=interest_factor,json=interestFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"interest_factor"` -} - -func (m *GenesisAccumulationTime) Reset() { *m = GenesisAccumulationTime{} } -func (m *GenesisAccumulationTime) String() string { return proto.CompactTextString(m) } -func (*GenesisAccumulationTime) ProtoMessage() {} -func (*GenesisAccumulationTime) Descriptor() ([]byte, []int) { - return fileDescriptor_e4494a90aaab0034, []int{4} -} -func (m *GenesisAccumulationTime) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisAccumulationTime) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisAccumulationTime.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 *GenesisAccumulationTime) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisAccumulationTime.Merge(m, src) -} -func (m *GenesisAccumulationTime) XXX_Size() int { - return m.Size() -} -func (m *GenesisAccumulationTime) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisAccumulationTime.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisAccumulationTime proto.InternalMessageInfo - -func (m *GenesisAccumulationTime) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func (m *GenesisAccumulationTime) GetPreviousAccumulationTime() time.Time { - if m != nil { - return m.PreviousAccumulationTime - } - return time.Time{} -} - -// GenesisTotalPrincipal defines the total principal and its corresponding collateral type -type GenesisTotalPrincipal struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - TotalPrincipal github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=total_principal,json=totalPrincipal,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"total_principal"` -} - -func (m *GenesisTotalPrincipal) Reset() { *m = GenesisTotalPrincipal{} } -func (m *GenesisTotalPrincipal) String() string { return proto.CompactTextString(m) } -func (*GenesisTotalPrincipal) ProtoMessage() {} -func (*GenesisTotalPrincipal) Descriptor() ([]byte, []int) { - return fileDescriptor_e4494a90aaab0034, []int{5} -} -func (m *GenesisTotalPrincipal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisTotalPrincipal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisTotalPrincipal.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 *GenesisTotalPrincipal) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisTotalPrincipal.Merge(m, src) -} -func (m *GenesisTotalPrincipal) XXX_Size() int { - return m.Size() -} -func (m *GenesisTotalPrincipal) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisTotalPrincipal.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisTotalPrincipal proto.InternalMessageInfo - -func (m *GenesisTotalPrincipal) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.cdp.v1beta1.GenesisState") - proto.RegisterType((*Params)(nil), "kava.cdp.v1beta1.Params") - proto.RegisterType((*DebtParam)(nil), "kava.cdp.v1beta1.DebtParam") - proto.RegisterType((*CollateralParam)(nil), "kava.cdp.v1beta1.CollateralParam") - proto.RegisterType((*GenesisAccumulationTime)(nil), "kava.cdp.v1beta1.GenesisAccumulationTime") - proto.RegisterType((*GenesisTotalPrincipal)(nil), "kava.cdp.v1beta1.GenesisTotalPrincipal") -} - -func init() { proto.RegisterFile("kava/cdp/v1beta1/genesis.proto", fileDescriptor_e4494a90aaab0034) } - -var fileDescriptor_e4494a90aaab0034 = []byte{ - // 1208 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x57, 0xdd, 0x6e, 0x1a, 0xc7, - 0x17, 0xf7, 0xda, 0xc4, 0x81, 0xb1, 0x63, 0xf0, 0xc4, 0x49, 0xd6, 0x8e, 0xfe, 0xc0, 0xdf, 0x55, - 0x1b, 0x7a, 0x11, 0x50, 0x52, 0x29, 0x52, 0xa5, 0xa8, 0x69, 0xd6, 0x28, 0x11, 0x4a, 0x2a, 0xa1, - 0xb5, 0xaf, 0xda, 0x8b, 0xd5, 0xec, 0xec, 0x80, 0x47, 0x2c, 0x3b, 0xdb, 0x99, 0x81, 0x26, 0x79, - 0x85, 0xaa, 0x6a, 0xd4, 0x97, 0xa8, 0x14, 0xf5, 0xb2, 0x0f, 0x91, 0xde, 0x45, 0xbd, 0xaa, 0x7a, - 0x41, 0x2a, 0xf2, 0x22, 0xd5, 0x7c, 0x00, 0x6b, 0x30, 0x52, 0x64, 0xd3, 0x1b, 0x76, 0xe7, 0x7c, - 0xfc, 0xce, 0xc7, 0x9c, 0x73, 0xf6, 0x00, 0xca, 0x3d, 0x34, 0x44, 0x0d, 0x1c, 0xa5, 0x8d, 0xe1, - 0xbd, 0x90, 0x48, 0x74, 0xaf, 0xd1, 0x25, 0x09, 0x11, 0x54, 0xd4, 0x53, 0xce, 0x24, 0x83, 0x25, - 0xc5, 0xaf, 0xe3, 0x28, 0xad, 0x5b, 0xfe, 0x41, 0x19, 0x33, 0xd1, 0x67, 0xa2, 0x11, 0x22, 0x41, - 0xa6, 0x4a, 0x98, 0xd1, 0xc4, 0x68, 0x1c, 0xec, 0x1b, 0x7e, 0xa0, 0x4f, 0x0d, 0x73, 0xb0, 0xac, - 0xbd, 0x2e, 0xeb, 0x32, 0x43, 0x57, 0x6f, 0x96, 0x5a, 0xe9, 0x32, 0xd6, 0x8d, 0x49, 0x43, 0x9f, - 0xc2, 0x41, 0xa7, 0x21, 0x69, 0x9f, 0x08, 0x89, 0xfa, 0xa9, 0x15, 0x38, 0x58, 0xf0, 0x51, 0xf9, - 0xa3, 0x79, 0x87, 0x7f, 0xe4, 0xc0, 0xf6, 0x53, 0xe3, 0xf1, 0xb1, 0x44, 0x92, 0xc0, 0x07, 0x60, - 0x33, 0x45, 0x1c, 0xf5, 0x85, 0xeb, 0x54, 0x9d, 0xda, 0xd6, 0x7d, 0xb7, 0x3e, 0x1f, 0x41, 0xbd, - 0xad, 0xf9, 0x5e, 0xee, 0xed, 0xa8, 0xb2, 0xe6, 0x5b, 0x69, 0xf8, 0x08, 0xe4, 0x70, 0x94, 0x0a, - 0x77, 0xbd, 0xba, 0x51, 0xdb, 0xba, 0x7f, 0x63, 0x51, 0xeb, 0xa8, 0xd9, 0xf6, 0xf6, 0x94, 0xca, - 0x78, 0x54, 0xc9, 0x1d, 0x35, 0xdb, 0xe2, 0xcd, 0x7b, 0xf3, 0xf4, 0xb5, 0x22, 0x7c, 0x0a, 0xf2, - 0x11, 0x49, 0x99, 0xa0, 0x52, 0xb8, 0x1b, 0x1a, 0x64, 0x7f, 0x11, 0xa4, 0x69, 0x24, 0xbc, 0x92, - 0x02, 0x7a, 0xf3, 0xbe, 0x92, 0xb7, 0x04, 0xe1, 0x4f, 0x95, 0xe1, 0x97, 0xa0, 0x28, 0x24, 0xe2, - 0x92, 0x26, 0xdd, 0x00, 0x47, 0x69, 0x40, 0x23, 0x37, 0x57, 0x75, 0x6a, 0x39, 0x6f, 0x77, 0x3c, - 0xaa, 0x5c, 0x3b, 0xb6, 0xac, 0xa3, 0x28, 0x6d, 0x35, 0xfd, 0x6b, 0x22, 0x73, 0x8c, 0xe0, 0xff, - 0x00, 0x88, 0x48, 0x28, 0x83, 0x88, 0x24, 0xac, 0xef, 0x5e, 0xa9, 0x3a, 0xb5, 0x82, 0x5f, 0x50, - 0x94, 0xa6, 0x22, 0xc0, 0xdb, 0xa0, 0xd0, 0x65, 0x43, 0xcb, 0xdd, 0xd4, 0xdc, 0x7c, 0x97, 0x0d, - 0x0d, 0xf3, 0x47, 0x07, 0xdc, 0x4e, 0x39, 0x19, 0x52, 0x36, 0x10, 0x01, 0xc2, 0x78, 0xd0, 0x1f, - 0xc4, 0x48, 0x52, 0x96, 0x04, 0xfa, 0x3e, 0xdc, 0xab, 0x3a, 0xa6, 0xcf, 0x17, 0x63, 0xb2, 0xe9, - 0x7f, 0x9c, 0x51, 0x39, 0xa1, 0x7d, 0xe2, 0x55, 0x6d, 0x8c, 0xee, 0x12, 0x01, 0xe1, 0xef, 0x4f, - 0xec, 0x2d, 0xb0, 0x20, 0x07, 0x25, 0xc9, 0x24, 0x8a, 0x83, 0x94, 0xd3, 0x04, 0xd3, 0x14, 0xc5, - 0xc2, 0xcd, 0x6b, 0x0f, 0xee, 0x2c, 0xf5, 0xe0, 0x44, 0x29, 0xb4, 0x27, 0xf2, 0x5e, 0xd9, 0xda, - 0xbf, 0x79, 0x2e, 0x5b, 0xf8, 0x45, 0x79, 0x96, 0x70, 0xf8, 0xdb, 0x26, 0xd8, 0x34, 0xb5, 0x01, - 0x4f, 0xc1, 0x2e, 0x66, 0x71, 0x8c, 0x24, 0xe1, 0xca, 0x87, 0x49, 0x41, 0x29, 0xfb, 0xff, 0x3f, - 0xa7, 0x34, 0xa6, 0xa2, 0x5a, 0xdd, 0x73, 0xad, 0xe5, 0xd2, 0x1c, 0x43, 0xf8, 0x25, 0x3c, 0x47, - 0x81, 0x5f, 0xdb, 0x2b, 0xd3, 0x36, 0xdc, 0x75, 0x5d, 0xb3, 0xb7, 0xcf, 0x2b, 0x9c, 0x50, 0x1a, - 0x70, 0x53, 0xb6, 0xfa, 0x56, 0x35, 0x01, 0x3e, 0x03, 0xbb, 0xdd, 0x98, 0x85, 0x28, 0x0e, 0x34, - 0x50, 0x4c, 0xfb, 0x54, 0xba, 0x1b, 0x1a, 0x68, 0xbf, 0x6e, 0xfb, 0x4f, 0x35, 0x6b, 0xc6, 0x5d, - 0x9a, 0x58, 0x98, 0xa2, 0xd1, 0x54, 0xe8, 0xcf, 0x95, 0x1e, 0x7c, 0x01, 0xf6, 0xc5, 0x80, 0xa7, - 0xb1, 0xaa, 0x81, 0x01, 0x36, 0xd7, 0x7f, 0xca, 0x89, 0x38, 0x65, 0xb1, 0x29, 0xc3, 0x82, 0xf7, - 0x50, 0x69, 0xfe, 0x3d, 0xaa, 0x7c, 0xd6, 0xa5, 0xf2, 0x74, 0x10, 0xd6, 0x31, 0xeb, 0xdb, 0x36, - 0xb7, 0x8f, 0xbb, 0x22, 0xea, 0x35, 0xe4, 0xcb, 0x94, 0x88, 0x7a, 0x2b, 0x91, 0x7f, 0xfe, 0x7e, - 0x17, 0x58, 0x2f, 0x5a, 0x89, 0xf4, 0x6f, 0x59, 0xf8, 0xc7, 0x06, 0xfd, 0x64, 0x02, 0x0e, 0x63, - 0x70, 0x7d, 0xde, 0x72, 0xcc, 0xa4, 0x29, 0xe2, 0x4b, 0xda, 0xdc, 0x3d, 0x6b, 0xf3, 0x39, 0x93, - 0x90, 0x83, 0x9b, 0x3a, 0x5b, 0x8b, 0x41, 0x6e, 0xae, 0xc0, 0xe0, 0x9e, 0xc2, 0x5e, 0x88, 0xb0, - 0x03, 0x4a, 0x67, 0x6c, 0xaa, 0xf0, 0xae, 0xae, 0xc0, 0xda, 0x4e, 0xc6, 0x9a, 0x8a, 0xed, 0x0e, - 0x28, 0x62, 0xca, 0xf1, 0x80, 0xca, 0x20, 0xe4, 0x04, 0xf5, 0x08, 0x77, 0xf3, 0x55, 0xa7, 0x96, - 0xf7, 0x77, 0x2c, 0xd9, 0x33, 0x54, 0xf8, 0x10, 0x1c, 0xc4, 0xf4, 0xfb, 0x01, 0x8d, 0x4c, 0x9f, - 0x87, 0x31, 0xc3, 0xbd, 0x80, 0x26, 0x92, 0xf0, 0x21, 0x8a, 0xdd, 0x42, 0xd5, 0xa9, 0x6d, 0xf8, - 0x6e, 0x46, 0xc2, 0x53, 0x02, 0x2d, 0xcb, 0x3f, 0xfc, 0x65, 0x1d, 0x14, 0xa6, 0x65, 0x09, 0xf7, - 0xc0, 0x15, 0x33, 0x57, 0x1c, 0x3d, 0x57, 0xcc, 0x41, 0xb9, 0xc2, 0x49, 0x87, 0x70, 0x92, 0x60, - 0x12, 0x20, 0x21, 0x88, 0xd4, 0x25, 0x5e, 0xf0, 0x77, 0xa6, 0xe4, 0xc7, 0x8a, 0x0a, 0xa9, 0x6a, - 0xb8, 0x64, 0x48, 0xb8, 0x50, 0x9e, 0x74, 0x10, 0x96, 0x8c, 0xeb, 0x22, 0xbe, 0x6c, 0x72, 0x4a, - 0x33, 0xd8, 0x27, 0x1a, 0x15, 0x7e, 0x67, 0x3b, 0xae, 0x13, 0x33, 0xc6, 0x57, 0x52, 0xd3, 0xba, - 0x19, 0x9f, 0x28, 0xb8, 0xc3, 0x9f, 0xf3, 0xa0, 0x38, 0xd7, 0xf5, 0x4b, 0x52, 0x03, 0x41, 0x4e, - 0xe1, 0xd9, 0x7c, 0xe8, 0x77, 0x95, 0x85, 0xec, 0x85, 0x70, 0xf5, 0xb8, 0x40, 0x16, 0x9a, 0x04, - 0x67, 0x3c, 0x6c, 0x12, 0xec, 0x97, 0x32, 0xb0, 0xbe, 0xfa, 0x85, 0x5f, 0xd9, 0x2c, 0x98, 0x71, - 0x91, 0xfb, 0xb8, 0x71, 0xa1, 0x03, 0x35, 0x83, 0x02, 0x01, 0xf5, 0xed, 0x09, 0x69, 0x4c, 0xe5, - 0xcb, 0xa0, 0x43, 0xc8, 0x05, 0x1a, 0x75, 0xd1, 0xcd, 0xed, 0x29, 0xe4, 0x13, 0x42, 0x60, 0x00, - 0xb6, 0x27, 0xad, 0x22, 0xe8, 0x2b, 0xb2, 0x92, 0xce, 0xdc, 0xb2, 0x88, 0xc7, 0xf4, 0x15, 0x81, - 0x7d, 0x70, 0x3d, 0x9b, 0xee, 0x94, 0x24, 0x28, 0x96, 0x2f, 0x2f, 0xd0, 0x93, 0x8b, 0x91, 0xc0, - 0x0c, 0x70, 0xdb, 0xe0, 0xc2, 0x07, 0x60, 0x47, 0xa4, 0x4c, 0x06, 0x7d, 0xc4, 0x7b, 0x44, 0xaa, - 0xef, 0x7a, 0x5e, 0x5b, 0x2a, 0x8d, 0x47, 0x95, 0xed, 0xe3, 0x94, 0xc9, 0x6f, 0x34, 0xa3, 0xd5, - 0xf4, 0xb7, 0xc5, 0xec, 0x14, 0xc1, 0x67, 0xe0, 0x46, 0xd6, 0xcd, 0x99, 0x7a, 0x41, 0xab, 0xdf, - 0x1a, 0x8f, 0x2a, 0xd7, 0x9f, 0xcf, 0x04, 0xa6, 0x28, 0xd9, 0xe0, 0xa6, 0x60, 0x43, 0xe0, 0xf6, - 0x08, 0x49, 0x09, 0x0f, 0x38, 0xf9, 0x01, 0xf1, 0x28, 0x48, 0x09, 0xc7, 0x24, 0x91, 0xa8, 0x4b, - 0x5c, 0xb0, 0x82, 0xc0, 0x6f, 0x1a, 0x74, 0x5f, 0x83, 0xb7, 0xa7, 0xd8, 0x6a, 0xbd, 0xf8, 0x04, - 0x9f, 0x12, 0xdc, 0x0b, 0x66, 0x9f, 0x40, 0xfa, 0xca, 0x44, 0x44, 0x93, 0x88, 0xbc, 0x08, 0x30, - 0x1b, 0x24, 0xd2, 0xdd, 0x5a, 0xc1, 0x25, 0x57, 0xb5, 0xa1, 0xa3, 0x79, 0x3b, 0x2d, 0x65, 0xe6, - 0x48, 0x59, 0x39, 0x7f, 0xdc, 0x6c, 0xff, 0x17, 0xe3, 0xe6, 0xf0, 0xa7, 0x75, 0x70, 0x6b, 0xc9, - 0x06, 0xa4, 0x27, 0xf5, 0x6c, 0xcd, 0xd0, 0xe3, 0xc0, 0xcc, 0x88, 0x9d, 0x19, 0xf9, 0x44, 0x0d, - 0x86, 0x10, 0x1c, 0x2c, 0xdf, 0xcd, 0xec, 0xd6, 0x70, 0x50, 0x37, 0x8b, 0x74, 0x7d, 0xb2, 0x48, - 0xd7, 0x4f, 0x26, 0x8b, 0xb4, 0x97, 0x57, 0x41, 0xbd, 0x7e, 0x5f, 0x71, 0x7c, 0x77, 0xd9, 0xce, - 0x05, 0x09, 0x28, 0xea, 0xd9, 0x4f, 0x84, 0xbc, 0xf8, 0x00, 0x5e, 0x2c, 0x88, 0x9d, 0x09, 0xa8, - 0xcd, 0xc7, 0xaf, 0x0e, 0xb8, 0x71, 0xee, 0x46, 0xf6, 0xf1, 0xd9, 0x20, 0xa0, 0x38, 0xb7, 0x1c, - 0x9a, 0x29, 0x7a, 0xd9, 0xef, 0xe8, 0xd9, 0x85, 0xd0, 0x7b, 0xf4, 0x76, 0x5c, 0x76, 0xde, 0x8d, - 0xcb, 0xce, 0x3f, 0xe3, 0xb2, 0xf3, 0xfa, 0x43, 0x79, 0xed, 0xdd, 0x87, 0xf2, 0xda, 0x5f, 0x1f, - 0xca, 0x6b, 0xdf, 0x7e, 0x9a, 0xc1, 0x57, 0xab, 0xda, 0xdd, 0x18, 0x85, 0x42, 0xbf, 0x35, 0x5e, - 0xe8, 0x3f, 0x2a, 0xda, 0x44, 0xb8, 0xa9, 0x6f, 0xe2, 0x8b, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, - 0x5c, 0xdf, 0x27, 0x18, 0x65, 0x0d, 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.TotalPrincipals) > 0 { - for iNdEx := len(m.TotalPrincipals) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TotalPrincipals[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - } - } - if len(m.PreviousAccumulationTimes) > 0 { - for iNdEx := len(m.PreviousAccumulationTimes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.PreviousAccumulationTimes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - } - if len(m.GovDenom) > 0 { - i -= len(m.GovDenom) - copy(dAtA[i:], m.GovDenom) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.GovDenom))) - i-- - dAtA[i] = 0x32 - } - if len(m.DebtDenom) > 0 { - i -= len(m.DebtDenom) - copy(dAtA[i:], m.DebtDenom) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.DebtDenom))) - i-- - dAtA[i] = 0x2a - } - if m.StartingCdpID != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.StartingCdpID)) - i-- - dAtA[i] = 0x20 - } - if len(m.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.CDPs) > 0 { - for iNdEx := len(m.CDPs) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.CDPs[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 (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 - if m.LiquidationBlockInterval != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.LiquidationBlockInterval)) - i-- - dAtA[i] = 0x48 - } - if m.CircuitBreaker { - i-- - if m.CircuitBreaker { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x40 - } - { - size := m.DebtAuctionLot.Size() - i -= size - if _, err := m.DebtAuctionLot.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - { - size := m.DebtAuctionThreshold.Size() - i -= size - if _, err := m.DebtAuctionThreshold.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size := m.SurplusAuctionLot.Size() - i -= size - if _, err := m.SurplusAuctionLot.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.SurplusAuctionThreshold.Size() - i -= size - if _, err := m.SurplusAuctionThreshold.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.GlobalDebtLimit.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.DebtParam.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.CollateralParams) > 0 { - for iNdEx := len(m.CollateralParams) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.CollateralParams[iNdEx].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 (m *DebtParam) 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 *DebtParam) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DebtParam) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.DebtFloor.Size() - i -= size - if _, err := m.DebtFloor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.ConversionFactor.Size() - i -= size - if _, err := m.ConversionFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.ReferenceAsset) > 0 { - i -= len(m.ReferenceAsset) - copy(dAtA[i:], m.ReferenceAsset) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.ReferenceAsset))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CollateralParam) 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 *CollateralParam) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CollateralParam) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.ConversionFactor.Size() - i -= size - if _, err := m.ConversionFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x62 - { - size := m.CheckCollateralizationIndexCount.Size() - i -= size - if _, err := m.CheckCollateralizationIndexCount.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x5a - { - size := m.KeeperRewardPercentage.Size() - i -= size - if _, err := m.KeeperRewardPercentage.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x52 - if len(m.LiquidationMarketID) > 0 { - i -= len(m.LiquidationMarketID) - copy(dAtA[i:], m.LiquidationMarketID) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.LiquidationMarketID))) - i-- - dAtA[i] = 0x4a - } - if len(m.SpotMarketID) > 0 { - i -= len(m.SpotMarketID) - copy(dAtA[i:], m.SpotMarketID) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.SpotMarketID))) - i-- - dAtA[i] = 0x42 - } - { - size := m.LiquidationPenalty.Size() - i -= size - if _, err := m.LiquidationPenalty.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - { - size := m.AuctionSize.Size() - i -= size - if _, err := m.AuctionSize.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size := m.StabilityFee.Size() - i -= size - if _, err := m.StabilityFee.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.DebtLimit.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.LiquidationRatio.Size() - i -= size - if _, err := m.LiquidationRatio.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Type) > 0 { - i -= len(m.Type) - copy(dAtA[i:], m.Type) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.Type))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *GenesisAccumulationTime) 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 *GenesisAccumulationTime) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisAccumulationTime) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.InterestFactor.Size() - i -= size - if _, err := m.InterestFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - n5, err5 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.PreviousAccumulationTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousAccumulationTime):]) - if err5 != nil { - return 0, err5 - } - i -= n5 - i = encodeVarintGenesis(dAtA, i, uint64(n5)) - i-- - dAtA[i] = 0x12 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *GenesisTotalPrincipal) 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 *GenesisTotalPrincipal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisTotalPrincipal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.TotalPrincipal.Size() - i -= size - if _, err := m.TotalPrincipal.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.CollateralType))) - 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.CDPs) > 0 { - for _, e := range m.CDPs { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.Deposits) > 0 { - for _, e := range m.Deposits { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if m.StartingCdpID != 0 { - n += 1 + sovGenesis(uint64(m.StartingCdpID)) - } - l = len(m.DebtDenom) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = len(m.GovDenom) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - if len(m.PreviousAccumulationTimes) > 0 { - for _, e := range m.PreviousAccumulationTimes { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.TotalPrincipals) > 0 { - for _, e := range m.TotalPrincipals { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.CollateralParams) > 0 { - for _, e := range m.CollateralParams { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - l = m.DebtParam.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.GlobalDebtLimit.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.SurplusAuctionThreshold.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.SurplusAuctionLot.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.DebtAuctionThreshold.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.DebtAuctionLot.Size() - n += 1 + l + sovGenesis(uint64(l)) - if m.CircuitBreaker { - n += 2 - } - if m.LiquidationBlockInterval != 0 { - n += 1 + sovGenesis(uint64(m.LiquidationBlockInterval)) - } - return n -} - -func (m *DebtParam) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = len(m.ReferenceAsset) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = m.ConversionFactor.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.DebtFloor.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *CollateralParam) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = len(m.Type) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = m.LiquidationRatio.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.DebtLimit.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.StabilityFee.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.AuctionSize.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.LiquidationPenalty.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = len(m.SpotMarketID) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = len(m.LiquidationMarketID) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = m.KeeperRewardPercentage.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.CheckCollateralizationIndexCount.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.ConversionFactor.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *GenesisAccumulationTime) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousAccumulationTime) - n += 1 + l + sovGenesis(uint64(l)) - l = m.InterestFactor.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *GenesisTotalPrincipal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = m.TotalPrincipal.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 CDPs", 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.CDPs = append(m.CDPs, CDP{}) - if err := m.CDPs[len(m.CDPs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposits", 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.Deposits = append(m.Deposits, Deposit{}) - if err := m.Deposits[len(m.Deposits)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field StartingCdpID", wireType) - } - m.StartingCdpID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.StartingCdpID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DebtDenom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DebtDenom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field GovDenom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.GovDenom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PreviousAccumulationTimes", 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.PreviousAccumulationTimes = append(m.PreviousAccumulationTimes, GenesisAccumulationTime{}) - if err := m.PreviousAccumulationTimes[len(m.PreviousAccumulationTimes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalPrincipals", 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.TotalPrincipals = append(m.TotalPrincipals, GenesisTotalPrincipal{}) - if err := m.TotalPrincipals[len(m.TotalPrincipals)-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 (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 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: 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 { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralParams", 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.CollateralParams = append(m.CollateralParams, CollateralParam{}) - if err := m.CollateralParams[len(m.CollateralParams)-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 DebtParam", 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.DebtParam.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field GlobalDebtLimit", 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.GlobalDebtLimit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SurplusAuctionThreshold", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SurplusAuctionThreshold.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SurplusAuctionLot", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SurplusAuctionLot.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DebtAuctionThreshold", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.DebtAuctionThreshold.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DebtAuctionLot", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.DebtAuctionLot.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CircuitBreaker", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CircuitBreaker = bool(v != 0) - case 9: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field LiquidationBlockInterval", wireType) - } - m.LiquidationBlockInterval = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.LiquidationBlockInterval |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - 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 (m *DebtParam) 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: DebtParam: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DebtParam: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ReferenceAsset", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ReferenceAsset = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ConversionFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ConversionFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DebtFloor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.DebtFloor.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 (m *CollateralParam) 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: CollateralParam: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CollateralParam: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Type = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LiquidationRatio", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.LiquidationRatio.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DebtLimit", 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.DebtLimit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StabilityFee", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.StabilityFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AuctionSize", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.AuctionSize.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LiquidationPenalty", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.LiquidationPenalty.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SpotMarketID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SpotMarketID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LiquidationMarketID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.LiquidationMarketID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field KeeperRewardPercentage", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.KeeperRewardPercentage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 11: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CheckCollateralizationIndexCount", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.CheckCollateralizationIndexCount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 12: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ConversionFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ConversionFactor.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 (m *GenesisAccumulationTime) 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: GenesisAccumulationTime: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisAccumulationTime: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PreviousAccumulationTime", 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 := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.PreviousAccumulationTime, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InterestFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.InterestFactor.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 (m *GenesisTotalPrincipal) 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: GenesisTotalPrincipal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisTotalPrincipal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalPrincipal", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TotalPrincipal.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/cdp/types/genesis_test.go b/x/cdp/types/genesis_test.go deleted file mode 100644 index ca9c8197..00000000 --- a/x/cdp/types/genesis_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package types_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/kava-labs/kava/x/cdp/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestGenesis_Default(t *testing.T) { - defaultGenesis := types.DefaultGenesisState() - - require.NoError(t, defaultGenesis.Validate()) - - defaultParams := types.DefaultParams() - assert.Equal(t, defaultParams, defaultGenesis.Params) -} - -func TestGenesisTotalPrincipal(t *testing.T) { - tests := []struct { - giveName string - giveCollateralType string - givePrincipal sdkmath.Int - wantIsError bool - wantError string - }{ - {"valid", "usdx", sdkmath.NewInt(10), false, ""}, - {"zero principal", "usdx", sdkmath.NewInt(0), false, ""}, - {"invalid empty collateral type", "", sdkmath.NewInt(10), true, "collateral type cannot be empty"}, - {"invalid negative principal", "usdx", sdkmath.NewInt(-10), true, "total principal should be positive"}, - {"both invalid", "", sdkmath.NewInt(-10), true, "collateral type cannot be empty"}, - } - - for _, tt := range tests { - t.Run(tt.giveName, func(t *testing.T) { - tp := types.NewGenesisTotalPrincipal(tt.giveCollateralType, tt.givePrincipal) - - err := tp.Validate() - if tt.wantIsError { - assert.Error(t, err) - assert.Contains(t, err.Error(), tt.wantError) - } else { - assert.NoError(t, err) - } - }) - } -} diff --git a/x/cdp/types/hooks.go b/x/cdp/types/hooks.go deleted file mode 100644 index 44bc732c..00000000 --- a/x/cdp/types/hooks.go +++ /dev/null @@ -1,25 +0,0 @@ -package types - -import sdk "github.com/cosmos/cosmos-sdk/types" - -// MultiCDPHooks combine multiple cdp hooks, all hook functions are run in array sequence -type MultiCDPHooks []CDPHooks - -// NewMultiCDPHooks returns a new MultiCDPHooks -func NewMultiCDPHooks(hooks ...CDPHooks) MultiCDPHooks { - return hooks -} - -// BeforeCDPModified runs before a cdp is modified -func (h MultiCDPHooks) BeforeCDPModified(ctx sdk.Context, cdp CDP) { - for i := range h { - h[i].BeforeCDPModified(ctx, cdp) - } -} - -// AfterCDPCreated runs before a cdp is created -func (h MultiCDPHooks) AfterCDPCreated(ctx sdk.Context, cdp CDP) { - for i := range h { - h[i].AfterCDPCreated(ctx, cdp) - } -} diff --git a/x/cdp/types/keys.go b/x/cdp/types/keys.go deleted file mode 100644 index 67921b6a..00000000 --- a/x/cdp/types/keys.go +++ /dev/null @@ -1,171 +0,0 @@ -package types - -import ( - "bytes" - "encoding/binary" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName The name that will be used throughout the module - ModuleName = "cdp" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default name for parameter store - DefaultParamspace = ModuleName - - // LiquidatorMacc module account for liquidator - LiquidatorMacc = "liquidator" -) - -var sep = []byte(":") - -// Keys for cdp store -// Items are stored with the following key: values -// - 0x00: []cdpID -// - One cdp owner can control one cdp per collateral type -// - 0x01:: CDP -// - cdps are prefix by denom prefix so we can iterate over cdps of one type -// - uses : as separator -// - 0x02::: cdpID -// - Ox03: nextCdpID -// - 0x04: debtDenom -// - 0x05::: Deposit -// - 0x06:totalPrincipal -// - 0x07:feeRate -// - 0x08:previousDistributionTime -// - 0x09:downTime -// - 0x10:totalDistributed - -// KVStore key prefixes -var ( - CdpIDKeyPrefix = []byte{0x01} - CdpKeyPrefix = []byte{0x02} - CollateralRatioIndexPrefix = []byte{0x03} - CdpIDKey = []byte{0x04} - DebtDenomKey = []byte{0x05} - GovDenomKey = []byte{0x06} - DepositKeyPrefix = []byte{0x07} - PrincipalKeyPrefix = []byte{0x08} - PricefeedStatusKeyPrefix = []byte{0x10} - PreviousAccrualTimePrefix = []byte{0x12} - InterestFactorPrefix = []byte{0x13} -) - -// GetCdpIDBytes returns the byte representation of the cdpID -func GetCdpIDBytes(cdpID uint64) (cdpIDBz []byte) { - cdpIDBz = make([]byte, 8) - binary.BigEndian.PutUint64(cdpIDBz, cdpID) - return -} - -// GetCdpIDFromBytes returns cdpID in uint64 format from a byte array -func GetCdpIDFromBytes(bz []byte) (cdpID uint64) { - return binary.BigEndian.Uint64(bz) -} - -// CdpKey key of a specific cdp in the store -func CdpKey(collateralType string, cdpID uint64) []byte { - return createKey([]byte(collateralType), sep, GetCdpIDBytes(cdpID)) -} - -// SplitCdpKey returns the component parts of a cdp key -func SplitCdpKey(key []byte) (string, uint64) { - split := bytes.Split(key, sep) - return string(split[0]), GetCdpIDFromBytes(split[1]) -} - -// DenomIterKey returns the key for iterating over cdps of a certain denom in the store -func DenomIterKey(collateralType string) []byte { - return append([]byte(collateralType), sep...) -} - -// SplitDenomIterKey returns the component part of a key for iterating over cdps by denom -func SplitDenomIterKey(key []byte) string { - split := bytes.Split(key, sep) - return string(split[0]) -} - -// DepositKey key of a specific deposit in the store -func DepositKey(cdpID uint64, depositor sdk.AccAddress) []byte { - return createKey(GetCdpIDBytes(cdpID), sep, depositor) -} - -// SplitDepositKey returns the component parts of a deposit key -func SplitDepositKey(key []byte) (uint64, sdk.AccAddress) { - cdpID := GetCdpIDFromBytes(key[0:8]) - addr := key[9:] - return cdpID, addr -} - -// DepositIterKey returns the prefix key for iterating over deposits to a cdp -func DepositIterKey(cdpID uint64) []byte { - return GetCdpIDBytes(cdpID) -} - -// SplitDepositIterKey returns the component parts of a key for iterating over deposits on a cdp -func SplitDepositIterKey(key []byte) (cdpID uint64) { - return GetCdpIDFromBytes(key) -} - -// CollateralRatioBytes returns the liquidation ratio as sortable bytes -func CollateralRatioBytes(ratio sdk.Dec) []byte { - ok := ValidSortableDec(ratio) - if !ok { - // set to max sortable if input is too large. - ratio = sdk.OneDec().Quo(sdk.SmallestDec()) - } - return SortableDecBytes(ratio) -} - -// CollateralRatioKey returns the key for querying a cdp by its liquidation ratio -func CollateralRatioKey(collateralType string, cdpID uint64, ratio sdk.Dec) []byte { - ratioBytes := CollateralRatioBytes(ratio) - idBytes := GetCdpIDBytes(cdpID) - - return createKey([]byte(collateralType), sep, ratioBytes, sep, idBytes) -} - -// SplitCollateralRatioKey split the collateral ratio key and return the denom, cdp id, and collateral:debt ratio -func SplitCollateralRatioKey(key []byte) (string, uint64, sdk.Dec) { - cdpID := GetCdpIDFromBytes(key[len(key)-8:]) - split := bytes.Split(key[:len(key)-8], sep) - collateralType := string(split[0]) - - ratio, err := ParseDecBytes(split[1]) - if err != nil { - panic(err) - } - return collateralType, cdpID, ratio -} - -// CollateralRatioIterKey returns the key for iterating over cdps by denom and liquidation ratio -func CollateralRatioIterKey(collateralType string, ratio sdk.Dec) []byte { - ratioBytes := CollateralRatioBytes(ratio) - return createKey([]byte(collateralType), sep, ratioBytes) -} - -// SplitCollateralRatioIterKey split the collateral ratio key and return the denom, cdp id, and collateral:debt ratio -func SplitCollateralRatioIterKey(key []byte) (string, sdk.Dec) { - split := bytes.Split(key, sep) - collateralType := string(split[0]) - - ratio, err := ParseDecBytes(split[1]) - if err != nil { - panic(err) - } - return collateralType, ratio -} - -func createKey(bytes ...[]byte) (r []byte) { - for _, b := range bytes { - r = append(r, b...) - } - return -} diff --git a/x/cdp/types/keys_test.go b/x/cdp/types/keys_test.go deleted file mode 100644 index adb3b839..00000000 --- a/x/cdp/types/keys_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/cometbft/cometbft/crypto/ed25519" -) - -var addr = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) - -func TestCdpKey(t *testing.T) { - key := CdpKey("kava-a", 2) - collateralType, id := SplitCdpKey(key) - require.Equal(t, int(id), 2) - require.Equal(t, "kava-a", collateralType) -} - -func TestDenomIterKey(t *testing.T) { - denomKey := DenomIterKey("kava-a") - collateralType := SplitDenomIterKey(denomKey) - require.Equal(t, "kava-a", collateralType) -} - -func TestDepositKey(t *testing.T) { - depositKey := DepositKey(2, addr) - id, a := SplitDepositKey(depositKey) - require.Equal(t, 2, int(id)) - require.Equal(t, a, addr) -} - -func TestDepositIterKey(t *testing.T) { - depositIterKey := DepositIterKey(2) - id := SplitDepositIterKey(depositIterKey) - require.Equal(t, 2, int(id)) -} - -func TestDepositIterKey_Invalid(t *testing.T) { - require.Panics(t, func() { SplitDepositIterKey([]byte{0x03}) }) -} - -func TestCollateralRatioKey(t *testing.T) { - collateralKey := CollateralRatioKey("kava-a", 2, sdk.MustNewDecFromStr("1.50")) - collateralType, id, ratio := SplitCollateralRatioKey(collateralKey) - require.Equal(t, "kava-a", collateralType) - require.Equal(t, 2, int(id)) - require.Equal(t, ratio, sdk.MustNewDecFromStr("1.50")) -} - -func TestCollateralRatioKey_BigRatio(t *testing.T) { - bigRatio := sdk.OneDec().Quo(sdk.SmallestDec()).Mul(sdk.OneDec().Add(sdk.OneDec())) - collateralKey := CollateralRatioKey("kava-a", 2, bigRatio) - collateralType, id, ratio := SplitCollateralRatioKey(collateralKey) - require.Equal(t, "kava-a", collateralType) - require.Equal(t, 2, int(id)) - require.Equal(t, ratio, MaxSortableDec) -} - -func TestCollateralRatioKey_Invalid(t *testing.T) { - require.Panics(t, func() { SplitCollateralRatioKey(badRatioKey()) }) -} - -func TestCollateralRatioIterKey(t *testing.T) { - collateralIterKey := CollateralRatioIterKey("kava-a", sdk.MustNewDecFromStr("1.50")) - collateralType, ratio := SplitCollateralRatioIterKey(collateralIterKey) - require.Equal(t, "kava-a", collateralType) - require.Equal(t, ratio, sdk.MustNewDecFromStr("1.50")) -} - -func TestCollateralRatioIterKey_Invalid(t *testing.T) { - require.Panics(t, func() { SplitCollateralRatioIterKey(badRatioIterKey()) }) -} - -func badRatioKey() []byte { - r := append(append(append(append([]byte{0x01}, sep...), []byte("nonsense")...), sep...), []byte{0xff}...) - return r -} - -func badRatioIterKey() []byte { - r := append(append([]byte{0x01}, sep...), []byte("nonsense")...) - return r -} diff --git a/x/cdp/types/msg.go b/x/cdp/types/msg.go deleted file mode 100644 index 32f6a308..00000000 --- a/x/cdp/types/msg.go +++ /dev/null @@ -1,312 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "strings" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// ensure Msg interface compliance at compile time -var ( - _ sdk.Msg = &MsgCreateCDP{} - _ sdk.Msg = &MsgDeposit{} - _ sdk.Msg = &MsgWithdraw{} - _ sdk.Msg = &MsgDrawDebt{} - _ sdk.Msg = &MsgRepayDebt{} - _ sdk.Msg = &MsgLiquidate{} -) - -// NewMsgCreateCDP returns a new MsgPlaceBid. -func NewMsgCreateCDP(sender sdk.AccAddress, collateral sdk.Coin, principal sdk.Coin, collateralType string) MsgCreateCDP { - return MsgCreateCDP{ - Sender: sender.String(), - Collateral: collateral, - Principal: principal, - CollateralType: collateralType, - } -} - -// Route return the message type used for routing the message. -func (msg MsgCreateCDP) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgCreateCDP) Type() string { return "create_cdp" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgCreateCDP) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if msg.Collateral.IsZero() || !msg.Collateral.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "collateral amount %s", msg.Collateral) - } - if msg.Principal.IsZero() || !msg.Principal.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "principal amount %s", msg.Principal) - } - if strings.TrimSpace(msg.CollateralType) == "" { - return fmt.Errorf("collateral type cannot be empty") - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgCreateCDP) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgCreateCDP) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgDeposit returns a new MsgDeposit -func NewMsgDeposit(owner sdk.AccAddress, depositor sdk.AccAddress, collateral sdk.Coin, collateralType string) MsgDeposit { - return MsgDeposit{ - Owner: owner.String(), - Depositor: depositor.String(), - Collateral: collateral, - CollateralType: collateralType, - } -} - -// Route return the message type used for routing the message. -func (msg MsgDeposit) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgDeposit) Type() string { return "deposit_cdp" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgDeposit) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Owner) - if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid owner address %s", err) - } - _, err = sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid depositor address %s", err) - } - - if !msg.Collateral.IsValid() || msg.Collateral.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "collateral amount %s", msg.Collateral) - } - if strings.TrimSpace(msg.CollateralType) == "" { - return fmt.Errorf("collateral type cannot be empty") - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgDeposit) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgDeposit) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - panic(err) - } - return []sdk.AccAddress{depositor} -} - -// NewMsgWithdraw returns a new MsgDeposit -func NewMsgWithdraw(owner sdk.AccAddress, depositor sdk.AccAddress, collateral sdk.Coin, collateralType string) MsgWithdraw { - return MsgWithdraw{ - Owner: owner.String(), - Depositor: depositor.String(), - Collateral: collateral, - CollateralType: collateralType, - } -} - -// Route return the message type used for routing the message. -func (msg MsgWithdraw) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgWithdraw) Type() string { return "withdraw_cdp" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgWithdraw) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Owner) - if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid owner address %s", err) - } - _, err = sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid depositor address %s", err) - } - - if !msg.Collateral.IsValid() || msg.Collateral.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "collateral amount %s", msg.Collateral) - } - if strings.TrimSpace(msg.CollateralType) == "" { - return fmt.Errorf("collateral type cannot be empty") - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgWithdraw) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgWithdraw) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - panic(err) - } - return []sdk.AccAddress{depositor} -} - -// NewMsgDrawDebt returns a new MsgDrawDebt -func NewMsgDrawDebt(sender sdk.AccAddress, collateralType string, principal sdk.Coin) MsgDrawDebt { - return MsgDrawDebt{ - Sender: sender.String(), - CollateralType: collateralType, - Principal: principal, - } -} - -// Route return the message type used for routing the message. -func (msg MsgDrawDebt) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgDrawDebt) Type() string { return "draw_cdp" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgDrawDebt) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid sender address %s", err) - } - - if strings.TrimSpace(msg.CollateralType) == "" { - return errors.New("cdp collateral type cannot be blank") - } - if msg.Principal.IsZero() || !msg.Principal.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "principal amount %s", msg.Principal) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgDrawDebt) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgDrawDebt) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgRepayDebt returns a new MsgRepayDebt -func NewMsgRepayDebt(sender sdk.AccAddress, collateralType string, payment sdk.Coin) MsgRepayDebt { - return MsgRepayDebt{ - Sender: sender.String(), - CollateralType: collateralType, - Payment: payment, - } -} - -// Route return the message type used for routing the message. -func (msg MsgRepayDebt) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgRepayDebt) Type() string { return "repay_cdp" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgRepayDebt) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid sender address %s", err) - } - - if strings.TrimSpace(msg.CollateralType) == "" { - return errors.New("cdp collateral type cannot be blank") - } - if msg.Payment.IsZero() || !msg.Payment.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "payment amount %s", msg.Payment) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgRepayDebt) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgRepayDebt) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgLiquidate returns a new MsgLiquidate -func NewMsgLiquidate(keeper, borrower sdk.AccAddress, ctype string) MsgLiquidate { - return MsgLiquidate{ - Keeper: keeper.String(), - Borrower: borrower.String(), - CollateralType: ctype, - } -} - -// Route return the message type used for routing the message. -func (msg MsgLiquidate) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgLiquidate) Type() string { return "liquidate" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgLiquidate) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Keeper) - if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid keeper address %s", err) - } - _, err = sdk.AccAddressFromBech32(msg.Borrower) - if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid borrower address %s", err) - } - - if strings.TrimSpace(msg.CollateralType) == "" { - return errorsmod.Wrap(ErrInvalidCollateral, "collateral type cannot be empty") - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgLiquidate) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgLiquidate) GetSigners() []sdk.AccAddress { - keeper, err := sdk.AccAddressFromBech32(msg.Keeper) - if err != nil { - panic(err) - } - return []sdk.AccAddress{keeper} -} diff --git a/x/cdp/types/msg_test.go b/x/cdp/types/msg_test.go deleted file mode 100644 index 41ec147a..00000000 --- a/x/cdp/types/msg_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var ( - coinsSingle = sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000) - coinsZero = sdk.NewCoin(sdk.DefaultBondDenom, sdk.ZeroInt()) - addrs = []sdk.AccAddress{ - sdk.AccAddress("test1"), - sdk.AccAddress("test2"), - } -) - -func TestMsgCreateCDP(t *testing.T) { - tests := []struct { - description string - sender sdk.AccAddress - collateral sdk.Coin - principal sdk.Coin - collateralType string - expectPass bool - }{ - {"create cdp", addrs[0], coinsSingle, coinsSingle, "type-a", true}, - {"create cdp no collateral", addrs[0], coinsZero, coinsSingle, "type-a", false}, - {"create cdp no debt", addrs[0], coinsSingle, coinsZero, "type-a", false}, - {"create cdp empty owner", sdk.AccAddress{}, coinsSingle, coinsSingle, "type-a", false}, - {"create cdp empty type", addrs[0], coinsSingle, coinsSingle, "", false}, - } - - for _, tc := range tests { - msg := NewMsgCreateCDP( - tc.sender, - tc.collateral, - tc.principal, - tc.collateralType, - ) - if tc.expectPass { - require.NoError(t, msg.ValidateBasic(), "test: %v", tc.description) - } else { - require.Error(t, msg.ValidateBasic(), "test: %v", tc.description) - } - } -} - -func TestMsgDeposit(t *testing.T) { - tests := []struct { - description string - sender sdk.AccAddress - depositor sdk.AccAddress - collateral sdk.Coin - collateralType string - expectPass bool - }{ - {"deposit", addrs[0], addrs[1], coinsSingle, "type-a", true}, - {"deposit same owner", addrs[0], addrs[0], coinsSingle, "type-a", true}, - {"deposit no collateral", addrs[0], addrs[1], coinsZero, "type-a", false}, - {"deposit empty owner", sdk.AccAddress{}, addrs[1], coinsSingle, "type-a", false}, - {"deposit empty depositor", addrs[0], sdk.AccAddress{}, coinsSingle, "type-a", false}, - {"deposit empty type", addrs[0], addrs[0], coinsSingle, "", false}, - } - - for _, tc := range tests { - msg := NewMsgDeposit( - tc.sender, - tc.depositor, - tc.collateral, - tc.collateralType, - ) - if tc.expectPass { - require.NoError(t, msg.ValidateBasic(), "test: %v", tc.description) - } else { - require.Error(t, msg.ValidateBasic(), "test: %v", tc.description) - } - } -} - -func TestMsgWithdraw(t *testing.T) { - tests := []struct { - description string - sender sdk.AccAddress - depositor sdk.AccAddress - collateral sdk.Coin - collateralType string - expectPass bool - }{ - {"withdraw", addrs[0], addrs[1], coinsSingle, "type-a", true}, - {"withdraw", addrs[0], addrs[0], coinsSingle, "type-a", true}, - {"withdraw no collateral", addrs[0], addrs[1], coinsZero, "type-a", false}, - {"withdraw empty owner", sdk.AccAddress{}, addrs[1], coinsSingle, "type-a", false}, - {"withdraw empty depositor", addrs[0], sdk.AccAddress{}, coinsSingle, "type-a", false}, - {"withdraw empty type", addrs[0], addrs[0], coinsSingle, "", false}, - } - - for _, tc := range tests { - msg := NewMsgWithdraw( - tc.sender, - tc.depositor, - tc.collateral, - tc.collateralType, - ) - if tc.expectPass { - require.NoError(t, msg.ValidateBasic(), "test: %v", tc.description) - } else { - require.Error(t, msg.ValidateBasic(), "test: %v", tc.description) - } - } -} - -func TestMsgDrawDebt(t *testing.T) { - tests := []struct { - description string - sender sdk.AccAddress - collateralType string - principal sdk.Coin - expectPass bool - }{ - {"draw debt", addrs[0], sdk.DefaultBondDenom, coinsSingle, true}, - {"draw debt no debt", addrs[0], sdk.DefaultBondDenom, coinsZero, false}, - {"draw debt empty owner", sdk.AccAddress{}, sdk.DefaultBondDenom, coinsSingle, false}, - {"draw debt empty denom", sdk.AccAddress{}, "", coinsSingle, false}, - } - - for _, tc := range tests { - msg := NewMsgDrawDebt( - tc.sender, - tc.collateralType, - tc.principal, - ) - if tc.expectPass { - require.NoError(t, msg.ValidateBasic(), "test: %v", tc.description) - } else { - require.Error(t, msg.ValidateBasic(), "test: %v", tc.description) - } - } -} - -func TestMsgRepayDebt(t *testing.T) { - tests := []struct { - description string - sender sdk.AccAddress - denom string - payment sdk.Coin - expectPass bool - }{ - {"repay debt", addrs[0], sdk.DefaultBondDenom, coinsSingle, true}, - {"repay debt no payment", addrs[0], sdk.DefaultBondDenom, coinsZero, false}, - {"repay debt empty owner", sdk.AccAddress{}, sdk.DefaultBondDenom, coinsSingle, false}, - {"repay debt empty denom", sdk.AccAddress{}, "", coinsSingle, false}, - } - - for _, tc := range tests { - msg := NewMsgRepayDebt( - tc.sender, - tc.denom, - tc.payment, - ) - if tc.expectPass { - require.NoError(t, msg.ValidateBasic(), "test: %v", tc.description) - } else { - require.Error(t, msg.ValidateBasic(), "test: %v", tc.description) - } - } -} diff --git a/x/cdp/types/params.go b/x/cdp/types/params.go deleted file mode 100644 index ca3356fb..00000000 --- a/x/cdp/types/params.go +++ /dev/null @@ -1,370 +0,0 @@ -package types - -import ( - "fmt" - "strings" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// Parameter keys -var ( - KeyGlobalDebtLimit = []byte("GlobalDebtLimit") - KeyCollateralParams = []byte("CollateralParams") - KeyDebtParam = []byte("DebtParam") - KeyCircuitBreaker = []byte("CircuitBreaker") - KeyDebtThreshold = []byte("DebtThreshold") - KeyDebtLot = []byte("DebtLot") - KeySurplusThreshold = []byte("SurplusThreshold") - KeySurplusLot = []byte("SurplusLot") - KeyBeginBlockerExecutionBlockInterval = []byte("BeginBlockerExecutionBlockInterval") - DefaultGlobalDebt = sdk.NewCoin(DefaultStableDenom, sdk.ZeroInt()) - DefaultCircuitBreaker = false - DefaultCollateralParams = CollateralParams{} - DefaultDebtParam = DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - } - DefaultCdpStartingID = uint64(1) - DefaultDebtDenom = "debt" - DefaultGovDenom = "ukava" - DefaultStableDenom = "usdx" - DefaultSurplusThreshold = sdkmath.NewInt(500000000000) - DefaultDebtThreshold = sdkmath.NewInt(100000000000) - DefaultSurplusLot = sdkmath.NewInt(10000000000) - DefaultDebtLot = sdkmath.NewInt(10000000000) - stabilityFeeMax = sdk.MustNewDecFromStr("1.000000051034942716") // 500% APR - // Run every block - DefaultBeginBlockerExecutionBlockInterval = int64(1) -) - -// NewParams returns a new params object -func NewParams( - debtLimit sdk.Coin, collateralParams CollateralParams, debtParam DebtParam, surplusThreshold, - surplusLot, debtThreshold, debtLot sdkmath.Int, breaker bool, beginBlockerExecutionBlockInterval int64, -) Params { - return Params{ - GlobalDebtLimit: debtLimit, - CollateralParams: collateralParams, - DebtParam: debtParam, - SurplusAuctionThreshold: surplusThreshold, - SurplusAuctionLot: surplusLot, - DebtAuctionThreshold: debtThreshold, - DebtAuctionLot: debtLot, - CircuitBreaker: breaker, - LiquidationBlockInterval: beginBlockerExecutionBlockInterval, - } -} - -// DefaultParams returns default params for cdp module -func DefaultParams() Params { - return NewParams( - DefaultGlobalDebt, DefaultCollateralParams, DefaultDebtParam, DefaultSurplusThreshold, - DefaultSurplusLot, DefaultDebtThreshold, DefaultDebtLot, - DefaultCircuitBreaker, DefaultBeginBlockerExecutionBlockInterval, - ) -} - -// NewCollateralParam returns a new CollateralParam -func NewCollateralParam( - denom, ctype string, liqRatio sdk.Dec, debtLimit sdk.Coin, stabilityFee sdk.Dec, auctionSize sdkmath.Int, - liqPenalty sdk.Dec, spotMarketID, liquidationMarketID string, keeperReward sdk.Dec, checkIndexCount sdkmath.Int, conversionFactor sdkmath.Int, -) CollateralParam { - return CollateralParam{ - Denom: denom, - Type: ctype, - LiquidationRatio: liqRatio, - DebtLimit: debtLimit, - StabilityFee: stabilityFee, - AuctionSize: auctionSize, - LiquidationPenalty: liqPenalty, - SpotMarketID: spotMarketID, - LiquidationMarketID: liquidationMarketID, - KeeperRewardPercentage: keeperReward, - CheckCollateralizationIndexCount: checkIndexCount, - ConversionFactor: conversionFactor, - } -} - -// CollateralParams array of CollateralParam -type CollateralParams []CollateralParam - -// NewDebtParam returns a new DebtParam -func NewDebtParam(denom, refAsset string, conversionFactor, debtFloor sdkmath.Int) DebtParam { - return DebtParam{ - Denom: denom, - ReferenceAsset: refAsset, - ConversionFactor: conversionFactor, - DebtFloor: debtFloor, - } -} - -// DebtParams array of DebtParam -type DebtParams []DebtParam - -// ParamKeyTable Key declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements the ParamSet interface and returns all the key/value pairs -// pairs of auth module's parameters. -// nolint -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyGlobalDebtLimit, &p.GlobalDebtLimit, validateGlobalDebtLimitParam), - paramtypes.NewParamSetPair(KeyCollateralParams, &p.CollateralParams, validateCollateralParams), - paramtypes.NewParamSetPair(KeyDebtParam, &p.DebtParam, validateDebtParam), - paramtypes.NewParamSetPair(KeyCircuitBreaker, &p.CircuitBreaker, validateCircuitBreakerParam), - paramtypes.NewParamSetPair(KeySurplusThreshold, &p.SurplusAuctionThreshold, validateSurplusAuctionThresholdParam), - paramtypes.NewParamSetPair(KeySurplusLot, &p.SurplusAuctionLot, validateSurplusAuctionLotParam), - paramtypes.NewParamSetPair(KeyDebtThreshold, &p.DebtAuctionThreshold, validateDebtAuctionThresholdParam), - paramtypes.NewParamSetPair(KeyDebtLot, &p.DebtAuctionLot, validateDebtAuctionLotParam), - paramtypes.NewParamSetPair(KeyBeginBlockerExecutionBlockInterval, &p.LiquidationBlockInterval, validateBeginBlockerExecutionBlockIntervalParam), - } -} - -// Validate checks that the parameters have valid values. -func (p Params) Validate() error { - if err := validateGlobalDebtLimitParam(p.GlobalDebtLimit); err != nil { - return err - } - - if err := validateCollateralParams(p.CollateralParams); err != nil { - return err - } - - if err := validateDebtParam(p.DebtParam); err != nil { - return err - } - - if err := validateCircuitBreakerParam(p.CircuitBreaker); err != nil { - return err - } - - if err := validateBeginBlockerExecutionBlockIntervalParam(p.LiquidationBlockInterval); err != nil { - return err - } - - if err := validateSurplusAuctionThresholdParam(p.SurplusAuctionThreshold); err != nil { - return err - } - - if err := validateSurplusAuctionLotParam(p.SurplusAuctionLot); err != nil { - return err - } - - if err := validateDebtAuctionThresholdParam(p.DebtAuctionThreshold); err != nil { - return err - } - - if err := validateDebtAuctionLotParam(p.DebtAuctionLot); err != nil { - return err - } - - if len(p.CollateralParams) == 0 { // default value OK - return nil - } - - if (DebtParam{}) != p.DebtParam { - if p.DebtParam.Denom != p.GlobalDebtLimit.Denom { - return fmt.Errorf("debt denom %s does not match global debt denom %s", - p.DebtParam.Denom, p.GlobalDebtLimit.Denom) - } - } - - // validate collateral params - collateralTypeDupMap := make(map[string]bool) - collateralParamsDebtLimit := sdk.ZeroInt() - - for _, cp := range p.CollateralParams { - // Collateral type eg busd-a should be unique, but denom can be same eg busd - _, exists := collateralTypeDupMap[cp.Type] - if exists { - return fmt.Errorf("duplicate collateral type %s", cp.Denom) - } - - collateralTypeDupMap[cp.Type] = true - - if cp.DebtLimit.Denom != p.GlobalDebtLimit.Denom { - return fmt.Errorf("collateral debt limit denom %s does not match global debt limit denom %s", - cp.DebtLimit.Denom, p.GlobalDebtLimit.Denom) - } - - collateralParamsDebtLimit = collateralParamsDebtLimit.Add(cp.DebtLimit.Amount) - - if cp.DebtLimit.Amount.GT(p.GlobalDebtLimit.Amount) { - return fmt.Errorf("collateral debt limit %s exceeds global debt limit: %s", cp.DebtLimit, p.GlobalDebtLimit) - } - } - - if collateralParamsDebtLimit.GT(p.GlobalDebtLimit.Amount) { - return fmt.Errorf("sum of collateral debt limits %s exceeds global debt limit %s", - collateralParamsDebtLimit, p.GlobalDebtLimit) - } - - return nil -} - -func validateGlobalDebtLimitParam(i interface{}) error { - globalDebtLimit, ok := i.(sdk.Coin) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if !globalDebtLimit.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "global debt limit %s", globalDebtLimit.String()) - } - - return nil -} - -func validateCollateralParams(i interface{}) error { - collateralParams, ok := i.(CollateralParams) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - typeDupMap := make(map[string]bool) - for _, cp := range collateralParams { - if err := sdk.ValidateDenom(cp.Denom); err != nil { - return fmt.Errorf("collateral denom invalid %s", cp.Denom) - } - - if strings.TrimSpace(cp.SpotMarketID) == "" { - return fmt.Errorf("spot market id cannot be blank %v", cp) - } - - if strings.TrimSpace(cp.Type) == "" { - return fmt.Errorf("collateral type cannot be blank %v", cp) - } - - if strings.TrimSpace(cp.LiquidationMarketID) == "" { - return fmt.Errorf("liquidation market id cannot be blank %v", cp) - } - - _, found := typeDupMap[cp.Type] - if found { - return fmt.Errorf("duplicate cdp collateral type: %s", cp.Type) - } - typeDupMap[cp.Type] = true - - if !cp.DebtLimit.IsValid() { - return fmt.Errorf("debt limit for all collaterals should be positive, is %s for %s", cp.DebtLimit, cp.Denom) - } - - if cp.LiquidationRatio.IsNil() || !cp.LiquidationRatio.IsPositive() { - return fmt.Errorf("liquidation ratio must be > 0") - } - - if cp.LiquidationPenalty.LT(sdk.ZeroDec()) || cp.LiquidationPenalty.GT(sdk.OneDec()) { - return fmt.Errorf("liquidation penalty should be between 0 and 1, is %s for %s", cp.LiquidationPenalty, cp.Denom) - } - if !cp.AuctionSize.IsPositive() { - return fmt.Errorf("auction size should be positive, is %s for %s", cp.AuctionSize, cp.Denom) - } - if cp.StabilityFee.LT(sdk.OneDec()) || cp.StabilityFee.GT(stabilityFeeMax) { - return fmt.Errorf("stability fee must be ≥ 1.0, ≤ %s, is %s for %s", stabilityFeeMax, cp.StabilityFee, cp.Denom) - } - if cp.KeeperRewardPercentage.IsNegative() || cp.KeeperRewardPercentage.GT(sdk.OneDec()) { - return fmt.Errorf("keeper reward percentage should be between 0 and 1, is %s for %s", cp.KeeperRewardPercentage, cp.Denom) - } - if cp.CheckCollateralizationIndexCount.IsNegative() { - return fmt.Errorf("keeper reward percentage should be positive, is %s for %s", cp.CheckCollateralizationIndexCount, cp.Denom) - } - } - - return nil -} - -func validateDebtParam(i interface{}) error { - debtParam, ok := i.(DebtParam) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - if err := sdk.ValidateDenom(debtParam.Denom); err != nil { - return fmt.Errorf("debt denom invalid %s", debtParam.Denom) - } - - return nil -} - -func validateCircuitBreakerParam(i interface{}) error { - _, ok := i.(bool) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return nil -} - -func validateSurplusAuctionThresholdParam(i interface{}) error { - sat, ok := i.(sdkmath.Int) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if !sat.IsPositive() { - return fmt.Errorf("surplus auction threshold should be positive: %s", sat) - } - - return nil -} - -func validateSurplusAuctionLotParam(i interface{}) error { - sal, ok := i.(sdkmath.Int) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if !sal.IsPositive() { - return fmt.Errorf("surplus auction lot should be positive: %s", sal) - } - - return nil -} - -func validateDebtAuctionThresholdParam(i interface{}) error { - dat, ok := i.(sdkmath.Int) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if !dat.IsPositive() { - return fmt.Errorf("debt auction threshold should be positive: %s", dat) - } - - return nil -} - -func validateDebtAuctionLotParam(i interface{}) error { - dal, ok := i.(sdkmath.Int) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if !dal.IsPositive() { - return fmt.Errorf("debt auction lot should be positive: %s", dal) - } - - return nil -} - -func validateBeginBlockerExecutionBlockIntervalParam(i interface{}) error { - bbebi, ok := i.(int64) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if bbebi <= 0 { - return fmt.Errorf("begin blocker execution block interval param should be positive: %d", bbebi) - } - - return nil -} diff --git a/x/cdp/types/params_test.go b/x/cdp/types/params_test.go deleted file mode 100644 index 0dd72767..00000000 --- a/x/cdp/types/params_test.go +++ /dev/null @@ -1,876 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/cdp/types" -) - -type ParamsTestSuite struct { - suite.Suite -} - -func (suite *ParamsTestSuite) SetupTest() { -} - -func (suite *ParamsTestSuite) TestParamValidation() { - type args struct { - globalDebtLimit sdk.Coin - collateralParams types.CollateralParams - debtParam types.DebtParam - surplusThreshold sdkmath.Int - surplusLot sdkmath.Int - debtThreshold sdkmath.Int - debtLot sdkmath.Int - breaker bool - beginBlockerExecutionBlockInterval int64 - } - type errArgs struct { - expectPass bool - contains string - } - - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - name: "default", - args: args{ - globalDebtLimit: types.DefaultGlobalDebt, - collateralParams: types.DefaultCollateralParams, - debtParam: types.DefaultDebtParam, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: true, - contains: "", - }, - }, - { - name: "valid single-collateral", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 4000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: true, - contains: "", - }, - }, - { - name: "invalid single-collateral mismatched debt denoms", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 4000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "susd", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "does not match global debt denom", - }, - }, - { - name: "invalid single-collateral over debt limit", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "exceeds global debt limit", - }, - }, - { - name: "valid multi-collateral", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 4000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(6), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: true, - contains: "", - }, - }, - { - name: "invalid multi-collateral over debt limit", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(6), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "sum of collateral debt limits", - }, - }, - { - name: "invalid multi-collateral multiple debt denoms", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 4000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("susd", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(6), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "does not match global debt limit denom", - }, - }, - { - name: "invalid collateral params empty denom", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "collateral denom invalid", - }, - }, - { - name: "invalid collateral params empty market id", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "", - LiquidationMarketID: "", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "market id cannot be blank", - }, - }, - { - name: "invalid collateral params duplicate denom + type", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "duplicate cdp collateral type", - }, - }, - { - name: "valid collateral params duplicate denom + different type", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - { - Denom: "bnb", - Type: "bnb-b", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: true, - contains: "", - }, - }, - { - name: "invalid collateral params nil debt limit", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.Coin{}, - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "debt limit for all collaterals should be positive", - }, - }, - { - name: "invalid collateral params liquidation ratio out of range", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("1.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "liquidation penalty should be between 0 and 1", - }, - }, - { - name: "invalid collateral params auction size zero", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdk.ZeroInt(), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "auction size should be positive", - }, - }, - { - name: "invalid collateral params stability fee out of range", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.1"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "stability fee must be ≥ 1.0", - }, - }, - { - name: "invalid collateral params zero liquidation ratio", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("0.0"), - DebtLimit: sdk.NewInt64Coin("usdx", 1_000_000_000_000), - StabilityFee: sdk.MustNewDecFromStr("1.1"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50_000_000_000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DefaultDebtParam, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "liquidation ratio must be > 0", - }, - }, - { - name: "invalid debt param empty denom", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "debt denom invalid", - }, - }, - { - name: "nil debt limit", - args: args{ - globalDebtLimit: sdk.Coin{}, - collateralParams: types.DefaultCollateralParams, - debtParam: types.DefaultDebtParam, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "global debt limit : invalid coins", - }, - }, - { - name: "zero surplus auction threshold", - args: args{ - globalDebtLimit: types.DefaultGlobalDebt, - collateralParams: types.DefaultCollateralParams, - debtParam: types.DefaultDebtParam, - surplusThreshold: sdk.ZeroInt(), - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "surplus auction threshold should be positive", - }, - }, - { - name: "zero debt auction threshold", - args: args{ - globalDebtLimit: types.DefaultGlobalDebt, - collateralParams: types.DefaultCollateralParams, - debtParam: types.DefaultDebtParam, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: sdk.ZeroInt(), - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "debt auction threshold should be positive", - }, - }, - { - name: "zero surplus auction lot", - args: args{ - globalDebtLimit: types.DefaultGlobalDebt, - collateralParams: types.DefaultCollateralParams, - debtParam: types.DefaultDebtParam, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: sdk.ZeroInt(), - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "surplus auction lot should be positive", - }, - }, - { - name: "zero debt auction lot", - args: args{ - globalDebtLimit: types.DefaultGlobalDebt, - collateralParams: types.DefaultCollateralParams, - debtParam: types.DefaultDebtParam, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: sdk.ZeroInt(), - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "debt auction lot should be positive", - }, - }, - { - name: "zero begin blocker execution interval", - args: args{ - globalDebtLimit: types.DefaultGlobalDebt, - collateralParams: types.DefaultCollateralParams, - debtParam: types.DefaultDebtParam, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: 0, - }, - errArgs: errArgs{ - expectPass: false, - contains: "begin blocker execution block interval param should be positive", - }, - }, - { - name: "negative begin blocker execution interval", - args: args{ - globalDebtLimit: types.DefaultGlobalDebt, - collateralParams: types.DefaultCollateralParams, - debtParam: types.DefaultDebtParam, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: -1, - }, - errArgs: errArgs{ - expectPass: false, - contains: "begin blocker execution block interval param should be positive", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - params := types.NewParams(tc.args.globalDebtLimit, tc.args.collateralParams, tc.args.debtParam, tc.args.surplusThreshold, tc.args.surplusLot, tc.args.debtThreshold, tc.args.debtLot, tc.args.breaker, tc.args.beginBlockerExecutionBlockInterval) - err := params.Validate() - if tc.errArgs.expectPass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Require().Contains(err.Error(), tc.errArgs.contains) - } - }) - } -} - -func TestParamsTestSuite(t *testing.T) { - suite.Run(t, new(ParamsTestSuite)) -} diff --git a/x/cdp/types/querier.go b/x/cdp/types/querier.go deleted file mode 100644 index f3e6a69b..00000000 --- a/x/cdp/types/querier.go +++ /dev/null @@ -1,27 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// QueryCdpsParams is the params for a filtered CDP query -type QueryCdpsParams struct { - Page int `json:"page" yaml:"page"` - Limit int `json:"limit" yaml:"limit"` - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - Owner sdk.AccAddress `json:"owner" yaml:"owner"` - ID uint64 `json:"id" yaml:"id"` - Ratio sdk.Dec `json:"ratio" yaml:"ratio"` -} - -// NewQueryCdpsParams creates a new QueryCdpsParams -func NewQueryCdpsParams(page, limit int, collateralType string, owner sdk.AccAddress, id uint64, ratio sdk.Dec) QueryCdpsParams { - return QueryCdpsParams{ - Page: page, - Limit: limit, - CollateralType: collateralType, - Owner: owner, - ID: id, - Ratio: ratio, - } -} diff --git a/x/cdp/types/query.pb.go b/x/cdp/types/query.pb.go deleted file mode 100644 index ca16689f..00000000 --- a/x/cdp/types/query.pb.go +++ /dev/null @@ -1,3857 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/cdp/v1beta1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types1 "github.com/cosmos/cosmos-sdk/types" - query "github.com/cosmos/cosmos-sdk/types/query" - types "github.com/cosmos/cosmos-sdk/x/auth/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 defines the 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_fd68799328aaf74a, []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 defines the response type for the Query/Params RPC method. -type QueryParamsResponse struct { - 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_fd68799328aaf74a, []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 - -// QueryAccountsRequest defines the request type for the Query/Accounts RPC method. -type QueryAccountsRequest struct { -} - -func (m *QueryAccountsRequest) Reset() { *m = QueryAccountsRequest{} } -func (m *QueryAccountsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAccountsRequest) ProtoMessage() {} -func (*QueryAccountsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{2} -} -func (m *QueryAccountsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAccountsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAccountsRequest.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 *QueryAccountsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAccountsRequest.Merge(m, src) -} -func (m *QueryAccountsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryAccountsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAccountsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAccountsRequest proto.InternalMessageInfo - -// QueryAccountsResponse defines the response type for the Query/Accounts RPC method. -type QueryAccountsResponse struct { - Accounts []types.ModuleAccount `protobuf:"bytes,1,rep,name=accounts,proto3" json:"accounts"` -} - -func (m *QueryAccountsResponse) Reset() { *m = QueryAccountsResponse{} } -func (m *QueryAccountsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAccountsResponse) ProtoMessage() {} -func (*QueryAccountsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{3} -} -func (m *QueryAccountsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAccountsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAccountsResponse.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 *QueryAccountsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAccountsResponse.Merge(m, src) -} -func (m *QueryAccountsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryAccountsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAccountsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAccountsResponse proto.InternalMessageInfo - -func (m *QueryAccountsResponse) GetAccounts() []types.ModuleAccount { - if m != nil { - return m.Accounts - } - return nil -} - -// QueryCdpRequest defines the request type for the Query/Cdp RPC method. -type QueryCdpRequest struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` -} - -func (m *QueryCdpRequest) Reset() { *m = QueryCdpRequest{} } -func (m *QueryCdpRequest) String() string { return proto.CompactTextString(m) } -func (*QueryCdpRequest) ProtoMessage() {} -func (*QueryCdpRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{4} -} -func (m *QueryCdpRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryCdpRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCdpRequest.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 *QueryCdpRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCdpRequest.Merge(m, src) -} -func (m *QueryCdpRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryCdpRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCdpRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCdpRequest proto.InternalMessageInfo - -func (m *QueryCdpRequest) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func (m *QueryCdpRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -// QueryCdpResponse defines the response type for the Query/Cdp RPC method. -type QueryCdpResponse struct { - Cdp CDPResponse `protobuf:"bytes,1,opt,name=cdp,proto3" json:"cdp"` -} - -func (m *QueryCdpResponse) Reset() { *m = QueryCdpResponse{} } -func (m *QueryCdpResponse) String() string { return proto.CompactTextString(m) } -func (*QueryCdpResponse) ProtoMessage() {} -func (*QueryCdpResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{5} -} -func (m *QueryCdpResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryCdpResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCdpResponse.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 *QueryCdpResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCdpResponse.Merge(m, src) -} -func (m *QueryCdpResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryCdpResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCdpResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCdpResponse proto.InternalMessageInfo - -func (m *QueryCdpResponse) GetCdp() CDPResponse { - if m != nil { - return m.Cdp - } - return CDPResponse{} -} - -// QueryCdpsRequest is the params for a filtered CDP query, the request type for the Query/Cdps RPC method. -type QueryCdpsRequest struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - ID uint64 `protobuf:"varint,3,opt,name=id,proto3" json:"id,omitempty"` - // sdk.Dec as a string - Ratio string `protobuf:"bytes,4,opt,name=ratio,proto3" json:"ratio,omitempty"` - Pagination *query.PageRequest `protobuf:"bytes,5,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryCdpsRequest) Reset() { *m = QueryCdpsRequest{} } -func (m *QueryCdpsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryCdpsRequest) ProtoMessage() {} -func (*QueryCdpsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{6} -} -func (m *QueryCdpsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryCdpsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCdpsRequest.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 *QueryCdpsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCdpsRequest.Merge(m, src) -} -func (m *QueryCdpsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryCdpsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCdpsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCdpsRequest proto.InternalMessageInfo - -func (m *QueryCdpsRequest) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func (m *QueryCdpsRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *QueryCdpsRequest) GetID() uint64 { - if m != nil { - return m.ID - } - return 0 -} - -func (m *QueryCdpsRequest) GetRatio() string { - if m != nil { - return m.Ratio - } - return "" -} - -func (m *QueryCdpsRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryCdpsResponse defines the response type for the Query/Cdps RPC method. -type QueryCdpsResponse struct { - Cdps CDPResponses `protobuf:"bytes,1,rep,name=cdps,proto3,castrepeated=CDPResponses" json:"cdps"` - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryCdpsResponse) Reset() { *m = QueryCdpsResponse{} } -func (m *QueryCdpsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryCdpsResponse) ProtoMessage() {} -func (*QueryCdpsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{7} -} -func (m *QueryCdpsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryCdpsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCdpsResponse.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 *QueryCdpsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCdpsResponse.Merge(m, src) -} -func (m *QueryCdpsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryCdpsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCdpsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCdpsResponse proto.InternalMessageInfo - -func (m *QueryCdpsResponse) GetCdps() CDPResponses { - if m != nil { - return m.Cdps - } - return nil -} - -func (m *QueryCdpsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryDepositsRequest defines the request type for the Query/Deposits RPC method. -type QueryDepositsRequest struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` -} - -func (m *QueryDepositsRequest) Reset() { *m = QueryDepositsRequest{} } -func (m *QueryDepositsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsRequest) ProtoMessage() {} -func (*QueryDepositsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{8} -} -func (m *QueryDepositsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsRequest.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 *QueryDepositsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsRequest.Merge(m, src) -} -func (m *QueryDepositsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsRequest proto.InternalMessageInfo - -func (m *QueryDepositsRequest) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func (m *QueryDepositsRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -// QueryDepositsResponse defines the response type for the Query/Deposits RPC method. -type QueryDepositsResponse struct { - Deposits Deposits `protobuf:"bytes,1,rep,name=deposits,proto3,castrepeated=Deposits" json:"deposits"` -} - -func (m *QueryDepositsResponse) Reset() { *m = QueryDepositsResponse{} } -func (m *QueryDepositsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsResponse) ProtoMessage() {} -func (*QueryDepositsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{9} -} -func (m *QueryDepositsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsResponse.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 *QueryDepositsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsResponse.Merge(m, src) -} -func (m *QueryDepositsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsResponse proto.InternalMessageInfo - -func (m *QueryDepositsResponse) GetDeposits() Deposits { - if m != nil { - return m.Deposits - } - return nil -} - -// QueryTotalPrincipalRequest defines the request type for the Query/TotalPrincipal RPC method. -type QueryTotalPrincipalRequest struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` -} - -func (m *QueryTotalPrincipalRequest) Reset() { *m = QueryTotalPrincipalRequest{} } -func (m *QueryTotalPrincipalRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalPrincipalRequest) ProtoMessage() {} -func (*QueryTotalPrincipalRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{10} -} -func (m *QueryTotalPrincipalRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalPrincipalRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalPrincipalRequest.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 *QueryTotalPrincipalRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalPrincipalRequest.Merge(m, src) -} -func (m *QueryTotalPrincipalRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalPrincipalRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalPrincipalRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalPrincipalRequest proto.InternalMessageInfo - -func (m *QueryTotalPrincipalRequest) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -// QueryTotalPrincipalResponse defines the response type for the Query/TotalPrincipal RPC method. -type QueryTotalPrincipalResponse struct { - TotalPrincipal TotalPrincipals `protobuf:"bytes,1,rep,name=total_principal,json=totalPrincipal,proto3,castrepeated=TotalPrincipals" json:"total_principal"` -} - -func (m *QueryTotalPrincipalResponse) Reset() { *m = QueryTotalPrincipalResponse{} } -func (m *QueryTotalPrincipalResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalPrincipalResponse) ProtoMessage() {} -func (*QueryTotalPrincipalResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{11} -} -func (m *QueryTotalPrincipalResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalPrincipalResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalPrincipalResponse.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 *QueryTotalPrincipalResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalPrincipalResponse.Merge(m, src) -} -func (m *QueryTotalPrincipalResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalPrincipalResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalPrincipalResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalPrincipalResponse proto.InternalMessageInfo - -func (m *QueryTotalPrincipalResponse) GetTotalPrincipal() TotalPrincipals { - if m != nil { - return m.TotalPrincipal - } - return nil -} - -// QueryTotalCollateralRequest defines the request type for the Query/TotalCollateral RPC method. -type QueryTotalCollateralRequest struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` -} - -func (m *QueryTotalCollateralRequest) Reset() { *m = QueryTotalCollateralRequest{} } -func (m *QueryTotalCollateralRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalCollateralRequest) ProtoMessage() {} -func (*QueryTotalCollateralRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{12} -} -func (m *QueryTotalCollateralRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalCollateralRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalCollateralRequest.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 *QueryTotalCollateralRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalCollateralRequest.Merge(m, src) -} -func (m *QueryTotalCollateralRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalCollateralRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalCollateralRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalCollateralRequest proto.InternalMessageInfo - -func (m *QueryTotalCollateralRequest) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -// QueryTotalCollateralResponse defines the response type for the Query/TotalCollateral RPC method. -type QueryTotalCollateralResponse struct { - TotalCollateral TotalCollaterals `protobuf:"bytes,1,rep,name=total_collateral,json=totalCollateral,proto3,castrepeated=TotalCollaterals" json:"total_collateral"` -} - -func (m *QueryTotalCollateralResponse) Reset() { *m = QueryTotalCollateralResponse{} } -func (m *QueryTotalCollateralResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalCollateralResponse) ProtoMessage() {} -func (*QueryTotalCollateralResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{13} -} -func (m *QueryTotalCollateralResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalCollateralResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalCollateralResponse.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 *QueryTotalCollateralResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalCollateralResponse.Merge(m, src) -} -func (m *QueryTotalCollateralResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalCollateralResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalCollateralResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalCollateralResponse proto.InternalMessageInfo - -func (m *QueryTotalCollateralResponse) GetTotalCollateral() TotalCollaterals { - if m != nil { - return m.TotalCollateral - } - return nil -} - -// CDPResponse defines the state of a single collateralized debt position. -type CDPResponse struct { - ID uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Type string `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"` - Collateral types1.Coin `protobuf:"bytes,4,opt,name=collateral,proto3" json:"collateral"` - Principal types1.Coin `protobuf:"bytes,5,opt,name=principal,proto3" json:"principal"` - AccumulatedFees types1.Coin `protobuf:"bytes,6,opt,name=accumulated_fees,json=accumulatedFees,proto3" json:"accumulated_fees"` - FeesUpdated time.Time `protobuf:"bytes,7,opt,name=fees_updated,json=feesUpdated,proto3,stdtime" json:"fees_updated"` - InterestFactor string `protobuf:"bytes,8,opt,name=interest_factor,json=interestFactor,proto3" json:"interest_factor,omitempty"` - CollateralValue types1.Coin `protobuf:"bytes,9,opt,name=collateral_value,json=collateralValue,proto3" json:"collateral_value"` - CollateralizationRatio string `protobuf:"bytes,10,opt,name=collateralization_ratio,json=collateralizationRatio,proto3" json:"collateralization_ratio,omitempty"` -} - -func (m *CDPResponse) Reset() { *m = CDPResponse{} } -func (m *CDPResponse) String() string { return proto.CompactTextString(m) } -func (*CDPResponse) ProtoMessage() {} -func (*CDPResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{14} -} -func (m *CDPResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CDPResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CDPResponse.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 *CDPResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_CDPResponse.Merge(m, src) -} -func (m *CDPResponse) XXX_Size() int { - return m.Size() -} -func (m *CDPResponse) XXX_DiscardUnknown() { - xxx_messageInfo_CDPResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_CDPResponse proto.InternalMessageInfo - -func (m *CDPResponse) GetID() uint64 { - if m != nil { - return m.ID - } - return 0 -} - -func (m *CDPResponse) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *CDPResponse) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -func (m *CDPResponse) GetCollateral() types1.Coin { - if m != nil { - return m.Collateral - } - return types1.Coin{} -} - -func (m *CDPResponse) GetPrincipal() types1.Coin { - if m != nil { - return m.Principal - } - return types1.Coin{} -} - -func (m *CDPResponse) GetAccumulatedFees() types1.Coin { - if m != nil { - return m.AccumulatedFees - } - return types1.Coin{} -} - -func (m *CDPResponse) GetFeesUpdated() time.Time { - if m != nil { - return m.FeesUpdated - } - return time.Time{} -} - -func (m *CDPResponse) GetInterestFactor() string { - if m != nil { - return m.InterestFactor - } - return "" -} - -func (m *CDPResponse) GetCollateralValue() types1.Coin { - if m != nil { - return m.CollateralValue - } - return types1.Coin{} -} - -func (m *CDPResponse) GetCollateralizationRatio() string { - if m != nil { - return m.CollateralizationRatio - } - return "" -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.cdp.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.cdp.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryAccountsRequest)(nil), "kava.cdp.v1beta1.QueryAccountsRequest") - proto.RegisterType((*QueryAccountsResponse)(nil), "kava.cdp.v1beta1.QueryAccountsResponse") - proto.RegisterType((*QueryCdpRequest)(nil), "kava.cdp.v1beta1.QueryCdpRequest") - proto.RegisterType((*QueryCdpResponse)(nil), "kava.cdp.v1beta1.QueryCdpResponse") - proto.RegisterType((*QueryCdpsRequest)(nil), "kava.cdp.v1beta1.QueryCdpsRequest") - proto.RegisterType((*QueryCdpsResponse)(nil), "kava.cdp.v1beta1.QueryCdpsResponse") - proto.RegisterType((*QueryDepositsRequest)(nil), "kava.cdp.v1beta1.QueryDepositsRequest") - proto.RegisterType((*QueryDepositsResponse)(nil), "kava.cdp.v1beta1.QueryDepositsResponse") - proto.RegisterType((*QueryTotalPrincipalRequest)(nil), "kava.cdp.v1beta1.QueryTotalPrincipalRequest") - proto.RegisterType((*QueryTotalPrincipalResponse)(nil), "kava.cdp.v1beta1.QueryTotalPrincipalResponse") - proto.RegisterType((*QueryTotalCollateralRequest)(nil), "kava.cdp.v1beta1.QueryTotalCollateralRequest") - proto.RegisterType((*QueryTotalCollateralResponse)(nil), "kava.cdp.v1beta1.QueryTotalCollateralResponse") - proto.RegisterType((*CDPResponse)(nil), "kava.cdp.v1beta1.CDPResponse") -} - -func init() { proto.RegisterFile("kava/cdp/v1beta1/query.proto", fileDescriptor_fd68799328aaf74a) } - -var fileDescriptor_fd68799328aaf74a = []byte{ - // 1142 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x56, 0xcf, 0x6f, 0xdb, 0x54, - 0x1c, 0x8f, 0xd3, 0xb4, 0x4b, 0x5f, 0xa7, 0x26, 0x3c, 0x42, 0xe7, 0x9a, 0x92, 0xa4, 0x1e, 0x5b, - 0x0b, 0xa2, 0x36, 0x2b, 0xe2, 0xb7, 0xd0, 0xd4, 0xb4, 0x74, 0x1a, 0x12, 0x52, 0x31, 0x05, 0x24, - 0x24, 0x14, 0x5e, 0xec, 0xd7, 0xcc, 0x90, 0xf8, 0x79, 0x7e, 0x76, 0x47, 0x99, 0x26, 0x04, 0x87, - 0x89, 0xe3, 0x04, 0x07, 0x0e, 0x48, 0x68, 0x17, 0x2e, 0x9c, 0xf9, 0x23, 0x76, 0x9c, 0x80, 0x03, - 0xa7, 0x0d, 0x5a, 0x0e, 0xfc, 0x19, 0xd3, 0x7b, 0xfe, 0x3a, 0x76, 0xe2, 0xa4, 0xed, 0x0e, 0xbb, - 0x44, 0xf1, 0xf7, 0xd7, 0xe7, 0xf3, 0xfd, 0xfa, 0xfb, 0xc3, 0x68, 0xe9, 0x4b, 0xb2, 0x4f, 0x4c, - 0xdb, 0xf1, 0xcd, 0xfd, 0x4b, 0x1d, 0x1a, 0x92, 0x4b, 0xe6, 0xf5, 0x88, 0x06, 0x07, 0x86, 0x1f, - 0xb0, 0x90, 0xe1, 0xaa, 0xd0, 0x1a, 0xb6, 0xe3, 0x1b, 0xa0, 0xd5, 0xea, 0x36, 0xe3, 0x7d, 0xc6, - 0x4d, 0x12, 0x85, 0xd7, 0x06, 0x2e, 0xe2, 0x21, 0xf6, 0xd0, 0x5e, 0x04, 0x7d, 0x87, 0x70, 0x1a, - 0x87, 0x1a, 0x58, 0xf9, 0xa4, 0xeb, 0x7a, 0x24, 0x74, 0x99, 0x07, 0xb6, 0xf5, 0xac, 0x6d, 0x62, - 0x65, 0x33, 0x37, 0xd1, 0x2f, 0xc6, 0xfa, 0xb6, 0x7c, 0x32, 0xe3, 0x07, 0x50, 0xd5, 0xba, 0xac, - 0xcb, 0x62, 0xb9, 0xf8, 0x07, 0xd2, 0xa5, 0x2e, 0x63, 0xdd, 0x1e, 0x35, 0x89, 0xef, 0x9a, 0xc4, - 0xf3, 0x58, 0x28, 0xd1, 0x12, 0x9f, 0x06, 0x68, 0xe5, 0x53, 0x27, 0xda, 0x33, 0x43, 0xb7, 0x4f, - 0x79, 0x48, 0xfa, 0x3e, 0x18, 0x68, 0xb9, 0x5a, 0x88, 0xcc, 0x81, 0x6b, 0x4e, 0xd7, 0xa5, 0x1e, - 0xe5, 0x2e, 0x04, 0xd7, 0x6b, 0x08, 0x7f, 0x20, 0xb2, 0xdd, 0x21, 0x01, 0xe9, 0x73, 0x8b, 0x5e, - 0x8f, 0x28, 0x0f, 0xf5, 0x4f, 0xd0, 0xd3, 0x43, 0x52, 0xee, 0x33, 0x8f, 0x53, 0xfc, 0x1a, 0x9a, - 0xf1, 0xa5, 0x44, 0x55, 0x9a, 0xca, 0xea, 0xdc, 0xba, 0x6a, 0x8c, 0xd6, 0xd9, 0x88, 0x3d, 0x5a, - 0xa5, 0x7b, 0x0f, 0x1a, 0x05, 0x0b, 0xac, 0xdf, 0x2a, 0x7f, 0x7f, 0xb7, 0x51, 0xf8, 0xff, 0x6e, - 0xa3, 0xa0, 0x2f, 0xa0, 0x9a, 0x0c, 0xbc, 0x61, 0xdb, 0x2c, 0xf2, 0xc2, 0x01, 0xe0, 0x67, 0xe8, - 0x99, 0x11, 0x39, 0x40, 0x6e, 0xa1, 0x32, 0x01, 0x99, 0xaa, 0x34, 0xa7, 0x56, 0xe7, 0xd6, 0x75, - 0x03, 0x2a, 0x2a, 0xdf, 0x5e, 0x82, 0xfb, 0x3e, 0x73, 0xa2, 0x1e, 0x05, 0x77, 0x80, 0x1f, 0x78, - 0xea, 0x5f, 0xa0, 0x8a, 0x0c, 0xbf, 0xe9, 0xf8, 0x80, 0x88, 0x57, 0x50, 0xc5, 0x66, 0xbd, 0x1e, - 0x09, 0x69, 0x40, 0x7a, 0xed, 0xf0, 0xc0, 0xa7, 0x32, 0xa9, 0x59, 0x6b, 0x3e, 0x15, 0xef, 0x1e, - 0xf8, 0x14, 0x1b, 0x68, 0x9a, 0xdd, 0xf0, 0x68, 0xa0, 0x16, 0x85, 0xba, 0xa5, 0xfe, 0xf1, 0xfb, - 0x5a, 0x0d, 0x18, 0x6c, 0x38, 0x4e, 0x40, 0x39, 0xff, 0x30, 0x0c, 0x5c, 0xaf, 0x6b, 0xc5, 0x66, - 0xfa, 0x55, 0x54, 0x4d, 0xb1, 0x20, 0x8b, 0x57, 0xd1, 0x94, 0xed, 0xf8, 0x50, 0xb5, 0xe7, 0xf2, - 0x55, 0xdb, 0xdc, 0xda, 0x49, 0x6c, 0x81, 0xbb, 0xb0, 0xd7, 0xff, 0x55, 0xd2, 0x58, 0xfc, 0x49, - 0x13, 0xc7, 0x0b, 0xa8, 0xe8, 0x3a, 0xea, 0x54, 0x53, 0x59, 0x2d, 0xb5, 0x66, 0x0e, 0x1f, 0x34, - 0x8a, 0x57, 0xb7, 0xac, 0xa2, 0xeb, 0xe0, 0x1a, 0x9a, 0x0e, 0x44, 0x43, 0xaa, 0x25, 0x09, 0x13, - 0x3f, 0xe0, 0x6d, 0x84, 0xd2, 0xc1, 0x50, 0xa7, 0x65, 0x66, 0x17, 0x93, 0x57, 0x23, 0x26, 0xc3, - 0x88, 0x07, 0x32, 0x6d, 0x8c, 0x2e, 0x85, 0x14, 0xac, 0x8c, 0xa7, 0xfe, 0xab, 0x82, 0x9e, 0xca, - 0xe4, 0x08, 0x05, 0xbb, 0x82, 0x4a, 0xb6, 0xe3, 0x27, 0xaf, 0xfc, 0x84, 0x8a, 0xd5, 0x44, 0xc5, - 0x7e, 0x7b, 0xd8, 0x38, 0x9b, 0x11, 0x72, 0x4b, 0x06, 0xc0, 0x57, 0x86, 0x68, 0x16, 0x25, 0xcd, - 0x95, 0x13, 0x69, 0xc6, 0x31, 0x86, 0x78, 0x32, 0xe8, 0xdc, 0x2d, 0xea, 0x33, 0xee, 0x86, 0x4f, - 0xfc, 0x75, 0xe8, 0x9f, 0xc3, 0x48, 0xa4, 0x80, 0x83, 0xda, 0x94, 0x1d, 0x90, 0x41, 0x7d, 0x16, - 0xf3, 0xf5, 0x01, 0xaf, 0x56, 0x15, 0x6a, 0x53, 0x1e, 0x84, 0x19, 0x38, 0xeb, 0xef, 0x22, 0x4d, - 0x22, 0xec, 0xb2, 0x90, 0xf4, 0x76, 0x02, 0xd7, 0xb3, 0x5d, 0x9f, 0xf4, 0x1e, 0x37, 0x31, 0xfd, - 0x5b, 0x05, 0x3d, 0x3b, 0x36, 0x0e, 0xf0, 0xed, 0xa0, 0x4a, 0x28, 0x34, 0x6d, 0x3f, 0x51, 0x01, - 0xed, 0x66, 0x9e, 0xf6, 0x70, 0x88, 0xd6, 0x39, 0x60, 0x5f, 0x19, 0x96, 0x73, 0x6b, 0x3e, 0x1c, - 0x12, 0xe8, 0xdb, 0x59, 0x0a, 0x9b, 0x03, 0x7e, 0x8f, 0x9d, 0xcb, 0x6d, 0x05, 0x2d, 0x8d, 0x0f, - 0x04, 0xc9, 0xec, 0xa1, 0x6a, 0x9c, 0x4c, 0xea, 0x08, 0xd9, 0x2c, 0x4f, 0xc8, 0x26, 0x0d, 0xd2, - 0x52, 0x21, 0x9d, 0xea, 0x88, 0x82, 0x5b, 0x71, 0x85, 0x52, 0x89, 0xfe, 0x43, 0x09, 0xcd, 0x65, - 0xda, 0x19, 0x86, 0x53, 0x19, 0x37, 0x9c, 0x99, 0xae, 0x4a, 0x46, 0x19, 0xa3, 0x92, 0x4c, 0x72, - 0x4a, 0x0a, 0xe5, 0x7f, 0x7c, 0x19, 0xa1, 0x0c, 0xe7, 0x92, 0x9c, 0x84, 0xc5, 0xa1, 0x49, 0x18, - 0xcc, 0x16, 0x73, 0x3d, 0x58, 0x43, 0x19, 0x17, 0xfc, 0x0e, 0x9a, 0x4d, 0xdf, 0xe0, 0xf4, 0xe9, - 0xfc, 0x53, 0x0f, 0xfc, 0x1e, 0xaa, 0x12, 0xdb, 0x8e, 0xfa, 0x91, 0x88, 0xe7, 0xb4, 0xf7, 0x28, - 0xe5, 0xea, 0xcc, 0xe9, 0xa2, 0x54, 0x32, 0x8e, 0xdb, 0x94, 0x8a, 0xa9, 0x3e, 0x2b, 0xfc, 0xdb, - 0x91, 0xef, 0x08, 0x99, 0x7a, 0x46, 0xc6, 0xd1, 0x8c, 0xf8, 0x52, 0x1a, 0xc9, 0xa5, 0x34, 0x76, - 0x93, 0x4b, 0xd9, 0x2a, 0x8b, 0x40, 0x77, 0x1e, 0x36, 0x14, 0x6b, 0x4e, 0x78, 0x7e, 0x14, 0x3b, - 0x8a, 0xc6, 0x70, 0xbd, 0x90, 0x06, 0x94, 0x87, 0xed, 0x3d, 0x62, 0x87, 0x2c, 0x50, 0xcb, 0x71, - 0x63, 0x24, 0xe2, 0x6d, 0x29, 0x15, 0xec, 0x33, 0x1d, 0xb4, 0x4f, 0x7a, 0x11, 0x55, 0x67, 0x4f, - 0xc9, 0x3e, 0x75, 0xfc, 0x58, 0xf8, 0xe1, 0xd7, 0xd1, 0xb9, 0x54, 0xe4, 0x7e, 0x2d, 0xf7, 0x4b, - 0x3b, 0x5e, 0xb1, 0x48, 0x82, 0x2f, 0xe4, 0xd4, 0x96, 0xf8, 0x5d, 0xff, 0xeb, 0x0c, 0x9a, 0x96, - 0xdd, 0x89, 0x6f, 0xa0, 0x99, 0xf8, 0xd2, 0xe2, 0xe7, 0xf3, 0x6d, 0x97, 0x3f, 0xe8, 0xda, 0x85, - 0x13, 0xac, 0xe2, 0x2e, 0xd3, 0x9b, 0xdf, 0xfd, 0xf9, 0xdf, 0x8f, 0x45, 0x0d, 0xab, 0x66, 0xee, - 0xb3, 0x21, 0x3e, 0xe5, 0xf8, 0x1b, 0x54, 0x4e, 0x6e, 0x34, 0xbe, 0x38, 0x21, 0xe8, 0xc8, 0x71, - 0xd7, 0x56, 0x4e, 0xb4, 0x03, 0x78, 0x5d, 0xc2, 0x2f, 0x61, 0x2d, 0x0f, 0x9f, 0x9c, 0x72, 0xfc, - 0x93, 0x82, 0xe6, 0x87, 0xb7, 0x01, 0x7e, 0x69, 0x42, 0xfc, 0xb1, 0x7b, 0x4d, 0x5b, 0x3b, 0xa5, - 0x35, 0x70, 0x5a, 0x95, 0x9c, 0x74, 0xdc, 0xcc, 0x73, 0x1a, 0xde, 0x41, 0xf8, 0x67, 0x05, 0x55, - 0x46, 0x06, 0x1b, 0x1f, 0x0b, 0x96, 0xdb, 0x53, 0x9a, 0x71, 0x5a, 0x73, 0x20, 0xf7, 0x82, 0x24, - 0x77, 0x1e, 0x2f, 0x4f, 0x20, 0x97, 0x61, 0xc2, 0x50, 0x49, 0x5c, 0x58, 0xac, 0x4f, 0x80, 0xc8, - 0x7c, 0x62, 0x68, 0xe7, 0x8f, 0xb5, 0x01, 0xec, 0xba, 0xc4, 0x56, 0xf1, 0x82, 0x39, 0xee, 0xf3, - 0x93, 0xe3, 0xdb, 0x0a, 0x9a, 0xda, 0x74, 0x7c, 0xbc, 0x3c, 0x39, 0x58, 0x82, 0xa7, 0x1f, 0x67, - 0x02, 0x70, 0x6f, 0x48, 0xb8, 0x75, 0xfc, 0xf2, 0x78, 0x38, 0xf3, 0xa6, 0xdc, 0x7c, 0xb7, 0xcc, - 0x9b, 0x23, 0x8b, 0xfe, 0x16, 0xfe, 0x45, 0x41, 0x83, 0xeb, 0x37, 0xb1, 0x67, 0x47, 0xce, 0xfa, - 0xc4, 0x9e, 0x1d, 0xbd, 0xc6, 0xfa, 0x86, 0xe4, 0xf5, 0x36, 0x7e, 0x73, 0x02, 0xaf, 0xe4, 0xda, - 0x4e, 0x26, 0xd8, 0xba, 0x7c, 0xef, 0xb0, 0xae, 0xdc, 0x3f, 0xac, 0x2b, 0xff, 0x1c, 0xd6, 0x95, - 0x3b, 0x47, 0xf5, 0xc2, 0xfd, 0xa3, 0x7a, 0xe1, 0xef, 0xa3, 0x7a, 0xe1, 0xd3, 0x0b, 0x5d, 0x37, - 0xbc, 0x16, 0x75, 0x0c, 0x9b, 0xf5, 0x65, 0xf8, 0xb5, 0x1e, 0xe9, 0xf0, 0x18, 0xe8, 0x2b, 0x09, - 0x25, 0x02, 0xf0, 0xce, 0x8c, 0x5c, 0x78, 0xaf, 0x3c, 0x0a, 0x00, 0x00, 0xff, 0xff, 0x2f, 0x73, - 0xf8, 0x07, 0x15, 0x0d, 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 { - // Params queries all parameters of the cdp module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Accounts queries the CDP module accounts. - Accounts(ctx context.Context, in *QueryAccountsRequest, opts ...grpc.CallOption) (*QueryAccountsResponse, error) - // TotalPrincipal queries the total principal of a given collateral type. - TotalPrincipal(ctx context.Context, in *QueryTotalPrincipalRequest, opts ...grpc.CallOption) (*QueryTotalPrincipalResponse, error) - // TotalCollateral queries the total collateral of a given collateral type. - TotalCollateral(ctx context.Context, in *QueryTotalCollateralRequest, opts ...grpc.CallOption) (*QueryTotalCollateralResponse, error) - // Cdps queries all active CDPs. - Cdps(ctx context.Context, in *QueryCdpsRequest, opts ...grpc.CallOption) (*QueryCdpsResponse, error) - // Cdp queries a CDP with the input owner address and collateral type. - Cdp(ctx context.Context, in *QueryCdpRequest, opts ...grpc.CallOption) (*QueryCdpResponse, error) - // Deposits queries deposits associated with the CDP owned by an address for a collateral type. - Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, 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, "/kava.cdp.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Accounts(ctx context.Context, in *QueryAccountsRequest, opts ...grpc.CallOption) (*QueryAccountsResponse, error) { - out := new(QueryAccountsResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Query/Accounts", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalPrincipal(ctx context.Context, in *QueryTotalPrincipalRequest, opts ...grpc.CallOption) (*QueryTotalPrincipalResponse, error) { - out := new(QueryTotalPrincipalResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Query/TotalPrincipal", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalCollateral(ctx context.Context, in *QueryTotalCollateralRequest, opts ...grpc.CallOption) (*QueryTotalCollateralResponse, error) { - out := new(QueryTotalCollateralResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Query/TotalCollateral", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Cdps(ctx context.Context, in *QueryCdpsRequest, opts ...grpc.CallOption) (*QueryCdpsResponse, error) { - out := new(QueryCdpsResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Query/Cdps", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Cdp(ctx context.Context, in *QueryCdpRequest, opts ...grpc.CallOption) (*QueryCdpResponse, error) { - out := new(QueryCdpResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Query/Cdp", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) { - out := new(QueryDepositsResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Query/Deposits", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries all parameters of the cdp module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Accounts queries the CDP module accounts. - Accounts(context.Context, *QueryAccountsRequest) (*QueryAccountsResponse, error) - // TotalPrincipal queries the total principal of a given collateral type. - TotalPrincipal(context.Context, *QueryTotalPrincipalRequest) (*QueryTotalPrincipalResponse, error) - // TotalCollateral queries the total collateral of a given collateral type. - TotalCollateral(context.Context, *QueryTotalCollateralRequest) (*QueryTotalCollateralResponse, error) - // Cdps queries all active CDPs. - Cdps(context.Context, *QueryCdpsRequest) (*QueryCdpsResponse, error) - // Cdp queries a CDP with the input owner address and collateral type. - Cdp(context.Context, *QueryCdpRequest) (*QueryCdpResponse, error) - // Deposits queries deposits associated with the CDP owned by an address for a collateral type. - Deposits(context.Context, *QueryDepositsRequest) (*QueryDepositsResponse, 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) Accounts(ctx context.Context, req *QueryAccountsRequest) (*QueryAccountsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Accounts not implemented") -} -func (*UnimplementedQueryServer) TotalPrincipal(ctx context.Context, req *QueryTotalPrincipalRequest) (*QueryTotalPrincipalResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalPrincipal not implemented") -} -func (*UnimplementedQueryServer) TotalCollateral(ctx context.Context, req *QueryTotalCollateralRequest) (*QueryTotalCollateralResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalCollateral not implemented") -} -func (*UnimplementedQueryServer) Cdps(ctx context.Context, req *QueryCdpsRequest) (*QueryCdpsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Cdps not implemented") -} -func (*UnimplementedQueryServer) Cdp(ctx context.Context, req *QueryCdpRequest) (*QueryCdpResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Cdp not implemented") -} -func (*UnimplementedQueryServer) Deposits(ctx context.Context, req *QueryDepositsRequest) (*QueryDepositsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposits 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: "/kava.cdp.v1beta1.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_Accounts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAccountsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Accounts(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Query/Accounts", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Accounts(ctx, req.(*QueryAccountsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalPrincipal_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalPrincipalRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalPrincipal(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Query/TotalPrincipal", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalPrincipal(ctx, req.(*QueryTotalPrincipalRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalCollateral_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalCollateralRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalCollateral(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Query/TotalCollateral", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalCollateral(ctx, req.(*QueryTotalCollateralRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Cdps_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryCdpsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Cdps(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Query/Cdps", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Cdps(ctx, req.(*QueryCdpsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Cdp_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryCdpRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Cdp(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Query/Cdp", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Cdp(ctx, req.(*QueryCdpRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Deposits_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDepositsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Deposits(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Query/Deposits", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Deposits(ctx, req.(*QueryDepositsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.cdp.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Accounts", - Handler: _Query_Accounts_Handler, - }, - { - MethodName: "TotalPrincipal", - Handler: _Query_TotalPrincipal_Handler, - }, - { - MethodName: "TotalCollateral", - Handler: _Query_TotalCollateral_Handler, - }, - { - MethodName: "Cdps", - Handler: _Query_Cdps_Handler, - }, - { - MethodName: "Cdp", - Handler: _Query_Cdp_Handler, - }, - { - MethodName: "Deposits", - Handler: _Query_Deposits_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/cdp/v1beta1/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 *QueryAccountsRequest) 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 *QueryAccountsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAccountsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryAccountsResponse) 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 *QueryAccountsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAccountsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Accounts) > 0 { - for iNdEx := len(m.Accounts) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Accounts[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 (m *QueryCdpRequest) 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 *QueryCdpRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCdpRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintQuery(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryCdpResponse) 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 *QueryCdpResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCdpResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Cdp.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 *QueryCdpsRequest) 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 *QueryCdpsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCdpsRequest) 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] = 0x2a - } - if len(m.Ratio) > 0 { - i -= len(m.Ratio) - copy(dAtA[i:], m.Ratio) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Ratio))) - i-- - dAtA[i] = 0x22 - } - if m.ID != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.ID)) - i-- - dAtA[i] = 0x18 - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintQuery(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryCdpsResponse) 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 *QueryCdpsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCdpsResponse) 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.Cdps) > 0 { - for iNdEx := len(m.Cdps) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Cdps[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 (m *QueryDepositsRequest) 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 *QueryDepositsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintQuery(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDepositsResponse) 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 *QueryDepositsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[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 (m *QueryTotalPrincipalRequest) 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 *QueryTotalPrincipalRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalPrincipalRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintQuery(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalPrincipalResponse) 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 *QueryTotalPrincipalResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalPrincipalResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.TotalPrincipal) > 0 { - for iNdEx := len(m.TotalPrincipal) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TotalPrincipal[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 (m *QueryTotalCollateralRequest) 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 *QueryTotalCollateralRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalCollateralRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintQuery(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalCollateralResponse) 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 *QueryTotalCollateralResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalCollateralResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.TotalCollateral) > 0 { - for iNdEx := len(m.TotalCollateral) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TotalCollateral[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 (m *CDPResponse) 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 *CDPResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CDPResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CollateralizationRatio) > 0 { - i -= len(m.CollateralizationRatio) - copy(dAtA[i:], m.CollateralizationRatio) - i = encodeVarintQuery(dAtA, i, uint64(len(m.CollateralizationRatio))) - i-- - dAtA[i] = 0x52 - } - { - size, err := m.CollateralValue.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - if len(m.InterestFactor) > 0 { - i -= len(m.InterestFactor) - copy(dAtA[i:], m.InterestFactor) - i = encodeVarintQuery(dAtA, i, uint64(len(m.InterestFactor))) - i-- - dAtA[i] = 0x42 - } - n6, err6 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.FeesUpdated, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.FeesUpdated):]) - if err6 != nil { - return 0, err6 - } - i -= n6 - i = encodeVarintQuery(dAtA, i, uint64(n6)) - i-- - dAtA[i] = 0x3a - { - size, err := m.AccumulatedFees.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.Principal.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.Collateral.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - if len(m.Type) > 0 { - i -= len(m.Type) - copy(dAtA[i:], m.Type) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Type))) - i-- - dAtA[i] = 0x1a - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if m.ID != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.ID)) - i-- - dAtA[i] = 0x8 - } - 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 *QueryAccountsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryAccountsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Accounts) > 0 { - for _, e := range m.Accounts { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryCdpRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryCdpResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Cdp.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryCdpsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.ID != 0 { - n += 1 + sovQuery(uint64(m.ID)) - } - l = len(m.Ratio) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryCdpsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Cdps) > 0 { - for _, e := range m.Cdps { - 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 (m *QueryDepositsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDepositsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Deposits) > 0 { - for _, e := range m.Deposits { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryTotalPrincipalRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryTotalPrincipalResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.TotalPrincipal) > 0 { - for _, e := range m.TotalPrincipal { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryTotalCollateralRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryTotalCollateralResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.TotalCollateral) > 0 { - for _, e := range m.TotalCollateral { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *CDPResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.ID != 0 { - n += 1 + sovQuery(uint64(m.ID)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Type) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = m.Collateral.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.Principal.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.AccumulatedFees.Size() - n += 1 + l + sovQuery(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.FeesUpdated) - n += 1 + l + sovQuery(uint64(l)) - l = len(m.InterestFactor) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = m.CollateralValue.Size() - n += 1 + l + sovQuery(uint64(l)) - l = len(m.CollateralizationRatio) - if l > 0 { - 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 *QueryAccountsRequest) 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: QueryAccountsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAccountsRequest: 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 *QueryAccountsResponse) 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: QueryAccountsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAccountsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Accounts", 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.Accounts = append(m.Accounts, types.ModuleAccount{}) - if err := m.Accounts[len(m.Accounts)-1].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 *QueryCdpRequest) 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: QueryCdpRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCdpRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - 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 *QueryCdpResponse) 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: QueryCdpResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCdpResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Cdp", 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.Cdp.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 *QueryCdpsRequest) 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: QueryCdpsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCdpsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - m.ID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Ratio", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Ratio = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - 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 *QueryCdpsResponse) 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: QueryCdpsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCdpsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Cdps", 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.Cdps = append(m.Cdps, CDPResponse{}) - if err := m.Cdps[len(m.Cdps)-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 (m *QueryDepositsRequest) 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: QueryDepositsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - 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 *QueryDepositsResponse) 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: QueryDepositsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposits", 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.Deposits = append(m.Deposits, Deposit{}) - if err := m.Deposits[len(m.Deposits)-1].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 *QueryTotalPrincipalRequest) 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: QueryTotalPrincipalRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalPrincipalRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - 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 *QueryTotalPrincipalResponse) 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: QueryTotalPrincipalResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalPrincipalResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalPrincipal", 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.TotalPrincipal = append(m.TotalPrincipal, TotalPrincipal{}) - if err := m.TotalPrincipal[len(m.TotalPrincipal)-1].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 *QueryTotalCollateralRequest) 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: QueryTotalCollateralRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalCollateralRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - 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 *QueryTotalCollateralResponse) 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: QueryTotalCollateralResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalCollateralResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalCollateral", 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.TotalCollateral = append(m.TotalCollateral, TotalCollateral{}) - if err := m.TotalCollateral[len(m.TotalCollateral)-1].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 *CDPResponse) 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: CDPResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CDPResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - m.ID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Type = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Collateral", 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.Collateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Principal", 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.Principal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AccumulatedFees", 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.AccumulatedFees.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FeesUpdated", 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 := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.FeesUpdated, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InterestFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.InterestFactor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralValue", 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.CollateralValue.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralizationRatio", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralizationRatio = string(dAtA[iNdEx:postIndex]) - 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/cdp/types/query.pb.gw.go b/x/cdp/types/query.pb.gw.go deleted file mode 100644 index ca1fd21e..00000000 --- a/x/cdp/types/query.pb.gw.go +++ /dev/null @@ -1,713 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/cdp/v1beta1/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_Accounts_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAccountsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Accounts(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Accounts_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAccountsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Accounts(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_TotalPrincipal_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_TotalPrincipal_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalPrincipalRequest - 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_TotalPrincipal_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.TotalPrincipal(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalPrincipal_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalPrincipalRequest - 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_TotalPrincipal_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.TotalPrincipal(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_TotalCollateral_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_TotalCollateral_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalCollateralRequest - 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_TotalCollateral_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.TotalCollateral(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalCollateral_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalCollateralRequest - 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_TotalCollateral_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.TotalCollateral(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Cdps_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Cdps_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCdpsRequest - 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_Cdps_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Cdps(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Cdps_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCdpsRequest - 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_Cdps_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Cdps(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Cdp_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCdpRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["owner"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "owner") - } - - protoReq.Owner, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "owner", err) - } - - val, ok = pathParams["collateral_type"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "collateral_type") - } - - protoReq.CollateralType, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "collateral_type", err) - } - - msg, err := client.Cdp(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Cdp_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCdpRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["owner"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "owner") - } - - protoReq.Owner, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "owner", err) - } - - val, ok = pathParams["collateral_type"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "collateral_type") - } - - protoReq.CollateralType, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "collateral_type", err) - } - - msg, err := server.Cdp(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["owner"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "owner") - } - - protoReq.Owner, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "owner", err) - } - - val, ok = pathParams["collateral_type"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "collateral_type") - } - - protoReq.CollateralType, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "collateral_type", err) - } - - msg, err := client.Deposits(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["owner"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "owner") - } - - protoReq.Owner, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "owner", err) - } - - val, ok = pathParams["collateral_type"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "collateral_type") - } - - protoReq.CollateralType, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "collateral_type", err) - } - - msg, err := server.Deposits(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_Accounts_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_Accounts_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_Accounts_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalPrincipal_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_TotalPrincipal_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_TotalPrincipal_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalCollateral_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_TotalCollateral_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_TotalCollateral_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Cdps_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_Cdps_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_Cdps_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Cdp_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_Cdp_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_Cdp_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_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_Deposits_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_Deposits_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_Accounts_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_Accounts_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_Accounts_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalPrincipal_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_TotalPrincipal_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_TotalPrincipal_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalCollateral_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_TotalCollateral_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_TotalCollateral_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Cdps_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_Cdps_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_Cdps_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Cdp_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_Cdp_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_Cdp_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_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_Deposits_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_Deposits_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{"kava", "cdp", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Accounts_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "cdp", "v1beta1", "accounts"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalPrincipal_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "cdp", "v1beta1", "totalPrincipal"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalCollateral_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "cdp", "v1beta1", "totalCollateral"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Cdps_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "cdp", "v1beta1", "cdps"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Cdp_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 1, 0, 4, 1, 5, 5}, []string{"kava", "cdp", "v1beta1", "cdps", "owner", "collateral_type"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Deposits_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 1, 0, 4, 1, 5, 5, 1, 0, 4, 1, 5, 6}, []string{"kava", "cdp", "v1beta1", "cdps", "deposits", "owner", "collateral_type"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Accounts_0 = runtime.ForwardResponseMessage - - forward_Query_TotalPrincipal_0 = runtime.ForwardResponseMessage - - forward_Query_TotalCollateral_0 = runtime.ForwardResponseMessage - - forward_Query_Cdps_0 = runtime.ForwardResponseMessage - - forward_Query_Cdp_0 = runtime.ForwardResponseMessage - - forward_Query_Deposits_0 = runtime.ForwardResponseMessage -) diff --git a/x/cdp/types/tx.pb.go b/x/cdp/types/tx.pb.go deleted file mode 100644 index f21bd475..00000000 --- a/x/cdp/types/tx.pb.go +++ /dev/null @@ -1,3015 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/cdp/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - 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 - -// MsgCreateCDP defines a message to create a new CDP. -type MsgCreateCDP struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Collateral types.Coin `protobuf:"bytes,2,opt,name=collateral,proto3" json:"collateral"` - Principal types.Coin `protobuf:"bytes,3,opt,name=principal,proto3" json:"principal"` - CollateralType string `protobuf:"bytes,4,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` -} - -func (m *MsgCreateCDP) Reset() { *m = MsgCreateCDP{} } -func (m *MsgCreateCDP) String() string { return proto.CompactTextString(m) } -func (*MsgCreateCDP) ProtoMessage() {} -func (*MsgCreateCDP) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{0} -} -func (m *MsgCreateCDP) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgCreateCDP) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCreateCDP.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 *MsgCreateCDP) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCreateCDP.Merge(m, src) -} -func (m *MsgCreateCDP) XXX_Size() int { - return m.Size() -} -func (m *MsgCreateCDP) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCreateCDP.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCreateCDP proto.InternalMessageInfo - -func (m *MsgCreateCDP) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgCreateCDP) GetCollateral() types.Coin { - if m != nil { - return m.Collateral - } - return types.Coin{} -} - -func (m *MsgCreateCDP) GetPrincipal() types.Coin { - if m != nil { - return m.Principal - } - return types.Coin{} -} - -func (m *MsgCreateCDP) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -// MsgCreateCDPResponse defines the Msg/CreateCDP response type. -type MsgCreateCDPResponse struct { - CdpID uint64 `protobuf:"varint,1,opt,name=cdp_id,json=cdpId,proto3" json:"cdp_id,omitempty"` -} - -func (m *MsgCreateCDPResponse) Reset() { *m = MsgCreateCDPResponse{} } -func (m *MsgCreateCDPResponse) String() string { return proto.CompactTextString(m) } -func (*MsgCreateCDPResponse) ProtoMessage() {} -func (*MsgCreateCDPResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{1} -} -func (m *MsgCreateCDPResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgCreateCDPResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCreateCDPResponse.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 *MsgCreateCDPResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCreateCDPResponse.Merge(m, src) -} -func (m *MsgCreateCDPResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgCreateCDPResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCreateCDPResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCreateCDPResponse proto.InternalMessageInfo - -func (m *MsgCreateCDPResponse) GetCdpID() uint64 { - if m != nil { - return m.CdpID - } - return 0 -} - -// MsgDeposit defines a message to deposit to a CDP. -type MsgDeposit struct { - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Collateral types.Coin `protobuf:"bytes,3,opt,name=collateral,proto3" json:"collateral"` - CollateralType string `protobuf:"bytes,4,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` -} - -func (m *MsgDeposit) Reset() { *m = MsgDeposit{} } -func (m *MsgDeposit) String() string { return proto.CompactTextString(m) } -func (*MsgDeposit) ProtoMessage() {} -func (*MsgDeposit) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{2} -} -func (m *MsgDeposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDeposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDeposit.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 *MsgDeposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDeposit.Merge(m, src) -} -func (m *MsgDeposit) XXX_Size() int { - return m.Size() -} -func (m *MsgDeposit) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDeposit.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDeposit proto.InternalMessageInfo - -func (m *MsgDeposit) GetDepositor() string { - if m != nil { - return m.Depositor - } - return "" -} - -func (m *MsgDeposit) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *MsgDeposit) GetCollateral() types.Coin { - if m != nil { - return m.Collateral - } - return types.Coin{} -} - -func (m *MsgDeposit) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -// MsgDepositResponse defines the Msg/Deposit response type. -type MsgDepositResponse struct { -} - -func (m *MsgDepositResponse) Reset() { *m = MsgDepositResponse{} } -func (m *MsgDepositResponse) String() string { return proto.CompactTextString(m) } -func (*MsgDepositResponse) ProtoMessage() {} -func (*MsgDepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{3} -} -func (m *MsgDepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDepositResponse.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 *MsgDepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDepositResponse.Merge(m, src) -} -func (m *MsgDepositResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgDepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDepositResponse proto.InternalMessageInfo - -// MsgWithdraw defines a message to withdraw collateral from a CDP. -type MsgWithdraw struct { - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Collateral types.Coin `protobuf:"bytes,3,opt,name=collateral,proto3" json:"collateral"` - CollateralType string `protobuf:"bytes,4,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` -} - -func (m *MsgWithdraw) Reset() { *m = MsgWithdraw{} } -func (m *MsgWithdraw) String() string { return proto.CompactTextString(m) } -func (*MsgWithdraw) ProtoMessage() {} -func (*MsgWithdraw) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{4} -} -func (m *MsgWithdraw) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdraw) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdraw.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 *MsgWithdraw) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdraw.Merge(m, src) -} -func (m *MsgWithdraw) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdraw) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdraw.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdraw proto.InternalMessageInfo - -func (m *MsgWithdraw) GetDepositor() string { - if m != nil { - return m.Depositor - } - return "" -} - -func (m *MsgWithdraw) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *MsgWithdraw) GetCollateral() types.Coin { - if m != nil { - return m.Collateral - } - return types.Coin{} -} - -func (m *MsgWithdraw) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -type MsgWithdrawResponse struct { -} - -func (m *MsgWithdrawResponse) Reset() { *m = MsgWithdrawResponse{} } -func (m *MsgWithdrawResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawResponse) ProtoMessage() {} -func (*MsgWithdrawResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{5} -} -func (m *MsgWithdrawResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawResponse.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 *MsgWithdrawResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawResponse.Merge(m, src) -} -func (m *MsgWithdrawResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawResponse proto.InternalMessageInfo - -// MsgDrawDebt defines a message to draw debt from a CDP. -type MsgDrawDebt struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - CollateralType string `protobuf:"bytes,2,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Principal types.Coin `protobuf:"bytes,3,opt,name=principal,proto3" json:"principal"` -} - -func (m *MsgDrawDebt) Reset() { *m = MsgDrawDebt{} } -func (m *MsgDrawDebt) String() string { return proto.CompactTextString(m) } -func (*MsgDrawDebt) ProtoMessage() {} -func (*MsgDrawDebt) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{6} -} -func (m *MsgDrawDebt) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDrawDebt) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDrawDebt.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 *MsgDrawDebt) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDrawDebt.Merge(m, src) -} -func (m *MsgDrawDebt) XXX_Size() int { - return m.Size() -} -func (m *MsgDrawDebt) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDrawDebt.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDrawDebt proto.InternalMessageInfo - -func (m *MsgDrawDebt) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgDrawDebt) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func (m *MsgDrawDebt) GetPrincipal() types.Coin { - if m != nil { - return m.Principal - } - return types.Coin{} -} - -// MsgDrawDebtResponse defines the Msg/DrawDebt response type. -type MsgDrawDebtResponse struct { -} - -func (m *MsgDrawDebtResponse) Reset() { *m = MsgDrawDebtResponse{} } -func (m *MsgDrawDebtResponse) String() string { return proto.CompactTextString(m) } -func (*MsgDrawDebtResponse) ProtoMessage() {} -func (*MsgDrawDebtResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{7} -} -func (m *MsgDrawDebtResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDrawDebtResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDrawDebtResponse.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 *MsgDrawDebtResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDrawDebtResponse.Merge(m, src) -} -func (m *MsgDrawDebtResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgDrawDebtResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDrawDebtResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDrawDebtResponse proto.InternalMessageInfo - -// MsgRepayDebt defines a message to repay debt from a CDP. -type MsgRepayDebt struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - CollateralType string `protobuf:"bytes,2,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Payment types.Coin `protobuf:"bytes,3,opt,name=payment,proto3" json:"payment"` -} - -func (m *MsgRepayDebt) Reset() { *m = MsgRepayDebt{} } -func (m *MsgRepayDebt) String() string { return proto.CompactTextString(m) } -func (*MsgRepayDebt) ProtoMessage() {} -func (*MsgRepayDebt) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{8} -} -func (m *MsgRepayDebt) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgRepayDebt) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgRepayDebt.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 *MsgRepayDebt) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgRepayDebt.Merge(m, src) -} -func (m *MsgRepayDebt) XXX_Size() int { - return m.Size() -} -func (m *MsgRepayDebt) XXX_DiscardUnknown() { - xxx_messageInfo_MsgRepayDebt.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgRepayDebt proto.InternalMessageInfo - -func (m *MsgRepayDebt) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgRepayDebt) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func (m *MsgRepayDebt) GetPayment() types.Coin { - if m != nil { - return m.Payment - } - return types.Coin{} -} - -// MsgRepayDebtResponse defines the Msg/RepayDebt response type. -type MsgRepayDebtResponse struct { -} - -func (m *MsgRepayDebtResponse) Reset() { *m = MsgRepayDebtResponse{} } -func (m *MsgRepayDebtResponse) String() string { return proto.CompactTextString(m) } -func (*MsgRepayDebtResponse) ProtoMessage() {} -func (*MsgRepayDebtResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{9} -} -func (m *MsgRepayDebtResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgRepayDebtResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgRepayDebtResponse.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 *MsgRepayDebtResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgRepayDebtResponse.Merge(m, src) -} -func (m *MsgRepayDebtResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgRepayDebtResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgRepayDebtResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgRepayDebtResponse proto.InternalMessageInfo - -// MsgLiquidate defines a message to attempt to liquidate a CDP whos -// collateralization ratio is under its liquidation ratio. -type MsgLiquidate struct { - Keeper string `protobuf:"bytes,1,opt,name=keeper,proto3" json:"keeper,omitempty"` - Borrower string `protobuf:"bytes,2,opt,name=borrower,proto3" json:"borrower,omitempty"` - CollateralType string `protobuf:"bytes,3,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` -} - -func (m *MsgLiquidate) Reset() { *m = MsgLiquidate{} } -func (m *MsgLiquidate) String() string { return proto.CompactTextString(m) } -func (*MsgLiquidate) ProtoMessage() {} -func (*MsgLiquidate) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{10} -} -func (m *MsgLiquidate) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgLiquidate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgLiquidate.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 *MsgLiquidate) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgLiquidate.Merge(m, src) -} -func (m *MsgLiquidate) XXX_Size() int { - return m.Size() -} -func (m *MsgLiquidate) XXX_DiscardUnknown() { - xxx_messageInfo_MsgLiquidate.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgLiquidate proto.InternalMessageInfo - -func (m *MsgLiquidate) GetKeeper() string { - if m != nil { - return m.Keeper - } - return "" -} - -func (m *MsgLiquidate) GetBorrower() string { - if m != nil { - return m.Borrower - } - return "" -} - -func (m *MsgLiquidate) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -// MsgLiquidateResponse defines the Msg/Liquidate response type. -type MsgLiquidateResponse struct { -} - -func (m *MsgLiquidateResponse) Reset() { *m = MsgLiquidateResponse{} } -func (m *MsgLiquidateResponse) String() string { return proto.CompactTextString(m) } -func (*MsgLiquidateResponse) ProtoMessage() {} -func (*MsgLiquidateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{11} -} -func (m *MsgLiquidateResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgLiquidateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgLiquidateResponse.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 *MsgLiquidateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgLiquidateResponse.Merge(m, src) -} -func (m *MsgLiquidateResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgLiquidateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgLiquidateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgLiquidateResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgCreateCDP)(nil), "kava.cdp.v1beta1.MsgCreateCDP") - proto.RegisterType((*MsgCreateCDPResponse)(nil), "kava.cdp.v1beta1.MsgCreateCDPResponse") - proto.RegisterType((*MsgDeposit)(nil), "kava.cdp.v1beta1.MsgDeposit") - proto.RegisterType((*MsgDepositResponse)(nil), "kava.cdp.v1beta1.MsgDepositResponse") - proto.RegisterType((*MsgWithdraw)(nil), "kava.cdp.v1beta1.MsgWithdraw") - proto.RegisterType((*MsgWithdrawResponse)(nil), "kava.cdp.v1beta1.MsgWithdrawResponse") - proto.RegisterType((*MsgDrawDebt)(nil), "kava.cdp.v1beta1.MsgDrawDebt") - proto.RegisterType((*MsgDrawDebtResponse)(nil), "kava.cdp.v1beta1.MsgDrawDebtResponse") - proto.RegisterType((*MsgRepayDebt)(nil), "kava.cdp.v1beta1.MsgRepayDebt") - proto.RegisterType((*MsgRepayDebtResponse)(nil), "kava.cdp.v1beta1.MsgRepayDebtResponse") - proto.RegisterType((*MsgLiquidate)(nil), "kava.cdp.v1beta1.MsgLiquidate") - proto.RegisterType((*MsgLiquidateResponse)(nil), "kava.cdp.v1beta1.MsgLiquidateResponse") -} - -func init() { proto.RegisterFile("kava/cdp/v1beta1/tx.proto", fileDescriptor_3b8c9334ad8ab0d3) } - -var fileDescriptor_3b8c9334ad8ab0d3 = []byte{ - // 639 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xdc, 0x55, 0xc1, 0x6e, 0xd3, 0x4c, - 0x10, 0x8e, 0x9b, 0x26, 0x6d, 0xb6, 0xbf, 0x7e, 0x90, 0x09, 0x28, 0x89, 0xc0, 0x8d, 0x22, 0x0a, - 0xbd, 0xd4, 0xa6, 0x05, 0x21, 0x38, 0xa0, 0x8a, 0x24, 0x97, 0x4a, 0x44, 0xaa, 0x5c, 0x24, 0x24, - 0x2e, 0xd1, 0xda, 0xbb, 0x72, 0xad, 0x26, 0xde, 0x65, 0x77, 0xdb, 0x34, 0x6f, 0xc1, 0x1b, 0x70, - 0x41, 0xe2, 0x05, 0x78, 0x88, 0x1e, 0x2b, 0x4e, 0x9c, 0x02, 0x4a, 0x4e, 0x3c, 0x01, 0x57, 0x64, - 0xaf, 0xbd, 0x8e, 0x52, 0x27, 0x04, 0x10, 0x17, 0x6e, 0xeb, 0xfd, 0x66, 0x3e, 0x7d, 0xdf, 0x78, - 0x66, 0x16, 0x54, 0x4f, 0xe0, 0x19, 0xb4, 0x5c, 0x44, 0xad, 0xb3, 0x5d, 0x07, 0x0b, 0xb8, 0x6b, - 0x89, 0x73, 0x93, 0x32, 0x22, 0x88, 0x7e, 0x3d, 0x84, 0x4c, 0x17, 0x51, 0x33, 0x86, 0x6a, 0x86, - 0x4b, 0x78, 0x9f, 0x70, 0xcb, 0x81, 0x1c, 0xab, 0x78, 0x97, 0xf8, 0x81, 0xcc, 0xa8, 0x55, 0x25, - 0xde, 0x8d, 0xbe, 0x2c, 0xf9, 0x11, 0x43, 0x65, 0x8f, 0x78, 0x44, 0xde, 0x87, 0x27, 0x79, 0xdb, - 0xf8, 0xa6, 0x81, 0xff, 0x3a, 0xdc, 0x6b, 0x31, 0x0c, 0x05, 0x6e, 0xb5, 0x0f, 0xf5, 0x07, 0xa0, - 0xc8, 0x71, 0x80, 0x30, 0xab, 0x68, 0x75, 0x6d, 0xbb, 0xd4, 0xac, 0x7c, 0xfa, 0xb8, 0x53, 0x8e, - 0x89, 0x9e, 0x23, 0xc4, 0x30, 0xe7, 0x47, 0x82, 0xf9, 0x81, 0x67, 0xc7, 0x71, 0xfa, 0x3e, 0x00, - 0x2e, 0xe9, 0xf5, 0xa0, 0xc0, 0x0c, 0xf6, 0x2a, 0x2b, 0x75, 0x6d, 0x7b, 0x63, 0xaf, 0x6a, 0xc6, - 0x29, 0xa1, 0xd0, 0x44, 0xbd, 0xd9, 0x22, 0x7e, 0xd0, 0x5c, 0xbd, 0x18, 0x6d, 0xe6, 0xec, 0xa9, - 0x14, 0xfd, 0x19, 0x28, 0x51, 0xe6, 0x07, 0xae, 0x4f, 0x61, 0xaf, 0x92, 0x5f, 0x2e, 0x3f, 0xcd, - 0xd0, 0xef, 0x83, 0x6b, 0x29, 0x59, 0x57, 0x0c, 0x29, 0xae, 0xac, 0x86, 0xd2, 0xed, 0xff, 0xd3, - 0xeb, 0x97, 0x43, 0x8a, 0x1b, 0x4f, 0x40, 0x79, 0xda, 0xaa, 0x8d, 0x39, 0x25, 0x01, 0xc7, 0x7a, - 0x1d, 0x14, 0x5d, 0x44, 0xbb, 0x3e, 0x8a, 0x2c, 0xaf, 0x36, 0x4b, 0xe3, 0xd1, 0x66, 0xa1, 0x85, - 0xe8, 0x41, 0xdb, 0x2e, 0xb8, 0x88, 0x1e, 0xa0, 0xc6, 0x48, 0x03, 0xa0, 0xc3, 0xbd, 0x36, 0xa6, - 0x84, 0xfb, 0x42, 0x7f, 0x0c, 0x4a, 0x48, 0x1e, 0xc9, 0xcf, 0xcb, 0x94, 0x86, 0xea, 0x26, 0x28, - 0x90, 0x41, 0x80, 0x59, 0x54, 0xa4, 0x45, 0x39, 0x32, 0x6c, 0xa6, 0xb2, 0xf9, 0x5f, 0xaf, 0xec, - 0xd2, 0xa5, 0x29, 0x03, 0x3d, 0xf5, 0x97, 0x14, 0xa6, 0xf1, 0x45, 0x03, 0x1b, 0x1d, 0xee, 0xbd, - 0xf2, 0xc5, 0x31, 0x62, 0x70, 0xf0, 0x0f, 0xfa, 0xbe, 0x09, 0x6e, 0x4c, 0x19, 0x54, 0xc6, 0x3f, - 0x48, 0xe3, 0x6d, 0x06, 0x07, 0x6d, 0xec, 0x88, 0xdf, 0x18, 0x8a, 0x0c, 0x05, 0x2b, 0x59, 0x0a, - 0xfe, 0xb0, 0xf9, 0x63, 0x03, 0x89, 0x50, 0x65, 0xe0, 0xbd, 0x1c, 0x6b, 0x1b, 0x53, 0x38, 0xfc, - 0xdb, 0x0e, 0x9e, 0x82, 0x35, 0x0a, 0x87, 0x7d, 0x1c, 0x88, 0x65, 0xf5, 0x27, 0xf1, 0x8d, 0x5b, - 0xd1, 0x44, 0x2a, 0x95, 0x4a, 0xfe, 0x3b, 0x29, 0xff, 0x85, 0xff, 0xe6, 0xd4, 0x47, 0x50, 0xe0, - 0x50, 0xfe, 0x09, 0xc6, 0x74, 0x19, 0xf9, 0x32, 0x4e, 0x7f, 0x04, 0xd6, 0x1d, 0xc2, 0x18, 0x19, - 0x2c, 0xd1, 0x76, 0x2a, 0x32, 0xcb, 0x74, 0x3e, 0xb3, 0x71, 0xa4, 0x72, 0x25, 0x30, 0x51, 0xbe, - 0xf7, 0x3d, 0x0f, 0xf2, 0x1d, 0xee, 0xe9, 0x47, 0xa0, 0x94, 0xee, 0x54, 0xc3, 0x9c, 0x5d, 0xe4, - 0xe6, 0xf4, 0x22, 0xaa, 0xdd, 0x5b, 0x8c, 0xab, 0x45, 0xd5, 0x01, 0x6b, 0xc9, 0x0a, 0xba, 0x9d, - 0x99, 0x12, 0xa3, 0xb5, 0xbb, 0x8b, 0x50, 0x45, 0x77, 0x08, 0xd6, 0xd5, 0x68, 0xdf, 0xc9, 0xcc, - 0x48, 0xe0, 0xda, 0xd6, 0x42, 0x78, 0x9a, 0x51, 0xcd, 0x4c, 0x36, 0x63, 0x02, 0xcf, 0x61, 0x9c, - 0x6d, 0xe4, 0xb0, 0x8e, 0x69, 0x13, 0x67, 0xd7, 0x51, 0xe1, 0x73, 0xea, 0x78, 0xa5, 0xbd, 0x42, - 0xd2, 0xb4, 0xb5, 0xb2, 0x49, 0x15, 0x3e, 0x87, 0xf4, 0xca, 0x9f, 0x6f, 0xee, 0x5f, 0x8c, 0x0d, - 0xed, 0x72, 0x6c, 0x68, 0x5f, 0xc7, 0x86, 0xf6, 0x76, 0x62, 0xe4, 0x2e, 0x27, 0x46, 0xee, 0xf3, - 0xc4, 0xc8, 0xbd, 0xde, 0xf2, 0x7c, 0x71, 0x7c, 0xea, 0x98, 0x2e, 0xe9, 0x5b, 0x21, 0xd7, 0x4e, - 0x0f, 0x3a, 0x3c, 0x3a, 0x59, 0xe7, 0xd1, 0xc3, 0x1f, 0xf6, 0x19, 0x77, 0x8a, 0xd1, 0x8b, 0xfc, - 0xf0, 0x47, 0x00, 0x00, 0x00, 0xff, 0xff, 0x2f, 0x75, 0x8a, 0x38, 0x11, 0x08, 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 { - // CreateCDP defines a method to create a new CDP. - CreateCDP(ctx context.Context, in *MsgCreateCDP, opts ...grpc.CallOption) (*MsgCreateCDPResponse, error) - // Deposit defines a method to deposit to a CDP. - Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) - // Withdraw defines a method to withdraw collateral from a CDP. - Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) - // DrawDebt defines a method to draw debt from a CDP. - DrawDebt(ctx context.Context, in *MsgDrawDebt, opts ...grpc.CallOption) (*MsgDrawDebtResponse, error) - // RepayDebt defines a method to repay debt from a CDP. - RepayDebt(ctx context.Context, in *MsgRepayDebt, opts ...grpc.CallOption) (*MsgRepayDebtResponse, error) - // Liquidate defines a method to attempt to liquidate a CDP whos - // collateralization ratio is under its liquidation ratio. - Liquidate(ctx context.Context, in *MsgLiquidate, opts ...grpc.CallOption) (*MsgLiquidateResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) CreateCDP(ctx context.Context, in *MsgCreateCDP, opts ...grpc.CallOption) (*MsgCreateCDPResponse, error) { - out := new(MsgCreateCDPResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Msg/CreateCDP", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) { - out := new(MsgDepositResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Msg/Deposit", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) { - out := new(MsgWithdrawResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Msg/Withdraw", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) DrawDebt(ctx context.Context, in *MsgDrawDebt, opts ...grpc.CallOption) (*MsgDrawDebtResponse, error) { - out := new(MsgDrawDebtResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Msg/DrawDebt", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) RepayDebt(ctx context.Context, in *MsgRepayDebt, opts ...grpc.CallOption) (*MsgRepayDebtResponse, error) { - out := new(MsgRepayDebtResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Msg/RepayDebt", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Liquidate(ctx context.Context, in *MsgLiquidate, opts ...grpc.CallOption) (*MsgLiquidateResponse, error) { - out := new(MsgLiquidateResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Msg/Liquidate", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // CreateCDP defines a method to create a new CDP. - CreateCDP(context.Context, *MsgCreateCDP) (*MsgCreateCDPResponse, error) - // Deposit defines a method to deposit to a CDP. - Deposit(context.Context, *MsgDeposit) (*MsgDepositResponse, error) - // Withdraw defines a method to withdraw collateral from a CDP. - Withdraw(context.Context, *MsgWithdraw) (*MsgWithdrawResponse, error) - // DrawDebt defines a method to draw debt from a CDP. - DrawDebt(context.Context, *MsgDrawDebt) (*MsgDrawDebtResponse, error) - // RepayDebt defines a method to repay debt from a CDP. - RepayDebt(context.Context, *MsgRepayDebt) (*MsgRepayDebtResponse, error) - // Liquidate defines a method to attempt to liquidate a CDP whos - // collateralization ratio is under its liquidation ratio. - Liquidate(context.Context, *MsgLiquidate) (*MsgLiquidateResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) CreateCDP(ctx context.Context, req *MsgCreateCDP) (*MsgCreateCDPResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method CreateCDP not implemented") -} -func (*UnimplementedMsgServer) Deposit(ctx context.Context, req *MsgDeposit) (*MsgDepositResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposit not implemented") -} -func (*UnimplementedMsgServer) Withdraw(ctx context.Context, req *MsgWithdraw) (*MsgWithdrawResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Withdraw not implemented") -} -func (*UnimplementedMsgServer) DrawDebt(ctx context.Context, req *MsgDrawDebt) (*MsgDrawDebtResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DrawDebt not implemented") -} -func (*UnimplementedMsgServer) RepayDebt(ctx context.Context, req *MsgRepayDebt) (*MsgRepayDebtResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RepayDebt not implemented") -} -func (*UnimplementedMsgServer) Liquidate(ctx context.Context, req *MsgLiquidate) (*MsgLiquidateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Liquidate not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_CreateCDP_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgCreateCDP) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).CreateCDP(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Msg/CreateCDP", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).CreateCDP(ctx, req.(*MsgCreateCDP)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Deposit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgDeposit) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Deposit(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Msg/Deposit", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Deposit(ctx, req.(*MsgDeposit)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Withdraw_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdraw) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Withdraw(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Msg/Withdraw", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Withdraw(ctx, req.(*MsgWithdraw)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_DrawDebt_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgDrawDebt) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).DrawDebt(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Msg/DrawDebt", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).DrawDebt(ctx, req.(*MsgDrawDebt)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_RepayDebt_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgRepayDebt) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).RepayDebt(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Msg/RepayDebt", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).RepayDebt(ctx, req.(*MsgRepayDebt)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Liquidate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgLiquidate) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Liquidate(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Msg/Liquidate", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Liquidate(ctx, req.(*MsgLiquidate)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.cdp.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "CreateCDP", - Handler: _Msg_CreateCDP_Handler, - }, - { - MethodName: "Deposit", - Handler: _Msg_Deposit_Handler, - }, - { - MethodName: "Withdraw", - Handler: _Msg_Withdraw_Handler, - }, - { - MethodName: "DrawDebt", - Handler: _Msg_DrawDebt_Handler, - }, - { - MethodName: "RepayDebt", - Handler: _Msg_RepayDebt_Handler, - }, - { - MethodName: "Liquidate", - Handler: _Msg_Liquidate_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/cdp/v1beta1/tx.proto", -} - -func (m *MsgCreateCDP) 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 *MsgCreateCDP) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCreateCDP) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintTx(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x22 - } - { - size, err := m.Principal.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.Collateral.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgCreateCDPResponse) 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 *MsgCreateCDPResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCreateCDPResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.CdpID != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.CdpID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *MsgDeposit) 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 *MsgDeposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDeposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintTx(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x22 - } - { - size, err := m.Collateral.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintTx(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgDepositResponse) 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 *MsgDepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgWithdraw) 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 *MsgWithdraw) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdraw) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintTx(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x22 - } - { - size, err := m.Collateral.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintTx(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawResponse) 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 *MsgWithdrawResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgDrawDebt) 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 *MsgDrawDebt) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDrawDebt) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Principal.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintTx(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgDrawDebtResponse) 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 *MsgDrawDebtResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDrawDebtResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgRepayDebt) 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 *MsgRepayDebt) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgRepayDebt) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Payment.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintTx(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgRepayDebtResponse) 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 *MsgRepayDebtResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgRepayDebtResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgLiquidate) 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 *MsgLiquidate) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgLiquidate) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintTx(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x1a - } - if len(m.Borrower) > 0 { - i -= len(m.Borrower) - copy(dAtA[i:], m.Borrower) - i = encodeVarintTx(dAtA, i, uint64(len(m.Borrower))) - i-- - dAtA[i] = 0x12 - } - if len(m.Keeper) > 0 { - i -= len(m.Keeper) - copy(dAtA[i:], m.Keeper) - i = encodeVarintTx(dAtA, i, uint64(len(m.Keeper))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgLiquidateResponse) 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 *MsgLiquidateResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgLiquidateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgCreateCDP) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Collateral.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.Principal.Size() - n += 1 + l + sovTx(uint64(l)) - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgCreateCDPResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CdpID != 0 { - n += 1 + sovTx(uint64(m.CdpID)) - } - return n -} - -func (m *MsgDeposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Collateral.Size() - n += 1 + l + sovTx(uint64(l)) - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgDepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgWithdraw) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Collateral.Size() - n += 1 + l + sovTx(uint64(l)) - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgWithdrawResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgDrawDebt) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Principal.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgDrawDebtResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgRepayDebt) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Payment.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgRepayDebtResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgLiquidate) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Keeper) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Borrower) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgLiquidateResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgCreateCDP) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgCreateCDP: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCreateCDP: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Collateral", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Collateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Principal", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Principal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgCreateCDPResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgCreateCDPResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCreateCDPResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CdpID", wireType) - } - m.CdpID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CdpID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDeposit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDeposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDeposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Collateral", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Collateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDepositResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdraw) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdraw: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdraw: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Collateral", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Collateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDrawDebt) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDrawDebt: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDrawDebt: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Principal", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Principal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDrawDebtResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDrawDebtResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDrawDebtResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgRepayDebt) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgRepayDebt: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgRepayDebt: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Payment", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Payment.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgRepayDebtResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgRepayDebtResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgRepayDebtResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgLiquidate) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgLiquidate: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgLiquidate: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Keeper", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Keeper = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Borrower", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Borrower = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgLiquidateResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgLiquidateResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgLiquidateResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/cdp/types/utils.go b/x/cdp/types/utils.go deleted file mode 100644 index 518fc0fd..00000000 --- a/x/cdp/types/utils.go +++ /dev/null @@ -1,100 +0,0 @@ -package types - -import ( - "bytes" - "fmt" - "strings" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// MaxSortableDec largest sortable sdk.Dec -var MaxSortableDec = sdk.OneDec().Quo(sdk.SmallestDec()) - -// ValidSortableDec sdk.Dec can't have precision of less than 10^-18 -func ValidSortableDec(dec sdk.Dec) bool { - return dec.Abs().LTE(MaxSortableDec) -} - -// SortableDecBytes returns a byte slice representation of a Dec that can be sorted. -// Left and right pads with 0s so there are 18 digits to left and right of the decimal point. -// For this reason, there is a maximum and minimum value for this, enforced by ValidSortableDec. -func SortableDecBytes(dec sdk.Dec) []byte { - if !ValidSortableDec(dec) { - panic("dec must be within bounds") - } - // Instead of adding an extra byte to all sortable decs in order to handle max sortable, we just - // makes its bytes be "max" which comes after all numbers in ASCIIbetical order - if dec.Equal(MaxSortableDec) { - return []byte("max") - } - // For the same reason, we make the bytes of minimum sortable dec be --, which comes before all numbers. - if dec.Equal(MaxSortableDec.Neg()) { - return []byte("--") - } - // We move the negative sign to the front of all the left padded 0s, to make negative numbers come before positive numbers - if dec.IsNegative() { - return append([]byte("-"), []byte(fmt.Sprintf(fmt.Sprintf("%%0%ds", sdk.Precision*2+1), dec.Abs().String()))...) - } - return []byte(fmt.Sprintf(fmt.Sprintf("%%0%ds", sdk.Precision*2+1), dec.String())) -} - -// ParseDecBytes parses a []byte encoded using SortableDecBytes back to sdk.Dec -func ParseDecBytes(db []byte) (sdk.Dec, error) { - strFromDecBytes := strings.Trim(string(db[:]), "0") - if string(strFromDecBytes[0]) == "." { - strFromDecBytes = "0" + strFromDecBytes - } - if string(strFromDecBytes[len(strFromDecBytes)-1]) == "." { - strFromDecBytes = strFromDecBytes + "0" - } - if bytes.Equal(db, []byte("max")) { - return MaxSortableDec, nil - } - if bytes.Equal(db, []byte("--")) { - return MaxSortableDec.Neg(), nil - } - dec, err := sdk.NewDecFromStr(strFromDecBytes) - if err != nil { - return sdk.Dec{}, err - } - return dec, nil -} - -// RelativePow raises x to the power of n, where x (and the result, z) are scaled by factor b. -// For example, RelativePow(210, 2, 100) = 441 (2.1^2 = 4.41) -// Only defined for positive ints. -func RelativePow(x sdkmath.Int, n sdkmath.Int, b sdkmath.Int) (z sdkmath.Int) { - if x.IsZero() { - if n.IsZero() { - z = b // 0^0 = 1 - return - } - z = sdk.ZeroInt() // otherwise 0^a = 0 - return - } - - z = x - if n.Mod(sdkmath.NewInt(2)).Equal(sdk.ZeroInt()) { - z = b - } - - halfOfB := b.Quo(sdkmath.NewInt(2)) - n = n.Quo(sdkmath.NewInt(2)) - - for n.GT(sdk.ZeroInt()) { - xSquared := x.Mul(x) - xSquaredRounded := xSquared.Add(halfOfB) - - x = xSquaredRounded.Quo(b) - - if n.Mod(sdkmath.NewInt(2)).Equal(sdk.OneInt()) { - zx := z.Mul(x) - zxRounded := zx.Add(halfOfB) - z = zxRounded.Quo(b) - } - n = n.Quo(sdkmath.NewInt(2)) - } - return -} diff --git a/x/cdp/types/utils_test.go b/x/cdp/types/utils_test.go deleted file mode 100644 index 88856df1..00000000 --- a/x/cdp/types/utils_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestSortableDecBytes(t *testing.T) { - tests := []struct { - d sdk.Dec - want []byte - }{ - {sdk.NewDec(0), []byte("000000000000000000.000000000000000000")}, - {sdk.NewDec(1), []byte("000000000000000001.000000000000000000")}, - {sdk.MustNewDecFromStr("2.0"), []byte("000000000000000002.000000000000000000")}, - {sdk.MustNewDecFromStr("-2.0"), []byte("-000000000000000002.000000000000000000")}, - {sdk.NewDec(10), []byte("000000000000000010.000000000000000000")}, - {sdk.NewDec(12340), []byte("000000000000012340.000000000000000000")}, - {sdk.NewDecWithPrec(12340, 4), []byte("000000000000000001.234000000000000000")}, - {sdk.NewDecWithPrec(12340, 5), []byte("000000000000000000.123400000000000000")}, - {sdk.NewDecWithPrec(12340, 8), []byte("000000000000000000.000123400000000000")}, - {sdk.NewDecWithPrec(1009009009009009009, 17), []byte("000000000000000010.090090090090090090")}, - {sdk.NewDecWithPrec(-1009009009009009009, 17), []byte("-000000000000000010.090090090090090090")}, - {sdk.NewDec(1000000000000000000), []byte("max")}, - {sdk.NewDec(-1000000000000000000), []byte("--")}, - } - for tcIndex, tc := range tests { - assert.Equal(t, tc.want, SortableDecBytes(tc.d), "bad String(), index: %v", tcIndex) - } - - assert.Panics(t, func() { SortableDecBytes(sdk.NewDec(1000000000000000001)) }) - assert.Panics(t, func() { SortableDecBytes(sdk.NewDec(-1000000000000000001)) }) -} - -func TestParseSortableDecBytes(t *testing.T) { - tests := []struct { - d sdk.Dec - want []byte - }{ - {sdk.NewDec(0), []byte("000000000000000000.000000000000000000")}, - {sdk.NewDec(1), []byte("000000000000000001.000000000000000000")}, - {sdk.MustNewDecFromStr("2.0"), []byte("000000000000000002.000000000000000000")}, - {sdk.MustNewDecFromStr("-2.0"), []byte("-000000000000000002.000000000000000000")}, - {sdk.NewDec(10), []byte("000000000000000010.000000000000000000")}, - {sdk.NewDec(12340), []byte("000000000000012340.000000000000000000")}, - {sdk.NewDecWithPrec(12340, 4), []byte("000000000000000001.234000000000000000")}, - {sdk.NewDecWithPrec(12340, 5), []byte("000000000000000000.123400000000000000")}, - {sdk.NewDecWithPrec(12340, 8), []byte("000000000000000000.000123400000000000")}, - {sdk.NewDecWithPrec(1009009009009009009, 17), []byte("000000000000000010.090090090090090090")}, - {sdk.NewDecWithPrec(-1009009009009009009, 17), []byte("-000000000000000010.090090090090090090")}, - {sdk.NewDec(1000000000000000000), []byte("max")}, - {sdk.NewDec(-1000000000000000000), []byte("--")}, - } - for tcIndex, tc := range tests { - b := SortableDecBytes(tc.d) - r, err := ParseDecBytes(b) - assert.NoError(t, err) - assert.Equal(t, tc.d, r, "bad Dec(), index: %v", tcIndex) - } -} - -func TestRelativePow(t *testing.T) { - tests := []struct { - args []sdkmath.Int - want sdkmath.Int - }{ - {[]sdkmath.Int{sdk.ZeroInt(), sdk.ZeroInt(), sdk.OneInt()}, sdk.OneInt()}, - {[]sdkmath.Int{sdk.ZeroInt(), sdk.ZeroInt(), sdkmath.NewInt(10)}, sdkmath.NewInt(10)}, - {[]sdkmath.Int{sdk.ZeroInt(), sdk.OneInt(), sdkmath.NewInt(10)}, sdk.ZeroInt()}, - {[]sdkmath.Int{sdkmath.NewInt(10), sdkmath.NewInt(2), sdk.OneInt()}, sdkmath.NewInt(100)}, - {[]sdkmath.Int{sdkmath.NewInt(210), sdkmath.NewInt(2), sdkmath.NewInt(100)}, sdkmath.NewInt(441)}, - {[]sdkmath.Int{sdkmath.NewInt(2100), sdkmath.NewInt(2), sdkmath.NewInt(1000)}, sdkmath.NewInt(4410)}, - {[]sdkmath.Int{sdkmath.NewInt(1000000001547125958), sdkmath.NewInt(600), sdkmath.NewInt(1000000000000000000)}, sdkmath.NewInt(1000000928276004850)}, - } - for i, tc := range tests { - res := RelativePow(tc.args[0], tc.args[1], tc.args[2]) - require.Equal(t, tc.want, res, "unexpected result for test case %d, input: %v, got: %v", i, tc.args, res) - } -} diff --git a/x/committee/abci.go b/x/committee/abci.go deleted file mode 100644 index 107c2289..00000000 --- a/x/committee/abci.go +++ /dev/null @@ -1,20 +0,0 @@ -package committee - -import ( - "time" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/kava-labs/kava/x/committee/keeper" - "github.com/kava-labs/kava/x/committee/types" -) - -// BeginBlocker runs at the start of every block. -func BeginBlocker(ctx sdk.Context, _ abci.RequestBeginBlock, k keeper.Keeper) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - - k.ProcessProposals(ctx) -} diff --git a/x/committee/abci_test.go b/x/committee/abci_test.go deleted file mode 100644 index 80bba989..00000000 --- a/x/committee/abci_test.go +++ /dev/null @@ -1,228 +0,0 @@ -package committee_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - "github.com/kava-labs/kava/app" - // "github.com/kava-labs/kava/x/cdp" - // cdptypes "github.com/kava-labs/kava/x/cdp/types" - "github.com/kava-labs/kava/x/committee" - "github.com/kava-labs/kava/x/committee/keeper" - "github.com/kava-labs/kava/x/committee/testutil" - "github.com/kava-labs/kava/x/committee/types" -) - -type ModuleTestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context - - addresses []sdk.AccAddress -} - -func (suite *ModuleTestSuite) SetupTest() { - suite.app = app.NewTestApp() - suite.keeper = suite.app.GetCommitteeKeeper() - suite.ctx = suite.app.NewContext(true, tmproto.Header{}) - _, suite.addresses = app.GeneratePrivKeyAddressPairs(5) -} - -func (suite *ModuleTestSuite) TestBeginBlock_ClosesExpired() { - suite.app.InitializeFromGenesisStates() - - memberCom := types.MustNewMemberCommittee( - 12, - "This committee is for testing.", - suite.addresses[:2], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.8"), - time.Hour*24*7, - types.TALLY_OPTION_DEADLINE, - ) - suite.keeper.SetCommittee(suite.ctx, memberCom) - - pprop1 := govv1beta1.NewTextProposal("Title 1", "A description of this proposal.") - id1, err := suite.keeper.SubmitProposal(suite.ctx, memberCom.Members[0], memberCom.ID, pprop1) - suite.NoError(err) - - oneHrLaterCtx := suite.ctx.WithBlockTime(suite.ctx.BlockTime().Add(time.Hour)) - pprop2 := govv1beta1.NewTextProposal("Title 2", "A description of this proposal.") - id2, err := suite.keeper.SubmitProposal(oneHrLaterCtx, memberCom.Members[0], memberCom.ID, pprop2) - suite.NoError(err) - - // Run BeginBlocker - proposalDurationLaterCtx := suite.ctx.WithBlockTime(suite.ctx.BlockTime().Add(memberCom.ProposalDuration)) - suite.NotPanics(func() { - committee.BeginBlocker(proposalDurationLaterCtx, abci.RequestBeginBlock{}, suite.keeper) - }) - - // Check expired proposals are gone - _, found := suite.keeper.GetProposal(suite.ctx, id1) - suite.False(found, "expected expired proposal to be closed") - _, found = suite.keeper.GetProposal(suite.ctx, id2) - suite.True(found, "expected non expired proposal to be not closed") -} - -// func (suite *ModuleTestSuite) TestBeginBlock_EnactsPassed() { -// suite.app.InitializeFromGenesisStates() - -// // setup committee -// normalCom := types.MustNewMemberCommittee(12, "committee description", suite.addresses[:2], -// []types.Permission{&types.GodPermission{}}, testutil.D("0.8"), time.Hour*24*7, types.TALLY_OPTION_FIRST_PAST_THE_POST) - -// suite.keeper.SetCommittee(suite.ctx, normalCom) - -// // setup 2 proposals -// previousCDPDebtThreshold := suite.app.GetCDPKeeper().GetParams(suite.ctx).DebtAuctionThreshold -// newDebtThreshold := previousCDPDebtThreshold.Add(i(1000000)) -// evenNewerDebtThreshold := newDebtThreshold.Add(i(1000000)) - -// pprop1 := params.NewParameterChangeProposal("Title 1", "A description of this proposal.", -// []params.ParamChange{{ -// Subspace: cdptypes.ModuleName, -// Key: string(cdp.KeyDebtThreshold), -// Value: string(cdp.ModuleCdc.MustMarshalJSON(newDebtThreshold)), -// }}, -// ) -// id1, err := suite.keeper.SubmitProposal(suite.ctx, normalCom.Members[0], normalCom.ID, pprop1) -// suite.NoError(err) - -// pprop2 := params.NewParameterChangeProposal("Title 2", "A description of this proposal.", -// []params.ParamChange{{ -// Subspace: cdptypes.ModuleName, -// Key: string(cdp.KeyDebtThreshold), -// Value: string(cdp.ModuleCdc.MustMarshalJSON(evenNewerDebtThreshold)), -// }}, -// ) -// id2, err := suite.keeper.SubmitProposal(suite.ctx, normalCom.Members[0], normalCom.ID, pprop2) -// suite.NoError(err) - -// // add enough votes to make the first proposal pass, but not the second -// suite.NoError(suite.keeper.AddVote(suite.ctx, id1, suite.addresses[0], types.Yes)) -// suite.NoError(suite.keeper.AddVote(suite.ctx, id1, suite.addresses[1], types.Yes)) -// suite.NoError(suite.keeper.AddVote(suite.ctx, id2, suite.addresses[0], types.Yes)) - -// // Run BeginBlocker -// suite.NotPanics(func() { -// committee.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}, suite.keeper) -// }) - -// // Check the param has been updated -// suite.Equal(newDebtThreshold, suite.app.GetCDPKeeper().GetParams(suite.ctx).DebtAuctionThreshold) -// // Check the passed proposal has gone -// _, found := suite.keeper.GetProposal(suite.ctx, id1) -// suite.False(found, "expected passed proposal to be enacted and closed") -// _, found = suite.keeper.GetProposal(suite.ctx, id2) -// suite.True(found, "expected non passed proposal to be not closed") -// } - -// func (suite *ModuleTestSuite) TestBeginBlock_DoesntEnactFailed() { -// suite.app.InitializeFromGenesisStates() - -// // setup committee -// memberCom := types.MustNewMemberCommittee(12, "committee description", suite.addresses[:1], -// []types.Permission{types.SoftwareUpgradePermission{}}, testutil.D("1.0"), time.Hour*24*7, types.TALLY_OPTION_FIRST_PAST_THE_POST) - -// firstBlockTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) -// ctx := suite.ctx.WithBlockTime(firstBlockTime) -// suite.keeper.SetCommittee(ctx, memberCom) - -// // setup an upgrade proposal -// pprop1 := upgradetypes.NewSoftwareUpgradeProposal("Title 1", "A description of this proposal.", -// upgradetypes.Plan{ -// Name: "upgrade-version-v0.23.1", -// Time: firstBlockTime.Add(time.Second * 5), -// Info: "some information about the upgrade", -// }, -// ) -// id1, err := suite.keeper.SubmitProposal(ctx, memberCom.Members[0], memberCom.ID, pprop1) -// suite.NoError(err) - -// // add enough votes to make the proposal pass -// suite.NoError(suite.keeper.AddVote(ctx, id1, suite.addresses[0], types.Yes)) - -// // Run BeginBlocker 10 seconds later (5 seconds after upgrade expires) -// tenSecLaterCtx := ctx.WithBlockTime(ctx.BlockTime().Add(time.Second * 10)) -// suite.NotPanics(func() { -// suite.app.BeginBlocker(tenSecLaterCtx, abci.RequestBeginBlock{}) -// }) - -// // Check the plan has not been stored -// _, found := suite.app.GetUpgradeKeeper().GetUpgradePlan(tenSecLaterCtx) -// suite.False(found) -// // Check the passed proposal has gone -// _, found = suite.keeper.GetProposal(tenSecLaterCtx, id1) -// suite.False(found, "expected failed proposal to be not enacted and closed") - -// // Check the chain doesn't halt -// oneMinLaterCtx := ctx.WithBlockTime(ctx.BlockTime().Add(time.Minute).Add(time.Second)) -// suite.NotPanics(func() { -// suite.app.BeginBlocker(oneMinLaterCtx, abci.RequestBeginBlock{}) -// }) -// } - -// func (suite *ModuleTestSuite) TestBeginBlock_EnactsPassedUpgrade() { -// suite.app.InitializeFromGenesisStates() - -// // setup committee -// memberCom := types.MustNewMemberCommittee( -// 12, -// "committee description", -// suite.addresses[:1], -// []types.Permission{types.SoftwareUpgradePermission{}}, -// testutil.D("1.0"), -// time.Hour*24*7, -// types.TALLY_OPTION_FIRST_PAST_THE_POST, -// ) - -// firstBlockTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) -// ctx := suite.ctx.WithBlockTime(firstBlockTime) -// suite.keeper.SetCommittee(ctx, memberCom) - -// // setup an upgrade proposal -// pprop1 := upgradetypes.NewSoftwareUpgradeProposal("Title 1", "A description of this proposal.", -// upgradetypes.Plan{ -// Name: "upgrade-version-v0.23.1", -// Time: firstBlockTime.Add(time.Minute * 1), -// Info: "some information about the upgrade", -// }, -// ) -// id1, err := suite.keeper.SubmitProposal(ctx, memberCom.Members[0], memberCom.ID, pprop1) -// suite.NoError(err) - -// // add enough votes to make the proposal pass -// suite.NoError(suite.keeper.AddVote(ctx, id1, suite.addresses[0], types.Yes)) - -// // Run BeginBlocker -// fiveSecLaterCtx := ctx.WithBlockTime(ctx.BlockTime().Add(time.Second * 5)) -// suite.NotPanics(func() { -// suite.app.BeginBlocker(fiveSecLaterCtx, abci.RequestBeginBlock{}) -// }) - -// // Check the plan has been stored -// _, found := suite.app.GetUpgradeKeeper().GetUpgradePlan(fiveSecLaterCtx) -// suite.True(found) -// // Check the passed proposal has gone -// _, found = suite.keeper.GetProposal(fiveSecLaterCtx, id1) -// suite.False(found, "expected passed proposal to be enacted and closed") - -// // Check the chain halts -// oneMinLaterCtx := ctx.WithBlockTime(ctx.BlockTime().Add(time.Minute)) -// suite.Panics(func() { -// suite.app.BeginBlocker(oneMinLaterCtx, abci.RequestBeginBlock{}) -// }) -// } - -func TestModuleTestSuite(t *testing.T) { - suite.Run(t, new(ModuleTestSuite)) -} diff --git a/x/committee/client/cli/cli_test.go b/x/committee/client/cli/cli_test.go deleted file mode 100644 index 7ec6de7b..00000000 --- a/x/committee/client/cli/cli_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package cli_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/committee/client/cli" -) - -type CLITestSuite struct { - suite.Suite - cdc codec.Codec -} - -func (suite *CLITestSuite) SetupTest() { - tApp := app.NewTestApp() - suite.cdc = tApp.AppCodec() -} - -func (suite *CLITestSuite) TestExampleCommitteeChangeProposal_NotPanics() { - suite.NotPanics(func() { cli.MustGetExampleCommitteeChangeProposal(suite.cdc) }) -} - -func (suite *CLITestSuite) TestExampleCommitteeDeleteProposal_NotPanics() { - suite.NotPanics(func() { cli.MustGetExampleCommitteeDeleteProposal(suite.cdc) }) -} - -func (suite *CLITestSuite) TestExampleParameterChangeProposal_NotPanics() { - suite.NotPanics(func() { cli.MustGetExampleParameterChangeProposal(suite.cdc) }) -} - -func TestCLITestSuite(t *testing.T) { - suite.Run(t, new(CLITestSuite)) -} diff --git a/x/committee/client/cli/query.go b/x/committee/client/cli/query.go deleted file mode 100644 index 3d09124a..00000000 --- a/x/committee/client/cli/query.go +++ /dev/null @@ -1,318 +0,0 @@ -package cli - -import ( - "context" - "fmt" - "strconv" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/version" - "github.com/kava-labs/kava/x/committee/client/common" - "github.com/kava-labs/kava/x/committee/types" -) - -// GetQueryCmd returns the cli query commands for this module -func GetQueryCmd() *cobra.Command { - queryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName), - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - // committees - getCmdQueryCommittee(), - getCmdQueryCommittees(), - // proposals - getCmdQueryNextProposalID(), - getCmdQueryProposal(), - getCmdQueryProposals(), - // votes - getCmdQueryVotes(), - // other - getCmdQueryProposer(), - getCmdQueryTally(), - getCmdQueryRawParams(), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - queryCmd.AddCommand(cmds...) - - return queryCmd -} - -// ------------------------------------------ -// Committees -// ------------------------------------------ - -// getCmdQueryCommittee implements a query committee command. -func getCmdQueryCommittee() *cobra.Command { - return &cobra.Command{ - Use: "committee [committee-id]", - Args: cobra.ExactArgs(1), - Short: "Query details of a single committee", - Example: fmt.Sprintf("%s query %s committee 1", version.AppName, types.ModuleName), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - // validate that the committee id is a uint - committeeID, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return fmt.Errorf("committee-id %s not a valid uint, please input a valid committee-id", args[0]) - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.Committee(context.Background(), &types.QueryCommitteeRequest{CommitteeId: committeeID}) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - } -} - -// getCmdQueryCommittees implements a query committees command. -func getCmdQueryCommittees() *cobra.Command { - return &cobra.Command{ - Use: "committees", - Args: cobra.NoArgs, - Short: "Query all committees", - Example: fmt.Sprintf("%s query %s committees", version.AppName, types.ModuleName), - 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.Committees(context.Background(), &types.QueryCommitteesRequest{}) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - } -} - -// ------------------------------------------ -// Proposals -// ------------------------------------------ - -// getCmdQueryNextProposalID implements a query next proposal ID command. -func getCmdQueryNextProposalID() *cobra.Command { - return &cobra.Command{ - Use: "next-proposal-id", - Short: "Query the next proposal ID", - Args: cobra.ExactArgs(0), - Example: fmt.Sprintf("%s query %s next-proposal-id", version.AppName, types.ModuleName), - 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.NextProposalID(context.Background(), &types.QueryNextProposalIDRequest{}) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - } -} - -// getCmdQueryProposal implements the query proposal command. -func getCmdQueryProposal() *cobra.Command { - return &cobra.Command{ - Use: "proposal [proposal-id]", - Args: cobra.ExactArgs(1), - Short: "Query details of a single proposal", - Example: fmt.Sprintf("%s query %s proposal 2", version.AppName, types.ModuleName), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - // Prepare params for querier - proposalID, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return fmt.Errorf("proposal-id %s not a valid uint", args[0]) - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.Proposal(context.Background(), &types.QueryProposalRequest{ - ProposalId: proposalID, - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -// getCmdQueryProposals implements a query proposals command. -func getCmdQueryProposals() *cobra.Command { - return &cobra.Command{ - Use: "proposals [committee-id]", - Short: "Query all proposals for a committee", - Args: cobra.ExactArgs(1), - Example: fmt.Sprintf("%s query %s proposals 1", version.AppName, types.ModuleName), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - // Prepare params for querier - committeeID, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return fmt.Errorf("committee-id %s not a valid uint", args[0]) - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.Proposals(context.Background(), &types.QueryProposalsRequest{ - CommitteeId: committeeID, - }) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - } -} - -// ------------------------------------------ -// Votes -// ------------------------------------------ - -// getCmdQueryVotes implements the command to query for proposal votes. -func getCmdQueryVotes() *cobra.Command { - return &cobra.Command{ - Use: "votes [proposal-id]", - Args: cobra.ExactArgs(1), - Short: "Query votes on a proposal", - Example: fmt.Sprintf("%s query %s votes 2", version.AppName, types.ModuleName), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - // Prepare params for querier - proposalID, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return fmt.Errorf("proposal-id %s not a valid int", args[0]) - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.Votes(context.Background(), &types.QueryVotesRequest{ - ProposalId: proposalID, - }) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - } -} - -// ------------------------------------------ -// Other -// ------------------------------------------ - -func getCmdQueryTally() *cobra.Command { - return &cobra.Command{ - Use: "tally [proposal-id]", - Args: cobra.ExactArgs(1), - Short: "Get the current tally of votes on a proposal", - Long: "Query the current tally of votes on a proposal to see the progress of the voting.", - Example: fmt.Sprintf("%s query %s tally 2", version.AppName, types.ModuleName), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - // Prepare params for querier - proposalID, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return fmt.Errorf("proposal-id %s not a valid int", args[0]) - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.Tally(context.Background(), &types.QueryTallyRequest{ - ProposalId: proposalID, - }) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - } -} - -func getCmdQueryProposer() *cobra.Command { - return &cobra.Command{ - Use: "proposer [proposal-id]", - Args: cobra.ExactArgs(1), - Short: "Query the proposer of a governance proposal", - Long: "Query which address proposed a proposal with a given ID.", - Example: fmt.Sprintf("%s query %s proposer 2", version.AppName, types.ModuleName), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - // validate that the proposalID is a uint - proposalID, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return fmt.Errorf("proposal-id %s is not a valid uint", args[0]) - } - prop, err := common.QueryProposer(clientCtx, proposalID) - if err != nil { - return err - } - - return clientCtx.PrintObjectLegacy(prop) - }, - } -} - -func getCmdQueryRawParams() *cobra.Command { - return &cobra.Command{ - Use: "raw-params [subspace] [key]", - Args: cobra.ExactArgs(2), - Short: "Query raw parameter values from any module.", - Long: "Query the byte value of any module's parameters. Useful in debugging and verifying governance proposals.", - Example: fmt.Sprintf("%s query %s raw-params cdp CollateralParams", version.AppName, types.ModuleName), - 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.RawParams(context.Background(), &types.QueryRawParamsRequest{ - Subspace: args[0], - Key: args[1], - }) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - } -} diff --git a/x/committee/client/cli/tx.go b/x/committee/client/cli/tx.go deleted file mode 100644 index 8aaaa882..00000000 --- a/x/committee/client/cli/tx.go +++ /dev/null @@ -1,325 +0,0 @@ -package cli - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "strconv" - "strings" - "time" - - "github.com/cometbft/cometbft/crypto" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - paramsproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - - "github.com/kava-labs/kava/x/committee/types" -) - -const PARAMS_CHANGE_PROPOSAL_EXAMPLE = ` -{ - "@type": "/cosmos.params.v1beta1.ParameterChangeProposal", - "title": "title", - "description": "description", - "changes": [{ "subspace": "subspace", "key": "key", "value": "value" }] -} -` - -const COMMITTEE_CHANGE_PROPOSAL_EXAMPLE = ` -{ - "@type": "/kava.committee.v1beta1.CommitteeChangeProposal", - "title": "A Title", - "description": "A proposal description.", - "new_committee": { - "@type": "/kava.committee.v1beta1.MemberCommittee", - "base_committee": { - "id": "34", - "description": "member committee", - "members": ["kava1ze7y9qwdddejmy7jlw4cymqqlt2wh05yhwmrv2"], - "permissions": [], - "vote_threshold": "1.000000000000000000", - "proposal_duration": "86400s", - "tally_option": "TALLY_OPTION_DEADLINE" - } - } -} -` - -const COMMITTEE_DELETE_PROPOSAL_EXAMPLE = ` -{ - "@type": "/kava.committee.v1beta1.CommitteeDeleteProposal", - "title": "A Title", - "description": "A proposal description.", - "committee_id": "1" -} -` - -func GetTxCmd() *cobra.Command { - txCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "committee governance transactions subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - getCmdVote(), - getCmdSubmitProposal(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - txCmd.AddCommand(cmds...) - - return txCmd -} - -// getCmdSubmitProposal returns the command to submit a proposal to a committee -func getCmdSubmitProposal() *cobra.Command { - cmd := &cobra.Command{ - Use: "submit-proposal [committee-id] [proposal-file]", - Short: "Submit a governance proposal to a particular committee", - Long: fmt.Sprintf(`Submit a proposal to a committee so they can vote on it. - -The proposal file must be the json encoded forms of the proposal type you want to submit. -For example: -%s -`, PARAMS_CHANGE_PROPOSAL_EXAMPLE), - Args: cobra.ExactArgs(2), - Example: fmt.Sprintf("%s tx %s submit-proposal 1 your-proposal.json", version.AppName, types.ModuleName), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - // Get proposing address - proposer := clientCtx.GetFromAddress() - - // Get committee ID - committeeID, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return fmt.Errorf("committee-id %s not a valid int", args[0]) - } - - // Get proposal content - var pubProposal types.PubProposal - contents, err := ioutil.ReadFile(args[1]) - if err != nil { - return err - } - if err := clientCtx.Codec.UnmarshalInterfaceJSON(contents, &pubProposal); err != nil { - return err - } - if err = pubProposal.ValidateBasic(); err != nil { - return err - } - - // Build message and run basic validation - msg, err := types.NewMsgSubmitProposal(pubProposal, proposer, committeeID) - if err != nil { - return err - } - err = msg.ValidateBasic() - if err != nil { - return err - } - - // Sign and broadcast message - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - return cmd -} - -// getCmdVote returns the command to vote on a proposal. -func getCmdVote() *cobra.Command { - return &cobra.Command{ - Use: "vote [proposal-id] [vote]", - Args: cobra.ExactArgs(2), - Short: "Vote for an active proposal", - Long: "Submit a [yes/no/abstain] vote for the proposal with id [proposal-id].", - Example: fmt.Sprintf("%s tx %s vote 2 yes", version.AppName, types.ModuleName), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - // Get voting address - from := clientCtx.GetFromAddress() - - // validate that the proposal id is a uint - proposalID, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return fmt.Errorf("proposal-id %s not a valid int, please input a valid proposal-id", args[0]) - } - - rawVote := strings.ToLower(strings.TrimSpace(args[1])) - if len(rawVote) == 0 { - return fmt.Errorf("must specify a vote") - } - - var vote types.VoteType - switch rawVote { - case "yes", "y": - vote = types.VOTE_TYPE_YES - case "no", "n": - vote = types.VOTE_TYPE_NO - case "abstain", "a": - vote = types.VOTE_TYPE_ABSTAIN - default: - return fmt.Errorf("must specify a valid vote type: (yes/y, no/n, abstain/a)") - } - - // Build vote message and run basic validation - msg := types.NewMsgVote(from, proposalID, vote) - err = msg.ValidateBasic() - if err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} - -// GetGovCmdSubmitProposal returns a command to submit a proposal to the gov module. It is passed to the gov module for use on its command subtree. -func GetGovCmdSubmitProposal() *cobra.Command { - cmd := &cobra.Command{ - Use: "committee [proposal-file] [deposit]", - Short: "Submit a governance proposal to change a committee.", - Long: fmt.Sprintf(`Submit a governance proposal to create, alter, or delete a committee. - -The proposal file must be the json encoded form of the proposal type you want to submit. -For example, to create or update a committee: -%s - -and to delete a committee: -%s -`, COMMITTEE_CHANGE_PROPOSAL_EXAMPLE, COMMITTEE_DELETE_PROPOSAL_EXAMPLE), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - // Get proposing address - proposer := clientCtx.GetFromAddress() - - // Get the deposit - deposit, err := sdk.ParseCoinsNormalized(args[1]) - if err != nil { - return err - } - - // Get the proposal - bz, err := ioutil.ReadFile(args[0]) - if err != nil { - return err - } - var content govv1beta1.Content - if err := clientCtx.Codec.UnmarshalInterfaceJSON(bz, &content); err != nil { - return err - } - if err = content.ValidateBasic(); err != nil { - return err - } - - // Build message and run basic validation - msg, err := govv1beta1.NewMsgSubmitProposal(content, deposit, proposer) - if err != nil { - return err - } - err = msg.ValidateBasic() - if err != nil { - return err - } - - // Sign and broadcast message - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - return cmd -} - -// MustGetExampleCommitteeChangeProposal is a helper function to return an example json proposal -func MustGetExampleCommitteeChangeProposal(cdc codec.Codec) string { - exampleChangeProposal, err := types.NewCommitteeChangeProposal( - "A Title", - "A description of this proposal.", - types.MustNewMemberCommittee( - 1, - "The description of this committee.", - []sdk.AccAddress{sdk.AccAddress(crypto.AddressHash([]byte("exampleAddress")))}, - []types.Permission{ - &types.GodPermission{}, - }, - sdk.MustNewDecFromStr("0.8"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ), - ) - if err != nil { - panic(err) - } - exampleChangeProposalBz, err := cdc.MarshalJSON(&exampleChangeProposal) - if err != nil { - panic(err) - } - var out bytes.Buffer - if err = json.Indent(&out, exampleChangeProposalBz, "", " "); err != nil { - panic(err) - } - return out.String() -} - -// MustGetExampleCommitteeDeleteProposal is a helper function to return an example json proposal -func MustGetExampleCommitteeDeleteProposal(cdc codec.Codec) string { - exampleDeleteProposal := types.NewCommitteeDeleteProposal( - "A Title", - "A description of this proposal.", - 1, - ) - bz, err := cdc.MarshalJSON(&exampleDeleteProposal) - if err != nil { - panic(err) - } - var out bytes.Buffer - if err = json.Indent(&out, bz, "", " "); err != nil { - panic(err) - } - return out.String() -} - -// MustGetExampleParameterChangeProposal is a helper function to return an example json proposal -func MustGetExampleParameterChangeProposal(cdc codec.Codec) string { - value := fmt.Sprintf("\"%d\"", 1000000000) - exampleParameterChangeProposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []paramsproposal.ParamChange{paramsproposal.NewParamChange("cdp", "SurplusAuctionThreshold", value)}, - ) - bz, err := cdc.MarshalJSON(exampleParameterChangeProposal) - if err != nil { - panic(err) - } - var out bytes.Buffer - if err = json.Indent(&out, bz, "", " "); err != nil { - panic(err) - } - return out.String() -} diff --git a/x/committee/client/common/query.go b/x/committee/client/common/query.go deleted file mode 100644 index 5efe31da..00000000 --- a/x/committee/client/common/query.go +++ /dev/null @@ -1,59 +0,0 @@ -package common - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" - authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" - - "github.com/kava-labs/kava/x/committee/types" -) - -// Note: QueryProposer is copied in from the gov module - -const ( - defaultPage = 1 - defaultLimit = 30 // should be consistent with tendermint/tendermint/rpc/core/pipe.go:19 -) - -// Proposer contains metadata of a governance proposal used for querying a proposer. -type Proposer struct { - ProposalID uint64 `json:"proposal_id" yaml:"proposal_id"` - Proposer string `json:"proposer" yaml:"proposer"` -} - -// NewProposer returns a new Proposer given id and proposer -func NewProposer(proposalID uint64, proposer string) Proposer { - return Proposer{proposalID, proposer} -} - -func (p Proposer) String() string { - return fmt.Sprintf("Proposal with ID %d was proposed by %s", p.ProposalID, p.Proposer) -} - -// QueryProposer will query for a proposer of a governance proposal by ID. -func QueryProposer(cliCtx client.Context, proposalID uint64) (Proposer, error) { - events := []string{ - fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeMsgSubmitProposal), - fmt.Sprintf("%s.%s='%s'", types.EventTypeProposalSubmit, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", proposalID))), - } - - // NOTE: SearchTxs is used to facilitate the txs query which does not currently - // support configurable pagination. - searchResult, err := authtx.QueryTxsByEvents(cliCtx, events, defaultPage, defaultLimit, "") - if err != nil { - return Proposer{}, err - } - - for _, info := range searchResult.Txs { - for _, msg := range info.GetTx().GetMsgs() { - // there should only be a single proposal under the given conditions - if subMsg, ok := msg.(*types.MsgSubmitProposal); ok { - return NewProposer(proposalID, subMsg.Proposer), nil - } - } - } - - return Proposer{}, fmt.Errorf("failed to find the proposer for proposalID %d", proposalID) -} diff --git a/x/committee/client/proposal_handler.go b/x/committee/client/proposal_handler.go deleted file mode 100644 index f2494526..00000000 --- a/x/committee/client/proposal_handler.go +++ /dev/null @@ -1,10 +0,0 @@ -package client - -import ( - govclient "github.com/cosmos/cosmos-sdk/x/gov/client" - - "github.com/kava-labs/kava/x/committee/client/cli" -) - -// ProposalHandler is a struct containing handler funcs for submiting CommitteeChange/Delete proposal txs to the gov module through the cli or rest. -var ProposalHandler = govclient.NewProposalHandler(cli.GetGovCmdSubmitProposal) diff --git a/x/committee/genesis.go b/x/committee/genesis.go deleted file mode 100644 index 7f9f9672..00000000 --- a/x/committee/genesis.go +++ /dev/null @@ -1,47 +0,0 @@ -package committee - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/committee/keeper" - "github.com/kava-labs/kava/x/committee/types" -) - -// InitGenesis initializes the store state from a genesis state. -func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, gs *types.GenesisState) { - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - keeper.SetNextProposalID(ctx, gs.NextProposalID) - - for _, com := range gs.GetCommittees() { - keeper.SetCommittee(ctx, com) - } - for _, p := range gs.Proposals { - keeper.SetProposal(ctx, p) - } - for _, v := range gs.Votes { - keeper.SetVote(ctx, v) - } -} - -// ExportGenesis returns a GenesisState for a given context and keeper. -func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) *types.GenesisState { - nextID, err := keeper.GetNextProposalID(ctx) - if err != nil { - panic(err) - } - committees := keeper.GetCommittees(ctx) - proposals := keeper.GetProposals(ctx) - votes := keeper.GetVotes(ctx) - - return types.NewGenesisState( - nextID, - committees, - proposals, - votes, - ) -} diff --git a/x/committee/genesis_test.go b/x/committee/genesis_test.go deleted file mode 100644 index 64f321f0..00000000 --- a/x/committee/genesis_test.go +++ /dev/null @@ -1,163 +0,0 @@ -package committee_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/committee" - "github.com/kava-labs/kava/x/committee/keeper" - "github.com/kava-labs/kava/x/committee/testutil" - "github.com/kava-labs/kava/x/committee/types" -) - -type GenesisTestSuite struct { - suite.Suite - - app app.TestApp - ctx sdk.Context - keeper keeper.Keeper - addresses []sdk.AccAddress -} - -func (suite *GenesisTestSuite) SetupTest() { - suite.app = app.NewTestApp() - suite.keeper = suite.app.GetCommitteeKeeper() - suite.ctx = suite.app.NewContext(true, tmproto.Header{}) - _, suite.addresses = app.GeneratePrivKeyAddressPairs(10) -} - -func (suite *GenesisTestSuite) TestInitGenesis() { - memberCom := types.MustNewMemberCommittee( - 1, - "This member committee is for testing.", - suite.addresses[:2], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ) - - tokenCom := types.MustNewTokenCommittee( - 1, - "This token committee is for testing.", - suite.addresses[:2], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - testutil.D("0.4"), - "hard", - ) - - // Most genesis validation tests are located in the types directory. The 'invalid' test cases are - // randomly selected subset of those tests. - testCases := []struct { - name string - genState *types.GenesisState - expectPass bool - }{ - { - name: "normal", - genState: types.DefaultGenesisState(), - expectPass: true, - }, - { - name: "member committee is correctly validated", - genState: types.NewGenesisState( - 1, - []types.Committee{memberCom}, - []types.Proposal{}, - []types.Vote{}, - ), - expectPass: true, - }, - { - name: "token committee is correctly validated", - genState: types.NewGenesisState( - 1, - []types.Committee{tokenCom}, - []types.Proposal{}, - []types.Vote{}, - ), - expectPass: true, - }, - { - name: "invalid: duplicate committee ID", - genState: types.NewGenesisState( - 1, - []types.Committee{memberCom, memberCom}, - []types.Proposal{}, - []types.Vote{}, - ), - expectPass: false, - }, - { - name: "invalid: proposal doesn't have committee", - genState: types.NewGenesisState( - 2, - []types.Committee{}, - []types.Proposal{{ID: 1, CommitteeID: 57}}, - []types.Vote{}, - ), - expectPass: false, - }, - { - name: "invalid: vote doesn't have proposal", - genState: types.NewGenesisState( - 1, - []types.Committee{}, - []types.Proposal{}, - []types.Vote{{Voter: suite.addresses[0], ProposalID: 1, VoteType: types.VOTE_TYPE_YES}}, - ), - expectPass: false, - }, - { - name: "invalid: next proposal ID isn't greater than proposal ID", - genState: types.NewGenesisState( - 4, - []types.Committee{memberCom}, - []types.Proposal{{ID: 3, CommitteeID: 1}, {ID: 4, CommitteeID: 1}}, - []types.Vote{}, - ), - expectPass: false, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Setup (note: suite.SetupTest is not run before every suite.Run) - suite.app = app.NewTestApp() - suite.keeper = suite.app.GetCommitteeKeeper() - suite.ctx = suite.app.NewContext(true, tmproto.Header{}) - - // Run - var exportedGenState *types.GenesisState - run := func() { - committee.InitGenesis(suite.ctx, suite.keeper, tc.genState) - exportedGenState = committee.ExportGenesis(suite.ctx, suite.keeper) - } - if tc.expectPass { - suite.Require().NotPanics(run) - } else { - suite.Require().Panics(run) - } - - // Check - if tc.expectPass { - expectedJson, err := suite.app.AppCodec().MarshalJSON(tc.genState) - suite.Require().NoError(err) - actualJson, err := suite.app.AppCodec().MarshalJSON(exportedGenState) - suite.Equal(expectedJson, actualJson) - } - }) - } -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(GenesisTestSuite)) -} diff --git a/x/committee/keeper/_param_permission_test.go b/x/committee/keeper/_param_permission_test.go deleted file mode 100644 index 8ebe9c26..00000000 --- a/x/committee/keeper/_param_permission_test.go +++ /dev/null @@ -1,268 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - bep3types "github.com/kava-labs/kava/x/bep3/types" - cdptypes "github.com/kava-labs/kava/x/cdp/types" - "github.com/kava-labs/kava/x/committee/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -type PermissionTestSuite struct { - suite.Suite - cdc codec.Codec -} - -func (suite *PermissionTestSuite) SetupTest() { - app := app.NewTestApp() - suite.cdc = app.AppCodec() -} - -func (suite *PermissionTestSuite) TestSubParamChangePermission_Allows() { - // cdp CollateralParams - testCPs := cdptypes.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: d("2.0"), - DebtLimit: c("usdx", 1000000000000), - StabilityFee: d("1.000000001547125958"), - LiquidationPenalty: d("0.05"), - AuctionSize: i(100), - Prefix: 0x20, - ConversionFactor: i(6), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - }, - { - Denom: "btc", - Type: "btc-a", - LiquidationRatio: d("1.5"), - DebtLimit: c("usdx", 1000000000), - StabilityFee: d("1.000000001547125958"), - LiquidationPenalty: d("0.10"), - AuctionSize: i(1000), - Prefix: 0x30, - ConversionFactor: i(8), - SpotMarketID: "btc:usd", - LiquidationMarketID: "btc:usd", - }, - } - testCPUpdatedDebtLimit := make(cdptypes.CollateralParams, len(testCPs)) - copy(testCPUpdatedDebtLimit, testCPs) - testCPUpdatedDebtLimit[0].DebtLimit = c("usdx", 5000000) - - // cdp DebtParam - testDP := cdptypes.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: i(6), - DebtFloor: i(10000000), - } - testDPUpdatedDebtFloor := testDP - testDPUpdatedDebtFloor.DebtFloor = i(1000) - - // cdp Genesis - testCDPParams := cdptypes.DefaultParams() - testCDPParams.CollateralParams = testCPs - testCDPParams.DebtParam = testDP - testCDPParams.GlobalDebtLimit = testCPs[0].DebtLimit.Add(testCPs[0].DebtLimit) // correct global debt limit to pass genesis validation - - testDeputy, err := sdk.AccAddressFromBech32("kava1xy7hrjy9r0algz9w3gzm8u6mrpq97kwta747gj") - suite.Require().NoError(err) - // bep3 Asset Params - testAPs := bep3types.AssetParams{ - bep3types.AssetParam{ - Denom: "bnb", - CoinID: 714, - SupplyLimit: bep3types.SupplyLimit{ - Limit: sdkmath.NewInt(350000000000000), - TimeLimited: false, - TimeBasedLimit: sdk.ZeroInt(), - TimePeriod: time.Hour, - }, - Active: true, - DeputyAddress: testDeputy, - FixedFee: sdkmath.NewInt(1000), - MinSwapAmount: sdk.OneInt(), - MaxSwapAmount: sdkmath.NewInt(1000000000000), - MinBlockLock: bep3types.DefaultMinBlockLock, - MaxBlockLock: bep3types.DefaultMaxBlockLock, - }, - bep3types.AssetParam{ - Denom: "inc", - CoinID: 9999, - SupplyLimit: bep3types.SupplyLimit{ - Limit: sdkmath.NewInt(100000000000000), - TimeLimited: true, - TimeBasedLimit: sdkmath.NewInt(50000000000), - TimePeriod: time.Hour, - }, - Active: false, - DeputyAddress: testDeputy, - FixedFee: sdkmath.NewInt(1000), - MinSwapAmount: sdk.OneInt(), - MaxSwapAmount: sdkmath.NewInt(1000000000000), - MinBlockLock: bep3types.DefaultMinBlockLock, - MaxBlockLock: bep3types.DefaultMaxBlockLock, - }, - } - testAPsUpdatedActive := make(bep3types.AssetParams, len(testAPs)) - copy(testAPsUpdatedActive, testAPs) - testAPsUpdatedActive[1].Active = true - - // bep3 Genesis - testBep3Params := bep3types.DefaultParams() - testBep3Params.AssetParams = testAPs - - // pricefeed Markets - testMs := pricefeedtypes.Markets{ - { - MarketID: "bnb:usd", - BaseAsset: "bnb", - QuoteAsset: "usd", - Oracles: []sdk.AccAddress{}, - Active: true, - }, - { - MarketID: "btc:usd", - BaseAsset: "btc", - QuoteAsset: "usd", - Oracles: []sdk.AccAddress{}, - Active: true, - }, - } - testMsUpdatedActive := make(pricefeedtypes.Markets, len(testMs)) - copy(testMsUpdatedActive, testMs) - testMsUpdatedActive[1].Active = true - - testcases := []struct { - name string - genState []app.GenesisState - permission types.SubParamChangePermission - pubProposal types.PubProposal - expectAllowed bool - }{ - { - name: "normal", - genState: []app.GenesisState{ - newPricefeedGenState([]string{"bnb", "btc"}, []sdk.Dec{d("15.01"), d("9500")}), - newCDPGenesisState(testCDPParams), - newBep3GenesisState(testBep3Params), - }, - permission: types.SubParamChangePermission{ - AllowedParams: types.AllowedParams{ - {Subspace: cdptypes.ModuleName, Key: string(cdptypes.KeyDebtThreshold)}, - {Subspace: cdptypes.ModuleName, Key: string(cdptypes.KeyCollateralParams)}, - {Subspace: cdptypes.ModuleName, Key: string(cdptypes.KeyDebtParam)}, - {Subspace: bep3types.ModuleName, Key: string(bep3types.KeyAssetParams)}, - {Subspace: pricefeedtypes.ModuleName, Key: string(pricefeedtypes.KeyMarkets)}, - }, - AllowedCollateralParams: types.AllowedCollateralParams{ - { - Type: "bnb-a", - DebtLimit: true, - StabilityFee: true, - }, - { // TODO currently even if a perm doesn't allow a change in one element it must still be present in list - Type: "btc-a", - }, - }, - AllowedDebtParam: types.AllowedDebtParam{ - DebtFloor: true, - }, - AllowedAssetParams: types.AllowedAssetParams{ - { - Denom: "bnb", - }, - { - Denom: "inc", - Active: true, - }, - }, - AllowedMarkets: types.AllowedMarkets{ - { - MarketID: "bnb:usd", - }, - { - MarketID: "btc:usd", - Active: true, - }, - }, - }, - pubProposal: paramstypes.NewParameterChangeProposal( - "A Title", - "A description for this proposal.", - []paramstypes.ParamChange{ - { - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtThreshold), - Value: string(suite.cdc.MustMarshalJSON(i(1234))), - }, - { - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - Value: string(suite.cdc.MustMarshalJSON(testCPUpdatedDebtLimit)), - }, - { - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - Value: string(suite.cdc.MustMarshalJSON(testDPUpdatedDebtFloor)), - }, - { - Subspace: bep3types.ModuleName, - Key: string(bep3types.KeyAssetParams), - Value: string(suite.cdc.MustMarshalJSON(testAPsUpdatedActive)), - }, - { - Subspace: pricefeedtypes.ModuleName, - Key: string(pricefeedtypes.KeyMarkets), - Value: string(suite.cdc.MustMarshalJSON(testMsUpdatedActive)), - }, - }, - ), - expectAllowed: true, - }, - { - name: "not allowed (wrong pubproposal type)", - permission: types.SubParamChangePermission{}, - pubProposal: govtypes.NewTextProposal("A Title", "A description for this proposal."), - expectAllowed: false, - }, - { - name: "not allowed (nil pubproposal)", - permission: types.SubParamChangePermission{}, - pubProposal: nil, - expectAllowed: false, - }, - // TODO more cases - } - - for _, tc := range testcases { - suite.Run(tc.name, func() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, abci.Header{}) - tApp.InitializeFromGenesisStates(tc.genState...) - - suite.Equal( - tc.expectAllowed, - tc.permission.Allows(ctx, tApp.Codec(), tApp.GetParamsKeeper(), tc.pubProposal), - ) - }) - } -} - -func TestPermissionTestSuite(t *testing.T) { - suite.Run(t, new(PermissionTestSuite)) -} diff --git a/x/committee/keeper/committee_test.go b/x/committee/keeper/committee_test.go deleted file mode 100644 index dca7454c..00000000 --- a/x/committee/keeper/committee_test.go +++ /dev/null @@ -1,189 +0,0 @@ -package keeper_test - -// import ( -// "testing" -// "time" - -// "github.com/stretchr/testify/suite" -// abci "github.com/cometbft/cometbft/abci/types" - -// govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" -// paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" - -// "github.com/kava-labs/kava/app" -// "github.com/kava-labs/kava/x/committee/types" -// ) - -// type TypesTestSuite struct { -// suite.Suite -// } - -// func (suite *TypesTestSuite) TestCommittee_HasPermissionsFor() { - -// testcases := []struct { -// name string -// permissions []types.Permission -// pubProposal types.PubProposal -// expectHasPermissions bool -// }{ -// { -// name: "normal (single permission)", -// permissions: []types.Permission{types.SimpleParamChangePermission{ -// AllowedParams: types.AllowedParams{ -// { -// Subspace: "cdp", -// Key: "DebtThreshold", -// }, -// }}}, -// pubProposal: paramstypes.NewParameterChangeProposal( -// "A Title", -// "A description of this proposal.", -// []paramstypes.ParamChange{ -// { -// Subspace: "cdp", -// Key: "DebtThreshold", - -// Value: `{"denom": "usdx", "amount": "1000000"}`, -// }, -// }, -// ), -// expectHasPermissions: true, -// }, -// { -// name: "normal (multiple permissions)", -// permissions: []types.Permission{ -// types.SimpleParamChangePermission{ -// AllowedParams: types.AllowedParams{ -// { -// Subspace: "cdp", -// Key: "DebtThreshold", -// }, -// }}, -// types.TextPermission{}, -// }, -// pubProposal: govtypes.NewTextProposal("A Proposal Title", "A description of this proposal"), -// expectHasPermissions: true, -// }, -// { -// name: "overruling permission", -// permissions: []types.Permission{ -// types.SimpleParamChangePermission{ -// AllowedParams: types.AllowedParams{ -// { -// Subspace: "cdp", -// Key: "DebtThreshold", -// }, -// }}, -// types.GodPermission{}, -// }, -// pubProposal: paramstypes.NewParameterChangeProposal( -// "A Title", -// "A description of this proposal.", -// []paramstypes.ParamChange{ -// { -// Subspace: "cdp", -// Key: "CollateralParams", - -// Value: `[]`, -// }, -// }, -// ), -// expectHasPermissions: true, -// }, -// { -// name: "no permissions", -// permissions: nil, -// pubProposal: paramstypes.NewParameterChangeProposal( -// "A Title", -// "A description of this proposal.", -// []paramstypes.ParamChange{ -// { -// Subspace: "cdp", -// Key: "CollateralParams", - -// Value: `[]`, -// }, -// }, -// ), -// expectHasPermissions: false, -// }, -// { -// name: "split permissions", -// // These permissions looks like they allow the param change proposal, however a proposal must pass a single permission independently of others. -// permissions: []types.Permission{ -// types.SimpleParamChangePermission{ -// AllowedParams: types.AllowedParams{ -// { -// Subspace: "cdp", -// Key: "DebtThreshold", -// }, -// }}, -// types.SimpleParamChangePermission{ -// AllowedParams: types.AllowedParams{ -// { -// Subspace: "cdp", -// Key: "DebtParams", -// }, -// }}, -// }, -// pubProposal: paramstypes.NewParameterChangeProposal( -// "A Title", -// "A description of this proposal.", -// []paramstypes.ParamChange{ -// { -// Subspace: "cdp", -// Key: "DebtThreshold", - -// Value: `{"denom": "usdx", "amount": "1000000"}`, -// }, -// { -// Subspace: "cdp", -// Key: "DebtParams", - -// Value: `[]`, -// }, -// }, -// ), -// expectHasPermissions: false, -// }, -// { -// name: "unregistered proposal", -// permissions: []types.Permission{ -// types.SimpleParamChangePermission{ -// AllowedParams: types.AllowedParams{ -// { -// Subspace: "cdp", -// Key: "DebtThreshold", -// }, -// }}, -// }, -// pubProposal: UnregisteredPubProposal{govtypes.TextProposal{Title: "A Title", Description: "A description."}}, -// expectHasPermissions: false, -// }, -// } - -// for _, tc := range testcases { -// suite.Run(tc.name, func() { -// tApp := app.NewTestApp() -// ctx := tApp.NewContext(true, abci.Header{}) -// tApp.InitializeFromGenesisStates() -// com := types.NewMemberCommittee( -// 12, -// "a description of this committee", -// nil, -// tc.permissions, -// d("0.5"), -// 24*time.Hour, -// types.FirstPastThePost, -// ) -// suite.Equal( -// tc.expectHasPermissions, -// com.HasPermissionsFor(ctx, tApp.Codec(), tApp.GetParamsKeeper(), tc.pubProposal), -// ) -// }) -// } -// } - -// func TestTypesTestSuite(t *testing.T) { -// suite.Run(t, new(TypesTestSuite)) -// } diff --git a/x/committee/keeper/gprc_query_test.go b/x/committee/keeper/gprc_query_test.go deleted file mode 100644 index aba08664..00000000 --- a/x/committee/keeper/gprc_query_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package keeper_test - -import ( - "context" - "testing" - - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/committee/testutil" - "github.com/kava-labs/kava/x/committee/types" -) - -type grpcQueryTestSuite struct { - testutil.Suite -} - -func (suite *grpcQueryTestSuite) SetupTest() { - suite.Suite.SetupTest() -} - -func (suite *grpcQueryTestSuite) TestVote() { - ctx, keeper, queryClient := suite.Ctx, suite.Keeper, suite.QueryClient - vote := types.Vote{ - ProposalID: 1, - Voter: suite.Addresses[0], - VoteType: types.VOTE_TYPE_ABSTAIN, - } - keeper.SetVote(ctx, vote) - - req := types.QueryVoteRequest{ - ProposalId: vote.ProposalID, - Voter: vote.Voter.String(), - } - res, err := queryClient.Vote(context.Background(), &req) - suite.Require().NoError(err) - suite.Require().Equal(vote.ProposalID, res.ProposalID) - suite.Require().Equal(vote.VoteType, res.VoteType) - suite.Require().Equal(vote.Voter.String(), res.Voter) - - queryRes, err := queryClient.Votes(context.Background(), &types.QueryVotesRequest{ - ProposalId: vote.ProposalID, - }) - - suite.Require().NoError(err) - suite.Require().Len(queryRes.Votes, 1) - suite.Require().Equal(vote.ProposalID, queryRes.Votes[0].ProposalID) - suite.Require().Equal(vote.VoteType, queryRes.Votes[0].VoteType) - suite.Require().Equal(vote.Voter.String(), queryRes.Votes[0].Voter) -} - -func TestGrpcQueryTestSuite(t *testing.T) { - suite.Run(t, new(grpcQueryTestSuite)) -} diff --git a/x/committee/keeper/grpc_query.go b/x/committee/keeper/grpc_query.go deleted file mode 100644 index 0ef0bb45..00000000 --- a/x/committee/keeper/grpc_query.go +++ /dev/null @@ -1,204 +0,0 @@ -package keeper - -import ( - "context" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - - "github.com/kava-labs/kava/x/committee/types" -) - -type queryServer struct { - keeper Keeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -var _ types.QueryServer = queryServer{} - -// Committees implements the gRPC service handler for querying committees. -func (s queryServer) Committees(ctx context.Context, req *types.QueryCommitteesRequest) (*types.QueryCommitteesResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - committees := s.keeper.GetCommittees(sdkCtx) - committeesAny, err := types.PackCommittees(committees) - if err != nil { - return nil, status.Errorf(codes.Unknown, "could not pack committees: %v", err) - } - - return &types.QueryCommitteesResponse{Committees: committeesAny}, nil -} - -// Committee implements the Query/Committee gRPC method. -func (s queryServer) Committee(c context.Context, req *types.QueryCommitteeRequest) (*types.QueryCommitteeResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(c) - committee, found := s.keeper.GetCommittee(ctx, req.CommitteeId) - if !found { - return nil, status.Errorf(codes.NotFound, "could not find committee for id: %v", req.CommitteeId) - } - committeeAny, err := types.PackCommittee(committee) - if err != nil { - return nil, status.Errorf(codes.Internal, "could not pack committees: %v", err) - } - return &types.QueryCommitteeResponse{Committee: committeeAny}, nil -} - -// Proposals implements the Query/Proposals gRPC method -func (s queryServer) Proposals(c context.Context, req *types.QueryProposalsRequest) (*types.QueryProposalsResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(c) - proposals := s.keeper.GetProposalsByCommittee(ctx, req.CommitteeId) - var proposalsResp []types.QueryProposalResponse - - for _, proposal := range proposals { - proposalsResp = append(proposalsResp, s.proposalResponseFromProposal(proposal)) - } - - return &types.QueryProposalsResponse{ - Proposals: proposalsResp, - }, nil -} - -// Proposal implements the Query/Proposal gRPC method -func (s queryServer) Proposal(c context.Context, req *types.QueryProposalRequest) (*types.QueryProposalResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(c) - proposal, found := s.keeper.GetProposal(ctx, req.ProposalId) - if !found { - return nil, status.Errorf(codes.NotFound, "cannot find proposal: %v", req.ProposalId) - } - proposalResp := s.proposalResponseFromProposal(proposal) - return &proposalResp, nil -} - -// NextProposalID implements the Query/NextProposalID gRPC method -func (s queryServer) NextProposalID(c context.Context, req *types.QueryNextProposalIDRequest) (*types.QueryNextProposalIDResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(c) - proposalID, err := s.keeper.GetNextProposalID(ctx) - if err != nil { - return nil, status.Errorf(codes.NotFound, "cannot find next proposal id: %v", err) - } - - return &types.QueryNextProposalIDResponse{NextProposalID: proposalID}, nil -} - -// Votes implements the Query/Votes gRPC method -func (s queryServer) Votes(c context.Context, req *types.QueryVotesRequest) (*types.QueryVotesResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(c) - - var queryResults []types.QueryVoteResponse - store := ctx.KVStore(s.keeper.storeKey) - votesStore := prefix.NewStore(store, append(types.VoteKeyPrefix, types.GetKeyFromID(req.ProposalId)...)) - pageRes, err := query.Paginate(votesStore, req.Pagination, func(key []byte, value []byte) error { - var vote types.Vote - if err := s.keeper.cdc.Unmarshal(value, &vote); err != nil { - return err - } - - queryResults = append(queryResults, s.votesResponseFromVote(vote)) - return nil - }) - if err != nil { - return nil, status.Error(codes.Internal, err.Error()) - } - - return &types.QueryVotesResponse{ - Votes: queryResults, - Pagination: pageRes, - }, nil -} - -// Vote implements the Query/Vote gRPC method -func (s queryServer) Vote(c context.Context, req *types.QueryVoteRequest) (*types.QueryVoteResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(c) - - voter, err := sdk.AccAddressFromBech32(req.Voter) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid voter address: %v", err) - } - vote, found := s.keeper.GetVote(ctx, req.ProposalId, voter) - if !found { - return nil, status.Errorf(codes.NotFound, "proposal id: %d, voter: %s", req.ProposalId, req.Voter) - } - voteResp := s.votesResponseFromVote(vote) - return &voteResp, nil -} - -// Tally implements the Query/Tally gRPC method -func (s queryServer) Tally(c context.Context, req *types.QueryTallyRequest) (*types.QueryTallyResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(c) - tally, found := s.keeper.GetProposalTallyResponse(ctx, req.ProposalId) - if !found { - return nil, status.Errorf(codes.NotFound, "proposal id: %d", req.ProposalId) - } - return tally, nil -} - -// RawParams implements the Query/RawParams gRPC method -func (s queryServer) RawParams(c context.Context, req *types.QueryRawParamsRequest) (*types.QueryRawParamsResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(c) - subspace, found := s.keeper.paramKeeper.GetSubspace(req.Subspace) - if !found { - return nil, status.Errorf(codes.NotFound, "subspace not found: %s", req.Subspace) - } - rawParams := subspace.GetRaw(ctx, []byte(req.Key)) - return &types.QueryRawParamsResponse{RawData: string(rawParams)}, nil -} - -func (s queryServer) proposalResponseFromProposal(proposal types.Proposal) types.QueryProposalResponse { - return types.QueryProposalResponse{ - PubProposal: proposal.Content, - ID: proposal.ID, - CommitteeID: proposal.CommitteeID, - Deadline: proposal.Deadline, - } -} - -func (s queryServer) votesResponseFromVote(vote types.Vote) types.QueryVoteResponse { - return types.QueryVoteResponse{ - ProposalID: vote.ProposalID, - Voter: vote.Voter.String(), - VoteType: vote.VoteType, - } -} diff --git a/x/committee/keeper/integration_test.go b/x/committee/keeper/integration_test.go deleted file mode 100644 index 75c04a0c..00000000 --- a/x/committee/keeper/integration_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package keeper_test - -import ( - "time" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/committee/keeper" - "github.com/kava-labs/kava/x/committee/testutil" - "github.com/kava-labs/kava/x/committee/types" -) - -// getProposalVoteMap collects up votes into a map indexed by proposalID -func getProposalVoteMap(k keeper.Keeper, ctx sdk.Context) map[uint64]([]types.Vote) { - proposalVoteMap := map[uint64]([]types.Vote){} - - k.IterateProposals(ctx, func(p types.Proposal) bool { - proposalVoteMap[p.ID] = k.GetVotesByProposal(ctx, p.ID) - return false - }) - return proposalVoteMap -} - -func (suite *keeperTestSuite) getAccount(addr sdk.AccAddress) authtypes.AccountI { - ak := suite.App.GetAccountKeeper() - return ak.GetAccount(suite.Ctx, addr) -} - -func mustNewTestMemberCommittee(addresses []sdk.AccAddress) *types.MemberCommittee { - com, err := types.NewMemberCommittee( - 12, - "This committee is for testing.", - addresses, - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ) - if err != nil { - panic(err) - } - return com -} - -// mustNewTestProposal returns a new test proposal. -func mustNewTestProposal() types.Proposal { - proposal, err := types.NewProposal( - govv1beta1.NewTextProposal("A Title", "A description of this proposal."), - 1, 1, time.Date(2010, time.January, 1, 0, 0, 0, 0, time.UTC), - ) - if err != nil { - panic(err) - } - return proposal -} - -// NewCommitteeGenesisState marshals a committee genesis state into json for use in initializing test apps. -func NewCommitteeGenesisState(cdc codec.Codec, gs *types.GenesisState) app.GenesisState { - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(gs)} -} diff --git a/x/committee/keeper/keeper.go b/x/committee/keeper/keeper.go deleted file mode 100644 index 703a90be..00000000 --- a/x/committee/keeper/keeper.go +++ /dev/null @@ -1,301 +0,0 @@ -package keeper - -import ( - "time" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store/prefix" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - "github.com/kava-labs/kava/x/committee/types" -) - -type Keeper struct { - cdc codec.Codec - storeKey storetypes.StoreKey - - paramKeeper types.ParamKeeper - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - - // Proposal router - router govv1beta1.Router -} - -func NewKeeper(cdc codec.Codec, storeKey storetypes.StoreKey, router govv1beta1.Router, - paramKeeper types.ParamKeeper, ak types.AccountKeeper, sk types.BankKeeper, -) Keeper { - // Logic in the keeper methods assume the set of gov handlers is fixed. - // So the gov router must be sealed so no handlers can be added or removed after the keeper is created. - router.Seal() - - return Keeper{ - cdc: cdc, - storeKey: storeKey, - paramKeeper: paramKeeper, - accountKeeper: ak, - bankKeeper: sk, - router: router, - } -} - -// ------------------------------------------ -// Committees -// ------------------------------------------ - -// GetCommittee gets a committee from the store. -func (k Keeper) GetCommittee(ctx sdk.Context, committeeID uint64) (types.Committee, bool) { - var committee types.Committee - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.CommitteeKeyPrefix) - bz := store.Get(types.GetKeyFromID(committeeID)) - if bz == nil { - return committee, false - } - err := k.cdc.UnmarshalInterface(bz, &committee) - if err != nil { - panic(err) - } - return committee, true -} - -// SetCommittee puts a committee into the store. -func (k Keeper) SetCommittee(ctx sdk.Context, committee types.Committee) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.CommitteeKeyPrefix) - bz, err := k.cdc.MarshalInterface(committee) - if err != nil { - panic(err) - } - store.Set(types.GetKeyFromID(committee.GetID()), bz) -} - -// DeleteCommittee removes a committee from the store. -func (k Keeper) DeleteCommittee(ctx sdk.Context, committeeID uint64) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.CommitteeKeyPrefix) - store.Delete(types.GetKeyFromID(committeeID)) -} - -// IterateCommittees provides an iterator over all stored committees. -// For each committee, cb will be called. If cb returns true, the iterator will close and stop. -func (k Keeper) IterateCommittees(ctx sdk.Context, cb func(committee types.Committee) (stop bool)) { - iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.CommitteeKeyPrefix) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var committee types.Committee - if err := k.cdc.UnmarshalInterface(iterator.Value(), &committee); err != nil { - panic(err) - } - if cb(committee) { - break - } - } -} - -// GetCommittees returns all stored committees. -func (k Keeper) GetCommittees(ctx sdk.Context) types.Committees { - results := types.Committees{} - k.IterateCommittees(ctx, func(com types.Committee) bool { - results = append(results, com) - return false - }) - return results -} - -// ------------------------------------------ -// Proposals -// ------------------------------------------ - -// SetNextProposalID stores an ID to be used for the next created proposal -func (k Keeper) SetNextProposalID(ctx sdk.Context, id uint64) { - store := ctx.KVStore(k.storeKey) - store.Set(types.NextProposalIDKey, types.GetKeyFromID(id)) -} - -// GetNextProposalID reads the next available global ID from store -func (k Keeper) GetNextProposalID(ctx sdk.Context) (uint64, error) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.NextProposalIDKey) - if bz == nil { - return 0, errorsmod.Wrap(types.ErrInvalidGenesis, "next proposal ID not set at genesis") - } - return types.Uint64FromBytes(bz), nil -} - -// IncrementNextProposalID increments the next proposal ID in the store by 1. -func (k Keeper) IncrementNextProposalID(ctx sdk.Context) error { - id, err := k.GetNextProposalID(ctx) - if err != nil { - return err - } - k.SetNextProposalID(ctx, id+1) - return nil -} - -// StoreNewProposal stores a proposal, adding a new ID -func (k Keeper) StoreNewProposal(ctx sdk.Context, pubProposal types.PubProposal, committeeID uint64, deadline time.Time) (uint64, error) { - newProposalID, err := k.GetNextProposalID(ctx) - if err != nil { - return 0, err - } - proposal, err := types.NewProposal( - pubProposal, - newProposalID, - committeeID, - deadline, - ) - if err != nil { - return 0, err - } - - k.SetProposal(ctx, proposal) - - err = k.IncrementNextProposalID(ctx) - if err != nil { - return 0, err - } - return newProposalID, nil -} - -// GetProposal gets a proposal from the store. -func (k Keeper) GetProposal(ctx sdk.Context, proposalID uint64) (types.Proposal, bool) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.ProposalKeyPrefix) - bz := store.Get(types.GetKeyFromID(proposalID)) - if bz == nil { - return types.Proposal{}, false - } - var proposal types.Proposal - k.cdc.MustUnmarshal(bz, &proposal) - return proposal, true -} - -// SetProposal puts a proposal into the store. -func (k Keeper) SetProposal(ctx sdk.Context, proposal types.Proposal) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.ProposalKeyPrefix) - bz := k.cdc.MustMarshal(&proposal) - store.Set(types.GetKeyFromID(proposal.ID), bz) -} - -// DeleteProposal removes a proposal from the store. -func (k Keeper) DeleteProposal(ctx sdk.Context, proposalID uint64) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.ProposalKeyPrefix) - store.Delete(types.GetKeyFromID(proposalID)) -} - -// IterateProposals provides an iterator over all stored proposals. -// For each proposal, cb will be called. If cb returns true, the iterator will close and stop. -func (k Keeper) IterateProposals(ctx sdk.Context, cb func(proposal types.Proposal) (stop bool)) { - iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.ProposalKeyPrefix) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var proposal types.Proposal - k.cdc.MustUnmarshal(iterator.Value(), &proposal) - if cb(proposal) { - break - } - } -} - -// GetProposals returns all stored proposals. -func (k Keeper) GetProposals(ctx sdk.Context) types.Proposals { - results := types.Proposals{} - k.IterateProposals(ctx, func(prop types.Proposal) bool { - results = append(results, prop) - return false - }) - return results -} - -// GetProposalsByCommittee returns all proposals for one committee. -func (k Keeper) GetProposalsByCommittee(ctx sdk.Context, committeeID uint64) types.Proposals { - results := types.Proposals{} - k.IterateProposals(ctx, func(prop types.Proposal) bool { - if prop.CommitteeID == committeeID { - results = append(results, prop) - } - return false - }) - return results -} - -// DeleteProposalAndVotes removes a proposal and its associated votes. -func (k Keeper) DeleteProposalAndVotes(ctx sdk.Context, proposalID uint64) { - votes := k.GetVotesByProposal(ctx, proposalID) - k.DeleteProposal(ctx, proposalID) - for _, v := range votes { - k.DeleteVote(ctx, v.ProposalID, v.Voter) - } -} - -// ------------------------------------------ -// Votes -// ------------------------------------------ - -// GetVote gets a vote from the store. -func (k Keeper) GetVote(ctx sdk.Context, proposalID uint64, voter sdk.AccAddress) (types.Vote, bool) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.VoteKeyPrefix) - bz := store.Get(types.GetVoteKey(proposalID, voter)) - if bz == nil { - return types.Vote{}, false - } - var vote types.Vote - k.cdc.MustUnmarshal(bz, &vote) - return vote, true -} - -// SetVote puts a vote into the store. -func (k Keeper) SetVote(ctx sdk.Context, vote types.Vote) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.VoteKeyPrefix) - bz := k.cdc.MustMarshal(&vote) - store.Set(types.GetVoteKey(vote.ProposalID, vote.Voter), bz) -} - -// DeleteVote removes a Vote from the store. -func (k Keeper) DeleteVote(ctx sdk.Context, proposalID uint64, voter sdk.AccAddress) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.VoteKeyPrefix) - store.Delete(types.GetVoteKey(proposalID, voter)) -} - -// IterateVotes provides an iterator over all stored votes. -// For each vote, cb will be called. If cb returns true, the iterator will close and stop. -func (k Keeper) IterateVotes(ctx sdk.Context, cb func(vote types.Vote) (stop bool)) { - iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.VoteKeyPrefix) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var vote types.Vote - k.cdc.MustUnmarshal(iterator.Value(), &vote) - - if cb(vote) { - break - } - } -} - -// GetVotes returns all stored votes. -func (k Keeper) GetVotes(ctx sdk.Context) []types.Vote { - results := []types.Vote{} - k.IterateVotes(ctx, func(vote types.Vote) bool { - results = append(results, vote) - return false - }) - return results -} - -// GetVotesByProposal returns all votes for one proposal. -func (k Keeper) GetVotesByProposal(ctx sdk.Context, proposalID uint64) []types.Vote { - results := []types.Vote{} - iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), append(types.VoteKeyPrefix, types.GetKeyFromID(proposalID)...)) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var vote types.Vote - k.cdc.MustUnmarshal(iterator.Value(), &vote) - results = append(results, vote) - } - - return results -} diff --git a/x/committee/keeper/keeper_test.go b/x/committee/keeper/keeper_test.go deleted file mode 100644 index 4ba614a7..00000000 --- a/x/committee/keeper/keeper_test.go +++ /dev/null @@ -1,171 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/committee/testutil" - "github.com/kava-labs/kava/x/committee/types" -) - -type keeperTestSuite struct { - testutil.Suite -} - -func (suite *keeperTestSuite) SetupTest() { - suite.Suite.SetupTest() -} - -func (suite *keeperTestSuite) TestGetSetDeleteCommittee() { - cdc := suite.App.AppCodec() - - // setup test - com := mustNewTestMemberCommittee(suite.Addresses) - - // write and read from store - suite.Keeper.SetCommittee(suite.Ctx, com) - readCommittee, found := suite.Keeper.GetCommittee(suite.Ctx, com.ID) - - // check before and after match - suite.Require().True(found) - expectedJson, err := cdc.MarshalJSON(com) - suite.Require().NoError(err) - actualJson, err := cdc.MarshalJSON(readCommittee) - suite.Require().NoError(err) - suite.Equal(expectedJson, actualJson) - suite.Require().Equal(com.GetPermissions(), readCommittee.GetPermissions()) - - // delete from store - suite.Keeper.DeleteCommittee(suite.Ctx, com.ID) - - // check does not exist - _, found = suite.Keeper.GetCommittee(suite.Ctx, com.ID) - suite.Require().False(found) -} - -func (suite *keeperTestSuite) TestGetSetDeleteProposal() { - // test setup - prop, err := types.NewProposal( - govv1beta1.NewTextProposal("A Title", "A description of this proposal."), - 12, - 0, - time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC), - ) - suite.Require().NoError(err) - - // write and read from store - suite.Keeper.SetProposal(suite.Ctx, prop) - readProposal, found := suite.Keeper.GetProposal(suite.Ctx, prop.ID) - - // check before and after match - suite.True(found) - suite.Equal(prop, readProposal) - - // delete from store - suite.Keeper.DeleteProposal(suite.Ctx, prop.ID) - - // check does not exist - _, found = suite.Keeper.GetProposal(suite.Ctx, prop.ID) - suite.False(found) -} - -func (suite *keeperTestSuite) TestGetSetDeleteVote() { - // test setup - vote := types.Vote{ - ProposalID: 12, - Voter: suite.Addresses[0], - } - - // write and read from store - suite.Keeper.SetVote(suite.Ctx, vote) - readVote, found := suite.Keeper.GetVote(suite.Ctx, vote.ProposalID, vote.Voter) - - // check before and after match - suite.True(found) - suite.Equal(vote, readVote) - - // delete from store - suite.Keeper.DeleteVote(suite.Ctx, vote.ProposalID, vote.Voter) - - // check does not exist - _, found = suite.Keeper.GetVote(suite.Ctx, vote.ProposalID, vote.Voter) - suite.False(found) -} - -func (suite *keeperTestSuite) TestGetCommittees() { - committeesCount := 10 - for i := 0; i < committeesCount; i++ { - com := mustNewTestMemberCommittee(suite.Addresses) - com.ID = uint64(i) - suite.Keeper.SetCommittee(suite.Ctx, com) - } - committees := suite.Keeper.GetCommittees(suite.Ctx) - suite.Require().Len(committees, committeesCount) -} - -func (suite *keeperTestSuite) TestGetAndSetProposal() { - proposal := mustNewTestProposal() - - // Get no proposal - actualProposal, found := suite.Keeper.GetProposal(suite.Ctx, proposal.ID) - suite.Require().False(found) - suite.Require().Equal(types.Proposal{}, actualProposal) - - // Set and get new proposal - suite.Keeper.SetProposal(suite.Ctx, proposal) - actualProposal, found = suite.Keeper.GetProposal(suite.Ctx, proposal.ID) - suite.Require().True(found) - suite.Require().Equal(proposal, actualProposal) -} - -func (suite *keeperTestSuite) TestGetProposalsByCommittee() { - committee := mustNewTestMemberCommittee(suite.Addresses) - proposalsCount := 4 - for i := 0; i < proposalsCount; i++ { - proposal := mustNewTestProposal() - proposal.ID = uint64(i) - proposal.CommitteeID = committee.ID - suite.Keeper.SetProposal(suite.Ctx, proposal) - } - proposal := mustNewTestProposal() - proposal.ID = uint64(proposalsCount) - proposal.CommitteeID = committee.ID + 1 - suite.Keeper.SetProposal(suite.Ctx, proposal) - - // No proposals - actualProposals := suite.Keeper.GetProposalsByCommittee(suite.Ctx, committee.ID+2) - suite.Require().Len(actualProposals, 0) - - // Proposals for existing committees - actualProposals = suite.Keeper.GetProposalsByCommittee(suite.Ctx, committee.ID) - suite.Require().Len(actualProposals, proposalsCount) - actualProposals = suite.Keeper.GetProposalsByCommittee(suite.Ctx, committee.ID+1) - suite.Require().Len(actualProposals, 1) - - // Make sure proposals have expected data - suite.Require().Equal(proposal, actualProposals[0]) -} - -func (suite *keeperTestSuite) TestGetVotesByProposal() { - proposal := mustNewTestProposal() - suite.Keeper.SetProposal(suite.Ctx, proposal) - votes := []types.Vote{ - types.NewVote(proposal.ID, suite.Addresses[0], types.VOTE_TYPE_NO), - types.NewVote(proposal.ID, suite.Addresses[1], types.VOTE_TYPE_ABSTAIN), - types.NewVote(proposal.ID, suite.Addresses[1], types.VOTE_TYPE_YES), - } - expectedVotes := []types.Vote{votes[0], votes[2]} - for _, vote := range votes { - suite.Keeper.SetVote(suite.Ctx, vote) - } - actualVotes := suite.Keeper.GetVotesByProposal(suite.Ctx, proposal.ID) - suite.Require().Len(actualVotes, len(expectedVotes)) - suite.Require().ElementsMatch(expectedVotes, actualVotes) -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(keeperTestSuite)) -} diff --git a/x/committee/keeper/msg_server.go b/x/committee/keeper/msg_server.go deleted file mode 100644 index 2458cad0..00000000 --- a/x/committee/keeper/msg_server.go +++ /dev/null @@ -1,70 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/committee/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the committee MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -// SubmitProposal handles MsgSubmitProposal messages -func (m msgServer) SubmitProposal(goCtx context.Context, msg *types.MsgSubmitProposal) (*types.MsgSubmitProposalResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - proposer, err := sdk.AccAddressFromBech32(msg.Proposer) - if err != nil { - return nil, err - } - - proposalID, err := m.keeper.SubmitProposal(ctx, proposer, msg.CommitteeID, msg.GetPubProposal()) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Proposer), - ), - ) - - return &types.MsgSubmitProposalResponse{ProposalID: proposalID}, nil -} - -// Vote handles MsgVote messages -func (m msgServer) Vote(goCtx context.Context, msg *types.MsgVote) (*types.MsgVoteResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - voter, err := sdk.AccAddressFromBech32(msg.Voter) - if err != nil { - return nil, err - } - - if err := m.keeper.AddVote(ctx, msg.ProposalID, voter, msg.VoteType); err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Voter), - ), - ) - - return &types.MsgVoteResponse{}, nil -} diff --git a/x/committee/keeper/msg_server_test.go b/x/committee/keeper/msg_server_test.go deleted file mode 100644 index f0141ca6..00000000 --- a/x/committee/keeper/msg_server_test.go +++ /dev/null @@ -1,195 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - proposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/committee/keeper" - "github.com/kava-labs/kava/x/committee/types" - swaptypes "github.com/kava-labs/kava/x/swap/types" -) - -//NewDistributionGenesisWithPool creates a default distribution genesis state with some coins in the community pool. -//func NewDistributionGenesisWithPool(communityPoolCoins sdk.Coins) app.GenesisState { -//gs := distribution.DefaultGenesisState() -//gs.FeePool = distribution.FeePool{CommunityPool: sdk.NewDecCoinsFromCoins(communityPoolCoins...)} -//return app.GenesisState{distribution.ModuleName: distribution.ModuleCdc.MustMarshalJSON(gs)} -//} - -type MsgServerTestSuite struct { - suite.Suite - - app app.TestApp - keeper keeper.Keeper - msgServer types.MsgServer - ctx sdk.Context - addresses []sdk.AccAddress - - communityPoolAmt sdk.Coins -} - -func (suite *MsgServerTestSuite) SetupTest() { - _, suite.addresses = app.GeneratePrivKeyAddressPairs(5) - suite.app = app.NewTestApp() - suite.keeper = suite.app.GetCommitteeKeeper() - suite.msgServer = keeper.NewMsgServerImpl(suite.keeper) - encodingCfg := app.MakeEncodingConfig() - cdc := encodingCfg.Marshaler - - memberCommittee, err := types.NewMemberCommittee( - 1, - "This committee is for testing.", - suite.addresses[:3], - []types.Permission{&types.GodPermission{}}, - sdk.MustNewDecFromStr("0.5"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ) - suite.Require().NoError(err) - - firstBlockTime := time.Date(1998, time.January, 1, 1, 0, 0, 0, time.UTC) - testGenesis := types.NewGenesisState( - 3, - []types.Committee{memberCommittee}, - []types.Proposal{}, - []types.Vote{}, - ) - suite.communityPoolAmt = sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000))) - suite.app.InitializeFromGenesisStates( - app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(testGenesis)}, - // TODO: not used? - // NewDistributionGenesisWithPool(suite.communityPoolAmt), - ) - suite.ctx = suite.app.NewContext(true, tmproto.Header{Height: 1, Time: firstBlockTime}) -} - -func (suite *MsgServerTestSuite) TestSubmitProposalMsg_Valid() { - msg, err := types.NewMsgSubmitProposal( - proposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []proposal.ParamChange{{ - Subspace: swaptypes.ModuleName, - Key: string(swaptypes.KeySwapFee), - Value: "\"0.001500000000000000\"", - }}, - ), - suite.addresses[0], - 1, - ) - suite.Require().NoError(err) - - res, err := suite.msgServer.SubmitProposal(sdk.WrapSDKContext(suite.ctx), msg) - - suite.NoError(err) - _, found := suite.keeper.GetProposal(suite.ctx, res.ProposalID) - suite.True(found) -} - -func (suite *MsgServerTestSuite) TestSubmitProposalMsg_Invalid() { - var committeeID uint64 = 1 - msg, err := types.NewMsgSubmitProposal( - proposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []proposal.ParamChange{{ - Subspace: swaptypes.ModuleName, - Key: "nonsense-key", - Value: "nonsense-value", - }}, - ), - suite.addresses[0], - committeeID, - ) - suite.Require().NoError(err) - - _, err = suite.msgServer.SubmitProposal(sdk.WrapSDKContext(suite.ctx), msg) - - suite.Error(err) - suite.Empty( - suite.keeper.GetProposalsByCommittee(suite.ctx, committeeID), - "proposal found when none should exist", - ) -} - -func (suite *MsgServerTestSuite) TestSubmitProposalMsg_ValidUpgrade() { - msg, err := types.NewMsgSubmitProposal( - upgradetypes.NewSoftwareUpgradeProposal( - "A Title", - "A description of this proposal.", - upgradetypes.Plan{ - Name: "emergency-shutdown-1", // identifier for the upgrade - Height: 100000, - Info: "Some information about the shutdown.", - }, - ), - suite.addresses[0], - 1, - ) - suite.Require().NoError(err) - - res, err := suite.msgServer.SubmitProposal(sdk.WrapSDKContext(suite.ctx), msg) - - suite.NoError(err) - _, found := suite.keeper.GetProposal(suite.ctx, res.ProposalID) - suite.True(found) -} - -// TODO: create a unregisted proto for tests? -func (suite *MsgServerTestSuite) TestSubmitProposalMsg_Unregistered() { - var committeeID uint64 = 1 - msg, err := types.NewMsgSubmitProposal( - &UnregisteredPubProposal{}, - suite.addresses[0], - committeeID, - ) - suite.Require().NoError(err) - - _, err = suite.msgServer.SubmitProposal(sdk.WrapSDKContext(suite.ctx), msg) - - suite.Error(err) - suite.Empty( - suite.keeper.GetProposalsByCommittee(suite.ctx, committeeID), - "proposal found when none should exist", - ) -} - -func (suite *MsgServerTestSuite) TestSubmitProposalMsgAndVote() { - msg, err := types.NewMsgSubmitProposal( - proposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []proposal.ParamChange{{ - Subspace: swaptypes.ModuleName, - Key: string(swaptypes.KeySwapFee), - Value: "\"0.001500000000000000\"", - }}, - ), - suite.addresses[0], - 1, - ) - suite.Require().NoError(err) - - res, err := suite.msgServer.SubmitProposal(sdk.WrapSDKContext(suite.ctx), msg) - suite.Require().NoError(err) - - proposal, found := suite.keeper.GetProposal(suite.ctx, res.ProposalID) - suite.Require().True(found) - - msgVote := types.NewMsgVote(suite.addresses[0], proposal.ID, types.VOTE_TYPE_YES) - _, err = suite.msgServer.Vote(sdk.WrapSDKContext(suite.ctx), msgVote) - suite.Require().NoError(err) -} - -func TestMsgServerTestSuite(t *testing.T) { - suite.Run(t, new(MsgServerTestSuite)) -} diff --git a/x/committee/keeper/proposal.go b/x/committee/keeper/proposal.go deleted file mode 100644 index 744a2b82..00000000 --- a/x/committee/keeper/proposal.go +++ /dev/null @@ -1,308 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/kava-labs/kava/x/committee/types" -) - -// SubmitProposal adds a proposal to a committee so that it can be voted on. -func (k Keeper) SubmitProposal(ctx sdk.Context, proposer sdk.AccAddress, committeeID uint64, pubProposal types.PubProposal) (uint64, error) { - // Limit proposals to only be submitted by committee members - com, found := k.GetCommittee(ctx, committeeID) - if !found { - return 0, errorsmod.Wrapf(types.ErrUnknownCommittee, "%d", committeeID) - } - if !com.HasMember(proposer) { - return 0, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "proposer not member of committee") - } - - // Check committee has permissions to enact proposal. - if !com.HasPermissionsFor(ctx, k.cdc, k.paramKeeper, pubProposal) { - return 0, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "committee does not have permissions to enact proposal") - } - - // Check proposal is valid - if err := k.ValidatePubProposal(ctx, pubProposal); err != nil { - return 0, err - } - - // Get a new ID and store the proposal - deadline := ctx.BlockTime().Add(com.GetProposalDuration()) - proposalID, err := k.StoreNewProposal(ctx, pubProposal, committeeID, deadline) - if err != nil { - return 0, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeProposalSubmit, - sdk.NewAttribute(types.AttributeKeyCommitteeID, fmt.Sprintf("%d", com.GetID())), - sdk.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf("%d", proposalID)), - sdk.NewAttribute(types.AttributeKeyDeadline, deadline.String()), - ), - ) - return proposalID, nil -} - -// AddVote submits a vote on a proposal. -func (k Keeper) AddVote(ctx sdk.Context, proposalID uint64, voter sdk.AccAddress, voteType types.VoteType) error { - // Validate - pr, found := k.GetProposal(ctx, proposalID) - if !found { - return errorsmod.Wrapf(types.ErrUnknownProposal, "%d", proposalID) - } - if pr.HasExpiredBy(ctx.BlockTime()) { - return errorsmod.Wrapf(types.ErrProposalExpired, "%s ≥ %s", ctx.BlockTime(), pr.Deadline) - } - com, found := k.GetCommittee(ctx, pr.CommitteeID) - if !found { - return errorsmod.Wrapf(types.ErrUnknownCommittee, "%d", pr.CommitteeID) - } - - if _, ok := com.(*types.MemberCommittee); ok { - if !com.HasMember(voter) { - return errorsmod.Wrap(sdkerrors.ErrUnauthorized, "voter must be a member of committee") - } - if voteType != types.VOTE_TYPE_YES { - return errorsmod.Wrap(types.ErrInvalidVoteType, "member committees only accept yes votes") - } - } - - // Store vote, overwriting any prior vote - k.SetVote(ctx, types.NewVote(proposalID, voter, voteType)) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeProposalVote, - sdk.NewAttribute(types.AttributeKeyCommitteeID, fmt.Sprintf("%d", com.GetID())), - sdk.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf("%d", pr.ID)), - sdk.NewAttribute(types.AttributeKeyVoter, voter.String()), - sdk.NewAttribute(types.AttributeKeyVote, fmt.Sprintf("%d", voteType)), - ), - ) - return nil -} - -// ValidatePubProposal checks if a pubproposal is valid. -func (k Keeper) ValidatePubProposal(ctx sdk.Context, pubProposal types.PubProposal) (returnErr error) { - if pubProposal == nil { - return errorsmod.Wrap(types.ErrInvalidPubProposal, "pub proposal cannot be nil") - } - if err := pubProposal.ValidateBasic(); err != nil { - return err - } - - if !k.router.HasRoute(pubProposal.ProposalRoute()) { - return errorsmod.Wrapf(types.ErrNoProposalHandlerExists, "%T", pubProposal) - } - - // Run the proposal's changes through the associated handler using a cached version of state to ensure changes are not permanent. - cacheCtx, _ := ctx.CacheContext() - handler := k.router.GetRoute(pubProposal.ProposalRoute()) - - // Handle an edge case where a param change proposal causes the proposal handler to panic. - // A param change proposal with a registered subspace value but unregistered key value will cause a panic in the param change proposal handler. - // This defer will catch panics and return a normal error: `recover()` gets the panic value, then the enclosing function's return value is swapped for an error. - // reference: https://stackoverflow.com/questions/33167282/how-to-return-a-value-in-a-go-function-that-panics?noredirect=1&lq=1 - defer func() { - if r := recover(); r != nil { - returnErr = errorsmod.Wrapf(types.ErrInvalidPubProposal, "proposal handler panicked: %s", r) - } - }() - - if err := handler(cacheCtx, pubProposal); err != nil { - return err - } - return nil -} - -func (k Keeper) ProcessProposals(ctx sdk.Context) { - k.IterateProposals(ctx, func(proposal types.Proposal) bool { - committee, found := k.GetCommittee(ctx, proposal.CommitteeID) - if !found { - k.CloseProposal(ctx, proposal, types.Failed) - return false - } - - if !proposal.HasExpiredBy(ctx.BlockTime()) { - if committee.GetTallyOption() == types.TALLY_OPTION_FIRST_PAST_THE_POST { - passed := k.GetProposalResult(ctx, proposal.ID, committee) - if passed { - outcome := k.attemptEnactProposal(ctx, proposal) - k.CloseProposal(ctx, proposal, outcome) - } - } - } else { - passed := k.GetProposalResult(ctx, proposal.ID, committee) - outcome := types.Failed - if passed { - outcome = k.attemptEnactProposal(ctx, proposal) - } - k.CloseProposal(ctx, proposal, outcome) - } - return false - }) -} - -func (k Keeper) GetProposalResult(ctx sdk.Context, proposalID uint64, committee types.Committee) bool { - switch com := committee.(type) { - case *types.MemberCommittee: - return k.GetMemberCommitteeProposalResult(ctx, proposalID, com) - case *types.TokenCommittee: - return k.GetTokenCommitteeProposalResult(ctx, proposalID, com) - default: // Should never hit default case - return false - } -} - -// GetMemberCommitteeProposalResult gets the result of a member committee proposal -func (k Keeper) GetMemberCommitteeProposalResult(ctx sdk.Context, proposalID uint64, committee types.Committee) bool { - currVotes := k.TallyMemberCommitteeVotes(ctx, proposalID) - possibleVotes := sdk.NewDec(int64(len(committee.GetMembers()))) - return currVotes.GTE(committee.GetVoteThreshold().Mul(possibleVotes)) // vote threshold requirements -} - -// TallyMemberCommitteeVotes returns the polling status of a member committee vote -func (k Keeper) TallyMemberCommitteeVotes(ctx sdk.Context, proposalID uint64) (totalVotes sdk.Dec) { - votes := k.GetVotesByProposal(ctx, proposalID) - return sdk.NewDec(int64(len(votes))) -} - -// GetTokenCommitteeProposalResult gets the result of a token committee proposal -func (k Keeper) GetTokenCommitteeProposalResult(ctx sdk.Context, proposalID uint64, committee *types.TokenCommittee) bool { - yesVotes, noVotes, totalVotes, possibleVotes := k.TallyTokenCommitteeVotes(ctx, proposalID, committee.TallyDenom) - if totalVotes.GTE(committee.Quorum.Mul(possibleVotes)) { // quorum requirement - nonAbstainVotes := yesVotes.Add(noVotes) - if yesVotes.GTE(nonAbstainVotes.Mul(committee.VoteThreshold)) { // vote threshold requirements - return true - } - } - return false -} - -// TallyMemberCommitteeVotes returns the polling status of a token committee vote. Returns yes votes, -// total current votes, total possible votes (equal to token supply), vote threshold (yes vote ratio -// required for proposal to pass), and quorum (votes tallied at this percentage). -func (k Keeper) TallyTokenCommitteeVotes(ctx sdk.Context, proposalID uint64, - tallyDenom string, -) (yesVotes, noVotes, totalVotes, possibleVotes sdk.Dec) { - votes := k.GetVotesByProposal(ctx, proposalID) - - yesVotes = sdk.ZeroDec() - noVotes = sdk.ZeroDec() - totalVotes = sdk.ZeroDec() - for _, vote := range votes { - // 1 token = 1 vote - acc := k.accountKeeper.GetAccount(ctx, vote.Voter) - accNumCoins := k.bankKeeper.GetBalance(ctx, acc.GetAddress(), tallyDenom).Amount - - // Add votes to counters - totalVotes = totalVotes.Add(sdk.NewDecFromInt(accNumCoins)) - if vote.VoteType == types.VOTE_TYPE_YES { - yesVotes = yesVotes.Add(sdk.NewDecFromInt(accNumCoins)) - } else if vote.VoteType == types.VOTE_TYPE_NO { - noVotes = noVotes.Add(sdk.NewDecFromInt(accNumCoins)) - } - } - - possibleVotesInt := k.bankKeeper.GetSupply(ctx, tallyDenom).Amount - return yesVotes, noVotes, totalVotes, sdk.NewDecFromInt(possibleVotesInt) -} - -func (k Keeper) attemptEnactProposal(ctx sdk.Context, proposal types.Proposal) types.ProposalOutcome { - err := k.enactProposal(ctx, proposal) - if err != nil { - return types.Invalid - } - return types.Passed -} - -// enactProposal makes the changes proposed in a proposal. -func (k Keeper) enactProposal(ctx sdk.Context, proposal types.Proposal) error { - // Check committee still has permissions for the proposal - // Since the proposal was submitted params could have changed, invalidating the permission of the committee. - com, found := k.GetCommittee(ctx, proposal.CommitteeID) - if !found { - return errorsmod.Wrapf(types.ErrUnknownCommittee, "%d", proposal.CommitteeID) - } - if !com.HasPermissionsFor(ctx, k.cdc, k.paramKeeper, proposal.GetContent()) { - return errorsmod.Wrap(sdkerrors.ErrUnauthorized, "committee does not have permissions to enact proposal") - } - - if err := k.ValidatePubProposal(ctx, proposal.GetContent()); err != nil { - return err - } - - // enact the proposal - handler := k.router.GetRoute(proposal.GetContent().ProposalRoute()) - if err := handler(ctx, proposal.GetContent()); err != nil { - // the handler should not error as it was checked in ValidatePubProposal - panic(fmt.Sprintf("unexpected handler error: %s", err)) - } - return nil -} - -// GetProposalTallyResponse returns the tally results of a proposal. -func (k Keeper) GetProposalTallyResponse(ctx sdk.Context, proposalID uint64) (*types.QueryTallyResponse, bool) { - proposal, found := k.GetProposal(ctx, proposalID) - if !found { - return nil, found - } - committee, found := k.GetCommittee(ctx, proposal.CommitteeID) - if !found { - return nil, found - } - var proposalTally types.QueryTallyResponse - switch com := committee.(type) { - case *types.MemberCommittee: - currVotes := k.TallyMemberCommitteeVotes(ctx, proposal.ID) - possibleVotes := sdk.NewDec(int64(len(com.Members))) - proposalTally = types.QueryTallyResponse{ - ProposalID: proposal.ID, - YesVotes: currVotes, - NoVotes: sdk.ZeroDec(), - CurrentVotes: currVotes, - PossibleVotes: possibleVotes, - VoteThreshold: com.VoteThreshold, - Quorum: sdk.ZeroDec(), - } - case *types.TokenCommittee: - yesVotes, noVotes, currVotes, possibleVotes := k.TallyTokenCommitteeVotes(ctx, proposal.ID, com.TallyDenom) - proposalTally = types.QueryTallyResponse{ - ProposalID: proposal.ID, - YesVotes: yesVotes, - NoVotes: noVotes, - CurrentVotes: currVotes, - PossibleVotes: possibleVotes, - VoteThreshold: com.VoteThreshold, - Quorum: com.Quorum, - } - } - return &proposalTally, true -} - -// CloseProposal deletes proposals and their votes, emitting an event denoting the final status of the proposal -func (k Keeper) CloseProposal(ctx sdk.Context, proposal types.Proposal, outcome types.ProposalOutcome) { - tally, _ := k.GetProposalTallyResponse(ctx, proposal.ID) - k.DeleteProposalAndVotes(ctx, proposal.ID) - - bz, err := k.cdc.MarshalJSON(tally) - if err != nil { - fmt.Println("error marshaling proposal tally to bytes:", tally.String()) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeProposalClose, - sdk.NewAttribute(types.AttributeKeyCommitteeID, fmt.Sprintf("%d", proposal.CommitteeID)), - sdk.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf("%d", proposal.ID)), - sdk.NewAttribute(types.AttributeKeyProposalTally, string(bz)), - sdk.NewAttribute(types.AttributeKeyProposalOutcome, outcome.String()), - ), - ) -} diff --git a/x/committee/keeper/proposal_test.go b/x/committee/keeper/proposal_test.go deleted file mode 100644 index 7fa10db5..00000000 --- a/x/committee/keeper/proposal_test.go +++ /dev/null @@ -1,1263 +0,0 @@ -package keeper_test - -import ( - "time" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - - "github.com/kava-labs/kava/app" - // bep3types "github.com/kava-labs/kava/x/bep3/types" - // cdptypes "github.com/kava-labs/kava/x/cdp/types" - - "github.com/kava-labs/kava/x/committee/testutil" - "github.com/kava-labs/kava/x/committee/types" - // "github.com/kava-labs/kava/x/pricefeed" -) - -// func newCDPGenesisState(params cdptypes.Params) app.GenesisState { -// genesis := cdptypes.DefaultGenesisState() -// genesis.Params = params -// return app.GenesisState{cdptypes.ModuleName: cdptypes.ModuleCdc.MustMarshalJSON(genesis)} -// } - -// func newBep3GenesisState(params bep3types.Params) app.GenesisState { -// genesis := bep3types.DefaultGenesisState() -// genesis.Params = params -// return app.GenesisState{bep3types.ModuleName: bep3types.ModuleCdc.MustMarshalJSON(genesis)} -// } - -// func newPricefeedGenState(assets []string, prices []sdk.Dec) app.GenesisState { -// if len(assets) != len(prices) { -// panic("assets and prices must be the same length") -// } -// pfGenesis := pricefeed.DefaultGenesisState() - -// for i := range assets { -// pfGenesis.Params.Markets = append( -// pfGenesis.Params.Markets, -// pricefeed.Market{ -// MarketID: assets[i] + ":usd", BaseAsset: assets[i], QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true, -// }) -// pfGenesis.PostedPrices = append( -// pfGenesis.PostedPrices, -// pricefeed.PostedPrice{ -// MarketID: assets[i] + ":usd", -// OracleAddress: sdk.AccAddress{}, -// Price: prices[i], -// Expiry: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), -// }) -// } -// return app.GenesisState{pricefeed.ModuleName: pricefeed.ModuleCdc.MustMarshalJSON(pfGenesis)} -// } - -// func (suite *keeperTestSuite) TestSubmitProposal() { -// defaultCommitteeID := uint64(12) -// normalCom := types.BaseCommittee{ -// ID: defaultCommitteeID, -// Description: "This committee is for testing.", -// Members: suite.Addresses[:2], -// Permissions: []types.Permission{&types.GodPermission{}}, -// VoteThreshold: testutil.D("0.667"), -// ProposalDuration: time.Hour * 24 * 7, -// TallyOption: types.TALLY_OPTION_FIRST_PAST_THE_POST, -// } - -// noPermissionsCom := normalCom -// noPermissionsCom.Permissions = []types.Permission{} - -// paramChangePermissionsCom := normalCom -// paramChangePermissionsCom.Permissions = []types.Permission{ -// types.paramsproposalbParamChangePermission{ -// AllowedParams: types.AllowedParams{ -// {Subspace: cdptypes.ModuleName, Key: string(cdptypes.KeyDebtThreshold)}, -// {Subspace: cdptypes.ModuleName, Key: string(cdptypes.KeyCollateralParams)}, -// }, -// AllowedCollateralParams: types.AllowedCollateralParams{ -// types.AllowedCollateralParam{ -// Type: "bnb-a", -// DebtLimit: true, -// StabilityFee: true, -// }, -// }, -// }, -// } - -// testCP := cdptypes.CollateralParams{{ -// Denom: "bnb", -// Type: "bnb-a", -// LiquidationRatio: testutil.D("1.5"), -// DebtLimit: testutil.C("usdx", 1000000000000), -// StabilityFee: testutil.D("1.000000001547125958"), // %5 apr -// LiquidationPenalty: testutil.D("0.05"), -// AuctionSize: i(100), -// Prefix: 0x20, -// ConversionFactor: i(6), -// LiquidationMarketID: "bnb:usd", -// SpotMarketID: "bnb:usd", -// }} -// testCDPParams := cdptypes.DefaultParams() -// testCDPParams.CollateralParams = testCP -// testCDPParams.GlobalDebtLimit = testCP[0].DebtLimit - -// newValidCP := make(cdptypes.CollateralParams, len(testCP)) -// copy(newValidCP, testCP) -// newValidCP[0].DebtLimit = testutil.C("usdx", 500000000000) - -// newInvalidCP := make(cdptypes.CollateralParams, len(testCP)) -// copy(newInvalidCP, testCP) -// newInvalidCP[0].SpotMarketID = "btc:usd" - -// testcases := []struct { -// name string -// committee types.BaseCommittee -// pubProposal types.PubProposal -// proposer sdk.AccAddress -// committeeID uint64 -// expectErr bool -// }{ -// { -// name: "normal text proposal", -// committee: normalCom, -// pubProposal: govtypes.NewTextProposal("A Title", "A description of this proposal."), -// proposer: normalCom.Members[0], -// committeeID: normalCom.ID, -// expectErr: false, -// }, -// { -// name: "normal param change proposal", -// committee: normalCom, -// pubProposal: paramsproposal.NewParameterChangeProposal( -// "A Title", "A description of this proposal.", -// []paramsproposal.ParamChange{ -// { -// Subspace: "cdp", Key: string(cdptypes.KeyDebtThreshold), Value: string(suite.app.Codec().MustMarshalJSON(i(1000000))), -// }, -// }, -// ), -// proposer: normalCom.Members[0], -// committeeID: normalCom.ID, -// expectErr: false, -// }, -// { -// name: "invalid proposal", -// committee: normalCom, -// pubProposal: nil, -// proposer: normalCom.Members[0], -// committeeID: normalCom.ID, -// expectErr: true, -// }, -// { -// name: "missing committee", -// // no committee -// pubProposal: govtypes.NewTextProposal("A Title", "A description of this proposal."), -// proposer: suite.Addresses[0], -// committeeID: 0, -// expectErr: true, -// }, -// { -// name: "not a member", -// committee: normalCom, -// pubProposal: govtypes.NewTextProposal("A Title", "A description of this proposal."), -// proposer: suite.Addresses[4], -// committeeID: normalCom.ID, -// expectErr: true, -// }, -// { -// name: "not enough permissions", -// committee: noPermissionsCom, -// pubProposal: govtypes.NewTextProposal("A Title", "A description of this proposal."), -// proposer: noPermissionsCom.Members[0], -// committeeID: noPermissionsCom.ID, -// expectErr: true, -// }, -// { -// name: "valid sub param change", -// committee: paramChangePermissionsCom, -// pubProposal: paramsproposal.NewParameterChangeProposal( -// "A Title", "A description of this proposal.", -// []paramsproposal.ParamChange{ -// { -// Subspace: "cdp", -// Key: string(cdptypes.KeyDebtThreshold), -// Value: string(suite.app.Codec().MustMarshalJSON(i(1000000000))), -// }, -// { -// Subspace: "cdp", -// Key: string(cdptypes.KeyCollateralParams), -// Value: string(suite.app.Codec().MustMarshalJSON(newValidCP)), -// }, -// }, -// ), -// proposer: paramChangePermissionsCom.Members[0], -// committeeID: paramChangePermissionsCom.ID, -// expectErr: false, -// }, -// { -// name: "invalid sub param change permission", -// committee: paramChangePermissionsCom, -// pubProposal: paramsproposal.NewParameterChangeProposal( -// "A Title", "A description of this proposal.", -// []paramsproposal.ParamChange{ -// { -// Subspace: "cdp", -// Key: string(cdptypes.KeyDebtThreshold), -// Value: string(suite.app.Codec().MustMarshalJSON(i(1000000000))), -// }, -// { -// Subspace: "cdp", -// Key: string(cdptypes.KeyCollateralParams), -// Value: string(suite.app.Codec().MustMarshalJSON(newInvalidCP)), -// }, -// }, -// ), -// proposer: paramChangePermissionsCom.Members[0], -// committeeID: paramChangePermissionsCom.ID, -// expectErr: true, -// }, -// } - -// for _, tc := range testcases { -// suite.Run(tc.name, func() { -// // Create local testApp because suite doesn't run the SetupTest function for subtests -// tApp := app.NewTestApp() -// keeper := tApp.GetCommitteeKeeper() -// ctx := tApp.NewContext(true, tmproto.Header{}) -// tApp.InitializeFromGenesisStates( -// newPricefeedGenState([]string{"bnb"}, []sdk.Dec{testutil.D("15.01")}), -// newCDPGenesisState(testCDPParams), -// ) -// // Cast BaseCommittee to MemberCommittee (if required) to meet Committee interface requirement -// if tc.committee.ID == defaultCommitteeID { -// keeper.SetCommittee(ctx, types.MustNewMemberCommittee( -// } - -// id, err := keeper.SubmitProposal(ctx, tc.proposer, tc.committeeID, tc.pubProposal) - -// if tc.expectErr { -// suite.NotNil(err) -// } else { -// suite.NoError(err) -// pr, found := keeper.GetProposal(ctx, id) -// suite.True(found) -// suite.Equal(tc.committeeID, pr.CommitteeID) -// suite.Equal(ctx.BlockTime().Add(tc.committee.GetProposalDuration()), pr.Deadline) -// } -// }) -// } -// } - -func (suite *keeperTestSuite) TestAddVote() { - memberCom := types.MustNewMemberCommittee( - 1, - "This member committee is for testing.", - suite.Addresses[:2], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ) - tokenCom := types.MustNewTokenCommittee( - 12, - "This token committee is for testing.", - suite.Addresses[:2], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.4"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - sdk.Dec{}, - "hard", - ) - nonMemberAddr := suite.Addresses[4] - firstBlockTime := time.Date(1998, time.January, 1, 1, 0, 0, 0, time.UTC) - - testcases := []struct { - name string - proposalID uint64 - committee types.Committee - voter sdk.AccAddress - voteType types.VoteType - voteTime time.Time - expectErr bool - }{ - { - name: "normal MemberCommittee", - committee: memberCom, - proposalID: types.DefaultNextProposalID, - voter: memberCom.Members[0], - voteType: types.VOTE_TYPE_YES, - expectErr: false, - }, - { - name: "normal TokenCommittee", - committee: tokenCom, - proposalID: types.DefaultNextProposalID, - voter: nonMemberAddr, - voteType: types.VOTE_TYPE_YES, - expectErr: false, - }, - { - name: "nonexistent proposal", - committee: memberCom, - proposalID: 9999999, - voter: memberCom.Members[0], - voteType: types.VOTE_TYPE_YES, - expectErr: true, - }, - { - name: "proposal expired", - committee: memberCom, - proposalID: types.DefaultNextProposalID, - voter: memberCom.Members[0], - voteTime: firstBlockTime.Add(memberCom.ProposalDuration), - voteType: types.VOTE_TYPE_YES, - expectErr: true, - }, - { - name: "MemberCommittee: voter not committee member", - committee: memberCom, - proposalID: types.DefaultNextProposalID, - voter: nonMemberAddr, - voteType: types.VOTE_TYPE_YES, - expectErr: true, - }, - { - name: "MemberCommittee: voter votes no", - committee: memberCom, - proposalID: types.DefaultNextProposalID, - voter: memberCom.Members[0], - voteType: types.VOTE_TYPE_NO, - expectErr: true, - }, - } - - for _, tc := range testcases { - suite.Run(tc.name, func() { - // Create local testApp because suite doesn't run the SetupTest function for subtests - tApp := app.NewTestApp() - keeper := tApp.GetCommitteeKeeper() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: firstBlockTime}) - tApp.InitializeFromGenesisStates() - - // setup the committee and proposal - keeper.SetCommittee(ctx, tc.committee) - _, err := keeper.SubmitProposal(ctx, tc.committee.GetMembers()[0], tc.committee.GetID(), govv1beta1.NewTextProposal("A Title", "A description of this proposal.")) - suite.NoError(err) - - ctx = ctx.WithBlockTime(tc.voteTime) - err = keeper.AddVote(ctx, tc.proposalID, tc.voter, tc.voteType) - - if tc.expectErr { - suite.NotNil(err) - } else { - suite.NoError(err) - _, found := keeper.GetVote(ctx, tc.proposalID, tc.voter) - suite.True(found) - } - }) - } -} - -func (suite *keeperTestSuite) TestTallyMemberCommitteeVotes() { - memberCom := types.MustNewMemberCommittee( - 12, - "This committee is for testing.", - suite.Addresses[:5], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_DEADLINE, - ) - var defaultProposalID uint64 = 1 - firstBlockTime := time.Date(1998, time.January, 1, 1, 0, 0, 0, time.UTC) - - testcases := []struct { - name string - votes []types.Vote - expectedVoteCount sdk.Dec - }{ - { - name: "has 0 votes", - votes: []types.Vote{}, - expectedVoteCount: testutil.D("0"), - }, - { - name: "has 1 vote", - votes: []types.Vote{ - {ProposalID: defaultProposalID, Voter: suite.Addresses[0], VoteType: types.VOTE_TYPE_YES}, - }, - expectedVoteCount: testutil.D("1"), - }, - { - name: "has multiple votes", - votes: []types.Vote{ - {ProposalID: defaultProposalID, Voter: suite.Addresses[0], VoteType: types.VOTE_TYPE_YES}, - {ProposalID: defaultProposalID, Voter: suite.Addresses[1], VoteType: types.VOTE_TYPE_YES}, - {ProposalID: defaultProposalID, Voter: suite.Addresses[2], VoteType: types.VOTE_TYPE_YES}, - {ProposalID: defaultProposalID, Voter: suite.Addresses[3], VoteType: types.VOTE_TYPE_YES}, - }, - expectedVoteCount: testutil.D("4"), - }, - } - - for _, tc := range testcases { - // Set up test app - tApp := app.NewTestApp() - keeper := tApp.GetCommitteeKeeper() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: firstBlockTime}) - - // Initialize test app with genesis state - tApp.InitializeFromGenesisStates( - committeeGenState( - tApp.AppCodec(), - []types.Committee{memberCom}, - []types.Proposal{types.MustNewProposal( - govv1beta1.NewTextProposal("A Title", "A description of this proposal."), - defaultProposalID, - memberCom.GetID(), - firstBlockTime.Add(time.Hour*24*7), - )}, - tc.votes, - ), - ) - - // Check that all votes are counted - currentVotes := keeper.TallyMemberCommitteeVotes(ctx, defaultProposalID) - suite.Equal(tc.expectedVoteCount, currentVotes) - } -} - -func (suite *keeperTestSuite) TestTallyTokenCommitteeVotes() { - tokenCom := types.MustNewTokenCommittee( - 12, - "This committee is for testing.", - suite.Addresses[:5], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_DEADLINE, - testutil.D("0.4"), - "hard", - ) - var defaultProposalID uint64 = 1 - firstBlockTime := time.Date(1998, time.January, 1, 1, 0, 0, 0, time.UTC) - - genAddrs := suite.Addresses[:8] // Genesis accounts - genCoinCounts := []int64{0, 0, 0, 10, 20, 30, 40, 50} // Genesis token balances - - testcases := []struct { - name string - votes []types.Vote - expectedYesVoteCount sdk.Dec - expectedNoVoteCount sdk.Dec - expectedTotalVoteCount sdk.Dec - }{ - { - name: "has 0 votes", - votes: []types.Vote{}, - expectedYesVoteCount: testutil.D("0"), - expectedNoVoteCount: testutil.D("0"), - expectedTotalVoteCount: testutil.D("0"), - }, - { - name: "counts token holder 'Yes' votes", - votes: []types.Vote{ - {ProposalID: defaultProposalID, Voter: genAddrs[4], VoteType: types.VOTE_TYPE_YES}, // Token holder - }, - expectedYesVoteCount: sdk.NewDec(genCoinCounts[4]), - expectedNoVoteCount: testutil.D("0"), - expectedTotalVoteCount: sdk.NewDec(genCoinCounts[4]), - }, - { - name: "does not count non-token holder 'Yes' votes", - votes: []types.Vote{ - {ProposalID: defaultProposalID, Voter: genAddrs[4], VoteType: types.VOTE_TYPE_YES}, // Token holder - {ProposalID: defaultProposalID, Voter: genAddrs[0], VoteType: types.VOTE_TYPE_YES}, // Non-token holder - }, - expectedYesVoteCount: sdk.NewDec(genCoinCounts[4]), - expectedNoVoteCount: testutil.D("0"), - expectedTotalVoteCount: sdk.NewDec(genCoinCounts[4]), - }, - { - name: "counts multiple 'Yes' votes from token holders", - votes: []types.Vote{ - {ProposalID: defaultProposalID, Voter: genAddrs[4], VoteType: types.VOTE_TYPE_YES}, // Token holder - {ProposalID: defaultProposalID, Voter: genAddrs[5], VoteType: types.VOTE_TYPE_YES}, // Token holder - {ProposalID: defaultProposalID, Voter: genAddrs[6], VoteType: types.VOTE_TYPE_YES}, // Token holder - }, - expectedYesVoteCount: sdk.NewDec(genCoinCounts[4] + genCoinCounts[5] + genCoinCounts[6]), - expectedNoVoteCount: testutil.D("0"), - expectedTotalVoteCount: sdk.NewDec(genCoinCounts[4] + genCoinCounts[5] + genCoinCounts[6]), - }, - { - name: "counts token holder 'No' votes", - votes: []types.Vote{ - {ProposalID: defaultProposalID, Voter: genAddrs[4], VoteType: types.VOTE_TYPE_NO}, // Token holder - }, - expectedYesVoteCount: testutil.D("0"), - expectedNoVoteCount: sdk.NewDec(genCoinCounts[4]), - expectedTotalVoteCount: sdk.NewDec(genCoinCounts[4]), - }, - { - name: "does not count non-token holder 'No' votes", - votes: []types.Vote{ - {ProposalID: defaultProposalID, Voter: genAddrs[4], VoteType: types.VOTE_TYPE_NO}, // Token holder - {ProposalID: defaultProposalID, Voter: genAddrs[0], VoteType: types.VOTE_TYPE_NO}, // Non-token holder - }, - expectedYesVoteCount: testutil.D("0"), - expectedNoVoteCount: sdk.NewDec(genCoinCounts[4]), - expectedTotalVoteCount: sdk.NewDec(genCoinCounts[4]), - }, - { - name: "counts multiple 'No' votes from token holders", - votes: []types.Vote{ - {ProposalID: defaultProposalID, Voter: genAddrs[4], VoteType: types.VOTE_TYPE_NO}, // Token holder - {ProposalID: defaultProposalID, Voter: genAddrs[5], VoteType: types.VOTE_TYPE_NO}, // Token holder - {ProposalID: defaultProposalID, Voter: genAddrs[6], VoteType: types.VOTE_TYPE_NO}, // Token holder - }, - expectedYesVoteCount: testutil.D("0"), - expectedNoVoteCount: sdk.NewDec(genCoinCounts[4] + genCoinCounts[5] + genCoinCounts[6]), - expectedTotalVoteCount: sdk.NewDec(genCoinCounts[4] + genCoinCounts[5] + genCoinCounts[6]), - }, - { - name: "includes token holder 'Abstain' votes in total vote count", - votes: []types.Vote{ - {ProposalID: defaultProposalID, Voter: genAddrs[4], VoteType: types.VOTE_TYPE_ABSTAIN}, // Token holder - }, - expectedYesVoteCount: testutil.D("0"), - expectedNoVoteCount: testutil.D("0"), - expectedTotalVoteCount: sdk.NewDec(genCoinCounts[4]), - }, - } - - // Convert accounts/token balances into format expected by genesis generation - var genCoins []sdk.Coins - var totalSupply sdk.Coins - for _, amount := range genCoinCounts { - userCoin := testutil.C("hard", amount) - genCoins = append(genCoins, testutil.Cs(userCoin)) - totalSupply = totalSupply.Add(userCoin) - } - - for _, tc := range testcases { - // Set up test app - tApp := app.NewTestApp() - keeper := tApp.GetCommitteeKeeper() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: firstBlockTime}) - - // Initialize test app with genesis state - tApp.InitializeFromGenesisStates( - committeeGenState( - tApp.AppCodec(), - []types.Committee{tokenCom}, - []types.Proposal{types.MustNewProposal( - govv1beta1.NewTextProposal("A Title", "A description of this proposal."), - defaultProposalID, - tokenCom.GetID(), - firstBlockTime.Add(time.Hour*24*7), - )}, - tc.votes, - ), - app.NewFundedGenStateWithCoins(tApp.AppCodec(), genCoins, genAddrs), - ) - - yesVotes, noVotes, currVotes, possibleVotes := keeper.TallyTokenCommitteeVotes(ctx, defaultProposalID, tokenCom.TallyDenom) - - // Check that all Yes votes are counted according to their weight - suite.Equal(tc.expectedYesVoteCount, yesVotes) - // Check that all No votes are counted according to their weight - suite.Equal(tc.expectedNoVoteCount, noVotes) - // Check that all non-Yes votes are counted according to their weight - suite.Equal(tc.expectedTotalVoteCount, currVotes) - // Check that possible votes equals the number of members on the committee - suite.Equal(sdk.NewDecFromInt(totalSupply.AmountOf(tokenCom.GetTallyDenom())), possibleVotes) - } -} - -func (suite *keeperTestSuite) TestGetMemberCommitteeProposalResult() { - memberCom := types.MustNewMemberCommittee( - - 12, - "This committee is for testing.", - suite.Addresses[:5], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_DEADLINE, - ) - var defaultID uint64 = 1 - firstBlockTime := time.Date(1998, time.January, 1, 1, 0, 0, 0, time.UTC) - - testcases := []struct { - name string - committee types.Committee - votes []types.Vote - proposalPasses bool - }{ - { - name: "enough votes", - committee: memberCom, - votes: []types.Vote{ - {ProposalID: defaultID, Voter: suite.Addresses[0], VoteType: types.VOTE_TYPE_YES}, - {ProposalID: defaultID, Voter: suite.Addresses[1], VoteType: types.VOTE_TYPE_YES}, - {ProposalID: defaultID, Voter: suite.Addresses[2], VoteType: types.VOTE_TYPE_YES}, - {ProposalID: defaultID, Voter: suite.Addresses[3], VoteType: types.VOTE_TYPE_YES}, - }, - proposalPasses: true, - }, - { - name: "not enough votes", - committee: memberCom, - votes: []types.Vote{ - {ProposalID: defaultID, Voter: suite.Addresses[0], VoteType: types.VOTE_TYPE_YES}, - }, - proposalPasses: false, - }, - } - - for _, tc := range testcases { - suite.Run(tc.name, func() { - // Create local testApp because suite doesn't run the SetupTest function for subtests - tApp := app.NewTestApp() - keeper := tApp.GetCommitteeKeeper() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: firstBlockTime}) - - tApp.InitializeFromGenesisStates( - committeeGenState( - tApp.AppCodec(), - []types.Committee{tc.committee}, - []types.Proposal{types.MustNewProposal( - govv1beta1.NewTextProposal("A Title", "A description of this proposal."), - defaultID, - tc.committee.GetID(), - firstBlockTime.Add(time.Hour*24*7), - )}, - tc.votes, - ), - ) - - proposalPasses := keeper.GetMemberCommitteeProposalResult(ctx, defaultID, tc.committee) - suite.Equal(tc.proposalPasses, proposalPasses) - }) - } -} - -func (suite *keeperTestSuite) TestGetTokenCommitteeProposalResult() { - tokenCom := types.MustNewTokenCommittee( - 12, - "This committee is for testing.", - suite.Addresses[:5], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_DEADLINE, - testutil.D("0.4"), - "hard", - ) - var defaultID uint64 = 1 - firstBlockTime := time.Date(1998, time.January, 1, 1, 0, 0, 0, time.UTC) - - genAddrs := suite.Addresses[:8] // Genesis accounts - genCoinCounts := []int64{0, 0, 0, 10, 20, 30, 40, 50} // Genesis token balances - - // ---------------------- Polling information ---------------------- - // 150hard total token supply: 150 possible votes - // 40% quroum: 60 votes required to meet quroum - // 66.67% voting threshold: 2/3rds of votes must be Yes votes - // ----------------------------------------------------------------- - - testcases := []struct { - name string - committee *types.TokenCommittee - votes []types.Vote - proposalPasses bool - }{ - { - name: "not enough votes to meet quroum", - committee: tokenCom, - votes: []types.Vote{ - {ProposalID: defaultID, Voter: genAddrs[7], VoteType: types.VOTE_TYPE_YES}, // Holds 50 tokens - }, - proposalPasses: false, // 60 vote quroum; 50 total votes; 50 yes votes. Doesn't pass 40% quroum. - }, - { - name: "enough votes to meet quroum and enough Yes votes to pass voting threshold", - committee: tokenCom, - votes: []types.Vote{ - {ProposalID: defaultID, Voter: genAddrs[3], VoteType: types.VOTE_TYPE_NO}, // Holds 10 tokens - {ProposalID: defaultID, Voter: genAddrs[7], VoteType: types.VOTE_TYPE_YES}, // Holds 50 tokens - }, - proposalPasses: true, // 60 vote quroum; 60 total votes; 50 Yes votes. Passes the 66.67% voting threshold. - }, - { - name: "enough votes to meet quroum via Abstain votes and enough Yes votes to pass voting threshold", - committee: tokenCom, - votes: []types.Vote{ - {ProposalID: defaultID, Voter: genAddrs[3], VoteType: types.VOTE_TYPE_ABSTAIN}, // Holds 10 tokens - {ProposalID: defaultID, Voter: genAddrs[7], VoteType: types.VOTE_TYPE_YES}, // Holds 50 tokens - }, - proposalPasses: true, // 60 vote quroum; 60 total votes; 50 Yes votes. Passes the 66.67% voting threshold. - }, - { - name: "enough votes to meet quroum but not enough Yes votes to pass voting threshold", - committee: tokenCom, - votes: []types.Vote{ - {ProposalID: defaultID, Voter: genAddrs[4], VoteType: types.VOTE_TYPE_YES}, // Holds 20 tokens - {ProposalID: defaultID, Voter: genAddrs[6], VoteType: types.VOTE_TYPE_NO}, // Holds 40 tokens - }, - proposalPasses: false, // 60 vote quroum; 60 total votes; 20 Yes votes. Doesn't pass 66.67% voting threshold. - }, - { - name: "enough votes to pass voting threshold (multiple Yes votes, multiple No votes)", - committee: tokenCom, - votes: []types.Vote{ - {ProposalID: defaultID, Voter: genAddrs[3], VoteType: types.VOTE_TYPE_YES}, // Holds 10 tokens - {ProposalID: defaultID, Voter: genAddrs[4], VoteType: types.VOTE_TYPE_YES}, // Holds 20 tokens - {ProposalID: defaultID, Voter: genAddrs[5], VoteType: types.VOTE_TYPE_YES}, // Holds 30 tokens - {ProposalID: defaultID, Voter: genAddrs[6], VoteType: types.VOTE_TYPE_NO}, // Holds 40 tokens - {ProposalID: defaultID, Voter: genAddrs[7], VoteType: types.VOTE_TYPE_YES}, // Holds 50 tokens - }, - proposalPasses: true, // 60 vote quroum; 150 total votes; 110 Yes votes. Passes the 66.67% voting threshold. - }, - { - name: "not enough votes to pass voting threshold (multiple Yes votes, multiple No votes)", - committee: tokenCom, - votes: []types.Vote{ - {ProposalID: defaultID, Voter: genAddrs[3], VoteType: types.VOTE_TYPE_YES}, // Holds 10 tokens - {ProposalID: defaultID, Voter: genAddrs[4], VoteType: types.VOTE_TYPE_YES}, // Holds 20 tokens - {ProposalID: defaultID, Voter: genAddrs[5], VoteType: types.VOTE_TYPE_YES}, // Holds 30 tokens - {ProposalID: defaultID, Voter: genAddrs[6], VoteType: types.VOTE_TYPE_YES}, // Holds 40 tokens - {ProposalID: defaultID, Voter: genAddrs[7], VoteType: types.VOTE_TYPE_NO}, // Holds 50 tokens - }, - proposalPasses: false, // 60 vote quroum; 150 total votes; 100 Yes votes. Doesn't pass 66.67% voting threshold. - }, - } - - // Convert accounts/token balances into format expected by genesis generation - var genCoins []sdk.Coins - var totalSupply sdk.Coins - for _, amount := range genCoinCounts { - userCoin := testutil.C("hard", amount) - genCoins = append(genCoins, testutil.Cs(userCoin)) - totalSupply = totalSupply.Add(userCoin) - } - - for _, tc := range testcases { - suite.Run(tc.name, func() { - // Create local testApp because suite doesn't run the SetupTest function for subtests - tApp := app.NewTestApp() - keeper := tApp.GetCommitteeKeeper() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: firstBlockTime}) - - tApp.InitializeFromGenesisStates( - committeeGenState( - tApp.AppCodec(), - []types.Committee{tc.committee}, - []types.Proposal{types.MustNewProposal( - govv1beta1.NewTextProposal("A Title", "A description of this proposal."), - defaultID, - tc.committee.GetID(), - firstBlockTime.Add(time.Hour*24*7), - )}, - tc.votes, - ), - app.NewFundedGenStateWithCoins(tApp.AppCodec(), genCoins, genAddrs), - ) - - proposalPasses := keeper.GetTokenCommitteeProposalResult(ctx, defaultID, tc.committee) - suite.Equal(tc.proposalPasses, proposalPasses) - }) - } -} - -func (suite *keeperTestSuite) TestCloseProposal() { - memberCom := types.MustNewMemberCommittee( - 12, - "This committee is for testing.", - suite.Addresses[:5], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_DEADLINE, - ) - - var proposalID uint64 = 1 - firstBlockTime := time.Date(1998, time.January, 1, 1, 0, 0, 0, time.UTC) - - tApp := app.NewTestApp() - keeper := tApp.GetCommitteeKeeper() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: firstBlockTime}) - - tApp.InitializeFromGenesisStates( - committeeGenState( - tApp.AppCodec(), - []types.Committee{memberCom}, - []types.Proposal{types.MustNewProposal( - govv1beta1.NewTextProposal("A Title", "A description of this proposal."), - proposalID, - memberCom.GetID(), - firstBlockTime.Add(time.Hour*24*7), - )}, - []types.Vote{}, - ), - ) - - // Confirm proposal exists - proposal, found := keeper.GetProposal(ctx, proposalID) - suite.True(found) - - // Close proposal - keeper.CloseProposal(ctx, proposal, types.Passed) - - events := ctx.EventManager().Events() - event := events[0] - suite.Require().Equal("proposal_close", event.Type) - - hasProposalTallyAttr := false - for _, attr := range event.Attributes { - if string(attr.GetKey()) == "proposal_tally" { - hasProposalTallyAttr = true - valueStr := string(attr.GetValue()) - suite.Contains(valueStr, "proposal_id") - suite.Contains(valueStr, "yes_votes") - suite.Contains(valueStr, "current_votes") - suite.Contains(valueStr, "possible_votes") - suite.Contains(valueStr, "vote_threshold") - suite.Contains(valueStr, "quorum") - } - } - suite.Require().True(hasProposalTallyAttr) - - // Confirm proposal doesn't exist - _, found = keeper.GetProposal(ctx, proposalID) - suite.False(found) -} - -func committeeGenState(cdc codec.Codec, committees []types.Committee, proposals []types.Proposal, votes []types.Vote) app.GenesisState { - gs := types.NewGenesisState( - uint64(len(proposals)+1), - committees, - proposals, - votes, - ) - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(gs)} -} - -func bankGenState(cdc codec.Codec, coins sdk.Coins) app.GenesisState { - gs := banktypes.DefaultGenesisState() - gs.Supply = coins - return app.GenesisState{banktypes.ModuleName: cdc.MustMarshalJSON(gs)} -} - -type UnregisteredPubProposal struct { - govv1beta1.TextProposal -} - -func (UnregisteredPubProposal) ProposalRoute() string { return "unregistered" } -func (UnregisteredPubProposal) ProposalType() string { return "unregistered" } - -var _ types.PubProposal = &UnregisteredPubProposal{} - -// func (suite *keeperTestSuite) TestValidatePubProposal() { - -// testcases := []struct { -// name string -// pubProposal types.PubProposal -// expectErr bool -// }{ -// { -// name: "valid (text proposal)", -// pubProposal: govtypes.NewTextProposal("A Title", "A description of this proposal."), -// expectErr: false, -// }, -// { -// name: "valid (param change proposal)", -// pubProposal: paramsproposal.NewParameterChangeProposal( -// "Change the debt limit", -// "This proposal changes the debt limit of the cdp module.", -// []paramsproposal.ParamChange{{ -// Subspace: cdptypes.ModuleName, -// Key: string(cdptypes.KeyGlobalDebtLimit), -// Value: string(types.ModuleCdc.MustMarshalJSON(c("usdx", 100000000000))), -// }}, -// ), -// expectErr: false, -// }, -// { -// name: "invalid (missing title)", -// pubProposal: govtypes.TextProposal{Description: "A description of this proposal."}, -// expectErr: true, -// }, -// { -// name: "invalid (unregistered)", -// pubProposal: UnregisteredPubProposal{govtypes.TextProposal{Title: "A Title", Description: "A description of this proposal."}}, -// expectErr: true, -// }, -// { -// name: "invalid (nil)", -// pubProposal: nil, -// expectErr: true, -// }, -// { -// name: "invalid (proposal handler fails)", -// pubProposal: paramsproposal.NewParameterChangeProposal( -// "A Title", -// "A description of this proposal.", -// []paramsproposal.ParamChange{{ -// Subspace: "nonsense-subspace", -// Key: "nonsense-key", -// Value: "nonsense-value", -// }}, -// ), -// expectErr: true, -// }, -// { -// name: "invalid (proposal handler panics)", -// pubProposal: paramsproposal.NewParameterChangeProposal( -// "A Title", -// "A description of this proposal.", -// []paramsproposal.ParamChange{{ -// Subspace: cdptypes.ModuleName, -// Key: "nonsense-key", // a valid Subspace but invalid Key will trigger a panic in the paramchange propsal handler -// Value: "nonsense-value", -// }}, -// ), -// expectErr: true, -// }, -// { -// name: "invalid (proposal handler fails - invalid json)", -// pubProposal: paramsproposal.NewParameterChangeProposal( -// "A Title", -// "A description of this proposal.", -// []paramsproposal.ParamChange{{ -// Subspace: cdptypes.ModuleName, -// Key: string(cdptypes.KeyGlobalDebtLimit), -// Value: `{"denom": "usdx",`, -// }}, -// ), -// expectErr: true, -// }, -// } - -// for _, tc := range testcases { -// suite.Run(tc.name, func() { -// err := suite.keeper.ValidatePubProposal(suite.ctx, tc.pubProposal) -// if tc.expectErr { -// suite.NotNil(err) -// } else { -// suite.NoError(err) -// } -// }) -// } -// } - -// func (suite *keeperTestSuite) TestProcessProposals() { - -// firstBlockTime := time.Date(1998, time.January, 1, 1, 0, 0, 0, time.UTC) - -// genAddrs := suite.Addresses[:4] // Genesis accounts -// genCoinCounts := []int64{1, 1, 1, 1} // Genesis token balances -// // Convert accounts/token balances into format expected by genesis generation -// var genCoins []sdk.Coins -// var totalSupply sdk.Coins -// for _, amount := range genCoinCounts { -// userCoin := testutil.C("hard", amount) -// genCoins = append(genCoins, testutil.Cs(userCoin)) -// totalSupply = totalSupply.Add(userCoin) -// } - -// // Set up committees -// committees := []types.Committee{ -// // 1. FPTP MemberCommmittee -// types.MustNewMemberCommittee( - -// 1, -// "FTPT MemberCommittee", -// genAddrs, -// []types.Permission{&types.GodPermission{}}, -// testutil.D("0.667"), -// time.Hour*24*7, -// types.TALLY_OPTION_FIRST_PAST_THE_POST, -// ), -// // 2. FPTP TokenCommittee -// types.MustNewTokenCommittee( - -// 2, -// "FTPT TokenCommittee", -// genAddrs, -// []types.Permission{&types.GodPermission{}}, -// testutil.D("0.667"), -// time.Hour*24*7, -// types.TALLY_OPTION_FIRST_PAST_THE_POST, -// testutil.D("0.30"), -// "hard", -// ), -// // 3. Deadline MemberCommmittee -// types.MustNewMemberCommittee( - -// 3, -// "Deadline MemberCommittee", -// genAddrs, -// []types.Permission{&types.GodPermission{}}, -// testutil.D("0.667"), -// time.Hour*24*7, -// types.TALLY_OPTION_DEADLINE, -// ), -// // 4. Deadline TokenCommittee -// types.MustNewTokenCommittee( -// 4, -// "Deadline TokenCommittee", -// genAddrs, -// []types.Permission{&types.GodPermission{}}, -// testutil.D("0.667"), -// time.Hour*24*7, -// types.TALLY_OPTION_DEADLINE, -// testutil.D("0.30"), -// "hard", -// ), -// // 5. PTP MemberCommmittee without permissions -// types.MustNewMemberCommittee( - -// 5, -// "FTPT MemberCommittee without permissions", -// genAddrs, -// nil, -// testutil.D("0.667"), -// time.Hour*24*7, -// types.TALLY_OPTION_FIRST_PAST_THE_POST, -// ), -// } - -// // Set up proposals that correspond 1:1 with each committee -// proposals := []types.Proposal{ -// types.MustNewProposal( -// govtypes.NewTextProposal("Proposal 1", "This proposal is for the FPTP MemberCommmittee."), -// 1, -// 1, -// firstBlockTime.Add(7*24*time.Hour), -// ), -// types.MustNewProposal( -// govtypes.NewTextProposal("Proposal 2", "This proposal is for the FPTP TokenCommittee."), -// 2, -// 2, - -// firstBlockTime.Add(7*24*time.Hour), -// ), -// types.MustNewProposal( -// govtypes.NewTextProposal("Proposal 3", "This proposal is for the Deadline MemberCommmittee."), -// 3, -// 3, - -// firstBlockTime.Add(7*24*time.Hour), -// ), -// types.MustNewProposal( -// govtypes.NewTextProposal("Proposal 4", "This proposal is for the Deadline TokenCommittee."), -// 4, -// 4, - -// firstBlockTime.Add(7*24*time.Hour), -// ), -// types.MustNewProposal( -// govtypes.NewTextProposal("Proposal 5", "This proposal is for the FPTP MemberCommmittee without permissions."), -// 5, -// 5, -// firstBlockTime.Add(7*24*time.Hour), -// ), -// } - -// // Each test case targets 1 committee/proposal via targeted votes -// testcases := []struct { -// name string -// ID uint64 -// votes []types.Vote -// expectedToCompleteBeforeDeadline bool -// expectedOutcome types.ProposalOutcome -// }{ -// { -// name: "FPTP MemberCommittee proposal does not have enough votes to pass", -// ID: 1, -// votes: []types.Vote{ -// {ProposalID: 1, Voter: genAddrs[0], VoteType: types.VOTE_TYPE_YES}, -// }, -// expectedToCompleteBeforeDeadline: false, -// expectedOutcome: types.Failed, -// }, -// { -// name: "FPTP MemberCommittee proposal has enough votes to pass before deadline", -// ID: 1, -// votes: []types.Vote{ -// {ProposalID: 1, Voter: genAddrs[0], VoteType: types.VOTE_TYPE_YES}, -// {ProposalID: 1, Voter: genAddrs[1], VoteType: types.VOTE_TYPE_YES}, -// {ProposalID: 1, Voter: genAddrs[2], VoteType: types.VOTE_TYPE_YES}, -// }, -// expectedToCompleteBeforeDeadline: true, -// expectedOutcome: types.Passed, -// }, -// { -// name: "FPTP TokenCommittee proposal does not have enough votes to pass", -// ID: 2, -// votes: []types.Vote{ -// {ProposalID: 2, Voter: genAddrs[0], VoteType: types.VOTE_TYPE_YES}, -// }, -// expectedToCompleteBeforeDeadline: false, -// expectedOutcome: types.Failed, -// }, -// { -// name: "FPTP TokenCommittee proposal has enough votes to pass before deadline", -// ID: 2, -// votes: []types.Vote{ -// {ProposalID: 2, Voter: genAddrs[0], VoteType: types.VOTE_TYPE_YES}, -// {ProposalID: 2, Voter: genAddrs[1], VoteType: types.VOTE_TYPE_YES}, -// {ProposalID: 2, Voter: genAddrs[2], VoteType: types.VOTE_TYPE_YES}, -// }, -// expectedToCompleteBeforeDeadline: true, -// expectedOutcome: types.Passed, -// }, -// { -// name: "Deadline MemberCommittee proposal with enough votes to pass only passes after deadline", -// ID: 3, -// votes: []types.Vote{ -// {ProposalID: 3, Voter: genAddrs[0], VoteType: types.VOTE_TYPE_YES}, -// {ProposalID: 3, Voter: genAddrs[1], VoteType: types.VOTE_TYPE_YES}, -// {ProposalID: 3, Voter: genAddrs[2], VoteType: types.VOTE_TYPE_YES}, -// }, -// expectedOutcome: types.Passed, -// }, -// { -// name: "Deadline MemberCommittee proposal doesn't have enough votes to pass", -// ID: 3, -// votes: []types.Vote{ -// {ProposalID: 3, Voter: genAddrs[0], VoteType: types.VOTE_TYPE_YES}, -// }, -// expectedOutcome: types.Failed, -// }, -// { -// name: "Deadline TokenCommittee proposal with enough votes to pass only passes after deadline", -// ID: 4, -// votes: []types.Vote{ -// {ProposalID: 4, Voter: genAddrs[0], VoteType: types.VOTE_TYPE_YES}, -// {ProposalID: 4, Voter: genAddrs[1], VoteType: types.VOTE_TYPE_YES}, -// {ProposalID: 4, Voter: genAddrs[2], VoteType: types.VOTE_TYPE_YES}, -// }, -// expectedOutcome: types.Passed, -// }, -// { -// name: "Deadline TokenCommittee proposal doesn't have enough votes to pass", -// ID: 4, -// votes: []types.Vote{ -// {ProposalID: 4, Voter: genAddrs[0], VoteType: types.VOTE_TYPE_YES}, -// }, -// expectedOutcome: types.Failed, -// }, -// { -// name: "FPTP MemberCommittee doesn't have permissions to enact passed proposal", -// ID: 5, -// votes: []types.Vote{ -// {ProposalID: 5, Voter: genAddrs[0], VoteType: types.VOTE_TYPE_YES}, -// {ProposalID: 5, Voter: genAddrs[1], VoteType: types.VOTE_TYPE_YES}, -// {ProposalID: 5, Voter: genAddrs[2], VoteType: types.VOTE_TYPE_YES}, -// }, -// expectedToCompleteBeforeDeadline: true, -// expectedOutcome: types.Invalid, -// }, -// } - -// for _, tc := range testcases { -// suite.Run(tc.name, func() { -// // Create local testApp because suite doesn't run the SetupTest function for subtests -// tApp := app.NewTestApp() -// keeper := tApp.GetCommitteeKeeper() -// ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: firstBlockTime}) - -// // Initialize all committees, proposals, and votes via Genesis -// tApp.InitializeFromGenesisStates( -// committeeGenState(tApp.AppCodec(), committees, proposals, tc.votes), -// bankGenState(tApp.AppCodec(), totalSupply), -// app.NewFundedGenStateWithCoins(tApp.AppCodec(), genCoins, genAddrs), -// ) - -// // Load committee from the store -// committee, found := keeper.GetCommittee(ctx, tc.ID) -// suite.True(found) - -// // Process proposals -// ctx = ctx.WithBlockTime(firstBlockTime) -// keeper.ProcessProposals(ctx) - -// // Fetch proposal and votes from the store -// votes := getProposalVoteMap(keeper, ctx) -// proposal, found := keeper.GetProposal(ctx, tc.ID) - -// if committee.GetTallyOption() == types.TALLY_OPTION_FIRST_PAST_THE_POST { -// if tc.expectedToCompleteBeforeDeadline { -// suite.False(found) -// suite.Empty(votes[tc.ID]) - -// // Check proposal outcome -// outcome, err := getProposalOutcome(tc.ID, ctx.EventManager().Events(), tApp.LegacyAmino()) -// suite.NoError(err) -// suite.Equal(tc.expectedOutcome, outcome) -// return -// } else { -// suite.True(found) -// suite.NotEmpty(votes[tc.ID]) -// } -// } - -// // Move block time to deadline -// ctx = ctx.WithBlockTime(proposal.Deadline) -// keeper.ProcessProposals(ctx) - -// // Fetch proposal and votes from the store -// votes = getProposalVoteMap(keeper, ctx) -// proposal, found = keeper.GetProposal(ctx, tc.ID) -// suite.False(found) -// suite.Empty(votes[proposal.ID]) - -// // Check proposal outcome -// outcome, err := getProposalOutcome(tc.ID, ctx.EventManager().Events(), tApp.LegacyAmino()) -// suite.NoError(err) -// suite.Equal(tc.expectedOutcome, outcome) -// }) -// } -// } - -// // getProposalOutcome checks the outcome of a proposal via a `proposal_close` event whose `proposal_id` -// // matches argument proposalID -// func getProposalOutcome(proposalID uint64, events sdk.Events, cdc *codec.LegacyAmino) (types.ProposalOutcome, error) { -// // Marshal proposal ID to match against event attribute -// x, _ := cdc.MarshalJSON(proposalID) -// marshaledID := x[1 : len(x)-1] - -// for _, event := range events { -// if event.Type == types.EventTypeProposalClose { -// var proposalOutcome types.ProposalOutcome -// correctProposal := false -// for _, attribute := range event.Attributes { -// // Only get outcome of specific proposal -// if bytes.Compare(attribute.GetKey(), []byte("proposal_id")) == 0 { -// if bytes.Compare(attribute.GetValue(), marshaledID) == 0 { -// correctProposal = true -// } -// } -// // Match event attribute bytes to marshaled outcome -// if bytes.Compare(attribute.GetKey(), []byte(types.AttributeKeyProposalOutcome)) == 0 { -// outcome, err := types.MatchMarshaledOutcome(attribute.GetValue(), cdc) -// if err != nil { -// return 0, err -// } -// proposalOutcome = outcome -// } -// } -// // If this is the desired proposal, return the outcome -// if correctProposal { -// return proposalOutcome, nil -// } -// } -// } -// return 0, nil -// } diff --git a/x/committee/module.go b/x/committee/module.go deleted file mode 100644 index f444e184..00000000 --- a/x/committee/module.go +++ /dev/null @@ -1,146 +0,0 @@ -package committee - -import ( - "context" - "encoding/json" - "fmt" - - "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/kava-labs/kava/x/committee/client/cli" - "github.com/kava-labs/kava/x/committee/keeper" - "github.com/kava-labs/kava/x/committee/types" -) - -// ConsensusVersion defines the current module consensus version. -const ConsensusVersion = 1 - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// ---------------------------------------------------------------------------- -// AppModuleBasic -// ---------------------------------------------------------------------------- - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// Registers legacy amino codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// RegisterInterfaces registers the module's interface types -func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { - types.RegisterInterfaces(reg) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) -} - -// ValidateGenesis module validate genesis -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 committee module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) -} - -// GetTxCmd returns committee module's root tx command. -func (a AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns committee module's root query command. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -// ---------------------------------------------------------------------------- -// AppModule -// ---------------------------------------------------------------------------- - -// AppModule implements the AppModule interface for committee module. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper types.AccountKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: accountKeeper, - } -} - -// Name returns committee module's name. -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// 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(), keeper.NewQueryServerImpl(am.keeper)) -} - -// RegisterInvariants registers committee module's invariants. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// InitGenesis performs committee 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 - cdc.MustUnmarshalJSON(gs, &genState) - InitGenesis(ctx, am.keeper, &genState) - return []abci.ValidatorUpdate{} -} - -// ExportGenesis returns committee 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 implements ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } - -// BeginBlock executes all ABCI BeginBlock logic respective to committee module. -func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { - BeginBlocker(ctx, req, am.keeper) -} - -// EndBlock executes all ABCI EndBlock logic respective to committee module. It -// returns no validator updates. -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/committee/proposal_handler.go b/x/committee/proposal_handler.go deleted file mode 100644 index 0ffbda5d..00000000 --- a/x/committee/proposal_handler.go +++ /dev/null @@ -1,55 +0,0 @@ -package committee - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/kava-labs/kava/x/committee/keeper" - "github.com/kava-labs/kava/x/committee/types" -) - -func NewProposalHandler(k keeper.Keeper) govv1beta1.Handler { - return func(ctx sdk.Context, content govv1beta1.Content) error { - switch c := content.(type) { - case *types.CommitteeChangeProposal: - return handleCommitteeChangeProposal(ctx, k, c) - case *types.CommitteeDeleteProposal: - return handleCommitteeDeleteProposal(ctx, k, c) - - default: - return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized %s proposal content type: %T", types.ModuleName, c) - } - } -} - -func handleCommitteeChangeProposal(ctx sdk.Context, k keeper.Keeper, committeeProposal *types.CommitteeChangeProposal) error { - if err := committeeProposal.ValidateBasic(); err != nil { - return errorsmod.Wrap(types.ErrInvalidPubProposal, err.Error()) - } - - // Remove all committee's ongoing proposals - proposals := k.GetProposalsByCommittee(ctx, committeeProposal.GetNewCommittee().GetID()) - for _, p := range proposals { - k.CloseProposal(ctx, p, types.Failed) - } - - // update/create the committee - k.SetCommittee(ctx, committeeProposal.GetNewCommittee()) - return nil -} - -func handleCommitteeDeleteProposal(ctx sdk.Context, k keeper.Keeper, committeeProposal *types.CommitteeDeleteProposal) error { - if err := committeeProposal.ValidateBasic(); err != nil { - return errorsmod.Wrap(types.ErrInvalidPubProposal, err.Error()) - } - - // Remove all committee's ongoing proposals - proposals := k.GetProposalsByCommittee(ctx, committeeProposal.CommitteeID) - for _, p := range proposals { - k.CloseProposal(ctx, p, types.Failed) - } - - k.DeleteCommittee(ctx, committeeProposal.CommitteeID) - return nil -} diff --git a/x/committee/proposal_handler_test.go b/x/committee/proposal_handler_test.go deleted file mode 100644 index 117554c8..00000000 --- a/x/committee/proposal_handler_test.go +++ /dev/null @@ -1,241 +0,0 @@ -package committee_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/committee" - "github.com/kava-labs/kava/x/committee/keeper" - "github.com/kava-labs/kava/x/committee/testutil" - "github.com/kava-labs/kava/x/committee/types" -) - -var testTime time.Time = time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC) - -func NewCommitteeGenState(cdc codec.Codec, gs *types.GenesisState) app.GenesisState { - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(gs)} -} - -type ProposalHandlerTestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context - - addresses []sdk.AccAddress - testGenesis *types.GenesisState -} - -func (suite *ProposalHandlerTestSuite) SetupTest() { - _, suite.addresses = app.GeneratePrivKeyAddressPairs(5) - suite.testGenesis = types.NewGenesisState( - 2, - []types.Committee{ - types.MustNewMemberCommittee( - 1, - "This committee is for testing.", - suite.addresses[:3], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ), - types.MustNewMemberCommittee( - 2, - "member committee", - suite.addresses[2:], - nil, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ), - }, - types.Proposals{ - types.MustNewProposal( - govv1beta1.NewTextProposal("A Title", "A description of this proposal."), 1, 1, testTime.Add(7*24*time.Hour), - ), - }, - []types.Vote{ - {ProposalID: 1, Voter: suite.addresses[0], VoteType: types.VOTE_TYPE_YES}, - }, - ) -} - -func (suite *ProposalHandlerTestSuite) TestProposalHandler_ChangeCommittee() { - testCases := []struct { - name string - proposal types.CommitteeChangeProposal - expectPass bool - }{ - { - name: "add new", - proposal: types.MustNewCommitteeChangeProposal( - "A Title", - "A proposal description.", - types.MustNewMemberCommittee( - 34, - "member committee", - suite.addresses[:1], - []types.Permission{}, - testutil.D("1"), - time.Hour*24, - types.TALLY_OPTION_DEADLINE, - ), - ), - expectPass: true, - }, - { - name: "update", - proposal: types.MustNewCommitteeChangeProposal( - "A Title", - "A proposal description.", - types.MustNewMemberCommittee( - suite.testGenesis.GetCommittees()[0].GetID(), - "member committee", - suite.addresses, // add new members - suite.testGenesis.GetCommittees()[0].GetPermissions(), - suite.testGenesis.GetCommittees()[0].GetVoteThreshold(), - suite.testGenesis.GetCommittees()[0].GetProposalDuration(), - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ), - ), - expectPass: true, - }, - { - name: "invalid title", - proposal: types.MustNewCommitteeChangeProposal( - "A Title That Is Much Too Long And Really Quite Unreasonable Given That It Is Trying To Fulfill The Roll Of An Acceptable Governance Proposal Title That Should Succinctly Communicate The Goal And Contents Of The Proposed Proposal To All Parties Involved", - "A proposal description.", - suite.testGenesis.GetCommittees()[0], - ), - expectPass: false, - }, - { - name: "invalid committee", - proposal: types.MustNewCommitteeChangeProposal( - "A Title", - "A proposal description.", - types.MustNewMemberCommittee( - suite.testGenesis.GetCommittees()[0].GetID(), - "member committee", - append(suite.addresses, suite.addresses[0]), // duplicate address - suite.testGenesis.GetCommittees()[0].GetPermissions(), - suite.testGenesis.GetCommittees()[0].GetVoteThreshold(), - suite.testGenesis.GetCommittees()[0].GetProposalDuration(), - types.TALLY_OPTION_DEADLINE, - ), - ), - expectPass: false, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Setup - suite.app = app.NewTestApp() - suite.keeper = suite.app.GetCommitteeKeeper() - suite.app = suite.app.InitializeFromGenesisStates( - NewCommitteeGenState(suite.app.AppCodec(), suite.testGenesis), - ) - suite.ctx = suite.app.NewContext(true, tmproto.Header{Height: 1, Time: testTime}) - handler := committee.NewProposalHandler(suite.keeper) - - oldProposals := suite.keeper.GetProposalsByCommittee(suite.ctx, tc.proposal.GetNewCommittee().GetID()) - - // Run - err := handler(suite.ctx, &tc.proposal) - - // Check - if tc.expectPass { - suite.NoError(err) - // check committee is accurate - actualCom, found := suite.keeper.GetCommittee(suite.ctx, tc.proposal.GetNewCommittee().GetID()) - suite.True(found) - testutil.AssertProtoMessageJSON(suite.T(), suite.app.AppCodec(), tc.proposal.GetNewCommittee(), actualCom) - - // check proposals and votes for this committee have been removed - suite.Empty(suite.keeper.GetProposalsByCommittee(suite.ctx, tc.proposal.GetNewCommittee().GetID())) - for _, p := range oldProposals { - suite.Empty(suite.keeper.GetVotesByProposal(suite.ctx, p.ID)) - } - } else { - suite.Error(err) - testutil.AssertProtoMessageJSON(suite.T(), suite.app.AppCodec(), suite.testGenesis, committee.ExportGenesis(suite.ctx, suite.keeper)) - } - }) - } -} - -func (suite *ProposalHandlerTestSuite) TestProposalHandler_DeleteCommittee() { - testCases := []struct { - name string - proposal types.CommitteeDeleteProposal - expectPass bool - }{ - { - name: "normal", - proposal: types.NewCommitteeDeleteProposal( - "A Title", - "A proposal description.", - suite.testGenesis.GetCommittees()[0].GetID(), - ), - expectPass: true, - }, - { - name: "invalid title", - proposal: types.NewCommitteeDeleteProposal( - "A Title That Is Much Too Long And Really Quite Unreasonable Given That It Is Trying To Fulfill The Roll Of An Acceptable Governance Proposal Title That Should Succinctly Communicate The Goal And Contents Of The Proposed Proposal To All Parties Involved", - "A proposal description.", - suite.testGenesis.GetCommittees()[1].GetID(), - ), - expectPass: false, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Setup - suite.app = app.NewTestApp() - suite.keeper = suite.app.GetCommitteeKeeper() - suite.app = suite.app.InitializeFromGenesisStates( - NewCommitteeGenState(suite.app.AppCodec(), suite.testGenesis), - ) - suite.ctx = suite.app.NewContext(true, tmproto.Header{Height: 1, Time: testTime}) - handler := committee.NewProposalHandler(suite.keeper) - - oldProposals := suite.keeper.GetProposalsByCommittee(suite.ctx, tc.proposal.CommitteeID) - - // Run - err := handler(suite.ctx, &tc.proposal) - - // Check - if tc.expectPass { - suite.NoError(err) - // check committee has been removed - _, found := suite.keeper.GetCommittee(suite.ctx, tc.proposal.CommitteeID) - suite.False(found) - - // check proposals and votes for this committee have been removed - suite.Empty(suite.keeper.GetProposalsByCommittee(suite.ctx, tc.proposal.CommitteeID)) - for _, p := range oldProposals { - suite.Empty(suite.keeper.GetVotesByProposal(suite.ctx, p.ID)) - } - } else { - suite.Error(err) - testutil.AssertProtoMessageJSON(suite.T(), suite.app.AppCodec(), suite.testGenesis, committee.ExportGenesis(suite.ctx, suite.keeper)) - } - }) - } -} - -func TestProposalHandlerTestSuite(t *testing.T) { - suite.Run(t, new(ProposalHandlerTestSuite)) -} diff --git a/x/committee/spec/01_concepts.md b/x/committee/spec/01_concepts.md deleted file mode 100644 index 8c6dbec9..00000000 --- a/x/committee/spec/01_concepts.md +++ /dev/null @@ -1,11 +0,0 @@ - - -# Concepts - -For a general introduction to governance using the Comsos-SDK, see [x/gov](https://github.com/cosmos/cosmos-sdk/blob/v0.38.3/x/gov/spec/01_concepts.md). - -This module provides companion governance functionality to `x/gov` by allowing the creation of committees, or groups of addresses that can vote on proposals for which they have permission and which bypass the usual on-chain governance structures. Permissions scope the types of proposals that committees can submit and vote on. This allows for committees with unlimited breadth (ie, a committee can have permission to perform any governance action), or narrowly scoped abilities (ie, a committee can only change a single parameter of a single module within a specified range). - -Committees are either member committees governed by a set of whitelisted addresses or token committees whose votes are weighted by token balance. For example, the [Kava Stability Committee](https://medium.com/kava-labs/kava-improves-governance-enabling-faster-response-to-volatile-markets-2d0fff6e5fa9) is a member committee that has the ability to protect critical protocol infrastructure by briefly pausing certain functionality; while the Hard Token Committee allows HARD token holders to participate in governance related to HARD protocol on the Kava blockchain. Further, committees can tally votes by either the "first-past-the-post" or "deadline" tallying procedure. Committees with "first-past-the-post" vote tallying enact proposals immediately once they pass, allowing greater flexibility than permitted by `x/gov`. Committees with "deadline" vote tallying evaluate proposals at their deadline, allowing time for all stakeholders to vote before a proposal is enacted or rejected. diff --git a/x/committee/spec/02_state.md b/x/committee/spec/02_state.md deleted file mode 100644 index e21ce5ac..00000000 --- a/x/committee/spec/02_state.md +++ /dev/null @@ -1,78 +0,0 @@ - - -# State - -## Genesis state - -`GenesisState` defines the state that must be persisted when the blockchain stops/restarts in order for normal function of the committee module to resume. - -```go -// GenesisState is state that must be provided at chain genesis. - type GenesisState struct { - NextProposalID uint64 `json:"next_proposal_id" yaml:"next_proposal_id"` - Committees []Committee `json:"committees" yaml:"committees"` - Proposals []Proposal `json:"proposals" yaml:"proposals"` - Votes []Vote `json:"votes" yaml:"votes"` - } -``` - -## Committees - -Each committee conforms to the `Committee` interface and is defined as either a `MemberCommittee` or a `TokenCommittee`: - -```go -// Committee is an interface for handling common actions on committees -type Committee interface { - GetID() uint64 - GetType() string - GetDescription() string - - GetMembers() []sdk.AccAddress - SetMembers([]sdk.AccAddress) BaseCommittee - HasMember(addr sdk.AccAddress) bool - - GetPermissions() []Permission - SetPermissions([]Permission) Committee - HasPermissionsFor(ctx sdk.Context, appCdc *codec.Codec, pk ParamKeeper, proposal PubProposal) bool - - GetProposalDuration() time.Duration - SetProposalDuration(time.Duration) BaseCommittee - - GetVoteThreshold() sdk.Dec - SetVoteThreshold(sdk.Dec) BaseCommittee - - GetTallyOption() TallyOption - Validate() error -} - -// BaseCommittee is a common type shared by all Committees -type BaseCommittee struct { - ID uint64 `json:"id" yaml:"id"` - Description string `json:"description" yaml:"description"` - Members []sdk.AccAddress `json:"members" yaml:"members"` - Permissions []Permission `json:"permissions" yaml:"permissions"` - VoteThreshold sdk.Dec `json:"vote_threshold" yaml:"vote_threshold"` // Smallest percentage that must vote for a proposal to pass - ProposalDuration time.Duration `json:"proposal_duration" yaml:"proposal_duration"` // The length of time a proposal remains active for. Proposals will close earlier if they get enough votes. - TallyOption TallyOption `json:"tally_option" yaml:"tally_option"` -} - -// MemberCommittee is an alias of BaseCommittee -type MemberCommittee struct { - BaseCommittee `json:"base_committee" yaml:"base_committee"` -} - -// TokenCommittee supports voting on proposals by token holders -type TokenCommittee struct { - BaseCommittee `json:"base_committee" yaml:"base_committee"` - Quorum sdk.Dec `json:"quorum" yaml:"quorum"` - TallyDenom string `json:"tally_denom" yaml:"tally_denom"` -} -``` - - - -## Store - -For complete implementation details for how items are stored, see [keys.go](../types/keys.go). The committee module store state consists of committees, proposals, and votes. When a proposal expires or passes, the proposal and associated votes are deleted from state. diff --git a/x/committee/spec/03_messages.md b/x/committee/spec/03_messages.md deleted file mode 100644 index 9e320645..00000000 --- a/x/committee/spec/03_messages.md +++ /dev/null @@ -1,39 +0,0 @@ - - -# Messages - -Committee members submit proposals using a `MsgSubmitProposal` - -```go -// MsgSubmitProposal is used by committee members to create a new proposal that they can vote on. -type MsgSubmitProposal struct { - PubProposal PubProposal `json:"pub_proposal" yaml:"pub_proposal"` - Proposer sdk.AccAddress `json:"proposer" yaml:"proposer"` - CommitteeID uint64 `json:"committee_id" yaml:"committee_id"` -} -``` - -## State Modifications - -- Generate new `ProposalID` -- Create new `Proposal` with deadline equal to the time that the proposal will expire. - -Valid votes include 'yes', 'no', and 'abstain'. - -```go -// MsgVote is submitted by committee members to vote on proposals. -type MsgVote struct { - ProposalID uint64 `json:"proposal_id" yaml:"proposal_id"` - Voter sdk.AccAddress `json:"voter" yaml:"voter"` - VoteType VoteType `json:"vote_type" yaml:"vote_type"` -} -``` - -## State Modifications - -- Create a new `Vote` -- When the proposal is evaluated: - - Enact the proposal (passed proposals may cause state modifications) - - Delete the proposal and associated votes diff --git a/x/committee/spec/04_events.md b/x/committee/spec/04_events.md deleted file mode 100644 index 9d5c8d70..00000000 --- a/x/committee/spec/04_events.md +++ /dev/null @@ -1,36 +0,0 @@ - - -# Events - -The `x/committee` module emits the following events: - -## MsgSubmitProposal - -| Type | Attribute Key | Attribute Value | -| --------------- | ------------- | ------------------ | -| proposal_submit | committee_id | {'committee ID}' | -| proposal_submit | proposal_id | {'proposal ID}' | -| message | module | committee | -| message | sender | {'sender address}' | - -## MsgVote - -| Type | Attribute Key | Attribute Value | -| ------------- | ------------- | ------------------ | -| proposal_vote | committee_id | {'committee ID}' | -| proposal_vote | proposal_id | {'proposal ID}' | -| proposal_vote | voter | {'voter address}' | -| proposal_vote | vote | {'vote type}' | -| message | module | committee | -| message | sender | {'sender address}' | - -## BeginBlock - -| Type | Attribute Key | Attribute Value | -| -------------- | ---------------- | ----------------------- | -| proposal_close | committee_id | {'committee ID}' | -| proposal_close | proposal_id | {'proposal ID}' | -| proposal_close | proposal_tally | {'proposal vote tally}' | -| proposal_close | proposal_outcome | {'proposal result}' | diff --git a/x/committee/spec/05_params.md b/x/committee/spec/05_params.md deleted file mode 100644 index 681e4ad9..00000000 --- a/x/committee/spec/05_params.md +++ /dev/null @@ -1,7 +0,0 @@ - - -# Parameters - -The committee module has no parameters. Committees are created using the `x/gov` module and inherit the parameters controlling governance proposals from `x/gov`. diff --git a/x/committee/spec/06_begin_block.md b/x/committee/spec/06_begin_block.md deleted file mode 100644 index 0cf5fa30..00000000 --- a/x/committee/spec/06_begin_block.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# Begin Block - -At the start of each block, proposals are processed. Active proposals with "first-past-the-post" vote tallying are evaluated and if they meet quorum and voting threshold requirements are enacted, resulting in the deletion of the proposal and any associated votes. If a "first-past-the-post" proposal doesn't meet quorum and voting threshold requirements by its deadline it is not enacted and is deleted. Proposals with "deadline" vote tallying are evaluated at their deadline before being deleted. - -```go -// BeginBlocker runs at the start of every block. -func BeginBlocker(ctx sdk.Context, _ abci.RequestBeginBlock, k Keeper) { - k.ProcessProposals(ctx) -} -``` diff --git a/x/committee/spec/README.md b/x/committee/spec/README.md deleted file mode 100644 index da753625..00000000 --- a/x/committee/spec/README.md +++ /dev/null @@ -1,38 +0,0 @@ - - -# `committee` - -## Table of Contents - - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** -5. **[Params](05_params.md)** -6. **[BeginBlock](06_begin_block.md)** - -## Overview - -The `x/committee` module is Cosmos-SDK module that acts as an additional governance module to `cosmos-sdk/x/gov`. - -It allows groups of accounts to vote on and enact proposals without a full chain governance vote. Certain proposal types can then be decided on quickly in emergency situations, or low risk parameter updates can be delegated to a smaller group of individuals. - -Committees work with "proposals", using the same type from the `gov` module so they are compatible with all existing proposal types such as param changes, or community pool spend, or text proposals. - -Committees have members and permissions. Committees are 'elected' via traditional `gov` proposals - ie. all coin-holders vote on the creation, deletion, and updating of committees. - -Members of committees vote on proposals, with one vote per member and no deposits or slashing. Only a member of a committee can submit a proposal for that committee. More sophisticated voting could be added, as well as the ability for committees to edit themselves or other committees. A proposal passes when the number of votes is over the threshold for that committee. Vote thresholds are set per committee. Committee members vote yes by casting a vote and vote no by abstaining from voting and letting the proposal expire. - -Permissions scope the allowed set of proposals a committee can enact. For example: - -- allow the committee to only change the cdp `CircuitBreaker` param. -- allow the committee to change auction bid increments, but only within the range [0, 0.1] -- allow the committee to only disable cdp msg types, but not staking or gov - -A permission acts as a filter for incoming gov proposals, rejecting them at the handler if they do not have the required permissions. A permission can be any type with a method `Allows(p Proposal) bool`. The handler will reject all proposals that are not explicitly allowed. This allows permissions to be parameterized to allow fine grained control specified at runtime. For example a generic parameter permission type can allow a committee to only change a particular param, or only change params within a certain range. diff --git a/x/committee/testutil/suite.go b/x/committee/testutil/suite.go deleted file mode 100644 index abc31441..00000000 --- a/x/committee/testutil/suite.go +++ /dev/null @@ -1,42 +0,0 @@ -package testutil - -import ( - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/committee/keeper" - "github.com/kava-labs/kava/x/committee/types" -) - -// Suite implements a test suite for the module integration tests -type Suite struct { - suite.Suite - - Keeper keeper.Keeper - BankKeeper bankkeeper.Keeper - App app.TestApp - Ctx sdk.Context - QueryClient types.QueryClient - Addresses []sdk.AccAddress -} - -// SetupTest instantiates a new app, keepers, and sets suite state -func (suite *Suite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - suite.App = app.NewTestApp() - suite.Keeper = suite.App.GetCommitteeKeeper() - suite.BankKeeper = suite.App.GetBankKeeper() - suite.Ctx = suite.App.NewContext(true, tmproto.Header{}) - _, accAddresses := app.GeneratePrivKeyAddressPairs(10) - suite.Addresses = accAddresses - - // Set query client - queryHelper := suite.App.NewQueryServerTestHelper(suite.Ctx) - queryHandler := keeper.NewQueryServerImpl(suite.Keeper) - types.RegisterQueryServer(queryHelper, queryHandler) - suite.QueryClient = types.NewQueryClient(queryHelper) -} diff --git a/x/committee/testutil/types.go b/x/committee/testutil/types.go deleted file mode 100644 index ec5c409c..00000000 --- a/x/committee/testutil/types.go +++ /dev/null @@ -1,25 +0,0 @@ -package testutil - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/gogoproto/proto" - "github.com/stretchr/testify/assert" -) - -// Avoid cluttering test cases with long function names -func I(in int64) sdkmath.Int { return sdkmath.NewInt(in) } -func D(str string) sdk.Dec { return sdk.MustNewDecFromStr(str) } -func C(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } -func Cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } - -func AssertProtoMessageJSON(t *testing.T, cdc codec.Codec, expected proto.Message, actual proto.Message) { - expectedJson, err := cdc.MarshalJSON(expected) - assert.NoError(t, err) - actualJson, err := cdc.MarshalJSON(actual) - assert.NoError(t, err) - assert.Equal(t, string(expectedJson), string(actualJson)) -} diff --git a/x/committee/types/codec.go b/x/committee/types/codec.go deleted file mode 100644 index 753bd011..00000000 --- a/x/committee/types/codec.go +++ /dev/null @@ -1,142 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/legacy" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - govcodec "github.com/cosmos/cosmos-sdk/x/gov/codec" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - proposaltypes "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - communitytypes "github.com/kava-labs/kava/x/community/types" - kavadisttypes "github.com/kava-labs/kava/x/kavadist/types" -) - -var ( - amino = codec.NewLegacyAmino() - - // ModuleCdc references the global x/committee module codec. Note, the codec should - // ONLY be used in certain instances of tests and for JSON encoding as Amino is - // still used for that purpose. - // - // The actual codec used for serialization should be provided to x/committee and - // defined at the application level. - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - // amino is not sealed so that other modules can register their own pubproposal and/or permission types. - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) - - // CommitteeChange/Delete proposals along with Permission types are - // registered on gov's ModuleCdc - RegisterLegacyAminoCodec(govcodec.Amino) - - // Register external module pubproposal types. Ideally these would be registered within the modules' types pkg init function. - // However registration happens here as a work-around. - RegisterProposalTypeCodec(distrtypes.CommunityPoolSpendProposal{}, "cosmos-sdk/CommunityPoolSpendProposal") - RegisterProposalTypeCodec(proposaltypes.ParameterChangeProposal{}, "cosmos-sdk/ParameterChangeProposal") - RegisterProposalTypeCodec(govv1beta1.TextProposal{}, "cosmos-sdk/TextProposal") - RegisterProposalTypeCodec(upgradetypes.SoftwareUpgradeProposal{}, "cosmos-sdk/SoftwareUpgradeProposal") - RegisterProposalTypeCodec(upgradetypes.CancelSoftwareUpgradeProposal{}, "cosmos-sdk/CancelSoftwareUpgradeProposal") - RegisterProposalTypeCodec(communitytypes.CommunityCDPRepayDebtProposal{}, "kava/CommunityCDPRepayDebtProposal") - RegisterProposalTypeCodec(communitytypes.CommunityCDPWithdrawCollateralProposal{}, "kava/CommunityCDPWithdrawCollateralProposal") - RegisterProposalTypeCodec(communitytypes.CommunityPoolLendWithdrawProposal{}, "kava/CommunityPoolLendWithdrawProposal") - RegisterProposalTypeCodec(kavadisttypes.CommunityPoolMultiSpendProposal{}, "kava/CommunityPoolMultiSpendProposal") -} - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - // Proposals - cdc.RegisterInterface((*PubProposal)(nil), nil) - cdc.RegisterConcrete(CommitteeChangeProposal{}, "kava/CommitteeChangeProposal", nil) - cdc.RegisterConcrete(CommitteeDeleteProposal{}, "kava/CommitteeDeleteProposal", nil) - - // Committees - cdc.RegisterInterface((*Committee)(nil), nil) - cdc.RegisterConcrete(BaseCommittee{}, "kava/BaseCommittee", nil) - cdc.RegisterConcrete(MemberCommittee{}, "kava/MemberCommittee", nil) - cdc.RegisterConcrete(TokenCommittee{}, "kava/TokenCommittee", nil) - - // Permissions - cdc.RegisterInterface((*Permission)(nil), nil) - cdc.RegisterConcrete(GodPermission{}, "kava/GodPermission", nil) - cdc.RegisterConcrete(TextPermission{}, "kava/TextPermission", nil) - cdc.RegisterConcrete(SoftwareUpgradePermission{}, "kava/SoftwareUpgradePermission", nil) - cdc.RegisterConcrete(ParamsChangePermission{}, "kava/ParamsChangePermission", nil) - cdc.RegisterConcrete(CommunityCDPRepayDebtPermission{}, "kava/CommunityCDPRepayDebtPermission", nil) - cdc.RegisterConcrete(CommunityCDPWithdrawCollateralPermission{}, "kava/CommunityCDPWithdrawCollateralPermission", nil) - cdc.RegisterConcrete(CommunityPoolLendWithdrawPermission{}, "kava/CommunityPoolLendWithdrawPermission", nil) - - // Msgs - legacy.RegisterAminoMsg(cdc, &MsgSubmitProposal{}, "kava/MsgSubmitProposal") - legacy.RegisterAminoMsg(cdc, &MsgVote{}, "kava/MsgVote") -} - -// RegisterProposalTypeCodec allows external modules to register their own pubproposal types on the -// internal ModuleCdc. This allows the MsgSubmitProposal to be correctly Amino encoded and decoded. -func RegisterProposalTypeCodec(o interface{}, name string) { - ModuleCdc.RegisterConcrete(o, name, nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgSubmitProposal{}, - &MsgVote{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) - - registry.RegisterInterface( - "kava.committee.v1beta1.Committee", - (*Committee)(nil), - &BaseCommittee{}, - &TokenCommittee{}, - &MemberCommittee{}, - ) - - registry.RegisterInterface( - "kava.committee.v1beta1.Permission", - (*Permission)(nil), - &GodPermission{}, - &TextPermission{}, - &SoftwareUpgradePermission{}, - &ParamsChangePermission{}, - &CommunityCDPRepayDebtPermission{}, - &CommunityCDPWithdrawCollateralPermission{}, - &CommunityPoolLendWithdrawPermission{}, - ) - - // Need to register PubProposal here since we use this as alias for the x/gov Content interface for all the proposal implementations used in this module. - // Note that all proposals supported by x/committee needed to be registered here, including the proposals from x/gov. - registry.RegisterInterface( - "kava.committee.v1beta1.PubProposal", - (*PubProposal)(nil), - &Proposal{}, - &distrtypes.CommunityPoolSpendProposal{}, - &govv1beta1.TextProposal{}, - &kavadisttypes.CommunityPoolMultiSpendProposal{}, - &proposaltypes.ParameterChangeProposal{}, - &upgradetypes.SoftwareUpgradeProposal{}, - &upgradetypes.CancelSoftwareUpgradeProposal{}, - &communitytypes.CommunityCDPRepayDebtProposal{}, - &communitytypes.CommunityCDPWithdrawCollateralProposal{}, - &communitytypes.CommunityPoolLendWithdrawProposal{}, - ) - - registry.RegisterImplementations( - (*govv1beta1.Content)(nil), - &CommitteeChangeProposal{}, - &CommitteeDeleteProposal{}, - ) -} diff --git a/x/committee/types/committee.go b/x/committee/types/committee.go deleted file mode 100644 index 9da95bda..00000000 --- a/x/committee/types/committee.go +++ /dev/null @@ -1,466 +0,0 @@ -package types - -import ( - fmt "fmt" - "time" - - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - proto "github.com/cosmos/gogoproto/proto" - "sigs.k8s.io/yaml" -) - -const MaxCommitteeDescriptionLength int = 512 - -const ( - BaseCommitteeType = "kava/BaseCommittee" - MemberCommitteeType = "kava/MemberCommittee" // Committee is composed of member addresses that vote to enact proposals within their permissions - TokenCommitteeType = "kava/TokenCommittee" // Committee is composed of token holders with voting power determined by total token balance - BondDenom = "ukava" -) - -// Marshal needed for protobuf compatibility. -func (t TallyOption) Marshal() ([]byte, error) { - return []byte{byte(t)}, nil -} - -// Unmarshal needed for protobuf compatibility. -func (t *TallyOption) Unmarshal(data []byte) error { - *t = TallyOption(data[0]) - return nil -} - -// Committee is an interface for handling common actions on committees -type Committee interface { - codec.ProtoMarshaler - codectypes.UnpackInterfacesMessage - - GetID() uint64 - GetType() string - GetDescription() string - - GetMembers() []sdk.AccAddress - SetMembers([]sdk.AccAddress) - HasMember(addr sdk.AccAddress) bool - - GetPermissions() []Permission - SetPermissions([]Permission) - HasPermissionsFor(ctx sdk.Context, appCdc codec.Codec, pk ParamKeeper, proposal PubProposal) bool - - GetProposalDuration() time.Duration - SetProposalDuration(time.Duration) - - GetVoteThreshold() sdk.Dec - SetVoteThreshold(sdk.Dec) - - GetTallyOption() TallyOption - Validate() error - - String() string -} - -var ( - _ Committee = &BaseCommittee{} - _ codectypes.UnpackInterfacesMessage = &Committees{} -) - -type Committees []Committee - -// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (c Committees) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - for _, committee := range c { - if err := committee.UnpackInterfaces(unpacker); err != nil { - return err - } - } - return nil -} - -// GetType is a getter for committee type -func (c *BaseCommittee) GetType() string { return BaseCommitteeType } - -// GetID is a getter for committee ID -func (c *BaseCommittee) GetID() uint64 { return c.ID } - -// GetDescription is a getter for committee description -func (c *BaseCommittee) GetDescription() string { return c.Description } - -// GetMembers is a getter for committee members -func (c BaseCommittee) GetMembers() []sdk.AccAddress { return c.Members } - -// SetMembers is a setter for committee members -func (c *BaseCommittee) SetMembers(members []sdk.AccAddress) { c.Members = members } - -// HasMember returns if a committee contains a given member address -func (c *BaseCommittee) HasMember(addr sdk.AccAddress) bool { - for _, m := range c.GetMembers() { - if m.Equals(addr) { - return true - } - } - return false -} - -// GetPermissions is a getter for committee permissions -func (c *BaseCommittee) GetPermissions() []Permission { - permissions, err := UnpackPermissions(c.Permissions) - if err != nil { - panic(err) - } - return permissions -} - -// SetPermissions is a setter for committee permissions -func (c *BaseCommittee) SetPermissions(permissions []Permission) { - if len(permissions) == 0 { - c.Permissions = nil - } - permissionsAny, err := PackPermissions(permissions) - if err != nil { - panic(err) - } - c.Permissions = permissionsAny -} - -// HasPermissionsFor returns whether the committee is authorized to enact a proposal. -// As long as one permission allows the proposal then it goes through. Its the OR of all permissions. -func (c BaseCommittee) HasPermissionsFor(ctx sdk.Context, appCdc codec.Codec, pk ParamKeeper, proposal PubProposal) bool { - for _, p := range c.GetPermissions() { - if p.Allows(ctx, pk, proposal) { - return true - } - } - return false -} - -// String implements fmt.Stringer -func (c BaseCommittee) String() string { - return fmt.Sprintf(`Committee %d: - Description: %s - Members: %s - Permissions: %s - VoteThreshold: %s - ProposalDuration: %s - TallyOption: %s`, - c.ID, c.Description, c.GetMembers(), c.Permissions, - c.VoteThreshold.String(), c.ProposalDuration.String(), - c.TallyOption.String(), - ) -} - -// GetVoteThreshold is a getter for committee VoteThreshold -func (c BaseCommittee) GetVoteThreshold() sdk.Dec { return c.VoteThreshold } - -// SetVoteThreshold is a setter for committee VoteThreshold -func (c *BaseCommittee) SetVoteThreshold(voteThreshold sdk.Dec) { - c.VoteThreshold = voteThreshold -} - -// GetProposalDuration is a getter for committee ProposalDuration -func (c BaseCommittee) GetProposalDuration() time.Duration { return c.ProposalDuration } - -// SetProposalDuration is a setter for committee ProposalDuration -func (c *BaseCommittee) SetProposalDuration(proposalDuration time.Duration) { - c.ProposalDuration = proposalDuration -} - -// GetTallyOption is a getter for committee TallyOption -func (c BaseCommittee) GetTallyOption() TallyOption { return c.TallyOption } - -// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (c BaseCommittee) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - for _, any := range c.Permissions { - var permission Permission - err := unpacker.UnpackAny(any, &permission) - if err != nil { - return err - } - } - return nil -} - -// Validate validates BaseCommittee fields -func (c BaseCommittee) Validate() error { - if len(c.Description) > MaxCommitteeDescriptionLength { - return fmt.Errorf("description length %d longer than max allowed %d", len(c.Description), MaxCommitteeDescriptionLength) - } - - if len(c.Members) <= 0 { - return fmt.Errorf("committee must have members") - } - - addressMap := make(map[string]bool, len(c.Members)) - for _, m := range c.Members { - // check there are no duplicate members - if _, ok := addressMap[m.String()]; ok { - return fmt.Errorf("committee cannot have duplicate members, %s", m) - } - // check for valid addresses - if m.Empty() { - return fmt.Errorf("committee cannot have empty member address") - } - addressMap[m.String()] = true - } - - // validate permissions - permissions, err := UnpackPermissions(c.Permissions) - if err != nil { - return err - } - for _, p := range permissions { - if p == nil { - return fmt.Errorf("committee cannot have a nil permission") - } - } - - if c.ProposalDuration < 0 { - return fmt.Errorf("invalid proposal duration: %s", c.ProposalDuration) - } - - // threshold must be in the range [0, 1] - if c.VoteThreshold.IsNil() || c.VoteThreshold.LTE(sdk.ZeroDec()) || c.VoteThreshold.GT(sdk.NewDec(1)) { - return fmt.Errorf("invalid threshold: %s", c.VoteThreshold) - } - - if c.TallyOption <= 0 || c.TallyOption > 2 { - return fmt.Errorf("invalid tally option: %d", c.TallyOption) - } - - return nil -} - -// NewMemberCommittee instantiates a new instance of MemberCommittee -func NewMemberCommittee(id uint64, description string, members []sdk.AccAddress, permissions []Permission, - threshold sdk.Dec, duration time.Duration, tallyOption TallyOption, -) (*MemberCommittee, error) { - permissionsAny, err := PackPermissions(permissions) - if err != nil { - return nil, err - } - return &MemberCommittee{ - BaseCommittee: &BaseCommittee{ - ID: id, - Description: description, - Members: members, - Permissions: permissionsAny, - VoteThreshold: threshold, - ProposalDuration: duration, - TallyOption: tallyOption, - }, - }, nil -} - -// MustNewMemberCommittee instantiates a new instance of MemberCommittee and panics on error -func MustNewMemberCommittee(id uint64, description string, members []sdk.AccAddress, permissions []Permission, - threshold sdk.Dec, duration time.Duration, tallyOption TallyOption, -) *MemberCommittee { - committee, err := NewMemberCommittee(id, description, members, permissions, threshold, duration, tallyOption) - if err != nil { - panic(err) - } - return committee -} - -// GetType is a getter for committee type -func (c MemberCommittee) GetType() string { return MemberCommitteeType } - -// NewTokenCommittee instantiates a new instance of TokenCommittee -func NewTokenCommittee(id uint64, description string, members []sdk.AccAddress, permissions []Permission, - threshold sdk.Dec, duration time.Duration, tallyOption TallyOption, quorum sdk.Dec, tallyDenom string, -) (*TokenCommittee, error) { - permissionsAny, err := PackPermissions(permissions) - if err != nil { - return nil, err - } - return &TokenCommittee{ - BaseCommittee: &BaseCommittee{ - ID: id, - Description: description, - Members: members, - Permissions: permissionsAny, - VoteThreshold: threshold, - ProposalDuration: duration, - TallyOption: tallyOption, - }, - Quorum: quorum, - TallyDenom: tallyDenom, - }, nil -} - -// MustNewTokenCommittee instantiates a new instance of TokenCommittee and panics on error -func MustNewTokenCommittee(id uint64, description string, members []sdk.AccAddress, permissions []Permission, - threshold sdk.Dec, duration time.Duration, tallyOption TallyOption, quorum sdk.Dec, tallyDenom string, -) *TokenCommittee { - committee, err := NewTokenCommittee(id, description, members, permissions, threshold, duration, tallyOption, quorum, tallyDenom) - if err != nil { - panic(err) - } - return committee -} - -// GetType is a getter for committee type -func (c TokenCommittee) GetType() string { return TokenCommitteeType } - -// GetQuorum returns the quorum of the committee -func (c TokenCommittee) GetQuorum() sdk.Dec { return c.Quorum } - -// GetTallyDenom returns the tally denom of the committee -func (c TokenCommittee) GetTallyDenom() string { return c.TallyDenom } - -// Validate validates the committee's fields -func (c TokenCommittee) Validate() error { - if c.TallyDenom == BondDenom { - return fmt.Errorf("invalid tally denom: %s", c.TallyDenom) - } - - err := sdk.ValidateDenom(c.TallyDenom) - if err != nil { - return err - } - - if c.Quorum.IsNil() || c.Quorum.IsNegative() || c.Quorum.GT(sdk.NewDec(1)) { - return fmt.Errorf("invalid quorum: %s", c.Quorum) - } - - return c.BaseCommittee.Validate() -} - -// ------------------------------------------ -// Proposals -// ------------------------------------------ - -// PubProposal is the interface that all proposals must fulfill to be submitted to a committee. -// Proposal types can be created external to this module. For example a ParamChangeProposal, or CommunityPoolSpendProposal. -// It is pinned to the equivalent type in the gov module to create compatibility between proposal types. -type PubProposal govv1beta1.Content - -var ( - _ PubProposal = Proposal{} - _ codectypes.UnpackInterfacesMessage = Proposals{} -) - -type Proposals []Proposal - -// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (p Proposals) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - for _, committee := range p { - if err := committee.UnpackInterfaces(unpacker); err != nil { - return err - } - } - return nil -} - -// NewProposal instantiates a new instance of Proposal -func NewProposal(pubProposal PubProposal, id uint64, committeeID uint64, deadline time.Time) (Proposal, error) { - msg, ok := pubProposal.(proto.Message) - if !ok { - return Proposal{}, fmt.Errorf("%T does not implement proto.Message", pubProposal) - } - proposalAny, err := codectypes.NewAnyWithValue(msg) - if err != nil { - return Proposal{}, err - } - return Proposal{ - Content: proposalAny, - ID: id, - CommitteeID: committeeID, - Deadline: deadline, - }, nil -} - -// MustNewProposal instantiates a new instance of Proposal and panics if there is an error -func MustNewProposal(pubProposal PubProposal, id uint64, committeeID uint64, deadline time.Time) Proposal { - proposal, err := NewProposal(pubProposal, id, committeeID, deadline) - if err != nil { - panic(err) - } - return proposal -} - -// GetPubProposal returns the PubProposal (govtypes.Content) -func (p Proposal) GetContent() PubProposal { - content, ok := p.Content.GetCachedValue().(PubProposal) - if !ok { - return nil - } - return content -} - -// String implements the fmt.Stringer interface. -func (p Proposal) String() string { - bz, _ := yaml.Marshal(p) - return string(bz) -} - -func (p Proposal) GetTitle() string { - content := p.GetContent() - if content == nil { - return "" - } - return content.GetTitle() -} - -func (p Proposal) GetDescription() string { - content := p.GetContent() - if content == nil { - return "" - } - return content.GetDescription() -} - -func (p Proposal) ProposalRoute() string { - content := p.GetContent() - if content == nil { - return "" - } - return content.ProposalRoute() -} - -func (p Proposal) ProposalType() string { - content := p.GetContent() - if content == nil { - return "" - } - return content.ProposalType() -} - -func (p Proposal) ValidateBasic() error { - content := p.GetContent() - if content == nil { - return nil - } - return content.ValidateBasic() -} - -// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (p Proposal) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - var content PubProposal - return unpacker.UnpackAny(p.Content, &content) -} - -// HasExpiredBy calculates if the proposal will have expired by a certain time. -// All votes must be cast before deadline, those cast at time == deadline are not valid -func (p Proposal) HasExpiredBy(time time.Time) bool { - return !time.Before(p.Deadline) -} - -// NewVote instantiates a new instance of Vote -func NewVote(proposalID uint64, voter sdk.AccAddress, voteType VoteType) Vote { - return Vote{ - ProposalID: proposalID, - Voter: voter, - VoteType: voteType, - } -} - -// Validates Vote fields -func (v Vote) Validate() error { - if v.Voter.Empty() { - return fmt.Errorf("voter address cannot be empty") - } - - return v.VoteType.Validate() -} diff --git a/x/committee/types/committee.pb.go b/x/committee/types/committee.pb.go deleted file mode 100644 index 12e02536..00000000 --- a/x/committee/types/committee.pb.go +++ /dev/null @@ -1,1068 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/committee/v1beta1/committee.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/codec/types" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/durationpb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 - -// TallyOption enumerates the valid types of a tally. -type TallyOption int32 - -const ( - // TALLY_OPTION_UNSPECIFIED defines a null tally option. - TALLY_OPTION_UNSPECIFIED TallyOption = 0 - // Votes are tallied each block and the proposal passes as soon as the vote threshold is reached - TALLY_OPTION_FIRST_PAST_THE_POST TallyOption = 1 - // Votes are tallied exactly once, when the deadline time is reached - TALLY_OPTION_DEADLINE TallyOption = 2 -) - -var TallyOption_name = map[int32]string{ - 0: "TALLY_OPTION_UNSPECIFIED", - 1: "TALLY_OPTION_FIRST_PAST_THE_POST", - 2: "TALLY_OPTION_DEADLINE", -} - -var TallyOption_value = map[string]int32{ - "TALLY_OPTION_UNSPECIFIED": 0, - "TALLY_OPTION_FIRST_PAST_THE_POST": 1, - "TALLY_OPTION_DEADLINE": 2, -} - -func (x TallyOption) String() string { - return proto.EnumName(TallyOption_name, int32(x)) -} - -func (TallyOption) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_a2549fd9d70ca349, []int{0} -} - -// BaseCommittee is a common type shared by all Committees -type BaseCommittee struct { - ID uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Members []github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,3,rep,name=members,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"members,omitempty"` - Permissions []*types.Any `protobuf:"bytes,4,rep,name=permissions,proto3" json:"permissions,omitempty"` - // Smallest percentage that must vote for a proposal to pass - VoteThreshold github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=vote_threshold,json=voteThreshold,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"vote_threshold"` - // The length of time a proposal remains active for. Proposals will close earlier if they get enough votes. - ProposalDuration time.Duration `protobuf:"bytes,6,opt,name=proposal_duration,json=proposalDuration,proto3,stdduration" json:"proposal_duration"` - TallyOption TallyOption `protobuf:"varint,7,opt,name=tally_option,json=tallyOption,proto3,enum=kava.committee.v1beta1.TallyOption" json:"tally_option,omitempty"` -} - -func (m *BaseCommittee) Reset() { *m = BaseCommittee{} } -func (*BaseCommittee) ProtoMessage() {} -func (*BaseCommittee) Descriptor() ([]byte, []int) { - return fileDescriptor_a2549fd9d70ca349, []int{0} -} -func (m *BaseCommittee) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BaseCommittee) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BaseCommittee.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 *BaseCommittee) XXX_Merge(src proto.Message) { - xxx_messageInfo_BaseCommittee.Merge(m, src) -} -func (m *BaseCommittee) XXX_Size() int { - return m.Size() -} -func (m *BaseCommittee) XXX_DiscardUnknown() { - xxx_messageInfo_BaseCommittee.DiscardUnknown(m) -} - -var xxx_messageInfo_BaseCommittee proto.InternalMessageInfo - -// MemberCommittee is an alias of BaseCommittee -type MemberCommittee struct { - *BaseCommittee `protobuf:"bytes,1,opt,name=base_committee,json=baseCommittee,proto3,embedded=base_committee" json:"base_committee,omitempty"` -} - -func (m *MemberCommittee) Reset() { *m = MemberCommittee{} } -func (*MemberCommittee) ProtoMessage() {} -func (*MemberCommittee) Descriptor() ([]byte, []int) { - return fileDescriptor_a2549fd9d70ca349, []int{1} -} -func (m *MemberCommittee) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MemberCommittee) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MemberCommittee.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 *MemberCommittee) XXX_Merge(src proto.Message) { - xxx_messageInfo_MemberCommittee.Merge(m, src) -} -func (m *MemberCommittee) XXX_Size() int { - return m.Size() -} -func (m *MemberCommittee) XXX_DiscardUnknown() { - xxx_messageInfo_MemberCommittee.DiscardUnknown(m) -} - -var xxx_messageInfo_MemberCommittee proto.InternalMessageInfo - -// TokenCommittee supports voting on proposals by token holders -type TokenCommittee struct { - *BaseCommittee `protobuf:"bytes,1,opt,name=base_committee,json=baseCommittee,proto3,embedded=base_committee" json:"base_committee,omitempty"` - Quorum github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=quorum,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"quorum"` - TallyDenom string `protobuf:"bytes,3,opt,name=tally_denom,json=tallyDenom,proto3" json:"tally_denom,omitempty"` -} - -func (m *TokenCommittee) Reset() { *m = TokenCommittee{} } -func (*TokenCommittee) ProtoMessage() {} -func (*TokenCommittee) Descriptor() ([]byte, []int) { - return fileDescriptor_a2549fd9d70ca349, []int{2} -} -func (m *TokenCommittee) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TokenCommittee) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TokenCommittee.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 *TokenCommittee) XXX_Merge(src proto.Message) { - xxx_messageInfo_TokenCommittee.Merge(m, src) -} -func (m *TokenCommittee) XXX_Size() int { - return m.Size() -} -func (m *TokenCommittee) XXX_DiscardUnknown() { - xxx_messageInfo_TokenCommittee.DiscardUnknown(m) -} - -var xxx_messageInfo_TokenCommittee proto.InternalMessageInfo - -func init() { - proto.RegisterEnum("kava.committee.v1beta1.TallyOption", TallyOption_name, TallyOption_value) - proto.RegisterType((*BaseCommittee)(nil), "kava.committee.v1beta1.BaseCommittee") - proto.RegisterType((*MemberCommittee)(nil), "kava.committee.v1beta1.MemberCommittee") - proto.RegisterType((*TokenCommittee)(nil), "kava.committee.v1beta1.TokenCommittee") -} - -func init() { - proto.RegisterFile("kava/committee/v1beta1/committee.proto", fileDescriptor_a2549fd9d70ca349) -} - -var fileDescriptor_a2549fd9d70ca349 = []byte{ - // 649 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x54, 0xcd, 0x6e, 0xd3, 0x40, - 0x10, 0xb6, 0x93, 0x90, 0xd2, 0x75, 0x1b, 0xd2, 0xa5, 0x54, 0x4e, 0x85, 0x6c, 0xab, 0x40, 0x15, - 0x81, 0x62, 0xab, 0xe1, 0xc6, 0x2d, 0xae, 0x13, 0xd5, 0x52, 0x69, 0x22, 0xc7, 0x3d, 0xc0, 0xc5, - 0xb2, 0xe3, 0x25, 0xb5, 0x1a, 0x67, 0x83, 0x77, 0x53, 0x35, 0x6f, 0xc0, 0x91, 0x63, 0x8f, 0x48, - 0xbc, 0x42, 0x1f, 0xa2, 0xea, 0xa9, 0xe2, 0x84, 0x38, 0x84, 0x92, 0x3e, 0x05, 0x9c, 0x90, 0xff, - 0x1a, 0x17, 0x8a, 0x04, 0x07, 0x4e, 0xde, 0xfd, 0xe6, 0x9b, 0x99, 0xfd, 0x66, 0x3e, 0x19, 0x6c, - 0x1e, 0xda, 0x47, 0xb6, 0xd2, 0xc3, 0xbe, 0xef, 0x51, 0x8a, 0x90, 0x72, 0xb4, 0xe5, 0x20, 0x6a, - 0x6f, 0xcd, 0x11, 0x79, 0x14, 0x60, 0x8a, 0xe1, 0x5a, 0xc8, 0x93, 0xe7, 0x68, 0xc2, 0x5b, 0xaf, - 0xf4, 0x30, 0xf1, 0x31, 0xb1, 0x22, 0x96, 0x12, 0x5f, 0xe2, 0x94, 0xf5, 0xd5, 0x3e, 0xee, 0xe3, - 0x18, 0x0f, 0x4f, 0x09, 0x5a, 0xe9, 0x63, 0xdc, 0x1f, 0x20, 0x25, 0xba, 0x39, 0xe3, 0x37, 0x8a, - 0x3d, 0x9c, 0x24, 0x21, 0xe1, 0xd7, 0x90, 0x3b, 0x0e, 0x6c, 0xea, 0xe1, 0x61, 0x1c, 0xdf, 0xf8, - 0x9e, 0x07, 0xcb, 0xaa, 0x4d, 0xd0, 0x76, 0xfa, 0x0a, 0xb8, 0x06, 0x72, 0x9e, 0xcb, 0xb3, 0x12, - 0x5b, 0x2d, 0xa8, 0xc5, 0xd9, 0x54, 0xcc, 0xe9, 0x9a, 0x91, 0xf3, 0x5c, 0x28, 0x01, 0xce, 0x45, - 0xa4, 0x17, 0x78, 0xa3, 0x30, 0x9d, 0xcf, 0x49, 0x6c, 0x75, 0xd1, 0xc8, 0x42, 0xd0, 0x01, 0x0b, - 0x3e, 0xf2, 0x1d, 0x14, 0x10, 0x3e, 0x2f, 0xe5, 0xab, 0x4b, 0xea, 0xce, 0x8f, 0xa9, 0x58, 0xeb, - 0x7b, 0xf4, 0x60, 0xec, 0x84, 0x32, 0x13, 0x29, 0xc9, 0xa7, 0x46, 0xdc, 0x43, 0x85, 0x4e, 0x46, - 0x88, 0xc8, 0x8d, 0x5e, 0xaf, 0xe1, 0xba, 0x01, 0x22, 0xe4, 0xd3, 0x69, 0xed, 0x7e, 0x22, 0x38, - 0x41, 0xd4, 0x09, 0x45, 0xc4, 0x48, 0x0b, 0xc3, 0x16, 0xe0, 0x46, 0x28, 0xf0, 0x3d, 0x42, 0x3c, - 0x3c, 0x24, 0x7c, 0x41, 0xca, 0x57, 0xb9, 0xfa, 0xaa, 0x1c, 0xab, 0x94, 0x53, 0x95, 0x72, 0x63, - 0x38, 0x51, 0x4b, 0xe7, 0xa7, 0x35, 0xd0, 0xb9, 0x26, 0x1b, 0xd9, 0x44, 0xb8, 0x0f, 0x4a, 0x47, - 0x98, 0x22, 0x8b, 0x1e, 0x04, 0x88, 0x1c, 0xe0, 0x81, 0xcb, 0xdf, 0x09, 0x05, 0xa9, 0xf2, 0xd9, - 0x54, 0x64, 0xbe, 0x4c, 0xc5, 0xcd, 0xbf, 0x78, 0xb6, 0x86, 0x7a, 0xc6, 0x72, 0x58, 0xc5, 0x4c, - 0x8b, 0xc0, 0x0e, 0x58, 0x19, 0x05, 0x78, 0x84, 0x89, 0x3d, 0xb0, 0xd2, 0x49, 0xf3, 0x45, 0x89, - 0xad, 0x72, 0xf5, 0xca, 0x6f, 0x8f, 0xd4, 0x12, 0x82, 0x7a, 0x37, 0x6c, 0x7a, 0xf2, 0x55, 0x64, - 0x8d, 0x72, 0x9a, 0x9d, 0xc6, 0x60, 0x0b, 0x2c, 0x51, 0x7b, 0x30, 0x98, 0x58, 0x38, 0x9e, 0xfb, - 0x82, 0xc4, 0x56, 0x4b, 0xf5, 0x47, 0xf2, 0xed, 0xde, 0x91, 0xcd, 0x90, 0xdb, 0x8e, 0xa8, 0x06, - 0x47, 0xe7, 0x97, 0x17, 0x2b, 0x27, 0x1f, 0x44, 0xe6, 0xfc, 0xb4, 0xb6, 0x78, 0xbd, 0xe9, 0x8d, - 0x63, 0x70, 0xef, 0x65, 0x34, 0xd6, 0xf9, 0xf2, 0x0d, 0x50, 0x72, 0x6c, 0x82, 0xac, 0xeb, 0xc2, - 0x91, 0x11, 0xb8, 0xfa, 0x93, 0x3f, 0xf5, 0xbb, 0xe1, 0x1d, 0xb5, 0x70, 0x31, 0x15, 0x59, 0x63, - 0xd9, 0xc9, 0x82, 0xb7, 0x75, 0xbe, 0x64, 0x41, 0xc9, 0xc4, 0x87, 0x68, 0xf8, 0x5f, 0x3b, 0xc3, - 0x16, 0x28, 0xbe, 0x1d, 0xe3, 0x60, 0xec, 0xc7, 0x6e, 0xfd, 0xe7, 0xe5, 0x26, 0xd9, 0x50, 0x04, - 0xf1, 0x28, 0x2d, 0x17, 0x0d, 0xb1, 0xcf, 0xe7, 0x23, 0xeb, 0x83, 0x08, 0xd2, 0x42, 0xe4, 0x16, - 0x89, 0x4f, 0x03, 0xc0, 0x65, 0x76, 0x01, 0x1f, 0x02, 0xde, 0x6c, 0xec, 0xee, 0xbe, 0xb2, 0xda, - 0x1d, 0x53, 0x6f, 0xef, 0x59, 0xfb, 0x7b, 0xdd, 0x4e, 0x73, 0x5b, 0x6f, 0xe9, 0x4d, 0xad, 0xcc, - 0xc0, 0xc7, 0x40, 0xba, 0x11, 0x6d, 0xe9, 0x46, 0xd7, 0xb4, 0x3a, 0x8d, 0xae, 0x69, 0x99, 0x3b, - 0x4d, 0xab, 0xd3, 0xee, 0x9a, 0x65, 0x16, 0x56, 0xc0, 0x83, 0x1b, 0x2c, 0xad, 0xd9, 0xd0, 0x76, - 0xf5, 0xbd, 0x66, 0x39, 0xb7, 0x5e, 0x78, 0xf7, 0x51, 0x60, 0x54, 0xfd, 0xec, 0x9b, 0xc0, 0x9c, - 0xcd, 0x04, 0xf6, 0x62, 0x26, 0xb0, 0x97, 0x33, 0x81, 0x7d, 0x7f, 0x25, 0x30, 0x17, 0x57, 0x02, - 0xf3, 0xf9, 0x4a, 0x60, 0x5e, 0x3f, 0xcb, 0xa8, 0x0e, 0x67, 0x5a, 0x1b, 0xd8, 0x0e, 0x89, 0x4e, - 0xca, 0x71, 0xe6, 0x6f, 0x15, 0xc9, 0x77, 0x8a, 0x91, 0x4b, 0x9f, 0xff, 0x0c, 0x00, 0x00, 0xff, - 0xff, 0x0d, 0x0b, 0x28, 0x7d, 0xcc, 0x04, 0x00, 0x00, -} - -func (m *BaseCommittee) 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 *BaseCommittee) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *BaseCommittee) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.TallyOption != 0 { - i = encodeVarintCommittee(dAtA, i, uint64(m.TallyOption)) - i-- - dAtA[i] = 0x38 - } - n1, err1 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.ProposalDuration, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.ProposalDuration):]) - if err1 != nil { - return 0, err1 - } - i -= n1 - i = encodeVarintCommittee(dAtA, i, uint64(n1)) - i-- - dAtA[i] = 0x32 - { - size := m.VoteThreshold.Size() - i -= size - if _, err := m.VoteThreshold.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintCommittee(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - if len(m.Permissions) > 0 { - for iNdEx := len(m.Permissions) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Permissions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintCommittee(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.Members) > 0 { - for iNdEx := len(m.Members) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Members[iNdEx]) - copy(dAtA[i:], m.Members[iNdEx]) - i = encodeVarintCommittee(dAtA, i, uint64(len(m.Members[iNdEx]))) - i-- - dAtA[i] = 0x1a - } - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintCommittee(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if m.ID != 0 { - i = encodeVarintCommittee(dAtA, i, uint64(m.ID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *MemberCommittee) 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 *MemberCommittee) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MemberCommittee) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.BaseCommittee != nil { - { - size, err := m.BaseCommittee.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintCommittee(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *TokenCommittee) 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 *TokenCommittee) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TokenCommittee) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.TallyDenom) > 0 { - i -= len(m.TallyDenom) - copy(dAtA[i:], m.TallyDenom) - i = encodeVarintCommittee(dAtA, i, uint64(len(m.TallyDenom))) - i-- - dAtA[i] = 0x1a - } - { - size := m.Quorum.Size() - i -= size - if _, err := m.Quorum.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintCommittee(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.BaseCommittee != nil { - { - size, err := m.BaseCommittee.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintCommittee(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintCommittee(dAtA []byte, offset int, v uint64) int { - offset -= sovCommittee(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *BaseCommittee) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.ID != 0 { - n += 1 + sovCommittee(uint64(m.ID)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovCommittee(uint64(l)) - } - if len(m.Members) > 0 { - for _, b := range m.Members { - l = len(b) - n += 1 + l + sovCommittee(uint64(l)) - } - } - if len(m.Permissions) > 0 { - for _, e := range m.Permissions { - l = e.Size() - n += 1 + l + sovCommittee(uint64(l)) - } - } - l = m.VoteThreshold.Size() - n += 1 + l + sovCommittee(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.ProposalDuration) - n += 1 + l + sovCommittee(uint64(l)) - if m.TallyOption != 0 { - n += 1 + sovCommittee(uint64(m.TallyOption)) - } - return n -} - -func (m *MemberCommittee) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.BaseCommittee != nil { - l = m.BaseCommittee.Size() - n += 1 + l + sovCommittee(uint64(l)) - } - return n -} - -func (m *TokenCommittee) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.BaseCommittee != nil { - l = m.BaseCommittee.Size() - n += 1 + l + sovCommittee(uint64(l)) - } - l = m.Quorum.Size() - n += 1 + l + sovCommittee(uint64(l)) - l = len(m.TallyDenom) - if l > 0 { - n += 1 + l + sovCommittee(uint64(l)) - } - return n -} - -func sovCommittee(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozCommittee(x uint64) (n int) { - return sovCommittee(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *BaseCommittee) 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 ErrIntOverflowCommittee - } - 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: BaseCommittee: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BaseCommittee: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - m.ID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCommittee - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCommittee - } - 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 ErrInvalidLengthCommittee - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthCommittee - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Members", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCommittee - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthCommittee - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthCommittee - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Members = append(m.Members, make([]byte, postIndex-iNdEx)) - copy(m.Members[len(m.Members)-1], dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Permissions", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCommittee - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCommittee - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCommittee - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Permissions = append(m.Permissions, &types.Any{}) - if err := m.Permissions[len(m.Permissions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field VoteThreshold", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCommittee - } - 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 ErrInvalidLengthCommittee - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthCommittee - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.VoteThreshold.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ProposalDuration", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCommittee - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCommittee - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCommittee - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.ProposalDuration, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TallyOption", wireType) - } - m.TallyOption = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCommittee - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TallyOption |= TallyOption(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipCommittee(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthCommittee - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MemberCommittee) 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 ErrIntOverflowCommittee - } - 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: MemberCommittee: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MemberCommittee: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseCommittee", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCommittee - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCommittee - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCommittee - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.BaseCommittee == nil { - m.BaseCommittee = &BaseCommittee{} - } - if err := m.BaseCommittee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipCommittee(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthCommittee - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TokenCommittee) 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 ErrIntOverflowCommittee - } - 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: TokenCommittee: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TokenCommittee: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseCommittee", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCommittee - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCommittee - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCommittee - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.BaseCommittee == nil { - m.BaseCommittee = &BaseCommittee{} - } - if err := m.BaseCommittee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Quorum", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCommittee - } - 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 ErrInvalidLengthCommittee - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthCommittee - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Quorum.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TallyDenom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCommittee - } - 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 ErrInvalidLengthCommittee - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthCommittee - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TallyDenom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipCommittee(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthCommittee - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipCommittee(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, ErrIntOverflowCommittee - } - 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, ErrIntOverflowCommittee - } - 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, ErrIntOverflowCommittee - } - 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, ErrInvalidLengthCommittee - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupCommittee - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthCommittee - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthCommittee = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowCommittee = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupCommittee = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/committee/types/committee_test.go b/x/committee/types/committee_test.go deleted file mode 100644 index f467cac5..00000000 --- a/x/committee/types/committee_test.go +++ /dev/null @@ -1,379 +0,0 @@ -package types_test - -import ( - "fmt" - "testing" - "time" - - "github.com/cometbft/cometbft/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/kava-labs/kava/x/committee/testutil" - "github.com/kava-labs/kava/x/committee/types" -) - -func TestBaseCommittee(t *testing.T) { - addresses := []sdk.AccAddress{ - sdk.AccAddress(crypto.AddressHash([]byte("KavaTest1"))), - sdk.AccAddress(crypto.AddressHash([]byte("KavaTest2"))), - sdk.AccAddress(crypto.AddressHash([]byte("KavaTest3"))), - } - - testCases := []struct { - name string - createCommittee func() (*types.MemberCommittee, error) - expectPass bool - }{ - { - name: "normal", - createCommittee: func() (*types.MemberCommittee, error) { - return types.NewMemberCommittee( - 1, - "This base committee is for testing.", - addresses[:3], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ) - }, - expectPass: true, - }, - { - name: "description length too long", - createCommittee: func() (*types.MemberCommittee, error) { - return types.NewMemberCommittee( - 1, - fmt.Sprintln("This base committee has a long description.", - "This base committee has a long description. This base committee has a long description.", - "This base committee has a long description. This base committee has a long description.", - "This base committee has a long description. This base committee has a long description.", - "This base committee has a long description. This base committee has a long description.", - "This base committee has a long description. This base committee has a long description.", - "This base committee has a long description. This base committee has a long description.", - "This base committee has a long description. This base committee has a long description."), - addresses[:3], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ) - }, - expectPass: false, - }, - { - name: "no members", - createCommittee: func() (*types.MemberCommittee, error) { - return types.NewMemberCommittee( - 1, - "This base committee is for testing.", - []sdk.AccAddress{}, - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ) - }, - expectPass: false, - }, - { - name: "duplicate member", - createCommittee: func() (*types.MemberCommittee, error) { - return types.NewMemberCommittee( - 1, - "This base committee is for testing.", - []sdk.AccAddress{addresses[2], addresses[2]}, - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ) - }, - expectPass: false, - }, - { - name: "nil permissions", - createCommittee: func() (*types.MemberCommittee, error) { - return types.NewMemberCommittee( - 1, - "This base committee is for testing.", - addresses[:3], - []types.Permission{nil}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ) - }, - expectPass: false, - }, - { - name: "negative proposal duration", - createCommittee: func() (*types.MemberCommittee, error) { - return types.NewMemberCommittee( - 1, - "This base committee is for testing.", - addresses[:3], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*-7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ) - }, - expectPass: false, - }, - { - name: "vote threshold is nil", - createCommittee: func() (*types.MemberCommittee, error) { - return types.NewMemberCommittee( - 1, - "This base committee is for testing.", - addresses[:3], - []types.Permission{&types.GodPermission{}}, - sdk.Dec{}, - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ) - }, - expectPass: false, - }, - { - name: "vote threshold is 0", - createCommittee: func() (*types.MemberCommittee, error) { - return types.NewMemberCommittee( - 1, - "This base committee is for testing.", - addresses[:3], - []types.Permission{&types.GodPermission{}}, - testutil.D("0"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ) - }, - expectPass: false, - }, - { - name: "vote threshold above 1", - createCommittee: func() (*types.MemberCommittee, error) { - return types.NewMemberCommittee( - 1, - "This base committee is for testing.", - addresses[:3], - []types.Permission{&types.GodPermission{}}, - testutil.D("1.001"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ) - }, - expectPass: false, - }, - { - name: "invalid tally option", - createCommittee: func() (*types.MemberCommittee, error) { - return types.NewMemberCommittee( - 1, - "This base committee is for testing.", - addresses[:3], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_UNSPECIFIED, - ) - }, - expectPass: false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - committee, err := tc.createCommittee() - if err != nil { - require.False(t, tc.expectPass) - } else { - err = committee.BaseCommittee.Validate() - if tc.expectPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - } - }) - } -} - -func TestMemberCommittee(t *testing.T) { - addresses := []sdk.AccAddress{ - sdk.AccAddress(crypto.AddressHash([]byte("KavaTest1"))), - sdk.AccAddress(crypto.AddressHash([]byte("KavaTest2"))), - sdk.AccAddress(crypto.AddressHash([]byte("KavaTest3"))), - } - - testCases := []struct { - name string - createCommittee func() (*types.MemberCommittee, error) - expectPass bool - }{ - { - name: "normal", - createCommittee: func() (*types.MemberCommittee, error) { - return types.NewMemberCommittee( - 1, - "This member committee is for testing.", - addresses[:3], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ) - }, - expectPass: true, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - committee, err := tc.createCommittee() - require.NoError(t, err) - require.Equal(t, types.MemberCommitteeType, committee.GetType()) - - err = committee.Validate() - if tc.expectPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } -} - -// TestTokenCommittee tests unique TokenCommittee functionality -func TestTokenCommittee(t *testing.T) { - addresses := []sdk.AccAddress{ - sdk.AccAddress(crypto.AddressHash([]byte("KavaTest1"))), - sdk.AccAddress(crypto.AddressHash([]byte("KavaTest2"))), - sdk.AccAddress(crypto.AddressHash([]byte("KavaTest3"))), - } - - testCases := []struct { - name string - createCommittee func() (*types.TokenCommittee, error) - expectPass bool - }{ - { - name: "normal", - createCommittee: func() (*types.TokenCommittee, error) { - return types.NewTokenCommittee( - 1, - "This token committee is for testing.", - addresses[:3], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - testutil.D("0.4"), - "hard", - ) - }, - expectPass: true, - }, - { - name: "nil quorum", - createCommittee: func() (*types.TokenCommittee, error) { - return types.NewTokenCommittee( - 1, - "This token committee is for testing.", - addresses[:3], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - sdk.Dec{}, - "hard", - ) - }, - expectPass: false, - }, - { - name: "negative quorum", - createCommittee: func() (*types.TokenCommittee, error) { - return types.NewTokenCommittee( - 1, - "This token committee is for testing.", - addresses[:3], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - testutil.D("-0.1"), - "hard", - ) - }, - expectPass: false, - }, - { - name: "quroum greater than 1", - createCommittee: func() (*types.TokenCommittee, error) { - return types.NewTokenCommittee( - 1, - "This token committee is for testing.", - addresses[:3], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - testutil.D("1.001"), - "hard", - ) - }, - expectPass: false, - }, - { - name: "bond denom as tally denom", - createCommittee: func() (*types.TokenCommittee, error) { - return types.NewTokenCommittee( - 1, - "This token committee is for testing.", - addresses[:3], - []types.Permission{&types.GodPermission{}}, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - testutil.D("0.4"), - types.BondDenom, - ) - }, - expectPass: false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - committee, err := tc.createCommittee() - assert.NoError(t, err) - assert.Equal(t, types.TokenCommitteeType, committee.GetType()) - - err = committee.Validate() - if tc.expectPass { - assert.NoError(t, err) - } else { - assert.Error(t, err) - } - }) - } -} - -func TestProposalGetContent(t *testing.T) { - mockTitle := "A Title" - mockDescription := "A Description" - proposal, err := types.NewProposal( - govv1beta1.NewTextProposal(mockTitle, mockDescription), - 1, 1, time.Date(2010, time.January, 1, 0, 0, 0, 0, time.UTC), - ) - assert.NoError(t, err) - content := proposal.GetContent() - assert.NotNil(t, content) - assert.Equal(t, mockTitle, content.GetTitle()) - assert.Equal(t, mockDescription, content.GetDescription()) -} diff --git a/x/committee/types/genesis.go b/x/committee/types/genesis.go deleted file mode 100644 index e34331b3..00000000 --- a/x/committee/types/genesis.go +++ /dev/null @@ -1,171 +0,0 @@ -package types - -import ( - "fmt" - - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" - proto "github.com/cosmos/gogoproto/proto" -) - -// DefaultNextProposalID is the starting poiint for proposal IDs. -const DefaultNextProposalID uint64 = 1 - -// NewGenesisState returns a new genesis state object for the module. -func NewGenesisState(nextProposalID uint64, committees []Committee, proposals Proposals, votes []Vote) *GenesisState { - packedCommittees, err := PackCommittees(committees) - if err != nil { - panic(err) - } - return &GenesisState{ - NextProposalID: nextProposalID, - Committees: packedCommittees, - Proposals: proposals, - Votes: votes, - } -} - -// DefaultGenesisState returns the default genesis state for the module. -func DefaultGenesisState() *GenesisState { - return NewGenesisState( - DefaultNextProposalID, - Committees{}, - Proposals{}, - []Vote{}, - ) -} - -func (gs GenesisState) GetCommittees() Committees { - committees, err := UnpackCommittees(gs.Committees) - if err != nil { - panic(err) - } - return committees -} - -// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (data GenesisState) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { - for _, any := range data.Committees { - var committee Committee - if err := unpacker.UnpackAny(any, &committee); err != nil { - return err - } - } - for _, p := range data.Proposals { - err := p.UnpackInterfaces(unpacker) - if err != nil { - return err - } - } - return nil -} - -// Validate performs basic validation of genesis data. -func (gs GenesisState) Validate() error { - // validate committees - committeeMap := make(map[uint64]bool, len(gs.Committees)) - committees, err := UnpackCommittees(gs.Committees) - if err != nil { - return err - } - for _, com := range committees { - // check there are no duplicate IDs - if _, ok := committeeMap[com.GetID()]; ok { - return fmt.Errorf("duplicate committee ID found in genesis state; id: %d", com.GetID()) - } - committeeMap[com.GetID()] = true - - // validate committee - if err := com.Validate(); err != nil { - return err - } - } - - // validate proposals - proposalMap := make(map[uint64]bool, len(gs.Proposals)) - for _, p := range gs.Proposals { - // check there are no duplicate IDs - if _, ok := proposalMap[p.ID]; ok { - return fmt.Errorf("duplicate proposal ID found in genesis state; id: %d", p.ID) - } - proposalMap[p.ID] = true - - // validate next proposal ID - if p.ID >= gs.NextProposalID { - return fmt.Errorf("NextProposalID is not greater than all proposal IDs; id: %d", p.ID) - } - - // check committee exists - if !committeeMap[p.CommitteeID] { - return fmt.Errorf("proposal refers to non existent committee; committee id: %d", p.CommitteeID) - } - - // validate pubProposal - if err := p.ValidateBasic(); err != nil { - return fmt.Errorf("proposal %d invalid: %w", p.ID, err) - } - } - - // validate votes - for _, v := range gs.Votes { - // validate committee - if err := v.Validate(); err != nil { - return err - } - - // check proposal exists - if !proposalMap[v.ProposalID] { - return fmt.Errorf("vote refers to non existent proposal; vote: %+v", v) - } - } - return nil -} - -// PackCommittees converts a committee slice to Any slice -func PackCommittees(committees []Committee) ([]*cdctypes.Any, error) { - committeesAny := make([]*cdctypes.Any, len(committees)) - for i, committee := range committees { - any, err := PackCommittee(committee) - if err != nil { - return nil, err - } - committeesAny[i] = any - } - - return committeesAny, nil -} - -// PackCommittee converts a committee to Any -func PackCommittee(committee Committee) (*cdctypes.Any, error) { - msg, ok := committee.(proto.Message) - if !ok { - return nil, fmt.Errorf("cannot proto marshal %T", committee) - } - any, err := cdctypes.NewAnyWithValue(msg) - if err != nil { - return nil, err - } - return any, nil -} - -// UnpackCommittees converts Any slice to Committee slice -func UnpackCommittees(committeesAny []*cdctypes.Any) (Committees, error) { - committees := make(Committees, len(committeesAny)) - for i, any := range committeesAny { - committee, err := UnpackCommittee(any) - if err != nil { - return nil, err - } - committees[i] = committee - } - - return committees, nil -} - -// UnpackCommittee converts Any to Committee -func UnpackCommittee(committeeAny *cdctypes.Any) (Committee, error) { - committee, ok := committeeAny.GetCachedValue().(Committee) - if !ok { - return nil, fmt.Errorf("unexpected committee when unpacking") - } - return committee, nil -} diff --git a/x/committee/types/genesis.pb.go b/x/committee/types/genesis.pb.go deleted file mode 100644 index 056c0700..00000000 --- a/x/committee/types/genesis.pb.go +++ /dev/null @@ -1,1029 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/committee/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/codec/types" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 - -// VoteType enumerates the valid types of a vote. -type VoteType int32 - -const ( - // VOTE_TYPE_UNSPECIFIED defines a no-op vote option. - VOTE_TYPE_UNSPECIFIED VoteType = 0 - // VOTE_TYPE_YES defines a yes vote option. - VOTE_TYPE_YES VoteType = 1 - // VOTE_TYPE_NO defines a no vote option. - VOTE_TYPE_NO VoteType = 2 - // VOTE_TYPE_ABSTAIN defines an abstain vote option. - VOTE_TYPE_ABSTAIN VoteType = 3 -) - -var VoteType_name = map[int32]string{ - 0: "VOTE_TYPE_UNSPECIFIED", - 1: "VOTE_TYPE_YES", - 2: "VOTE_TYPE_NO", - 3: "VOTE_TYPE_ABSTAIN", -} - -var VoteType_value = map[string]int32{ - "VOTE_TYPE_UNSPECIFIED": 0, - "VOTE_TYPE_YES": 1, - "VOTE_TYPE_NO": 2, - "VOTE_TYPE_ABSTAIN": 3, -} - -func (x VoteType) String() string { - return proto.EnumName(VoteType_name, int32(x)) -} - -func (VoteType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_919b27ac60d8c5fd, []int{0} -} - -// GenesisState defines the committee module's genesis state. -type GenesisState struct { - NextProposalID uint64 `protobuf:"varint,1,opt,name=next_proposal_id,json=nextProposalId,proto3" json:"next_proposal_id,omitempty"` - Committees []*types.Any `protobuf:"bytes,2,rep,name=committees,proto3" json:"committees,omitempty"` - Proposals Proposals `protobuf:"bytes,3,rep,name=proposals,proto3,castrepeated=Proposals" json:"proposals"` - Votes []Vote `protobuf:"bytes,4,rep,name=votes,proto3" json:"votes"` -} - -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_919b27ac60d8c5fd, []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 - -// Proposal is an internal record of a governance proposal submitted to a committee. -type Proposal struct { - Content *types.Any `protobuf:"bytes,1,opt,name=content,proto3" json:"content,omitempty"` - ID uint64 `protobuf:"varint,2,opt,name=id,proto3" json:"id,omitempty"` - CommitteeID uint64 `protobuf:"varint,3,opt,name=committee_id,json=committeeId,proto3" json:"committee_id,omitempty"` - Deadline time.Time `protobuf:"bytes,4,opt,name=deadline,proto3,stdtime" json:"deadline"` -} - -func (m *Proposal) Reset() { *m = Proposal{} } -func (*Proposal) ProtoMessage() {} -func (*Proposal) Descriptor() ([]byte, []int) { - return fileDescriptor_919b27ac60d8c5fd, []int{1} -} -func (m *Proposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Proposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Proposal.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 *Proposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_Proposal.Merge(m, src) -} -func (m *Proposal) XXX_Size() int { - return m.Size() -} -func (m *Proposal) XXX_DiscardUnknown() { - xxx_messageInfo_Proposal.DiscardUnknown(m) -} - -var xxx_messageInfo_Proposal proto.InternalMessageInfo - -// Vote is an internal record of a single governance vote. -type Vote struct { - ProposalID uint64 `protobuf:"varint,1,opt,name=proposal_id,json=proposalId,proto3" json:"proposal_id,omitempty"` - Voter github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,2,opt,name=voter,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"voter,omitempty"` - VoteType VoteType `protobuf:"varint,3,opt,name=vote_type,json=voteType,proto3,enum=kava.committee.v1beta1.VoteType" json:"vote_type,omitempty"` -} - -func (m *Vote) Reset() { *m = Vote{} } -func (m *Vote) String() string { return proto.CompactTextString(m) } -func (*Vote) ProtoMessage() {} -func (*Vote) Descriptor() ([]byte, []int) { - return fileDescriptor_919b27ac60d8c5fd, []int{2} -} -func (m *Vote) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Vote) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Vote.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 *Vote) XXX_Merge(src proto.Message) { - xxx_messageInfo_Vote.Merge(m, src) -} -func (m *Vote) XXX_Size() int { - return m.Size() -} -func (m *Vote) XXX_DiscardUnknown() { - xxx_messageInfo_Vote.DiscardUnknown(m) -} - -var xxx_messageInfo_Vote proto.InternalMessageInfo - -func init() { - proto.RegisterEnum("kava.committee.v1beta1.VoteType", VoteType_name, VoteType_value) - proto.RegisterType((*GenesisState)(nil), "kava.committee.v1beta1.GenesisState") - proto.RegisterType((*Proposal)(nil), "kava.committee.v1beta1.Proposal") - proto.RegisterType((*Vote)(nil), "kava.committee.v1beta1.Vote") -} - -func init() { - proto.RegisterFile("kava/committee/v1beta1/genesis.proto", fileDescriptor_919b27ac60d8c5fd) -} - -var fileDescriptor_919b27ac60d8c5fd = []byte{ - // 647 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x54, 0x3f, 0x6f, 0xd3, 0x40, - 0x14, 0xb7, 0x1d, 0x53, 0x92, 0x4b, 0x1a, 0xd2, 0xa3, 0xad, 0xd2, 0x08, 0xd9, 0x55, 0xc5, 0x50, - 0x81, 0x62, 0xab, 0x65, 0x41, 0x15, 0x48, 0xc4, 0x49, 0x00, 0x2f, 0x69, 0x71, 0x42, 0xa5, 0x32, - 0x10, 0x39, 0xf1, 0x61, 0xac, 0x26, 0xbe, 0x28, 0x77, 0x8d, 0x9a, 0x6f, 0xd0, 0xb1, 0x23, 0x23, - 0x12, 0x4c, 0xcc, 0xfd, 0x10, 0x55, 0xa7, 0x8a, 0x89, 0x01, 0xb9, 0xc8, 0xfd, 0x06, 0x8c, 0x4c, - 0xe8, 0xce, 0x7f, 0x12, 0x51, 0x3a, 0xf9, 0xdd, 0x7b, 0xbf, 0xf7, 0xe7, 0xf7, 0x7b, 0x4f, 0x06, - 0x0f, 0x0f, 0xed, 0x89, 0xad, 0xf7, 0xf1, 0x70, 0xe8, 0x51, 0x8a, 0x90, 0x3e, 0xd9, 0xea, 0x21, - 0x6a, 0x6f, 0xe9, 0x2e, 0xf2, 0x11, 0xf1, 0x88, 0x36, 0x1a, 0x63, 0x8a, 0xe1, 0x2a, 0x43, 0x69, - 0x29, 0x4a, 0x8b, 0x51, 0x95, 0xb5, 0x3e, 0x26, 0x43, 0x4c, 0xba, 0x1c, 0xa5, 0x47, 0x8f, 0x28, - 0xa5, 0xb2, 0xec, 0x62, 0x17, 0x47, 0x7e, 0x66, 0xc5, 0xde, 0x35, 0x17, 0x63, 0x77, 0x80, 0x74, - 0xfe, 0xea, 0x1d, 0x7d, 0xd0, 0x6d, 0x7f, 0x1a, 0x87, 0xd4, 0x7f, 0x43, 0xd4, 0x1b, 0x22, 0x42, - 0xed, 0xe1, 0x28, 0x02, 0x6c, 0x7c, 0x95, 0x40, 0xe1, 0x55, 0x34, 0x56, 0x9b, 0xda, 0x14, 0xc1, - 0x67, 0xa0, 0xe4, 0xa3, 0x63, 0xca, 0xba, 0x8f, 0x30, 0xb1, 0x07, 0x5d, 0xcf, 0x29, 0x8b, 0xeb, - 0xe2, 0xa6, 0x6c, 0xc0, 0x30, 0x50, 0x8b, 0x2d, 0x74, 0x4c, 0xf7, 0xe2, 0x90, 0xd9, 0xb0, 0x8a, - 0xfe, 0xfc, 0xdb, 0x81, 0x75, 0x00, 0x52, 0x42, 0xa4, 0x2c, 0xad, 0x67, 0x36, 0xf3, 0xdb, 0xcb, - 0x5a, 0x34, 0x84, 0x96, 0x0c, 0xa1, 0xd5, 0xfc, 0xa9, 0xb1, 0x78, 0x71, 0x56, 0xcd, 0xd5, 0x13, - 0xac, 0x35, 0x97, 0x06, 0xdf, 0x80, 0x5c, 0xd2, 0x9d, 0x94, 0x33, 0xbc, 0xc6, 0xba, 0xf6, 0x7f, - 0xb1, 0xb4, 0xa4, 0xb7, 0xb1, 0x74, 0x1e, 0xa8, 0xc2, 0xb7, 0x2b, 0x35, 0x97, 0x78, 0x88, 0x35, - 0xab, 0x02, 0x9f, 0x82, 0x3b, 0x13, 0x4c, 0x11, 0x29, 0xcb, 0xbc, 0xdc, 0x83, 0xdb, 0xca, 0xed, - 0x63, 0x8a, 0x0c, 0x99, 0x95, 0xb2, 0xa2, 0x84, 0x1d, 0xf9, 0xe4, 0xb3, 0x2a, 0x6c, 0xfc, 0x16, - 0x41, 0x36, 0x29, 0x0c, 0x5b, 0xe0, 0x6e, 0x1f, 0xfb, 0x14, 0xf9, 0x94, 0x2b, 0x73, 0x1b, 0x43, - 0xe5, 0xe2, 0xac, 0x5a, 0x89, 0xd7, 0xe7, 0xe2, 0x49, 0xda, 0xa3, 0x1e, 0xe5, 0x5a, 0x49, 0x11, - 0xb8, 0x0a, 0x24, 0xcf, 0x29, 0x4b, 0x5c, 0xe4, 0x85, 0x30, 0x50, 0x25, 0xb3, 0x61, 0x49, 0x9e, - 0x03, 0xb7, 0x41, 0x21, 0x9d, 0x90, 0xad, 0x21, 0xc3, 0x11, 0xf7, 0xc2, 0x40, 0xcd, 0xa7, 0xc2, - 0x99, 0x0d, 0x2b, 0x9f, 0x82, 0x4c, 0x07, 0xbe, 0x00, 0x59, 0x07, 0xd9, 0xce, 0xc0, 0xf3, 0x51, - 0x59, 0xe6, 0xc3, 0x55, 0x6e, 0x0c, 0xd7, 0x49, 0x6e, 0xc0, 0xc8, 0x32, 0xa6, 0xa7, 0x57, 0xaa, - 0x68, 0xa5, 0x59, 0x3b, 0x59, 0x46, 0xf8, 0x13, 0x23, 0xfd, 0x53, 0x04, 0x32, 0x13, 0x04, 0xea, - 0x20, 0x7f, 0xf3, 0x1c, 0x8a, 0x61, 0xa0, 0x82, 0xb9, 0x53, 0x00, 0xa3, 0xd9, 0x19, 0xbc, 0x8f, - 0xe4, 0x1e, 0x73, 0x52, 0x05, 0xe3, 0xf5, 0x9f, 0x40, 0xad, 0xba, 0x1e, 0xfd, 0x78, 0xd4, 0x63, - 0x9a, 0xc7, 0x37, 0x1d, 0x7f, 0xaa, 0xc4, 0x39, 0xd4, 0xe9, 0x74, 0x84, 0x88, 0x56, 0xeb, 0xf7, - 0x6b, 0x8e, 0x33, 0x46, 0x84, 0x7c, 0x3f, 0xab, 0xde, 0x8f, 0xa5, 0x8b, 0x3d, 0xc6, 0x94, 0x22, - 0x12, 0x2d, 0x65, 0x0c, 0x9f, 0x83, 0x1c, 0x33, 0xba, 0x2c, 0x8d, 0xcb, 0x52, 0xbc, 0xfd, 0x42, - 0x18, 0x83, 0xce, 0x74, 0x84, 0xac, 0xec, 0x24, 0xb6, 0xa2, 0x9d, 0x3e, 0x72, 0x41, 0x36, 0x89, - 0xc1, 0x35, 0xb0, 0xb2, 0xbf, 0xdb, 0x69, 0x76, 0x3b, 0x07, 0x7b, 0xcd, 0xee, 0xdb, 0x56, 0x7b, - 0xaf, 0x59, 0x37, 0x5f, 0x9a, 0xcd, 0x46, 0x49, 0x80, 0x4b, 0x60, 0x71, 0x16, 0x3a, 0x68, 0xb6, - 0x4b, 0x22, 0x2c, 0x81, 0xc2, 0xcc, 0xd5, 0xda, 0x2d, 0x49, 0x70, 0x05, 0x2c, 0xcd, 0x3c, 0x35, - 0xa3, 0xdd, 0xa9, 0x99, 0xad, 0x52, 0xa6, 0x22, 0x9f, 0x7c, 0x51, 0x04, 0xa3, 0x79, 0x1e, 0x2a, - 0xe2, 0x65, 0xa8, 0x88, 0xbf, 0x42, 0x45, 0x3c, 0xbd, 0x56, 0x84, 0xcb, 0x6b, 0x45, 0xf8, 0x71, - 0xad, 0x08, 0xef, 0x1e, 0xcf, 0x89, 0xc2, 0xc6, 0xaf, 0x0e, 0xec, 0x1e, 0xe1, 0x96, 0x7e, 0x3c, - 0xf7, 0xff, 0xe0, 0xea, 0xf4, 0x16, 0xf8, 0x02, 0x9f, 0xfc, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x6a, - 0x30, 0x5b, 0x09, 0x5e, 0x04, 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.Votes) > 0 { - for iNdEx := len(m.Votes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Votes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.Proposals) > 0 { - for iNdEx := len(m.Proposals) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Proposals[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Committees) > 0 { - for iNdEx := len(m.Committees) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Committees[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if m.NextProposalID != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.NextProposalID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *Proposal) 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 *Proposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Proposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Deadline, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Deadline):]) - if err1 != nil { - return 0, err1 - } - i -= n1 - i = encodeVarintGenesis(dAtA, i, uint64(n1)) - i-- - dAtA[i] = 0x22 - if m.CommitteeID != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.CommitteeID)) - i-- - dAtA[i] = 0x18 - } - if m.ID != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.ID)) - i-- - dAtA[i] = 0x10 - } - if m.Content != nil { - { - size, err := m.Content.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 (m *Vote) 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 *Vote) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Vote) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.VoteType != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.VoteType)) - i-- - dAtA[i] = 0x18 - } - if len(m.Voter) > 0 { - i -= len(m.Voter) - copy(dAtA[i:], m.Voter) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.Voter))) - i-- - dAtA[i] = 0x12 - } - if m.ProposalID != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.ProposalID)) - i-- - dAtA[i] = 0x8 - } - 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 - if m.NextProposalID != 0 { - n += 1 + sovGenesis(uint64(m.NextProposalID)) - } - if len(m.Committees) > 0 { - for _, e := range m.Committees { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.Proposals) > 0 { - for _, e := range m.Proposals { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.Votes) > 0 { - for _, e := range m.Votes { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func (m *Proposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Content != nil { - l = m.Content.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - if m.ID != 0 { - n += 1 + sovGenesis(uint64(m.ID)) - } - if m.CommitteeID != 0 { - n += 1 + sovGenesis(uint64(m.CommitteeID)) - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Deadline) - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *Vote) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.ProposalID != 0 { - n += 1 + sovGenesis(uint64(m.ProposalID)) - } - l = len(m.Voter) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - if m.VoteType != 0 { - n += 1 + sovGenesis(uint64(m.VoteType)) - } - 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 != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field NextProposalID", wireType) - } - m.NextProposalID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.NextProposalID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Committees", 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.Committees = append(m.Committees, &types.Any{}) - if err := m.Committees[len(m.Committees)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Proposals", 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.Proposals = append(m.Proposals, Proposal{}) - if err := m.Proposals[len(m.Proposals)-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 Votes", 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.Votes = append(m.Votes, Vote{}) - if err := m.Votes[len(m.Votes)-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 (m *Proposal) 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: Proposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Proposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Content", 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 m.Content == nil { - m.Content = &types.Any{} - } - if err := m.Content.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - m.ID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CommitteeID", wireType) - } - m.CommitteeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CommitteeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deadline", 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 := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Deadline, 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 (m *Vote) 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: Vote: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Vote: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ProposalID", wireType) - } - m.ProposalID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ProposalID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Voter", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Voter = append(m.Voter[:0], dAtA[iNdEx:postIndex]...) - if m.Voter == nil { - m.Voter = []byte{} - } - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field VoteType", wireType) - } - m.VoteType = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.VoteType |= VoteType(b&0x7F) << shift - if b < 0x80 { - break - } - } - 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/committee/types/genesis_test.go b/x/committee/types/genesis_test.go deleted file mode 100644 index 98f6e8e5..00000000 --- a/x/committee/types/genesis_test.go +++ /dev/null @@ -1,186 +0,0 @@ -package types_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - "github.com/cometbft/cometbft/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - "github.com/kava-labs/kava/x/committee/testutil" - "github.com/kava-labs/kava/x/committee/types" -) - -func TestGenesisState_Validate(t *testing.T) { - testTime := time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC) - addresses := []sdk.AccAddress{ - sdk.AccAddress(crypto.AddressHash([]byte("KavaTest1"))), - sdk.AccAddress(crypto.AddressHash([]byte("KavaTest2"))), - sdk.AccAddress(crypto.AddressHash([]byte("KavaTest3"))), - sdk.AccAddress(crypto.AddressHash([]byte("KavaTest4"))), - sdk.AccAddress(crypto.AddressHash([]byte("KavaTest5"))), - } - - testGenesis := types.NewGenesisState( - 2, - []types.Committee{ - types.MustNewMemberCommittee( - 1, - "This members committee is for testing.", - addresses[:3], - nil, - testutil.D("0.667"), - time.Hour*24*7, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ), - types.MustNewMemberCommittee( - 2, - "This members committee is also for testing.", - addresses[:3], - nil, - testutil.D("0.8"), - time.Hour*24*21, - types.TALLY_OPTION_FIRST_PAST_THE_POST, - ), - types.MustNewTokenCommittee( - 3, - "This token committee is for testing.", - addresses[:3], - nil, - testutil.D("0.8"), - time.Hour*24*21, - types.TALLY_OPTION_DEADLINE, - sdk.MustNewDecFromStr("0.4"), - "hard", - ), - }, - types.Proposals{ - types.MustNewProposal( - govv1beta1.NewTextProposal("A Title", "A description of this proposal."), 1, 1, testTime.Add(7*24*time.Hour)), - }, - []types.Vote{ - {ProposalID: 1, Voter: addresses[0], VoteType: types.VOTE_TYPE_YES}, - {ProposalID: 1, Voter: addresses[1], VoteType: types.VOTE_TYPE_YES}, - }, - ) - - testCases := []struct { - name string - genState *types.GenesisState - expectPass bool - }{ - { - name: "default", - genState: types.DefaultGenesisState(), - expectPass: true, - }, - { - name: "normal", - genState: testGenesis, - expectPass: true, - }, - { - name: "duplicate committee IDs", - genState: types.NewGenesisState( - testGenesis.NextProposalID, - append(testGenesis.GetCommittees(), testGenesis.GetCommittees()[0]), - testGenesis.Proposals, - testGenesis.Votes, - ), - expectPass: false, - }, - { - name: "invalid committee", - genState: types.NewGenesisState( - testGenesis.NextProposalID, - append(testGenesis.GetCommittees(), &types.MemberCommittee{BaseCommittee: &types.BaseCommittee{}}), - testGenesis.Proposals, - testGenesis.Votes, - ), - expectPass: false, - }, - { - name: "duplicate proposal IDs", - genState: types.NewGenesisState( - testGenesis.NextProposalID, - testGenesis.GetCommittees(), - append(testGenesis.Proposals, testGenesis.Proposals[0]), - testGenesis.Votes, - ), - expectPass: false, - }, - { - name: "invalid NextProposalID", - genState: types.NewGenesisState( - 0, - testGenesis.GetCommittees(), - testGenesis.Proposals, - testGenesis.Votes, - ), - expectPass: false, - }, - { - name: "proposal without committee", - genState: types.NewGenesisState( - testGenesis.NextProposalID+1, - testGenesis.GetCommittees(), - append( - testGenesis.Proposals, - types.MustNewProposal( - govv1beta1.NewTextProposal("A Title", "A description of this proposal."), - testGenesis.NextProposalID, - 47, // doesn't exist - testTime.Add(7*24*time.Hour), - ), - ), - testGenesis.Votes, - ), - expectPass: false, - }, - { - name: "invalid proposal", - genState: types.NewGenesisState( - testGenesis.NextProposalID, - testGenesis.GetCommittees(), - append(testGenesis.Proposals, types.Proposal{}), - testGenesis.Votes, - ), - expectPass: false, - }, - { - name: "vote without proposal", - genState: types.NewGenesisState( - testGenesis.NextProposalID, - testGenesis.GetCommittees(), - nil, - testGenesis.Votes, - ), - expectPass: false, - }, - { - name: "invalid vote", - genState: types.NewGenesisState( - testGenesis.NextProposalID, - testGenesis.GetCommittees(), - testGenesis.Proposals, - append(testGenesis.Votes, types.Vote{}), - ), - expectPass: false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.genState.Validate() - - if tc.expectPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } -} diff --git a/x/committee/types/msg.go b/x/committee/types/msg.go deleted file mode 100644 index 6b3d2aac..00000000 --- a/x/committee/types/msg.go +++ /dev/null @@ -1,153 +0,0 @@ -package types - -import ( - fmt "fmt" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/gogoproto/proto" -) - -const ( - TypeMsgSubmitProposal = "commmittee_submit_proposal" // 'committee' prefix appended to avoid potential conflicts with gov msg types - TypeMsgVote = "committee_vote" -) - -var ( - _, _ sdk.Msg = &MsgSubmitProposal{}, &MsgVote{} - _ types.UnpackInterfacesMessage = &MsgSubmitProposal{} -) - -// NewMsgSubmitProposal creates a new MsgSubmitProposal instance -func NewMsgSubmitProposal(pubProposal PubProposal, proposer sdk.AccAddress, committeeID uint64) (*MsgSubmitProposal, error) { - msg, ok := pubProposal.(proto.Message) - if !ok { - return &MsgSubmitProposal{}, fmt.Errorf("can't proto marshal %T", msg) - } - any, err := types.NewAnyWithValue(msg) - if err != nil { - return &MsgSubmitProposal{}, err - } - return &MsgSubmitProposal{ - PubProposal: any, - Proposer: proposer.String(), - CommitteeID: committeeID, - }, nil -} - -func (msg MsgSubmitProposal) GetPubProposal() PubProposal { - content, ok := msg.PubProposal.GetCachedValue().(PubProposal) - if !ok { - return nil - } - return content -} - -// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (m MsgSubmitProposal) UnpackInterfaces(unpacker types.AnyUnpacker) error { - var content PubProposal - return unpacker.UnpackAny(m.PubProposal, &content) -} - -// Route return the message type used for routing the message. -func (msg MsgSubmitProposal) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within events. -func (msg MsgSubmitProposal) Type() string { return TypeMsgSubmitProposal } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgSubmitProposal) ValidateBasic() error { - if msg.GetPubProposal() == nil { - return errorsmod.Wrap(ErrInvalidPubProposal, "pub proposal cannot be nil") - } - if _, err := sdk.AccAddressFromBech32(msg.Proposer); err != nil { - return err - } - return msg.GetPubProposal().ValidateBasic() -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgSubmitProposal) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgSubmitProposal) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.GetProposer()} -} - -func (msg MsgSubmitProposal) GetProposer() sdk.AccAddress { - address, err := sdk.AccAddressFromBech32(msg.Proposer) - if err != nil { - return sdk.AccAddress{} - } - return address -} - -// Marshal needed for protobuf compatibility. -func (vt VoteType) Marshal() ([]byte, error) { - return []byte{byte(vt)}, nil -} - -// Unmarshal needed for protobuf compatibility. -func (vt *VoteType) Unmarshal(data []byte) error { - *vt = VoteType(data[0]) - return nil -} - -func (vt VoteType) Validate() error { - if vt <= 0 || vt > 3 { - return fmt.Errorf("invalid vote type: %d", vt) - } - return nil -} - -// Format implements the fmt.Formatter interface. -func (vo VoteType) Format(s fmt.State, verb rune) { - switch verb { - case 's': - s.Write([]byte(vo.String())) - default: - s.Write([]byte(fmt.Sprintf("%v", byte(vo)))) - } -} - -// NewMsgVote creates a message to cast a vote on an active proposal -func NewMsgVote(voter sdk.AccAddress, proposalID uint64, voteType VoteType) *MsgVote { - return &MsgVote{proposalID, voter.String(), voteType} -} - -// Route return the message type used for routing the message. -func (msg MsgVote) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within events. -func (msg MsgVote) Type() string { return TypeMsgVote } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgVote) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Voter); err != nil { - return err - } - return msg.VoteType.Validate() -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgVote) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgVote) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.GetVoter()} -} - -func (msg MsgVote) GetVoter() sdk.AccAddress { - address, err := sdk.AccAddressFromBech32(msg.Voter) - if err != nil { - return sdk.AccAddress{} - } - return address -} diff --git a/x/committee/types/msg_test.go b/x/committee/types/msg_test.go deleted file mode 100644 index e3d65bc6..00000000 --- a/x/committee/types/msg_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package types - -import ( - "testing" - - "github.com/cometbft/cometbft/crypto" - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -func MustNewMsgSubmitProposal(pubProposal PubProposal, proposer sdk.AccAddress, committeeId uint64) *MsgSubmitProposal { - proposal, err := NewMsgSubmitProposal(pubProposal, proposer, committeeId) - if err != nil { - panic(err) - } - return proposal -} - -func TestMsgSubmitProposal_ValidateBasic(t *testing.T) { - addr := sdk.AccAddress(crypto.AddressHash([]byte("KavaTest1"))) - tests := []struct { - name string - msg *MsgSubmitProposal - expectPass bool - }{ - { - name: "normal", - msg: MustNewMsgSubmitProposal(govv1beta1.NewTextProposal("A Title", "A proposal description."), addr, 3), - expectPass: true, - }, - { - name: "empty address", - msg: MustNewMsgSubmitProposal(govv1beta1.NewTextProposal("A Title", "A proposal description."), nil, 3), - expectPass: false, - }, - { - name: "invalid proposal", - msg: &MsgSubmitProposal{PubProposal: &types.Any{}, Proposer: addr.String(), CommitteeID: 3}, - expectPass: false, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - - if tc.expectPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } -} - -func TestMsgVote_ValidateBasic(t *testing.T) { - addr := sdk.AccAddress(crypto.AddressHash([]byte("KavaTest1"))) - tests := []struct { - name string - msg MsgVote - expectPass bool - }{ - { - name: "normal", - msg: MsgVote{5, addr.String(), VOTE_TYPE_YES}, - expectPass: true, - }, - { - name: "No", - msg: MsgVote{5, addr.String(), VOTE_TYPE_NO}, - expectPass: true, - }, - { - name: "Abstain", - msg: MsgVote{5, addr.String(), VOTE_TYPE_ABSTAIN}, - expectPass: true, - }, - { - name: "Null vote", - msg: MsgVote{5, addr.String(), VOTE_TYPE_UNSPECIFIED}, - expectPass: false, - }, - { - name: "empty address", - msg: MsgVote{5, "", VOTE_TYPE_YES}, - expectPass: false, - }, - { - name: "invalid vote (greater)", - msg: MsgVote{5, addr.String(), 4}, - expectPass: false, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - - if tc.expectPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } -} diff --git a/x/committee/types/param_permissions_test.go b/x/committee/types/param_permissions_test.go deleted file mode 100644 index d4251714..00000000 --- a/x/committee/types/param_permissions_test.go +++ /dev/null @@ -1,1105 +0,0 @@ -package types_test - -import ( - fmt "fmt" - "testing" - - sdkmath "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - paramsproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - cdptypes "github.com/kava-labs/kava/x/cdp/types" - types "github.com/kava-labs/kava/x/committee/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -type ParamsChangeTestSuite struct { - suite.Suite - - ctx sdk.Context - pk types.ParamKeeper - - cdpCollateralParams cdptypes.CollateralParams - cdpDebtParam cdptypes.DebtParam - cdpCollateralRequirements []types.SubparamRequirement -} - -func (suite *ParamsChangeTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - suite.ctx = ctx - suite.pk = tApp.GetParamsKeeper() - - suite.cdpDebtParam = cdptypes.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(1000), - } - - suite.cdpCollateralParams = cdptypes.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("2.0"), - DebtLimit: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - StabilityFee: sdk.MustNewDecFromStr("1.02"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(100), - ConversionFactor: sdkmath.NewInt(6), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - CheckCollateralizationIndexCount: sdkmath.NewInt(0), - }, - { - Denom: "btc", - Type: "btc-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - StabilityFee: sdk.MustNewDecFromStr("1.01"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.10"), - AuctionSize: sdkmath.NewInt(1000), - ConversionFactor: sdkmath.NewInt(8), - SpotMarketID: "btc:usd", - LiquidationMarketID: "btc:usd", - CheckCollateralizationIndexCount: sdkmath.NewInt(1), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.12"), - }, - } - suite.cdpCollateralRequirements = []types.SubparamRequirement{ - { - Key: "type", - Val: "bnb-a", - AllowedSubparamAttrChanges: []string{"conversion_factor", "liquidation_ratio", "spot_market_id"}, - }, - { - Key: "type", - Val: "btc-a", - AllowedSubparamAttrChanges: []string{"stability_fee", "debt_limit", "auction_size", "keeper_reward_percentage"}, - }, - } -} - -func (s *ParamsChangeTestSuite) TestSingleSubparams_CdpDeptParams() { - testcases := []struct { - name string - expected bool - permission types.AllowedParamsChange - paramChange paramsproposal.ParamChange - }{ - { - name: "allow changes to all allowed fields", - expected: true, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom", "reference_asset", "conversion_factor", "debt_floor"}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "DebtParam", - Value: `{ - "denom": "bnb", - "reference_asset": "bnbx", - "conversion_factor": "11", - "debt_floor": "1200" - }`, - }, - }, - { - name: "allows changes only to certain fields", - expected: true, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom", "debt_floor"}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "DebtParam", - Value: `{ - "denom": "bnb", - "reference_asset": "usd", - "conversion_factor": "6", - "debt_floor": "1100" - }`, - }, - }, - { - name: "fails if changing attr that is not allowed", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom", "debt_floor"}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "DebtParam", - Value: `{ - "denom": "usdx", - "reference_asset": "usd", - "conversion_factor": "7", - "debt_floor": "1000" - }`, - }, - }, - { - name: "fails if there are unexpected param change attrs", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom"}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "DebtParam", - Value: `{ - "denom": "usdx", - "reference_asset": "usd", - "conversion_factor": "6", - "debt_floor": "1000", - "extra_attr": "123" - }`, - }, - }, - { - name: "fails if there are missing param change attrs", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom", "reference_asset"}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "DebtParam", - // debt_floor is missing - Value: `{ - "denom": "usdx", - "reference_asset": "usd", - "conversion_factor": "11.000000000000000000", - }`, - }, - }, - { - name: "fails if subspace does not match", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom"}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "auction", - Key: "DebtParam", - Value: `{ - "denom": "usdx", - "reference_asset": "usd", - "conversion_factor": "6", - "debt_floor": "1000" - }`, - }, - }, - } - - for _, tc := range testcases { - s.Run(tc.name, func() { - s.SetupTest() - - subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) - s.Require().True(found) - subspace.Set(s.ctx, cdptypes.KeyDebtParam, s.cdpDebtParam) - - permission := types.ParamsChangePermission{ - AllowedParamsChanges: types.AllowedParamsChanges{tc.permission}, - } - proposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []paramsproposal.ParamChange{tc.paramChange}, - ) - s.Require().Equal( - tc.expected, - permission.Allows(s.ctx, s.pk, proposal), - ) - }) - } -} - -func (s *ParamsChangeTestSuite) TestMultiSubparams_CdpCollateralParams() { - unchangedBnbValue := `{ - "denom": "bnb", - "type": "bnb-a", - "liquidation_ratio": "2.000000000000000000", - "debt_limit": { "denom": "usdx", "amount": "100" }, - "stability_fee": "1.020000000000000000", - "auction_size": "100", - "liquidation_penalty": "0.050000000000000000", - "spot_market_id": "bnb:usd", - "liquidation_market_id": "bnb:usd", - "keeper_reward_percentage": "0", - "check_collateralization_index_count": "0", - "conversion_factor": "6" - }` - unchangedBtcValue := `{ - "denom": "btc", - "type": "btc-a", - "liquidation_ratio": "1.500000000000000000", - "debt_limit": { "denom": "usdx", "amount": "100" }, - "stability_fee": "1.010000000000000000", - "auction_size": "1000", - "liquidation_penalty": "0.100000000000000000", - "spot_market_id": "btc:usd", - "liquidation_market_id": "btc:usd", - "keeper_reward_percentage": "0.12", - "check_collateralization_index_count": "1", - "conversion_factor": "8" - }` - - testcases := []struct { - name string - expected bool - permission types.AllowedParamsChange - paramChange paramsproposal.ParamChange - }{ - { - name: "succeeds when changing allowed values and keeping not allowed the same", - expected: true, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: s.cdpCollateralRequirements, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - Value: `[{ - "denom": "bnb", - "type": "bnb-a", - "liquidation_ratio": "2.010000000000000000", - "debt_limit": { "denom": "usdx", "amount": "100" }, - "stability_fee": "1.020000000000000000", - "auction_size": "100", - "liquidation_penalty": "0.050000000000000000", - "spot_market_id": "bnbc:usd", - "liquidation_market_id": "bnb:usd", - "keeper_reward_percentage": "0", - "check_collateralization_index_count": "0", - "conversion_factor": "9" - }, - { - "denom": "btc", - "type": "btc-a", - "liquidation_ratio": "1.500000000000000000", - "debt_limit": { "denom": "usdx", "amount": "200" }, - "stability_fee": "2.010000000000000000", - "auction_size": "1200", - "liquidation_penalty": "0.100000000000000000", - "spot_market_id": "btc:usd", - "liquidation_market_id": "btc:usd", - "keeper_reward_percentage": "0.000000000000000000", - "check_collateralization_index_count": "1", - "conversion_factor": "8" - }]`, - }, - }, - { - name: "succeeds if nothing is changed", - expected: true, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: s.cdpCollateralRequirements, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, unchangedBtcValue), - }, - }, - { - name: "fails if changed records are not the same length as existing records", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: s.cdpCollateralRequirements, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - Value: fmt.Sprintf("[%s]", unchangedBnbValue), - }, - }, - { - name: "fails if incoming records are missing a existing record", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: s.cdpCollateralRequirements, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - // same length as existing records but missing one with the correct key/value pair - Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, unchangedBnbValue), - }, - }, - { - name: "fails when changing an attribute that is not allowed", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: s.cdpCollateralRequirements, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - // changed liquidation_ratio, which is not whitelisted - Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, `{ - "denom": "btc", - "type": "btc-a", - "liquidation_ratio": "1.2", - "debt_limit": { "denom": "usdx", "amount": "100" }, - "stability_fee": "1.01", - "auction_size": "1000", - "liquidation_penalty": "0.1", - "spot_market_id": "btc:usd", - "liquidation_market_id": "btc:usd", - "keeper_reward_percentage": "0.12", - "check_collateralization_index_count": "1", - "conversion_factor": "8" - }`), - }, - }, - { - name: "fails when requirements does not include an existing record", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: []types.SubparamRequirement{s.cdpCollateralRequirements[0]}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, unchangedBtcValue), - }, - }, - { - name: "fails when changes has missing key", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: []types.SubparamRequirement{s.cdpCollateralRequirements[0]}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - // missing check_collateralization_index_count - Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, `{ - "denom": "btc", - "type": "btc-a", - "liquidation_ratio": "1.500000000000000000", - "debt_limit": { "denom": "usdx", "amount": "100" }, - "stability_fee": "1.010000000000000000", - "auction_size": "1000", - "liquidation_penalty": "0.100000000000000000", - "spot_market_id": "btc:usd", - "liquidation_market_id": "btc:usd", - "keeper_reward_percentage": "0.12", - "conversion_factor": "8" - }`), - }, - }, - { - name: "fails when changes has same keys length but an unknown key", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: []types.SubparamRequirement{s.cdpCollateralRequirements[0]}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - // missspelled denom key - Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, `{ - "denoms": "btc", - "type": "btc-a", - "liquidation_ratio": "1.500000000000000000", - "debt_limit": { "denom": "usdx", "amount": "100" }, - "stability_fee": "1.010000000000000000", - "auction_size": "1000", - "liquidation_penalty": "0.100000000000000000", - "spot_market_id": "btc:usd", - "liquidation_market_id": "btc:usd", - "keeper_reward_percentage": "0.12", - "check_collateralization_index_count": "1", - "conversion_factor": "8" - }`), - }, - }, - { - name: "fails when attr is not allowed and has different value", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: []types.SubparamRequirement{s.cdpCollateralRequirements[0]}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - // liquidation_ratio changed value but is not allowed - Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, `{ - "denom": "btc", - "type": "btc-a", - "liquidation_ratio": "1.510000000000000000", - "debt_limit": { "denom": "usdx", "amount": "100" }, - "stability_fee": "1.010000000000000000", - "auction_size": "1000", - "liquidation_penalty": "0.100000000000000000", - "spot_market_id": "btc:usd", - "liquidation_market_id": "btc:usd", - "keeper_reward_percentage": "0.12", - "check_collateralization_index_count": "1", - "conversion_factor": "8" - }`), - }, - }, - { - name: "succeeds when param attr is not allowed but is same", - expected: true, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: s.cdpCollateralRequirements, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - // liquidation_ratio is not allowed but the same - // stability_fee is allowed but changed - Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, `{ - "denom": "btc", - "type": "btc-a", - "liquidation_ratio": "1.500000000000000000", - "debt_limit": { "denom": "usdx", "amount": "100" }, - "stability_fee": "1.020000000000000000", - "auction_size": "1000", - "liquidation_penalty": "0.100000000000000000", - "spot_market_id": "btc:usd", - "liquidation_market_id": "btc:usd", - "keeper_reward_percentage": "0.12", - "check_collateralization_index_count": "1", - "conversion_factor": "8" - }`), - }, - }, - } - - for _, tc := range testcases { - s.Run(tc.name, func() { - s.SetupTest() - - subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) - s.Require().True(found) - subspace.Set(s.ctx, cdptypes.KeyCollateralParams, s.cdpCollateralParams) - - permission := types.ParamsChangePermission{ - AllowedParamsChanges: types.AllowedParamsChanges{tc.permission}, - } - proposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []paramsproposal.ParamChange{tc.paramChange}, - ) - s.Require().Equal( - tc.expected, - permission.Allows(s.ctx, s.pk, proposal), - ) - }) - } -} - -func (s *ParamsChangeTestSuite) TestAllowedParamsChange_InvalidJSON() { - subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) - s.Require().True(found) - subspace.Set(s.ctx, cdptypes.KeyDebtParam, s.cdpDebtParam) - - permission := types.ParamsChangePermission{ - AllowedParamsChanges: types.AllowedParamsChanges{{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom", "reference_asset", "conversion_factor", "debt_floor"}, - }}, - } - proposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []paramsproposal.ParamChange{ - { - Subspace: "cdp", - Key: "DebtParam", - Value: `{badjson}`, - }, - }, - ) - s.Require().Equal( - false, - permission.Allows(s.ctx, s.pk, proposal), - ) -} - -func (s *ParamsChangeTestSuite) TestAllowedParamsChange_InvalidJSONArray() { - subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) - s.Require().True(found) - subspace.Set(s.ctx, cdptypes.KeyCollateralParams, s.cdpCollateralParams) - permission := types.ParamsChangePermission{ - AllowedParamsChanges: types.AllowedParamsChanges{{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: s.cdpCollateralRequirements, - }}, - } - proposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []paramsproposal.ParamChange{ - { - Subspace: "cdp", - Key: string(cdptypes.KeyCollateralParams), - Value: `[badjson]`, - }, - }, - ) - s.Require().Equal( - false, - permission.Allows(s.ctx, s.pk, proposal), - ) -} - -func (s *ParamsChangeTestSuite) TestAllowedParamsChange_NoSubspaceData() { - permission := types.ParamsChangePermission{ - AllowedParamsChanges: types.AllowedParamsChanges{{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom"}, - }}, - } - proposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []paramsproposal.ParamChange{{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - Value: `{}`, - }}, - ) - s.Require().Panics(func() { - permission.Allows(s.ctx, s.pk, proposal) - }) -} - -func (s *ParamsChangeTestSuite) TestParamsChangePermission_NoAllowedChanged() { - permission := types.ParamsChangePermission{} - proposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []paramsproposal.ParamChange{ - { - Key: string(cdptypes.KeyDebtParam), - Subspace: cdptypes.ModuleName, - Value: `{}`, - }, - }, - ) - s.Require().False(permission.Allows(s.ctx, s.pk, proposal)) -} - -func (s *ParamsChangeTestSuite) TestParamsChangePermission_PassWhenOneAllowed() { - subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) - s.Require().True(found) - subspace.Set(s.ctx, cdptypes.KeyDebtParam, s.cdpDebtParam) - - permission := types.ParamsChangePermission{ - AllowedParamsChanges: types.AllowedParamsChanges{ - { - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom"}, - }, - { - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"reference_asset"}, - }, - }, - } - proposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - // test success if one AllowedParamsChange is allowed and the other is not - []paramsproposal.ParamChange{ - { - Key: string(cdptypes.KeyDebtParam), - Subspace: cdptypes.ModuleName, - Value: `{ - "denom": "usdx", - "reference_asset": "usd2", - "conversion_factor": "6", - "debt_floor": "1000" - }`, - }, - }, - ) - s.Require().True(permission.Allows(s.ctx, s.pk, proposal)) -} - -// Test subparam value with slice data unchanged comparision -func (s *ParamsChangeTestSuite) TestParamsChangePermission_SliceSubparamComparision() { - permission := types.ParamsChangePermission{ - AllowedParamsChanges: types.AllowedParamsChanges{{ - Subspace: pricefeedtypes.ModuleName, - Key: string(pricefeedtypes.KeyMarkets), - MultiSubparamsRequirements: []types.SubparamRequirement{ - { - Key: "market_id", - Val: "xrp:usd", - AllowedSubparamAttrChanges: []string{"quote_asset", "oracles"}, - }, - { - Key: "market_id", - Val: "btc:usd", - AllowedSubparamAttrChanges: []string{"active"}, - }, - }, - }}, - } - _, oracles := app.GeneratePrivKeyAddressPairs(5) - - testcases := []struct { - name string - expected bool - value string - }{ - { - name: "success changing allowed attrs", - expected: true, - value: fmt.Sprintf(`[{ - "market_id": "xrp:usd", - "base_asset": "xrp", - "quote_asset": "usdx", - "oracles": [], - "active": true - }, - { - "market_id": "btc:usd", - "base_asset": "btc", - "quote_asset": "usd", - "oracles": ["%s"], - "active": false - }]`, oracles[1].String()), - }, - { - name: "fails when changing not allowed attr (oracles)", - expected: false, - value: fmt.Sprintf(`[{ - "market_id": "xrp:usd", - "base_asset": "xrp", - "quote_asset": "usdx", - "oracles": ["%s"], - "active": true - }, - { - "market_id": "btc:usd", - "base_asset": "btc", - "quote_asset": "usd", - "oracles": ["%s"], - "active": false - }]`, oracles[0].String(), oracles[2].String()), - }, - } - for _, tc := range testcases { - s.Run(tc.name, func() { - s.SetupTest() - - subspace, found := s.pk.GetSubspace(pricefeedtypes.ModuleName) - s.Require().True(found) - currentMs := pricefeedtypes.Markets{ - {MarketID: "xrp:usd", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: []sdk.AccAddress{oracles[0]}, Active: true}, - {MarketID: "btc:usd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{oracles[1]}, Active: true}, - } - subspace.Set(s.ctx, pricefeedtypes.KeyMarkets, ¤tMs) - - proposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []paramsproposal.ParamChange{{ - Subspace: pricefeedtypes.ModuleName, - Key: string(pricefeedtypes.KeyMarkets), - Value: tc.value, - }}, - ) - s.Require().Equal( - tc.expected, - permission.Allows(s.ctx, s.pk, proposal), - ) - }) - } -} - -func (s *ParamsChangeTestSuite) TestParamsChangePermission_NoSubparamRequirements() { - permission := types.ParamsChangePermission{ - AllowedParamsChanges: types.AllowedParamsChanges{{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeySurplusThreshold), - }}, - } - - testcases := []struct { - name string - expected bool - changes []paramsproposal.ParamChange - }{ - { - name: "success when changing allowed params", - expected: true, - changes: []paramsproposal.ParamChange{{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeySurplusThreshold), - Value: sdkmath.NewInt(120).String(), - }}, - }, - { - name: "fail when changing not allowed params", - expected: false, - changes: []paramsproposal.ParamChange{{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeySurplusLot), - Value: sdkmath.NewInt(120).String(), - }}, - }, - { - name: "fail if one change is not allowed", - expected: false, - changes: []paramsproposal.ParamChange{ - { - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeySurplusThreshold), - Value: sdkmath.NewInt(120).String(), - }, - { - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeySurplusLot), - Value: sdkmath.NewInt(120).String(), - }, - }, - }, - } - - for _, tc := range testcases { - s.Run(tc.name, func() { - s.SetupTest() - - subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) - s.Require().True(found) - subspace.Set(s.ctx, cdptypes.KeySurplusThreshold, sdkmath.NewInt(100)) - subspace.Set(s.ctx, cdptypes.KeySurplusLot, sdkmath.NewInt(110)) - - proposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - tc.changes, - ) - s.Require().Equal( - tc.expected, - permission.Allows(s.ctx, s.pk, proposal), - ) - }) - } -} - -func TestParamsChangeTestSuite(t *testing.T) { - suite.Run(t, new(ParamsChangeTestSuite)) -} - -func TestAllowedParamsChanges_Get(t *testing.T) { - exampleAPCs := types.AllowedParamsChanges{ - { - Subspace: "subspaceA", - Key: "key1", - SingleSubparamAllowedAttrs: []string{"attribute1"}, - }, - { - Subspace: "subspaceA", - Key: "key2", - SingleSubparamAllowedAttrs: []string{"attribute2"}, - }, - } - - type args struct { - subspace, key string - } - testCases := []struct { - name string - apcs types.AllowedParamsChanges - args args - found bool - out types.AllowedParamsChange - }{ - { - name: "when element exists it is found", - apcs: exampleAPCs, - args: args{ - subspace: "subspaceA", - key: "key2", - }, - found: true, - out: exampleAPCs[1], - }, - { - name: "when element doesn't exist it isn't found", - apcs: exampleAPCs, - args: args{ - subspace: "subspaceB", - key: "key1", - }, - found: false, - }, - { - name: "when slice is nil, no elements are found", - apcs: nil, - args: args{ - subspace: "", - key: "", - }, - found: false, - }, - { - name: "when slice is empty, no elements are found", - apcs: types.AllowedParamsChanges{}, - args: args{ - subspace: "subspaceA", - key: "key1", - }, - found: false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - out, found := tc.apcs.Get(tc.args.subspace, tc.args.key) - require.Equal(t, tc.found, found) - require.Equal(t, tc.out, out) - }) - } -} - -func TestAllowedParamsChanges_Set(t *testing.T) { - exampleAPCs := types.AllowedParamsChanges{ - { - Subspace: "subspaceA", - Key: "key1", - SingleSubparamAllowedAttrs: []string{"attribute1"}, - }, - { - Subspace: "subspaceA", - Key: "key2", - SingleSubparamAllowedAttrs: []string{"attribute2"}, - }, - } - - type args struct { - subspace, key string - } - testCases := []struct { - name string - apcs types.AllowedParamsChanges - arg types.AllowedParamsChange - out types.AllowedParamsChanges - }{ - { - name: "when element isn't present it is added", - apcs: exampleAPCs, - arg: types.AllowedParamsChange{ - Subspace: "subspaceB", - Key: "key1", - SingleSubparamAllowedAttrs: []string{"attribute1"}, - }, - out: append(exampleAPCs, types.AllowedParamsChange{ - Subspace: "subspaceB", - Key: "key1", - SingleSubparamAllowedAttrs: []string{"attribute1"}, - }), - }, - { - name: "when element matches, it is overwritten", - apcs: exampleAPCs, - arg: types.AllowedParamsChange{ - Subspace: "subspaceA", - Key: "key2", - SingleSubparamAllowedAttrs: []string{"attribute3"}, - }, - out: types.AllowedParamsChanges{ - { - Subspace: "subspaceA", - Key: "key1", - SingleSubparamAllowedAttrs: []string{"attribute1"}, - }, - { - Subspace: "subspaceA", - Key: "key2", - SingleSubparamAllowedAttrs: []string{"attribute3"}, - }, - }, - }, - { - name: "when element matches, it is overwritten", - apcs: exampleAPCs, - arg: types.AllowedParamsChange{ - Subspace: "subspaceA", - Key: "key2", - SingleSubparamAllowedAttrs: []string{"attribute3"}, - }, - out: types.AllowedParamsChanges{ - { - Subspace: "subspaceA", - Key: "key1", - SingleSubparamAllowedAttrs: []string{"attribute1"}, - }, - { - Subspace: "subspaceA", - Key: "key2", - SingleSubparamAllowedAttrs: []string{"attribute3"}, - }, - }, - }, - { - name: "when slice is nil, elements are added", - apcs: nil, - arg: types.AllowedParamsChange{ - Subspace: "subspaceA", - Key: "key2", - SingleSubparamAllowedAttrs: []string{"attribute3"}, - }, - out: types.AllowedParamsChanges{ - { - Subspace: "subspaceA", - Key: "key2", - SingleSubparamAllowedAttrs: []string{"attribute3"}, - }, - }, - }, - { - name: "when slice is empty, elements are added", - apcs: types.AllowedParamsChanges{}, - arg: types.AllowedParamsChange{ - Subspace: "subspaceA", - Key: "key2", - SingleSubparamAllowedAttrs: []string{"attribute3"}, - }, - out: types.AllowedParamsChanges{ - { - Subspace: "subspaceA", - Key: "key2", - SingleSubparamAllowedAttrs: []string{"attribute3"}, - }, - }, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - (&tc.apcs).Set(tc.arg) - require.Equal(t, tc.out, tc.apcs) - }) - } -} - -func TestAllowedParamsChanges_Delete(t *testing.T) { - exampleAPCs := types.AllowedParamsChanges{ - { - Subspace: "subspaceA", - Key: "key1", - SingleSubparamAllowedAttrs: []string{"attribute1"}, - }, - { - Subspace: "subspaceA", - Key: "key2", - SingleSubparamAllowedAttrs: []string{"attribute2"}, - }, - } - - type args struct { - subspace, key string - } - testCases := []struct { - name string - apcs types.AllowedParamsChanges - args args - out types.AllowedParamsChanges - }{ - { - name: "when element exists it is removed", - apcs: exampleAPCs, - args: args{ - subspace: "subspaceA", - key: "key2", - }, - out: types.AllowedParamsChanges{ - { - Subspace: "subspaceA", - Key: "key1", - SingleSubparamAllowedAttrs: []string{"attribute1"}, - }, - }, - }, - { - name: "when element doesn't exist, none are removed", - apcs: exampleAPCs, - args: args{ - subspace: "subspaceB", - key: "key1", - }, - out: exampleAPCs, - }, - { - name: "when slice is nil, nothing happens", - apcs: nil, - args: args{ - subspace: "subspaceA", - key: "key1", - }, - out: nil, - }, - { - name: "when slice is empty, nothing happens", - apcs: types.AllowedParamsChanges{}, - args: args{ - subspace: "subspaceA", - key: "key1", - }, - out: types.AllowedParamsChanges{}, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - (&tc.apcs).Delete(tc.args.subspace, tc.args.key) - require.Equal(t, tc.out, tc.apcs) - }) - } -} diff --git a/x/committee/types/permissions.go b/x/committee/types/permissions.go deleted file mode 100644 index 3e4d6e77..00000000 --- a/x/committee/types/permissions.go +++ /dev/null @@ -1,314 +0,0 @@ -package types - -import ( - "encoding/json" - fmt "fmt" - "reflect" - "strings" - - "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - paramsproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - proto "github.com/cosmos/gogoproto/proto" - communitytypes "github.com/kava-labs/kava/x/community/types" -) - -// Permission is anything with a method that validates whether a proposal is allowed by it or not. -type Permission interface { - Allows(sdk.Context, ParamKeeper, PubProposal) bool -} - -func PackPermissions(permissions []Permission) ([]*types.Any, error) { - permissionsAny := make([]*types.Any, len(permissions)) - for i, permission := range permissions { - msg, ok := permission.(proto.Message) - if !ok { - return nil, fmt.Errorf("cannot proto marshal %T", permission) - } - any, err := types.NewAnyWithValue(msg) - if err != nil { - return nil, err - } - permissionsAny[i] = any - } - return permissionsAny, nil -} - -func UnpackPermissions(permissionsAny []*types.Any) ([]Permission, error) { - permissions := make([]Permission, len(permissionsAny)) - for i, any := range permissionsAny { - permission, ok := any.GetCachedValue().(Permission) - if !ok { - return nil, fmt.Errorf("expected base committee permission") - } - permissions[i] = permission - } - - return permissions, nil -} - -var ( - _ Permission = GodPermission{} - _ Permission = TextPermission{} - _ Permission = SoftwareUpgradePermission{} - _ Permission = ParamsChangePermission{} - _ Permission = CommunityCDPRepayDebtPermission{} - _ Permission = CommunityPoolLendWithdrawPermission{} - _ Permission = CommunityCDPWithdrawCollateralPermission{} -) - -// Allows implement permission interface for GodPermission. -func (GodPermission) Allows(sdk.Context, ParamKeeper, PubProposal) bool { return true } - -// Allows implement permission interface for TextPermission. -func (TextPermission) Allows(_ sdk.Context, _ ParamKeeper, p PubProposal) bool { - _, ok := p.(*govv1beta1.TextProposal) - return ok -} - -// Allows implement permission interface for SoftwareUpgradePermission. -func (SoftwareUpgradePermission) Allows(_ sdk.Context, _ ParamKeeper, p PubProposal) bool { - _, ok := p.(*upgradetypes.SoftwareUpgradeProposal) - return ok -} - -// Allows implement permission interface for CommunityCDPRepayDebtPermission. -func (CommunityCDPRepayDebtPermission) Allows(_ sdk.Context, _ ParamKeeper, p PubProposal) bool { - _, ok := p.(*communitytypes.CommunityCDPRepayDebtProposal) - return ok -} - -// Allows implement permission interface for CommunityCDPWithdrawCollateralPermission. -func (CommunityCDPWithdrawCollateralPermission) Allows(_ sdk.Context, _ ParamKeeper, p PubProposal) bool { - _, ok := p.(*communitytypes.CommunityCDPWithdrawCollateralProposal) - return ok -} - -// Allows implement permission interface for CommunityPoolLendWithdrawPermission. -func (CommunityPoolLendWithdrawPermission) Allows(_ sdk.Context, _ ParamKeeper, p PubProposal) bool { - _, ok := p.(*communitytypes.CommunityPoolLendWithdrawProposal) - return ok -} - -// Allows implement permission interface for ParamsChangePermission. -func (perm ParamsChangePermission) Allows(ctx sdk.Context, pk ParamKeeper, p PubProposal) bool { - proposal, ok := p.(*paramsproposal.ParameterChangeProposal) - if !ok { - return false - } - - // Check if all proposal changes are allowed by this permission. - for _, change := range proposal.Changes { - targetedParamsChange := perm.AllowedParamsChanges.filterByParamChange(change) - - // We allow the proposal param change if any of the targeted AllowedParamsChange allows it. - // This give the option of having multiple rules for the same subspace/key if needed. - allowed := false - for _, pc := range targetedParamsChange { - if pc.allowsParamChange(ctx, change, pk) { - allowed = true - break - } - } - - // If no target param change allows the proposed change, then the proposal is rejected. - if !allowed { - return false - } - } - - return true -} - -type AllowedParamsChanges []AllowedParamsChange - -// Get searches the allowedParamsChange slice for the first item matching a subspace and key. -// It returns false if not found. -func (changes AllowedParamsChanges) Get(subspace, key string) (AllowedParamsChange, bool) { - for _, apc := range changes { - if apc.Subspace == subspace && apc.Key == key { - return apc, true - } - } - return AllowedParamsChange{}, false -} - -// Set adds a new AllowedParamsChange, overwriting the first exiting item with matching subspace and key. -func (changes *AllowedParamsChanges) Set(newChange AllowedParamsChange) { - for i, apc := range *changes { - if apc.Subspace == newChange.Subspace && apc.Key == newChange.Key { - (*changes)[i] = newChange - return - } - } - *changes = append(*changes, newChange) -} - -// Delete removes the first AllowedParamsChange matching subspace and key. -func (changes *AllowedParamsChanges) Delete(subspace, key string) { - var found bool - var foundAt int - - for i, apc := range *changes { - if apc.Subspace == subspace && apc.Key == key { - found = true - foundAt = i - break - } - } - if !found { - return - } - *changes = append( - (*changes)[:foundAt], - (*changes)[foundAt+1:]..., - ) -} - -// filterByParamChange returns all targeted AllowedParamsChange that matches a given ParamChange's subspace and key. -func (changes AllowedParamsChanges) filterByParamChange(paramChange paramsproposal.ParamChange) AllowedParamsChanges { - filtered := []AllowedParamsChange{} - for _, p := range changes { - if paramChange.Subspace == p.Subspace && paramChange.Key == p.Key { - filtered = append(filtered, p) - } - } - return filtered -} - -// SubparamChanges is a map of sub param change keys and its values. -type SubparamChanges map[string]interface{} - -// MultiSubparamChanges is a slice of SubparamChanges. -type MultiSubparamChanges []SubparamChanges - -func (allowed AllowedParamsChange) allowsMultiParamsChange(currentRecords MultiSubparamChanges, incomingRecords MultiSubparamChanges) bool { - // do not allow new records from being added or removed for multi-subparam changes. - if len(currentRecords) != len(incomingRecords) { - return false - } - - for _, current := range currentRecords { - // find the incoming record and the requirements for each current record - var req *SubparamRequirement - var incoming *SubparamChanges - for _, v := range allowed.MultiSubparamsRequirements { - if current[v.Key] == v.Val { - req = &v - break - } - } - - // all records should have a requirement, otherwise the change is not allowed - if req == nil { - return false - } - - for _, v := range incomingRecords { - if v[req.Key] == req.Val { - incoming = &v - break - } - } - - // disallow the change if no incoming record found for current record. - if incoming == nil { - return false - } - - // check incoming changes are allowed - allowed := validateParamChangesAreAllowed(current, *incoming, req.AllowedSubparamAttrChanges) - - if !allowed { - return false - } - } - - return true -} - -func validateParamChangesAreAllowed(current SubparamChanges, incoming SubparamChanges, allowList []string) bool { - // make sure we are not adding or removing any new attributes - if len(current) != len(incoming) { - return false - } - - // Warning: ranging over maps iterates through keys in a random order. - // All state machine code must be deterministic between validators. - // This function's output is deterministic despite the range. - for k, v := range current { - isAllowed := false - - // check if the param attr key is in the allow list - for _, allowedKey := range allowList { - if k == allowedKey { - isAllowed = true - break - } - } - - // if not allowed, incoming value needs to be the same, or it is rejected - if !isAllowed && !reflect.DeepEqual(v, incoming[k]) { - return false - } - } - - return true -} - -func (allowed AllowedParamsChange) allowsSingleParamsChange(current SubparamChanges, incoming SubparamChanges) bool { - return validateParamChangesAreAllowed(current, incoming, allowed.SingleSubparamAllowedAttrs) -} - -// allowsParamChange returns true if the given proposal param change is allowed by the AllowedParamsChange rules. -func (allowed AllowedParamsChange) allowsParamChange(ctx sdk.Context, paramsChange paramsproposal.ParamChange, pk ParamKeeper) bool { - // Check if param change matches target subspace and key. - if allowed.Subspace != paramsChange.Subspace && allowed.Key != paramsChange.Key { - return false - } - - // Allow all param changes if no subparam rules are specified. - if len(allowed.SingleSubparamAllowedAttrs) == 0 && len(allowed.MultiSubparamsRequirements) == 0 { - return true - } - - subspace, found := pk.GetSubspace(paramsChange.Subspace) - if !found { - return false - } - currentRaw := subspace.GetRaw(ctx, []byte(paramsChange.Key)) - - // Check if current param value is an array before unmarshalling to corresponding types - tdata := strings.TrimLeft(string(currentRaw), "\t\r\n") - isArray := len(tdata) > 0 && tdata[0] == '[' - - // Handle multi param value validation - if isArray { - var changeValue MultiSubparamChanges - if err := json.Unmarshal([]byte(paramsChange.Value), &changeValue); err != nil { - return false - } - - var currentValue MultiSubparamChanges - if err := json.Unmarshal(currentRaw, ¤tValue); err != nil { - panic(err) - } - - return allowed.allowsMultiParamsChange(currentValue, changeValue) - } - - // Handle single param value validation - var changeValue SubparamChanges - if err := json.Unmarshal([]byte(paramsChange.Value), &changeValue); err != nil { - return false - } - - var currentValue SubparamChanges - if err := json.Unmarshal(currentRaw, ¤tValue); err != nil { - panic(err) - } - - return allowed.allowsSingleParamsChange(currentValue, changeValue) -} diff --git a/x/committee/types/permissions.pb.go b/x/committee/types/permissions.pb.go deleted file mode 100644 index 6b570947..00000000 --- a/x/committee/types/permissions.pb.go +++ /dev/null @@ -1,1697 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/committee/v1beta1/permissions.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - _ "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 - -// GodPermission allows any governance proposal. It is used mainly for testing. -type GodPermission struct { -} - -func (m *GodPermission) Reset() { *m = GodPermission{} } -func (m *GodPermission) String() string { return proto.CompactTextString(m) } -func (*GodPermission) ProtoMessage() {} -func (*GodPermission) Descriptor() ([]byte, []int) { - return fileDescriptor_bdfaf7be16465ae4, []int{0} -} -func (m *GodPermission) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GodPermission) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GodPermission.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 *GodPermission) XXX_Merge(src proto.Message) { - xxx_messageInfo_GodPermission.Merge(m, src) -} -func (m *GodPermission) XXX_Size() int { - return m.Size() -} -func (m *GodPermission) XXX_DiscardUnknown() { - xxx_messageInfo_GodPermission.DiscardUnknown(m) -} - -var xxx_messageInfo_GodPermission proto.InternalMessageInfo - -// SoftwareUpgradePermission permission type for software upgrade proposals -type SoftwareUpgradePermission struct { -} - -func (m *SoftwareUpgradePermission) Reset() { *m = SoftwareUpgradePermission{} } -func (m *SoftwareUpgradePermission) String() string { return proto.CompactTextString(m) } -func (*SoftwareUpgradePermission) ProtoMessage() {} -func (*SoftwareUpgradePermission) Descriptor() ([]byte, []int) { - return fileDescriptor_bdfaf7be16465ae4, []int{1} -} -func (m *SoftwareUpgradePermission) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SoftwareUpgradePermission) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SoftwareUpgradePermission.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 *SoftwareUpgradePermission) XXX_Merge(src proto.Message) { - xxx_messageInfo_SoftwareUpgradePermission.Merge(m, src) -} -func (m *SoftwareUpgradePermission) XXX_Size() int { - return m.Size() -} -func (m *SoftwareUpgradePermission) XXX_DiscardUnknown() { - xxx_messageInfo_SoftwareUpgradePermission.DiscardUnknown(m) -} - -var xxx_messageInfo_SoftwareUpgradePermission proto.InternalMessageInfo - -// TextPermission allows any text governance proposal. -type TextPermission struct { -} - -func (m *TextPermission) Reset() { *m = TextPermission{} } -func (m *TextPermission) String() string { return proto.CompactTextString(m) } -func (*TextPermission) ProtoMessage() {} -func (*TextPermission) Descriptor() ([]byte, []int) { - return fileDescriptor_bdfaf7be16465ae4, []int{2} -} -func (m *TextPermission) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TextPermission) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TextPermission.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 *TextPermission) XXX_Merge(src proto.Message) { - xxx_messageInfo_TextPermission.Merge(m, src) -} -func (m *TextPermission) XXX_Size() int { - return m.Size() -} -func (m *TextPermission) XXX_DiscardUnknown() { - xxx_messageInfo_TextPermission.DiscardUnknown(m) -} - -var xxx_messageInfo_TextPermission proto.InternalMessageInfo - -// CommunityCDPRepayDebtPermission allows submission of CommunityCDPRepayDebtProposal -type CommunityCDPRepayDebtPermission struct { -} - -func (m *CommunityCDPRepayDebtPermission) Reset() { *m = CommunityCDPRepayDebtPermission{} } -func (m *CommunityCDPRepayDebtPermission) String() string { return proto.CompactTextString(m) } -func (*CommunityCDPRepayDebtPermission) ProtoMessage() {} -func (*CommunityCDPRepayDebtPermission) Descriptor() ([]byte, []int) { - return fileDescriptor_bdfaf7be16465ae4, []int{3} -} -func (m *CommunityCDPRepayDebtPermission) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityCDPRepayDebtPermission) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityCDPRepayDebtPermission.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 *CommunityCDPRepayDebtPermission) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityCDPRepayDebtPermission.Merge(m, src) -} -func (m *CommunityCDPRepayDebtPermission) XXX_Size() int { - return m.Size() -} -func (m *CommunityCDPRepayDebtPermission) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityCDPRepayDebtPermission.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityCDPRepayDebtPermission proto.InternalMessageInfo - -// CommunityCDPWithdrawCollateralPermission allows submission of CommunityCDPWithdrawCollateralProposal -type CommunityCDPWithdrawCollateralPermission struct { -} - -func (m *CommunityCDPWithdrawCollateralPermission) Reset() { - *m = CommunityCDPWithdrawCollateralPermission{} -} -func (m *CommunityCDPWithdrawCollateralPermission) String() string { return proto.CompactTextString(m) } -func (*CommunityCDPWithdrawCollateralPermission) ProtoMessage() {} -func (*CommunityCDPWithdrawCollateralPermission) Descriptor() ([]byte, []int) { - return fileDescriptor_bdfaf7be16465ae4, []int{4} -} -func (m *CommunityCDPWithdrawCollateralPermission) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityCDPWithdrawCollateralPermission) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityCDPWithdrawCollateralPermission.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 *CommunityCDPWithdrawCollateralPermission) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityCDPWithdrawCollateralPermission.Merge(m, src) -} -func (m *CommunityCDPWithdrawCollateralPermission) XXX_Size() int { - return m.Size() -} -func (m *CommunityCDPWithdrawCollateralPermission) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityCDPWithdrawCollateralPermission.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityCDPWithdrawCollateralPermission proto.InternalMessageInfo - -// CommunityPoolLendWithdrawPermission allows submission of CommunityPoolLendWithdrawProposal -type CommunityPoolLendWithdrawPermission struct { -} - -func (m *CommunityPoolLendWithdrawPermission) Reset() { *m = CommunityPoolLendWithdrawPermission{} } -func (m *CommunityPoolLendWithdrawPermission) String() string { return proto.CompactTextString(m) } -func (*CommunityPoolLendWithdrawPermission) ProtoMessage() {} -func (*CommunityPoolLendWithdrawPermission) Descriptor() ([]byte, []int) { - return fileDescriptor_bdfaf7be16465ae4, []int{5} -} -func (m *CommunityPoolLendWithdrawPermission) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolLendWithdrawPermission) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolLendWithdrawPermission.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 *CommunityPoolLendWithdrawPermission) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolLendWithdrawPermission.Merge(m, src) -} -func (m *CommunityPoolLendWithdrawPermission) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolLendWithdrawPermission) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolLendWithdrawPermission.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolLendWithdrawPermission proto.InternalMessageInfo - -// ParamsChangePermission allows any parameter or sub parameter change proposal. -type ParamsChangePermission struct { - AllowedParamsChanges AllowedParamsChanges `protobuf:"bytes,1,rep,name=allowed_params_changes,json=allowedParamsChanges,proto3,castrepeated=AllowedParamsChanges" json:"allowed_params_changes"` -} - -func (m *ParamsChangePermission) Reset() { *m = ParamsChangePermission{} } -func (m *ParamsChangePermission) String() string { return proto.CompactTextString(m) } -func (*ParamsChangePermission) ProtoMessage() {} -func (*ParamsChangePermission) Descriptor() ([]byte, []int) { - return fileDescriptor_bdfaf7be16465ae4, []int{6} -} -func (m *ParamsChangePermission) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ParamsChangePermission) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ParamsChangePermission.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 *ParamsChangePermission) XXX_Merge(src proto.Message) { - xxx_messageInfo_ParamsChangePermission.Merge(m, src) -} -func (m *ParamsChangePermission) XXX_Size() int { - return m.Size() -} -func (m *ParamsChangePermission) XXX_DiscardUnknown() { - xxx_messageInfo_ParamsChangePermission.DiscardUnknown(m) -} - -var xxx_messageInfo_ParamsChangePermission proto.InternalMessageInfo - -func (m *ParamsChangePermission) GetAllowedParamsChanges() AllowedParamsChanges { - if m != nil { - return m.AllowedParamsChanges - } - return nil -} - -// AllowedParamsChange contains data on the allowed parameter changes for subspace, key, and sub params requirements. -type AllowedParamsChange struct { - Subspace string `protobuf:"bytes,1,opt,name=subspace,proto3" json:"subspace,omitempty"` - Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"` - // Requirements for when the subparam value is a single record. This contains list of allowed attribute keys that can - // be changed on the subparam record. - SingleSubparamAllowedAttrs []string `protobuf:"bytes,3,rep,name=single_subparam_allowed_attrs,json=singleSubparamAllowedAttrs,proto3" json:"single_subparam_allowed_attrs,omitempty"` - // Requirements for when the subparam value is a list of records. The requirements contains requirements for each - // record in the list. - MultiSubparamsRequirements []SubparamRequirement `protobuf:"bytes,4,rep,name=multi_subparams_requirements,json=multiSubparamsRequirements,proto3" json:"multi_subparams_requirements"` -} - -func (m *AllowedParamsChange) Reset() { *m = AllowedParamsChange{} } -func (m *AllowedParamsChange) String() string { return proto.CompactTextString(m) } -func (*AllowedParamsChange) ProtoMessage() {} -func (*AllowedParamsChange) Descriptor() ([]byte, []int) { - return fileDescriptor_bdfaf7be16465ae4, []int{7} -} -func (m *AllowedParamsChange) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AllowedParamsChange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AllowedParamsChange.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 *AllowedParamsChange) XXX_Merge(src proto.Message) { - xxx_messageInfo_AllowedParamsChange.Merge(m, src) -} -func (m *AllowedParamsChange) XXX_Size() int { - return m.Size() -} -func (m *AllowedParamsChange) XXX_DiscardUnknown() { - xxx_messageInfo_AllowedParamsChange.DiscardUnknown(m) -} - -var xxx_messageInfo_AllowedParamsChange proto.InternalMessageInfo - -func (m *AllowedParamsChange) GetSubspace() string { - if m != nil { - return m.Subspace - } - return "" -} - -func (m *AllowedParamsChange) GetKey() string { - if m != nil { - return m.Key - } - return "" -} - -func (m *AllowedParamsChange) GetSingleSubparamAllowedAttrs() []string { - if m != nil { - return m.SingleSubparamAllowedAttrs - } - return nil -} - -func (m *AllowedParamsChange) GetMultiSubparamsRequirements() []SubparamRequirement { - if m != nil { - return m.MultiSubparamsRequirements - } - return nil -} - -// SubparamRequirement contains requirements for a single record in a subparam value list -type SubparamRequirement struct { - // The required attr key of the param record. - Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` - // The required param value for the param record key. The key and value is used to match to the target param record. - Val string `protobuf:"bytes,2,opt,name=val,proto3" json:"val,omitempty"` - // The sub param attrs that are allowed to be changed. - AllowedSubparamAttrChanges []string `protobuf:"bytes,3,rep,name=allowed_subparam_attr_changes,json=allowedSubparamAttrChanges,proto3" json:"allowed_subparam_attr_changes,omitempty"` -} - -func (m *SubparamRequirement) Reset() { *m = SubparamRequirement{} } -func (m *SubparamRequirement) String() string { return proto.CompactTextString(m) } -func (*SubparamRequirement) ProtoMessage() {} -func (*SubparamRequirement) Descriptor() ([]byte, []int) { - return fileDescriptor_bdfaf7be16465ae4, []int{8} -} -func (m *SubparamRequirement) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SubparamRequirement) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SubparamRequirement.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 *SubparamRequirement) XXX_Merge(src proto.Message) { - xxx_messageInfo_SubparamRequirement.Merge(m, src) -} -func (m *SubparamRequirement) XXX_Size() int { - return m.Size() -} -func (m *SubparamRequirement) XXX_DiscardUnknown() { - xxx_messageInfo_SubparamRequirement.DiscardUnknown(m) -} - -var xxx_messageInfo_SubparamRequirement proto.InternalMessageInfo - -func (m *SubparamRequirement) GetKey() string { - if m != nil { - return m.Key - } - return "" -} - -func (m *SubparamRequirement) GetVal() string { - if m != nil { - return m.Val - } - return "" -} - -func (m *SubparamRequirement) GetAllowedSubparamAttrChanges() []string { - if m != nil { - return m.AllowedSubparamAttrChanges - } - return nil -} - -func init() { - proto.RegisterType((*GodPermission)(nil), "kava.committee.v1beta1.GodPermission") - proto.RegisterType((*SoftwareUpgradePermission)(nil), "kava.committee.v1beta1.SoftwareUpgradePermission") - proto.RegisterType((*TextPermission)(nil), "kava.committee.v1beta1.TextPermission") - proto.RegisterType((*CommunityCDPRepayDebtPermission)(nil), "kava.committee.v1beta1.CommunityCDPRepayDebtPermission") - proto.RegisterType((*CommunityCDPWithdrawCollateralPermission)(nil), "kava.committee.v1beta1.CommunityCDPWithdrawCollateralPermission") - proto.RegisterType((*CommunityPoolLendWithdrawPermission)(nil), "kava.committee.v1beta1.CommunityPoolLendWithdrawPermission") - proto.RegisterType((*ParamsChangePermission)(nil), "kava.committee.v1beta1.ParamsChangePermission") - proto.RegisterType((*AllowedParamsChange)(nil), "kava.committee.v1beta1.AllowedParamsChange") - proto.RegisterType((*SubparamRequirement)(nil), "kava.committee.v1beta1.SubparamRequirement") -} - -func init() { - proto.RegisterFile("kava/committee/v1beta1/permissions.proto", fileDescriptor_bdfaf7be16465ae4) -} - -var fileDescriptor_bdfaf7be16465ae4 = []byte{ - // 507 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x93, 0x4f, 0x8b, 0xd3, 0x40, - 0x18, 0x87, 0x1b, 0xb3, 0x88, 0x3b, 0xe2, 0xb2, 0x64, 0x4b, 0xc9, 0x86, 0x35, 0x2d, 0xf5, 0x12, - 0x28, 0x9b, 0x50, 0xc5, 0xcb, 0xde, 0xda, 0xae, 0x78, 0xf1, 0x50, 0xb2, 0x8a, 0xe0, 0x25, 0x4c, - 0x9a, 0x31, 0x0d, 0x3b, 0xc9, 0xc4, 0x79, 0x27, 0xed, 0x16, 0x04, 0xbf, 0x82, 0x5f, 0x43, 0xcf, - 0x7e, 0x88, 0xc5, 0xd3, 0x1e, 0x3d, 0xa9, 0xb4, 0x1f, 0xc3, 0x8b, 0xe4, 0x6f, 0x03, 0x1b, 0x72, - 0x9b, 0x79, 0xf3, 0xfc, 0xde, 0xc9, 0x33, 0x2f, 0x83, 0x8c, 0x6b, 0xbc, 0xc2, 0xd6, 0x82, 0x85, - 0x61, 0x20, 0x04, 0x21, 0xd6, 0x6a, 0xec, 0x12, 0x81, 0xc7, 0x56, 0x4c, 0x78, 0x18, 0x00, 0x04, - 0x2c, 0x02, 0x33, 0xe6, 0x4c, 0x30, 0xa5, 0x97, 0x92, 0x66, 0x45, 0x9a, 0x05, 0xa9, 0x9d, 0x2e, - 0x18, 0x84, 0x0c, 0x9c, 0x8c, 0xb2, 0xf2, 0x4d, 0x1e, 0xd1, 0xba, 0x3e, 0xf3, 0x59, 0x5e, 0x4f, - 0x57, 0x79, 0x75, 0xd8, 0x47, 0x4f, 0x5e, 0x33, 0x6f, 0x5e, 0x1d, 0x70, 0x71, 0xf4, 0xf3, 0xc7, - 0x39, 0xda, 0xef, 0x87, 0x23, 0x74, 0x7a, 0xc5, 0x3e, 0x8a, 0x35, 0xe6, 0xe4, 0x5d, 0xec, 0x73, - 0xec, 0x91, 0x16, 0x78, 0x80, 0x8e, 0xde, 0x92, 0x1b, 0xd1, 0x42, 0x8c, 0x51, 0x7f, 0xc6, 0xc2, - 0x30, 0x89, 0x02, 0xb1, 0x99, 0x5d, 0xce, 0x6d, 0x12, 0xe3, 0xcd, 0x25, 0x71, 0xdb, 0x22, 0x17, - 0xc8, 0xa8, 0x47, 0xde, 0x07, 0x62, 0xe9, 0x71, 0xbc, 0x9e, 0x31, 0x4a, 0xb1, 0x20, 0x1c, 0xd3, - 0x96, 0xec, 0x4b, 0xf4, 0xac, 0xca, 0xce, 0x19, 0xa3, 0x6f, 0x48, 0xe4, 0x95, 0x0d, 0x5a, 0x62, - 0xdf, 0x24, 0xd4, 0x9b, 0x63, 0x8e, 0x43, 0x98, 0x2d, 0x71, 0xe4, 0xd7, 0x94, 0x95, 0x2f, 0xa8, - 0x87, 0x29, 0x65, 0x6b, 0xe2, 0x39, 0x71, 0x46, 0x38, 0x8b, 0x0c, 0x01, 0x55, 0x1a, 0xc8, 0xc6, - 0xe3, 0xe7, 0x23, 0xb3, 0x79, 0x34, 0xe6, 0x24, 0x4f, 0xd5, 0xdb, 0x4e, 0xcf, 0x6e, 0x7f, 0xf7, - 0x3b, 0xdf, 0xff, 0xf4, 0xbb, 0x0d, 0x1f, 0xc1, 0xee, 0xe2, 0x86, 0xea, 0xbd, 0x7f, 0xfd, 0x27, - 0xa1, 0x93, 0x86, 0xb8, 0xa2, 0xa1, 0x47, 0x90, 0xb8, 0x10, 0xe3, 0x05, 0x51, 0xa5, 0x81, 0x64, - 0x1c, 0xda, 0xd5, 0x5e, 0x39, 0x46, 0xf2, 0x35, 0xd9, 0xa8, 0x0f, 0xb2, 0x72, 0xba, 0x54, 0x26, - 0xe8, 0x29, 0x04, 0x91, 0x4f, 0x89, 0x03, 0x89, 0x9b, 0x89, 0x39, 0xa5, 0x26, 0x16, 0x82, 0x83, - 0x2a, 0x0f, 0x64, 0xe3, 0xd0, 0xd6, 0x72, 0xe8, 0xaa, 0x60, 0x8a, 0x73, 0x27, 0x29, 0xa1, 0x00, - 0x3a, 0x0b, 0x13, 0x2a, 0x82, 0xaa, 0x03, 0x38, 0x9c, 0x7c, 0x4a, 0x02, 0x4e, 0x42, 0x12, 0x09, - 0x50, 0x0f, 0xda, 0xef, 0xa7, 0xec, 0x69, 0xef, 0x33, 0xd3, 0x83, 0xf4, 0x7e, 0x6c, 0x2d, 0x6b, - 0x5b, 0x7e, 0x87, 0x1a, 0x00, 0xc3, 0xcf, 0xe8, 0xa4, 0x21, 0x58, 0x0a, 0x4a, 0x7b, 0xc1, 0x63, - 0x24, 0xaf, 0x30, 0x2d, 0x95, 0x57, 0x98, 0xa6, 0xca, 0xa5, 0xe2, 0xde, 0x59, 0x08, 0x5e, 0x0d, - 0xb4, 0x50, 0x2e, 0xa0, 0xca, 0x59, 0x08, 0x5e, 0xcc, 0x62, 0xfa, 0xea, 0x76, 0xab, 0x4b, 0x77, - 0x5b, 0x5d, 0xfa, 0xbb, 0xd5, 0xa5, 0xaf, 0x3b, 0xbd, 0x73, 0xb7, 0xd3, 0x3b, 0xbf, 0x76, 0x7a, - 0xe7, 0xc3, 0xc8, 0x0f, 0xc4, 0x32, 0x71, 0x53, 0x4f, 0x2b, 0x15, 0x3e, 0xa7, 0xd8, 0x85, 0x6c, - 0x65, 0xdd, 0xd4, 0x5e, 0xb8, 0xd8, 0xc4, 0x04, 0xdc, 0x87, 0xd9, 0x5b, 0x7c, 0xf1, 0x3f, 0x00, - 0x00, 0xff, 0xff, 0x64, 0xe8, 0xa8, 0x0a, 0x00, 0x04, 0x00, 0x00, -} - -func (m *GodPermission) 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 *GodPermission) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GodPermission) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *SoftwareUpgradePermission) 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 *SoftwareUpgradePermission) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SoftwareUpgradePermission) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *TextPermission) 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 *TextPermission) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TextPermission) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *CommunityCDPRepayDebtPermission) 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 *CommunityCDPRepayDebtPermission) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityCDPRepayDebtPermission) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *CommunityCDPWithdrawCollateralPermission) 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 *CommunityCDPWithdrawCollateralPermission) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityCDPWithdrawCollateralPermission) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *CommunityPoolLendWithdrawPermission) 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 *CommunityPoolLendWithdrawPermission) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolLendWithdrawPermission) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *ParamsChangePermission) 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 *ParamsChangePermission) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ParamsChangePermission) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.AllowedParamsChanges) > 0 { - for iNdEx := len(m.AllowedParamsChanges) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.AllowedParamsChanges[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintPermissions(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *AllowedParamsChange) 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 *AllowedParamsChange) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AllowedParamsChange) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.MultiSubparamsRequirements) > 0 { - for iNdEx := len(m.MultiSubparamsRequirements) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.MultiSubparamsRequirements[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintPermissions(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.SingleSubparamAllowedAttrs) > 0 { - for iNdEx := len(m.SingleSubparamAllowedAttrs) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.SingleSubparamAllowedAttrs[iNdEx]) - copy(dAtA[i:], m.SingleSubparamAllowedAttrs[iNdEx]) - i = encodeVarintPermissions(dAtA, i, uint64(len(m.SingleSubparamAllowedAttrs[iNdEx]))) - i-- - dAtA[i] = 0x1a - } - } - if len(m.Key) > 0 { - i -= len(m.Key) - copy(dAtA[i:], m.Key) - i = encodeVarintPermissions(dAtA, i, uint64(len(m.Key))) - i-- - dAtA[i] = 0x12 - } - if len(m.Subspace) > 0 { - i -= len(m.Subspace) - copy(dAtA[i:], m.Subspace) - i = encodeVarintPermissions(dAtA, i, uint64(len(m.Subspace))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *SubparamRequirement) 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 *SubparamRequirement) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SubparamRequirement) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.AllowedSubparamAttrChanges) > 0 { - for iNdEx := len(m.AllowedSubparamAttrChanges) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.AllowedSubparamAttrChanges[iNdEx]) - copy(dAtA[i:], m.AllowedSubparamAttrChanges[iNdEx]) - i = encodeVarintPermissions(dAtA, i, uint64(len(m.AllowedSubparamAttrChanges[iNdEx]))) - i-- - dAtA[i] = 0x1a - } - } - if len(m.Val) > 0 { - i -= len(m.Val) - copy(dAtA[i:], m.Val) - i = encodeVarintPermissions(dAtA, i, uint64(len(m.Val))) - i-- - dAtA[i] = 0x12 - } - if len(m.Key) > 0 { - i -= len(m.Key) - copy(dAtA[i:], m.Key) - i = encodeVarintPermissions(dAtA, i, uint64(len(m.Key))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintPermissions(dAtA []byte, offset int, v uint64) int { - offset -= sovPermissions(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *GodPermission) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *SoftwareUpgradePermission) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *TextPermission) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *CommunityCDPRepayDebtPermission) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *CommunityCDPWithdrawCollateralPermission) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *CommunityPoolLendWithdrawPermission) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *ParamsChangePermission) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.AllowedParamsChanges) > 0 { - for _, e := range m.AllowedParamsChanges { - l = e.Size() - n += 1 + l + sovPermissions(uint64(l)) - } - } - return n -} - -func (m *AllowedParamsChange) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Subspace) - if l > 0 { - n += 1 + l + sovPermissions(uint64(l)) - } - l = len(m.Key) - if l > 0 { - n += 1 + l + sovPermissions(uint64(l)) - } - if len(m.SingleSubparamAllowedAttrs) > 0 { - for _, s := range m.SingleSubparamAllowedAttrs { - l = len(s) - n += 1 + l + sovPermissions(uint64(l)) - } - } - if len(m.MultiSubparamsRequirements) > 0 { - for _, e := range m.MultiSubparamsRequirements { - l = e.Size() - n += 1 + l + sovPermissions(uint64(l)) - } - } - return n -} - -func (m *SubparamRequirement) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Key) - if l > 0 { - n += 1 + l + sovPermissions(uint64(l)) - } - l = len(m.Val) - if l > 0 { - n += 1 + l + sovPermissions(uint64(l)) - } - if len(m.AllowedSubparamAttrChanges) > 0 { - for _, s := range m.AllowedSubparamAttrChanges { - l = len(s) - n += 1 + l + sovPermissions(uint64(l)) - } - } - return n -} - -func sovPermissions(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozPermissions(x uint64) (n int) { - return sovPermissions(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *GodPermission) 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 ErrIntOverflowPermissions - } - 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: GodPermission: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GodPermission: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipPermissions(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthPermissions - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *SoftwareUpgradePermission) 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 ErrIntOverflowPermissions - } - 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: SoftwareUpgradePermission: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SoftwareUpgradePermission: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipPermissions(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthPermissions - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TextPermission) 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 ErrIntOverflowPermissions - } - 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: TextPermission: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TextPermission: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipPermissions(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthPermissions - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityCDPRepayDebtPermission) 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 ErrIntOverflowPermissions - } - 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: CommunityCDPRepayDebtPermission: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityCDPRepayDebtPermission: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipPermissions(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthPermissions - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityCDPWithdrawCollateralPermission) 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 ErrIntOverflowPermissions - } - 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: CommunityCDPWithdrawCollateralPermission: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityCDPWithdrawCollateralPermission: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipPermissions(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthPermissions - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityPoolLendWithdrawPermission) 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 ErrIntOverflowPermissions - } - 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: CommunityPoolLendWithdrawPermission: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolLendWithdrawPermission: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipPermissions(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthPermissions - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ParamsChangePermission) 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 ErrIntOverflowPermissions - } - 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: ParamsChangePermission: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ParamsChangePermission: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AllowedParamsChanges", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPermissions - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthPermissions - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthPermissions - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AllowedParamsChanges = append(m.AllowedParamsChanges, AllowedParamsChange{}) - if err := m.AllowedParamsChanges[len(m.AllowedParamsChanges)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipPermissions(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthPermissions - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *AllowedParamsChange) 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 ErrIntOverflowPermissions - } - 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: AllowedParamsChange: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AllowedParamsChange: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Subspace", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPermissions - } - 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 ErrInvalidLengthPermissions - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthPermissions - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Subspace = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPermissions - } - 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 ErrInvalidLengthPermissions - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthPermissions - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Key = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SingleSubparamAllowedAttrs", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPermissions - } - 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 ErrInvalidLengthPermissions - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthPermissions - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SingleSubparamAllowedAttrs = append(m.SingleSubparamAllowedAttrs, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MultiSubparamsRequirements", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPermissions - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthPermissions - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthPermissions - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MultiSubparamsRequirements = append(m.MultiSubparamsRequirements, SubparamRequirement{}) - if err := m.MultiSubparamsRequirements[len(m.MultiSubparamsRequirements)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipPermissions(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthPermissions - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *SubparamRequirement) 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 ErrIntOverflowPermissions - } - 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: SubparamRequirement: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SubparamRequirement: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPermissions - } - 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 ErrInvalidLengthPermissions - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthPermissions - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Key = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Val", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPermissions - } - 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 ErrInvalidLengthPermissions - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthPermissions - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Val = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AllowedSubparamAttrChanges", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPermissions - } - 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 ErrInvalidLengthPermissions - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthPermissions - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AllowedSubparamAttrChanges = append(m.AllowedSubparamAttrChanges, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipPermissions(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthPermissions - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipPermissions(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, ErrIntOverflowPermissions - } - 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, ErrIntOverflowPermissions - } - 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, ErrIntOverflowPermissions - } - 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, ErrInvalidLengthPermissions - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupPermissions - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthPermissions - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthPermissions = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowPermissions = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupPermissions = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/committee/types/permissions_test.go b/x/committee/types/permissions_test.go deleted file mode 100644 index 2fe4c8a8..00000000 --- a/x/committee/types/permissions_test.go +++ /dev/null @@ -1,302 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - paramsproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - - "github.com/kava-labs/kava/x/committee/types" - communitytypes "github.com/kava-labs/kava/x/community/types" -) - -func TestPackPermissions_Success(t *testing.T) { - _, err := types.PackPermissions([]types.Permission{&types.GodPermission{}}) - require.NoError(t, err) -} - -func TestPackPermissions_Failure(t *testing.T) { - _, err := types.PackPermissions([]types.Permission{nil}) - require.Error(t, err) -} - -func TestUnpackPermissions_Success(t *testing.T) { - packedPermissions, err := types.PackPermissions([]types.Permission{&types.GodPermission{}}) - require.NoError(t, err) - unpackedPermissions, err := types.UnpackPermissions(packedPermissions) - require.NoError(t, err) - require.Len(t, unpackedPermissions, 1) - _, ok := unpackedPermissions[0].(*types.GodPermission) - require.True(t, ok) -} - -func TestUnpackPermissions_Failure(t *testing.T) { - vote, err := codectypes.NewAnyWithValue(&types.Vote{ProposalID: 1}) - require.NoError(t, err) - _, err = types.UnpackPermissions([]*codectypes.Any{vote}) - require.Error(t, err) -} - -func TestCommunityCDPRepayDebtPermission_Allows(t *testing.T) { - permission := types.CommunityCDPRepayDebtPermission{} - testcases := []struct { - name string - proposal types.PubProposal - allowed bool - }{ - { - name: "allowed for correct proposal", - proposal: communitytypes.NewCommunityCDPRepayDebtProposal( - "repay x/community cdp debt", - "repays debt on a cdp position", - "collateral-type", - sdk.NewInt64Coin("ukava", 1e10), - ), - allowed: true, - }, - { - name: "fails for nil proposal", - proposal: nil, - allowed: false, - }, - { - name: "fails for wrong proposal", - proposal: newTestParamsChangeProposalWithChanges([]paramsproposal.ParamChange{ - {Subspace: "cdp", Key: "DebtThreshold", Value: `test`}, - }), - allowed: false, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - require.Equal(t, tc.allowed, permission.Allows(sdk.Context{}, nil, tc.proposal)) - }) - } -} - -func TestCommunityPoolLendWithdrawPermission_Allows(t *testing.T) { - permission := types.CommunityPoolLendWithdrawPermission{} - testcases := []struct { - name string - proposal types.PubProposal - allowed bool - }{ - { - name: "allowed for correct proposal", - proposal: communitytypes.NewCommunityPoolLendWithdrawProposal( - "withdraw lend position", - "this fake proposal withdraws a lend position for the community pool", - sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e10))), - ), - allowed: true, - }, - { - name: "fails for nil proposal", - proposal: nil, - allowed: false, - }, - { - name: "fails for wrong proposal", - proposal: newTestParamsChangeProposalWithChanges([]paramsproposal.ParamChange{ - {Subspace: "cdp", Key: "DebtThreshold", Value: `test`}, - }), - allowed: false, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - require.Equal(t, tc.allowed, permission.Allows(sdk.Context{}, nil, tc.proposal)) - }) - } -} - -func TestCommunityCDPWithdrawCollateralPermission_Allows(t *testing.T) { - permission := types.CommunityCDPWithdrawCollateralPermission{} - testcases := []struct { - name string - proposal types.PubProposal - allowed bool - }{ - { - name: "allowed for correct proposal", - proposal: communitytypes.NewCommunityCDPWithdrawCollateralProposal( - "withdraw x/community cdp collateral", - "yes", - "collateral-type", - sdk.NewInt64Coin("ukava", 1e10), - ), - allowed: true, - }, - { - name: "fails for nil proposal", - proposal: nil, - allowed: false, - }, - { - name: "fails for wrong proposal", - proposal: newTestParamsChangeProposalWithChanges([]paramsproposal.ParamChange{ - {Subspace: "cdp", Key: "DebtThreshold", Value: `test`}, - }), - allowed: false, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - require.Equal(t, tc.allowed, permission.Allows(sdk.Context{}, nil, tc.proposal)) - }) - } -} - -func TestParamsChangePermission_SimpleParamsChange_Allows(t *testing.T) { - testPermission := types.ParamsChangePermission{ - AllowedParamsChanges: types.AllowedParamsChanges{ - types.AllowedParamsChange{ - Subspace: "cdp", - Key: "DebtThreshold", - }, - types.AllowedParamsChange{ - Subspace: "cdp", - Key: "SurplusThreshold", - }, - types.AllowedParamsChange{ - Subspace: "auction", - Key: "BidDuration", - }, - types.AllowedParamsChange{ - Subspace: "bep3", - Key: "MinAmount", - }, - }, - } - - testcases := []struct { - name string - permission types.ParamsChangePermission - pubProposal types.PubProposal - expectAllowed bool - }{ - { - name: "normal (single param)", - permission: testPermission, - pubProposal: newTestParamsChangeProposalWithChanges( - []paramsproposal.ParamChange{ - { - Subspace: "cdp", - Key: "DebtThreshold", - Value: `test`, - }, - }, - ), - expectAllowed: true, - }, - { - name: "not allowed (no allowed params change)", - permission: testPermission, - pubProposal: newTestParamsChangeProposalWithChanges( - []paramsproposal.ParamChange{ - { - Subspace: "kavadist", - Key: "TestKey", - Value: `100`, - }, - }, - ), - expectAllowed: false, - }, - { - name: "allowed (multiple params)", - permission: testPermission, - pubProposal: newTestParamsChangeProposalWithChanges( - []paramsproposal.ParamChange{ - { - Subspace: "cdp", - Key: "DebtThreshold", - Value: `test`, - }, - { - Subspace: "cdp", - Key: "SurplusThreshold", - Value: `100`, - }, - { - Subspace: "bep3", - Key: "MinAmount", - Value: `test`, - }, - }, - ), - expectAllowed: true, - }, - { - name: "not allowed (multiple params)", - permission: testPermission, - pubProposal: newTestParamsChangeProposalWithChanges( - []paramsproposal.ParamChange{ - { - Subspace: "cdp", - Key: "DebtThreshold", - Value: `test`, - }, - { - Subspace: "cdp", - Key: "SurplusThreshold", - Value: `100`, - }, - { - Subspace: "bep3", - Key: "Duration", - Value: `test`, - }, - }, - ), - expectAllowed: false, - }, - { - name: "not allowed (empty allowed params)", - permission: types.ParamsChangePermission{AllowedParamsChanges: types.AllowedParamsChanges{}}, - pubProposal: newTestParamsChangeProposalWithChanges( - []paramsproposal.ParamChange{ - { - Subspace: "cdp", - Key: "DebtThreshold", - Value: `test`, - }, - }, - ), - expectAllowed: false, - }, - { - name: "not allowed (mismatched pubproposal type)", - permission: testPermission, - pubProposal: govv1beta1.NewTextProposal("A Title", "A description of this proposal."), - expectAllowed: false, - }, - { - name: "not allowed (nil pubproposal)", - permission: testPermission, - pubProposal: nil, - expectAllowed: false, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - require.Equal(t, tc.expectAllowed, tc.permission.Allows(sdk.Context{}, nil, tc.pubProposal)) - }) - } -} - -func newTestParamsChangeProposalWithChanges(changes []paramsproposal.ParamChange) types.PubProposal { - return paramsproposal.NewParameterChangeProposal( - "A Title", - "A description for this proposal.", - changes, - ) -} diff --git a/x/committee/types/proposal.go b/x/committee/types/proposal.go deleted file mode 100644 index d5595b5b..00000000 --- a/x/committee/types/proposal.go +++ /dev/null @@ -1,134 +0,0 @@ -package types - -import ( - errorsmod "cosmossdk.io/errors" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -const ( - ProposalTypeCommitteeChange = "CommitteeChange" - ProposalTypeCommitteeDelete = "CommitteeDelete" -) - -// ProposalOutcome indicates the status of a proposal when it's closed and deleted from the store -type ProposalOutcome uint64 - -const ( - // Passed indicates that the proposal passed and was successfully enacted - Passed ProposalOutcome = iota - // Failed indicates that the proposal failed and was not enacted - Failed - // Invalid indicates that proposal passed but an error occurred when attempting to enact it - Invalid -) - -var toString = map[ProposalOutcome]string{ - Passed: "Passed", - Failed: "Failed", - Invalid: "Invalid", -} - -func (p ProposalOutcome) String() string { - return toString[p] -} - -// ensure proposal types fulfill the PubProposal interface and the gov Content interface. -var _, _ govv1beta1.Content = &CommitteeChangeProposal{}, &CommitteeDeleteProposal{} -var _, _ PubProposal = &CommitteeChangeProposal{}, &CommitteeDeleteProposal{} - -// ensure CommitteeChangeProposal fulfill the codectypes.UnpackInterfacesMessage interface -var _ codectypes.UnpackInterfacesMessage = &CommitteeChangeProposal{} - -func init() { - // Gov proposals need to be registered on gov's ModuleCdc so MsgSubmitProposal can be encoded. - govv1beta1.RegisterProposalType(ProposalTypeCommitteeChange) - govv1beta1.RegisterProposalType(ProposalTypeCommitteeDelete) -} - -func NewCommitteeChangeProposal(title string, description string, newCommittee Committee) (CommitteeChangeProposal, error) { - committeeAny, err := PackCommittee(newCommittee) - if err != nil { - return CommitteeChangeProposal{}, err - } - return CommitteeChangeProposal{ - Title: title, - Description: description, - NewCommittee: committeeAny, - }, nil -} - -func MustNewCommitteeChangeProposal(title string, description string, newCommittee Committee) CommitteeChangeProposal { - proposal, err := NewCommitteeChangeProposal(title, description, newCommittee) - if err != nil { - panic(err) - } - return proposal -} - -// GetTitle returns the title of the proposal. -func (ccp CommitteeChangeProposal) GetTitle() string { return ccp.Title } - -// GetDescription returns the description of the proposal. -func (ccp CommitteeChangeProposal) GetDescription() string { return ccp.Description } - -// ProposalRoute returns the routing key of the proposal. -func (ccp CommitteeChangeProposal) ProposalRoute() string { return RouterKey } - -// ProposalType returns the type of the proposal. -func (ccp CommitteeChangeProposal) ProposalType() string { return ProposalTypeCommitteeChange } - -// GetNewCommittee returns the new committee of the proposal. -func (ccp CommitteeChangeProposal) GetNewCommittee() Committee { - committee, err := UnpackCommittee(ccp.NewCommittee) - if err != nil { - panic(err) - } - return committee -} - -// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (ccp CommitteeChangeProposal) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - var committee Committee - return unpacker.UnpackAny(ccp.NewCommittee, &committee) -} - -// ValidateBasic runs basic stateless validity checks -func (ccp CommitteeChangeProposal) ValidateBasic() error { - if err := govv1beta1.ValidateAbstract(&ccp); err != nil { - return err - } - committee, err := UnpackCommittee(ccp.NewCommittee) - if err != nil { - return errorsmod.Wrap(ErrInvalidCommittee, err.Error()) - } - if err := committee.Validate(); err != nil { - return errorsmod.Wrap(ErrInvalidCommittee, err.Error()) - } - return nil -} - -func NewCommitteeDeleteProposal(title string, description string, committeeID uint64) CommitteeDeleteProposal { - return CommitteeDeleteProposal{ - Title: title, - Description: description, - CommitteeID: committeeID, - } -} - -// GetTitle returns the title of the proposal. -func (cdp CommitteeDeleteProposal) GetTitle() string { return cdp.Title } - -// GetDescription returns the description of the proposal. -func (cdp CommitteeDeleteProposal) GetDescription() string { return cdp.Description } - -// ProposalRoute returns the routing key of the proposal. -func (cdp CommitteeDeleteProposal) ProposalRoute() string { return RouterKey } - -// ProposalType returns the type of the proposal. -func (cdp CommitteeDeleteProposal) ProposalType() string { return ProposalTypeCommitteeDelete } - -// ValidateBasic runs basic stateless validity checks -func (cdp CommitteeDeleteProposal) ValidateBasic() error { - return govv1beta1.ValidateAbstract(&cdp) -} diff --git a/x/committee/types/proposal.pb.go b/x/committee/types/proposal.pb.go deleted file mode 100644 index a329a925..00000000 --- a/x/committee/types/proposal.pb.go +++ /dev/null @@ -1,658 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/committee/v1beta1/proposal.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/codec/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 - -// CommitteeChangeProposal is a gov proposal for creating a new committee or modifying an existing one. -type CommitteeChangeProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - NewCommittee *types.Any `protobuf:"bytes,3,opt,name=new_committee,json=newCommittee,proto3" json:"new_committee,omitempty"` -} - -func (m *CommitteeChangeProposal) Reset() { *m = CommitteeChangeProposal{} } -func (m *CommitteeChangeProposal) String() string { return proto.CompactTextString(m) } -func (*CommitteeChangeProposal) ProtoMessage() {} -func (*CommitteeChangeProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_4886de4a6c720e57, []int{0} -} -func (m *CommitteeChangeProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommitteeChangeProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommitteeChangeProposal.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 *CommitteeChangeProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommitteeChangeProposal.Merge(m, src) -} -func (m *CommitteeChangeProposal) XXX_Size() int { - return m.Size() -} -func (m *CommitteeChangeProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CommitteeChangeProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CommitteeChangeProposal proto.InternalMessageInfo - -// CommitteeDeleteProposal is a gov proposal for removing a committee. -type CommitteeDeleteProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - CommitteeID uint64 `protobuf:"varint,3,opt,name=committee_id,json=committeeId,proto3" json:"committee_id,omitempty"` -} - -func (m *CommitteeDeleteProposal) Reset() { *m = CommitteeDeleteProposal{} } -func (m *CommitteeDeleteProposal) String() string { return proto.CompactTextString(m) } -func (*CommitteeDeleteProposal) ProtoMessage() {} -func (*CommitteeDeleteProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_4886de4a6c720e57, []int{1} -} -func (m *CommitteeDeleteProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommitteeDeleteProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommitteeDeleteProposal.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 *CommitteeDeleteProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommitteeDeleteProposal.Merge(m, src) -} -func (m *CommitteeDeleteProposal) XXX_Size() int { - return m.Size() -} -func (m *CommitteeDeleteProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CommitteeDeleteProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CommitteeDeleteProposal proto.InternalMessageInfo - -func init() { - proto.RegisterType((*CommitteeChangeProposal)(nil), "kava.committee.v1beta1.CommitteeChangeProposal") - proto.RegisterType((*CommitteeDeleteProposal)(nil), "kava.committee.v1beta1.CommitteeDeleteProposal") -} - -func init() { - proto.RegisterFile("kava/committee/v1beta1/proposal.proto", fileDescriptor_4886de4a6c720e57) -} - -var fileDescriptor_4886de4a6c720e57 = []byte{ - // 348 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x92, 0xbf, 0x4e, 0x02, 0x41, - 0x10, 0xc6, 0xef, 0xfc, 0x97, 0x70, 0x07, 0x31, 0xb9, 0x10, 0x05, 0x8a, 0x95, 0x90, 0x98, 0x90, - 0x18, 0x76, 0x03, 0x76, 0x76, 0x02, 0x85, 0x74, 0x86, 0xd2, 0x86, 0xec, 0xc1, 0xb8, 0x5c, 0x3c, - 0x76, 0x2e, 0xdc, 0x02, 0xf2, 0x16, 0xbe, 0x84, 0x6f, 0x40, 0xe7, 0x0b, 0x10, 0x2a, 0x4a, 0x2b, - 0xa3, 0xc7, 0x8b, 0x98, 0xfb, 0xc3, 0x86, 0xce, 0xc2, 0x6e, 0xbe, 0x6f, 0xbe, 0xcb, 0xfc, 0x6e, - 0x66, 0xad, 0xeb, 0x17, 0x3e, 0xe7, 0x6c, 0x88, 0x93, 0x89, 0xa7, 0x14, 0x00, 0x9b, 0x37, 0x5d, - 0x50, 0xbc, 0xc9, 0x82, 0x29, 0x06, 0x18, 0x72, 0x9f, 0x06, 0x53, 0x54, 0xe8, 0x5c, 0xc4, 0x31, - 0xaa, 0x63, 0x34, 0x8b, 0x55, 0xca, 0x43, 0x0c, 0x27, 0x18, 0x0e, 0x92, 0x14, 0x4b, 0x45, 0xfa, - 0x49, 0xa5, 0x28, 0x50, 0x60, 0xea, 0xc7, 0x55, 0xe6, 0x96, 0x05, 0xa2, 0xf0, 0x81, 0x25, 0xca, - 0x9d, 0x3d, 0x33, 0x2e, 0x97, 0x69, 0xab, 0xf6, 0x61, 0x5a, 0x97, 0x9d, 0xfd, 0x84, 0xce, 0x98, - 0x4b, 0x01, 0x8f, 0x19, 0x85, 0x53, 0xb4, 0x4e, 0x95, 0xa7, 0x7c, 0x28, 0x99, 0x55, 0xb3, 0x9e, - 0xeb, 0xa7, 0xc2, 0xa9, 0x5a, 0xf6, 0x08, 0xc2, 0xe1, 0xd4, 0x0b, 0x94, 0x87, 0xb2, 0x74, 0x94, - 0xf4, 0x0e, 0x2d, 0xe7, 0xc1, 0x2a, 0x48, 0x58, 0x0c, 0x34, 0x78, 0xe9, 0xb8, 0x6a, 0xd6, 0xed, - 0x56, 0x91, 0xa6, 0x18, 0x74, 0x8f, 0x41, 0xef, 0xe5, 0xb2, 0x5d, 0xd8, 0xac, 0x1a, 0x39, 0x4d, - 0xd0, 0xcf, 0x4b, 0x58, 0x68, 0x75, 0x47, 0x36, 0xab, 0x46, 0x25, 0xfb, 0x41, 0x81, 0xf3, 0xfd, - 0x06, 0x68, 0x07, 0xa5, 0x02, 0xa9, 0x6a, 0xef, 0x87, 0xf4, 0x5d, 0xf0, 0x41, 0xfd, 0x9f, 0xbe, - 0x65, 0xe5, 0x35, 0xf9, 0xc0, 0x1b, 0x25, 0xf0, 0x27, 0xed, 0xf3, 0xe8, 0xeb, 0xca, 0xd6, 0xa3, - 0x7a, 0xdd, 0xbe, 0xad, 0x43, 0xbd, 0xd1, 0x5f, 0x9c, 0xed, 0xde, 0xfa, 0x87, 0x18, 0xeb, 0x88, - 0x98, 0xdb, 0x88, 0x98, 0xdf, 0x11, 0x31, 0xdf, 0x76, 0xc4, 0xd8, 0xee, 0x88, 0xf1, 0xb9, 0x23, - 0xc6, 0xd3, 0x8d, 0xf0, 0xd4, 0x78, 0xe6, 0xc6, 0x97, 0x66, 0xf1, 0xc9, 0x1b, 0x3e, 0x77, 0xc3, - 0xa4, 0x62, 0xaf, 0x07, 0xaf, 0x44, 0x2d, 0x03, 0x08, 0xdd, 0xb3, 0x64, 0x7b, 0xb7, 0xbf, 0x01, - 0x00, 0x00, 0xff, 0xff, 0x58, 0x7f, 0x45, 0x9a, 0x44, 0x02, 0x00, 0x00, -} - -func (m *CommitteeChangeProposal) 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 *CommitteeChangeProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommitteeChangeProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.NewCommittee != nil { - { - size, err := m.NewCommittee.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CommitteeDeleteProposal) 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 *CommitteeDeleteProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommitteeDeleteProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.CommitteeID != 0 { - i = encodeVarintProposal(dAtA, i, uint64(m.CommitteeID)) - i-- - dAtA[i] = 0x18 - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintProposal(dAtA []byte, offset int, v uint64) int { - offset -= sovProposal(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *CommitteeChangeProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if m.NewCommittee != nil { - l = m.NewCommittee.Size() - n += 1 + l + sovProposal(uint64(l)) - } - return n -} - -func (m *CommitteeDeleteProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if m.CommitteeID != 0 { - n += 1 + sovProposal(uint64(m.CommitteeID)) - } - return n -} - -func sovProposal(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozProposal(x uint64) (n int) { - return sovProposal(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *CommitteeChangeProposal) 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 ErrIntOverflowProposal - } - 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: CommitteeChangeProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommitteeChangeProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NewCommittee", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.NewCommittee == nil { - m.NewCommittee = &types.Any{} - } - if err := m.NewCommittee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommitteeDeleteProposal) 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 ErrIntOverflowProposal - } - 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: CommitteeDeleteProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommitteeDeleteProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CommitteeID", wireType) - } - m.CommitteeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CommitteeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipProposal(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, ErrIntOverflowProposal - } - 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, ErrIntOverflowProposal - } - 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, ErrIntOverflowProposal - } - 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, ErrInvalidLengthProposal - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupProposal - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthProposal - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthProposal = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowProposal = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupProposal = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/committee/types/query.pb.go b/x/committee/types/query.pb.go deleted file mode 100644 index 335f8d8f..00000000 --- a/x/committee/types/query.pb.go +++ /dev/null @@ -1,4034 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/committee/v1beta1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/codec/types" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - 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" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 - -// QueryCommitteesRequest defines the request type for querying x/committee committees. -type QueryCommitteesRequest struct { -} - -func (m *QueryCommitteesRequest) Reset() { *m = QueryCommitteesRequest{} } -func (m *QueryCommitteesRequest) String() string { return proto.CompactTextString(m) } -func (*QueryCommitteesRequest) ProtoMessage() {} -func (*QueryCommitteesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{0} -} -func (m *QueryCommitteesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryCommitteesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCommitteesRequest.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 *QueryCommitteesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCommitteesRequest.Merge(m, src) -} -func (m *QueryCommitteesRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryCommitteesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCommitteesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCommitteesRequest proto.InternalMessageInfo - -// QueryCommitteesResponse defines the response type for querying x/committee committees. -type QueryCommitteesResponse struct { - Committees []*types.Any `protobuf:"bytes,1,rep,name=committees,proto3" json:"committees,omitempty"` -} - -func (m *QueryCommitteesResponse) Reset() { *m = QueryCommitteesResponse{} } -func (m *QueryCommitteesResponse) String() string { return proto.CompactTextString(m) } -func (*QueryCommitteesResponse) ProtoMessage() {} -func (*QueryCommitteesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{1} -} -func (m *QueryCommitteesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryCommitteesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCommitteesResponse.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 *QueryCommitteesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCommitteesResponse.Merge(m, src) -} -func (m *QueryCommitteesResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryCommitteesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCommitteesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCommitteesResponse proto.InternalMessageInfo - -// QueryCommitteeRequest defines the request type for querying x/committee committee. -type QueryCommitteeRequest struct { - CommitteeId uint64 `protobuf:"varint,1,opt,name=committee_id,json=committeeId,proto3" json:"committee_id,omitempty"` -} - -func (m *QueryCommitteeRequest) Reset() { *m = QueryCommitteeRequest{} } -func (m *QueryCommitteeRequest) String() string { return proto.CompactTextString(m) } -func (*QueryCommitteeRequest) ProtoMessage() {} -func (*QueryCommitteeRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{2} -} -func (m *QueryCommitteeRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryCommitteeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCommitteeRequest.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 *QueryCommitteeRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCommitteeRequest.Merge(m, src) -} -func (m *QueryCommitteeRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryCommitteeRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCommitteeRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCommitteeRequest proto.InternalMessageInfo - -// QueryCommitteeResponse defines the response type for querying x/committee committee. -type QueryCommitteeResponse struct { - Committee *types.Any `protobuf:"bytes,1,opt,name=committee,proto3" json:"committee,omitempty"` -} - -func (m *QueryCommitteeResponse) Reset() { *m = QueryCommitteeResponse{} } -func (m *QueryCommitteeResponse) String() string { return proto.CompactTextString(m) } -func (*QueryCommitteeResponse) ProtoMessage() {} -func (*QueryCommitteeResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{3} -} -func (m *QueryCommitteeResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryCommitteeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCommitteeResponse.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 *QueryCommitteeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCommitteeResponse.Merge(m, src) -} -func (m *QueryCommitteeResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryCommitteeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCommitteeResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCommitteeResponse proto.InternalMessageInfo - -// QueryProposalsRequest defines the request type for querying x/committee proposals. -type QueryProposalsRequest struct { - CommitteeId uint64 `protobuf:"varint,1,opt,name=committee_id,json=committeeId,proto3" json:"committee_id,omitempty"` -} - -func (m *QueryProposalsRequest) Reset() { *m = QueryProposalsRequest{} } -func (m *QueryProposalsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryProposalsRequest) ProtoMessage() {} -func (*QueryProposalsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{4} -} -func (m *QueryProposalsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryProposalsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryProposalsRequest.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 *QueryProposalsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryProposalsRequest.Merge(m, src) -} -func (m *QueryProposalsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryProposalsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryProposalsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryProposalsRequest proto.InternalMessageInfo - -// QueryProposalsResponse defines the response type for querying x/committee proposals. -type QueryProposalsResponse struct { - Proposals []QueryProposalResponse `protobuf:"bytes,1,rep,name=proposals,proto3" json:"proposals"` -} - -func (m *QueryProposalsResponse) Reset() { *m = QueryProposalsResponse{} } -func (m *QueryProposalsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryProposalsResponse) ProtoMessage() {} -func (*QueryProposalsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{5} -} -func (m *QueryProposalsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryProposalsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryProposalsResponse.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 *QueryProposalsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryProposalsResponse.Merge(m, src) -} -func (m *QueryProposalsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryProposalsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryProposalsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryProposalsResponse proto.InternalMessageInfo - -// QueryProposalRequest defines the request type for querying x/committee proposal. -type QueryProposalRequest struct { - ProposalId uint64 `protobuf:"varint,1,opt,name=proposal_id,json=proposalId,proto3" json:"proposal_id,omitempty"` -} - -func (m *QueryProposalRequest) Reset() { *m = QueryProposalRequest{} } -func (m *QueryProposalRequest) String() string { return proto.CompactTextString(m) } -func (*QueryProposalRequest) ProtoMessage() {} -func (*QueryProposalRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{6} -} -func (m *QueryProposalRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryProposalRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryProposalRequest.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 *QueryProposalRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryProposalRequest.Merge(m, src) -} -func (m *QueryProposalRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryProposalRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryProposalRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryProposalRequest proto.InternalMessageInfo - -// QueryProposalResponse defines the response type for querying x/committee proposal. -type QueryProposalResponse struct { - PubProposal *types.Any `protobuf:"bytes,1,opt,name=pub_proposal,json=pubProposal,proto3" json:"pub_proposal,omitempty"` - ID uint64 `protobuf:"varint,2,opt,name=id,proto3" json:"id,omitempty"` - CommitteeID uint64 `protobuf:"varint,3,opt,name=committee_id,json=committeeId,proto3" json:"committee_id,omitempty"` - Deadline time.Time `protobuf:"bytes,4,opt,name=deadline,proto3,stdtime" json:"deadline"` -} - -func (m *QueryProposalResponse) Reset() { *m = QueryProposalResponse{} } -func (m *QueryProposalResponse) String() string { return proto.CompactTextString(m) } -func (*QueryProposalResponse) ProtoMessage() {} -func (*QueryProposalResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{7} -} -func (m *QueryProposalResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryProposalResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryProposalResponse.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 *QueryProposalResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryProposalResponse.Merge(m, src) -} -func (m *QueryProposalResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryProposalResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryProposalResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryProposalResponse proto.InternalMessageInfo - -// QueryNextProposalIDRequest defines the request type for querying x/committee NextProposalID. -type QueryNextProposalIDRequest struct { -} - -func (m *QueryNextProposalIDRequest) Reset() { *m = QueryNextProposalIDRequest{} } -func (m *QueryNextProposalIDRequest) String() string { return proto.CompactTextString(m) } -func (*QueryNextProposalIDRequest) ProtoMessage() {} -func (*QueryNextProposalIDRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{8} -} -func (m *QueryNextProposalIDRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryNextProposalIDRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryNextProposalIDRequest.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 *QueryNextProposalIDRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryNextProposalIDRequest.Merge(m, src) -} -func (m *QueryNextProposalIDRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryNextProposalIDRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryNextProposalIDRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryNextProposalIDRequest proto.InternalMessageInfo - -// QueryNextProposalIDRequest defines the response type for querying x/committee NextProposalID. -type QueryNextProposalIDResponse struct { - NextProposalID uint64 `protobuf:"varint,1,opt,name=next_proposal_id,json=nextProposalId,proto3" json:"next_proposal_id,omitempty"` -} - -func (m *QueryNextProposalIDResponse) Reset() { *m = QueryNextProposalIDResponse{} } -func (m *QueryNextProposalIDResponse) String() string { return proto.CompactTextString(m) } -func (*QueryNextProposalIDResponse) ProtoMessage() {} -func (*QueryNextProposalIDResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{9} -} -func (m *QueryNextProposalIDResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryNextProposalIDResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryNextProposalIDResponse.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 *QueryNextProposalIDResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryNextProposalIDResponse.Merge(m, src) -} -func (m *QueryNextProposalIDResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryNextProposalIDResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryNextProposalIDResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryNextProposalIDResponse proto.InternalMessageInfo - -// QueryVotesRequest defines the request type for querying x/committee votes. -type QueryVotesRequest struct { - ProposalId uint64 `protobuf:"varint,1,opt,name=proposal_id,json=proposalId,proto3" json:"proposal_id,omitempty"` - Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryVotesRequest) Reset() { *m = QueryVotesRequest{} } -func (m *QueryVotesRequest) String() string { return proto.CompactTextString(m) } -func (*QueryVotesRequest) ProtoMessage() {} -func (*QueryVotesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{10} -} -func (m *QueryVotesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryVotesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryVotesRequest.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 *QueryVotesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryVotesRequest.Merge(m, src) -} -func (m *QueryVotesRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryVotesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryVotesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryVotesRequest proto.InternalMessageInfo - -// QueryVotesResponse defines the response type for querying x/committee votes. -type QueryVotesResponse struct { - // votes defined the queried votes. - Votes []QueryVoteResponse `protobuf:"bytes,1,rep,name=votes,proto3" json:"votes"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryVotesResponse) Reset() { *m = QueryVotesResponse{} } -func (m *QueryVotesResponse) String() string { return proto.CompactTextString(m) } -func (*QueryVotesResponse) ProtoMessage() {} -func (*QueryVotesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{11} -} -func (m *QueryVotesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryVotesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryVotesResponse.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 *QueryVotesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryVotesResponse.Merge(m, src) -} -func (m *QueryVotesResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryVotesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryVotesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryVotesResponse proto.InternalMessageInfo - -// QueryVoteRequest defines the request type for querying x/committee vote. -type QueryVoteRequest struct { - ProposalId uint64 `protobuf:"varint,1,opt,name=proposal_id,json=proposalId,proto3" json:"proposal_id,omitempty"` - Voter string `protobuf:"bytes,2,opt,name=voter,proto3" json:"voter,omitempty"` -} - -func (m *QueryVoteRequest) Reset() { *m = QueryVoteRequest{} } -func (m *QueryVoteRequest) String() string { return proto.CompactTextString(m) } -func (*QueryVoteRequest) ProtoMessage() {} -func (*QueryVoteRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{12} -} -func (m *QueryVoteRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryVoteRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryVoteRequest.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 *QueryVoteRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryVoteRequest.Merge(m, src) -} -func (m *QueryVoteRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryVoteRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryVoteRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryVoteRequest proto.InternalMessageInfo - -// QueryVoteResponse defines the response type for querying x/committee vote. -type QueryVoteResponse struct { - ProposalID uint64 `protobuf:"varint,1,opt,name=proposal_id,json=proposalId,proto3" json:"proposal_id,omitempty"` - Voter string `protobuf:"bytes,2,opt,name=voter,proto3" json:"voter,omitempty"` - VoteType VoteType `protobuf:"varint,3,opt,name=vote_type,json=voteType,proto3,enum=kava.committee.v1beta1.VoteType" json:"vote_type,omitempty"` -} - -func (m *QueryVoteResponse) Reset() { *m = QueryVoteResponse{} } -func (m *QueryVoteResponse) String() string { return proto.CompactTextString(m) } -func (*QueryVoteResponse) ProtoMessage() {} -func (*QueryVoteResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{13} -} -func (m *QueryVoteResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryVoteResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryVoteResponse.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 *QueryVoteResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryVoteResponse.Merge(m, src) -} -func (m *QueryVoteResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryVoteResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryVoteResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryVoteResponse proto.InternalMessageInfo - -// QueryTallyRequest defines the request type for querying x/committee tally. -type QueryTallyRequest struct { - ProposalId uint64 `protobuf:"varint,1,opt,name=proposal_id,json=proposalId,proto3" json:"proposal_id,omitempty"` -} - -func (m *QueryTallyRequest) Reset() { *m = QueryTallyRequest{} } -func (m *QueryTallyRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTallyRequest) ProtoMessage() {} -func (*QueryTallyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{14} -} -func (m *QueryTallyRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTallyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTallyRequest.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 *QueryTallyRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTallyRequest.Merge(m, src) -} -func (m *QueryTallyRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTallyRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTallyRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTallyRequest proto.InternalMessageInfo - -// QueryTallyResponse defines the response type for querying x/committee tally. -type QueryTallyResponse struct { - ProposalID uint64 `protobuf:"varint,1,opt,name=proposal_id,json=proposalId,proto3" json:"proposal_id,omitempty"` - YesVotes github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=yes_votes,json=yesVotes,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"yes_votes"` - NoVotes github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=no_votes,json=noVotes,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"no_votes"` - CurrentVotes github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=current_votes,json=currentVotes,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"current_votes"` - PossibleVotes github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=possible_votes,json=possibleVotes,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"possible_votes"` - VoteThreshold github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,6,opt,name=vote_threshold,json=voteThreshold,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"vote_threshold"` - Quorum github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,7,opt,name=quorum,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"quorum"` -} - -func (m *QueryTallyResponse) Reset() { *m = QueryTallyResponse{} } -func (m *QueryTallyResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTallyResponse) ProtoMessage() {} -func (*QueryTallyResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{15} -} -func (m *QueryTallyResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTallyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTallyResponse.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 *QueryTallyResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTallyResponse.Merge(m, src) -} -func (m *QueryTallyResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTallyResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTallyResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTallyResponse proto.InternalMessageInfo - -// QueryRawParamsRequest defines the request type for querying x/committee raw params. -type QueryRawParamsRequest struct { - Subspace string `protobuf:"bytes,1,opt,name=subspace,proto3" json:"subspace,omitempty"` - Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"` -} - -func (m *QueryRawParamsRequest) Reset() { *m = QueryRawParamsRequest{} } -func (m *QueryRawParamsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRawParamsRequest) ProtoMessage() {} -func (*QueryRawParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{16} -} -func (m *QueryRawParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRawParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRawParamsRequest.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 *QueryRawParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRawParamsRequest.Merge(m, src) -} -func (m *QueryRawParamsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryRawParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRawParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRawParamsRequest proto.InternalMessageInfo - -// QueryRawParamsResponse defines the response type for querying x/committee raw params. -type QueryRawParamsResponse struct { - RawData string `protobuf:"bytes,1,opt,name=raw_data,json=rawData,proto3" json:"raw_data,omitempty"` -} - -func (m *QueryRawParamsResponse) Reset() { *m = QueryRawParamsResponse{} } -func (m *QueryRawParamsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryRawParamsResponse) ProtoMessage() {} -func (*QueryRawParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b81d271efeb6eee5, []int{17} -} -func (m *QueryRawParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRawParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRawParamsResponse.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 *QueryRawParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRawParamsResponse.Merge(m, src) -} -func (m *QueryRawParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryRawParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRawParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRawParamsResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryCommitteesRequest)(nil), "kava.committee.v1beta1.QueryCommitteesRequest") - proto.RegisterType((*QueryCommitteesResponse)(nil), "kava.committee.v1beta1.QueryCommitteesResponse") - proto.RegisterType((*QueryCommitteeRequest)(nil), "kava.committee.v1beta1.QueryCommitteeRequest") - proto.RegisterType((*QueryCommitteeResponse)(nil), "kava.committee.v1beta1.QueryCommitteeResponse") - proto.RegisterType((*QueryProposalsRequest)(nil), "kava.committee.v1beta1.QueryProposalsRequest") - proto.RegisterType((*QueryProposalsResponse)(nil), "kava.committee.v1beta1.QueryProposalsResponse") - proto.RegisterType((*QueryProposalRequest)(nil), "kava.committee.v1beta1.QueryProposalRequest") - proto.RegisterType((*QueryProposalResponse)(nil), "kava.committee.v1beta1.QueryProposalResponse") - proto.RegisterType((*QueryNextProposalIDRequest)(nil), "kava.committee.v1beta1.QueryNextProposalIDRequest") - proto.RegisterType((*QueryNextProposalIDResponse)(nil), "kava.committee.v1beta1.QueryNextProposalIDResponse") - proto.RegisterType((*QueryVotesRequest)(nil), "kava.committee.v1beta1.QueryVotesRequest") - proto.RegisterType((*QueryVotesResponse)(nil), "kava.committee.v1beta1.QueryVotesResponse") - proto.RegisterType((*QueryVoteRequest)(nil), "kava.committee.v1beta1.QueryVoteRequest") - proto.RegisterType((*QueryVoteResponse)(nil), "kava.committee.v1beta1.QueryVoteResponse") - proto.RegisterType((*QueryTallyRequest)(nil), "kava.committee.v1beta1.QueryTallyRequest") - proto.RegisterType((*QueryTallyResponse)(nil), "kava.committee.v1beta1.QueryTallyResponse") - proto.RegisterType((*QueryRawParamsRequest)(nil), "kava.committee.v1beta1.QueryRawParamsRequest") - proto.RegisterType((*QueryRawParamsResponse)(nil), "kava.committee.v1beta1.QueryRawParamsResponse") -} - -func init() { - proto.RegisterFile("kava/committee/v1beta1/query.proto", fileDescriptor_b81d271efeb6eee5) -} - -var fileDescriptor_b81d271efeb6eee5 = []byte{ - // 1211 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x96, 0xc1, 0x6f, 0xe3, 0xc4, - 0x17, 0xc7, 0xeb, 0x34, 0xed, 0x26, 0x2f, 0xdb, 0xfe, 0xfa, 0x1b, 0x95, 0x92, 0x86, 0x55, 0xd2, - 0x35, 0xab, 0xa5, 0x5b, 0x88, 0x4d, 0x53, 0x50, 0x05, 0xa2, 0x82, 0x4d, 0xdb, 0x45, 0x11, 0x12, - 0xea, 0x9a, 0xc2, 0x81, 0x95, 0x88, 0x26, 0xf5, 0x6c, 0x6a, 0x35, 0xb1, 0x5d, 0x8f, 0xd3, 0x36, - 0x2a, 0xbd, 0x70, 0x47, 0x5a, 0x09, 0x81, 0xb4, 0x07, 0x24, 0x84, 0x40, 0x42, 0xe2, 0x86, 0xf6, - 0x8f, 0xa8, 0xf6, 0xb4, 0x12, 0x17, 0xc4, 0x21, 0x40, 0xca, 0x1f, 0x82, 0x3c, 0x33, 0x9e, 0xb8, - 0x49, 0xdb, 0xb8, 0x39, 0x25, 0xb6, 0xdf, 0xfb, 0xce, 0x67, 0xde, 0xbc, 0x79, 0xef, 0x81, 0xba, - 0x87, 0x0f, 0xb0, 0xbe, 0xe3, 0x34, 0x9b, 0x96, 0xef, 0x13, 0xa2, 0x1f, 0x2c, 0xd7, 0x88, 0x8f, - 0x97, 0xf5, 0xfd, 0x16, 0xf1, 0xda, 0x9a, 0xeb, 0x39, 0xbe, 0x83, 0xe6, 0x02, 0x1b, 0x4d, 0xda, - 0x68, 0xc2, 0x26, 0xb7, 0xb4, 0xe3, 0xd0, 0xa6, 0x43, 0xf5, 0x1a, 0xa6, 0x84, 0x3b, 0x48, 0x77, - 0x17, 0xd7, 0x2d, 0x1b, 0xfb, 0x96, 0x63, 0x73, 0x8d, 0xdc, 0x3c, 0xb7, 0xad, 0xb2, 0x27, 0x9d, - 0x3f, 0x88, 0x4f, 0xb3, 0x75, 0xa7, 0xee, 0xf0, 0xf7, 0xc1, 0x3f, 0xf1, 0xf6, 0x56, 0xdd, 0x71, - 0xea, 0x0d, 0xa2, 0x63, 0xd7, 0xd2, 0xb1, 0x6d, 0x3b, 0x3e, 0x53, 0x0b, 0x7d, 0xe6, 0xc5, 0x57, - 0xf6, 0x54, 0x6b, 0x3d, 0xd6, 0xb1, 0x2d, 0x68, 0x73, 0x85, 0xfe, 0x4f, 0xbe, 0xd5, 0x24, 0xd4, - 0xc7, 0x4d, 0x57, 0x18, 0xdc, 0xb9, 0x64, 0xcb, 0x75, 0x62, 0x13, 0x6a, 0x89, 0x15, 0xd4, 0x2c, - 0xcc, 0x3d, 0x0c, 0xb6, 0xb4, 0x1e, 0xda, 0x51, 0x83, 0xec, 0xb7, 0x08, 0xf5, 0xd5, 0x2f, 0xe0, - 0xe5, 0x81, 0x2f, 0xd4, 0x75, 0x6c, 0x4a, 0xd0, 0x3a, 0x80, 0xd4, 0xa5, 0x59, 0x65, 0x61, 0x7c, - 0x31, 0x53, 0x9a, 0xd5, 0x38, 0x90, 0x16, 0x02, 0x69, 0xf7, 0xed, 0x76, 0x79, 0xea, 0xf9, 0xb3, - 0x62, 0x5a, 0x2a, 0x18, 0x11, 0x37, 0xf5, 0x5d, 0x78, 0xe9, 0xbc, 0xbe, 0x58, 0x18, 0xdd, 0x86, - 0x9b, 0xd2, 0xac, 0x6a, 0x99, 0x59, 0x65, 0x41, 0x59, 0x4c, 0x1a, 0x19, 0xf9, 0xae, 0x62, 0xaa, - 0x8f, 0xfa, 0xa9, 0x25, 0xda, 0x7d, 0x48, 0x4b, 0x43, 0xe6, 0x19, 0x93, 0xac, 0xe7, 0x25, 0xc1, - 0xb6, 0x3c, 0xc7, 0x75, 0x28, 0x6e, 0xd0, 0x6b, 0x80, 0xed, 0x09, 0xb0, 0x88, 0xaf, 0x00, 0x7b, - 0x08, 0x69, 0x37, 0x7c, 0x29, 0x42, 0x56, 0xd4, 0x2e, 0xce, 0x38, 0xed, 0x9c, 0x44, 0xa8, 0x50, - 0x4e, 0x9e, 0x76, 0x0a, 0x63, 0x46, 0x4f, 0x45, 0x5d, 0x85, 0xd9, 0x3e, 0x4b, 0xce, 0x59, 0x80, - 0x4c, 0x68, 0xd4, 0xc3, 0x84, 0xf0, 0x55, 0xc5, 0x54, 0xbf, 0x4e, 0xf4, 0x6d, 0x51, 0x52, 0x3e, - 0x86, 0x9b, 0x6e, 0xab, 0x56, 0x0d, 0x6d, 0xaf, 0x8c, 0x60, 0xb1, 0xdb, 0x29, 0x64, 0xb6, 0x5a, - 0xb5, 0x50, 0xe4, 0xf9, 0xb3, 0x62, 0x4e, 0x64, 0x7c, 0xdd, 0x39, 0x90, 0x9b, 0x59, 0x77, 0x6c, - 0x9f, 0xd8, 0xbe, 0x91, 0x71, 0x7b, 0xa6, 0x68, 0x0e, 0x12, 0x96, 0x99, 0x4d, 0x04, 0x64, 0xe5, - 0xc9, 0x6e, 0xa7, 0x90, 0xa8, 0x6c, 0x18, 0x09, 0xcb, 0x44, 0xa5, 0xbe, 0x10, 0x8f, 0x33, 0x8b, - 0xff, 0x05, 0x2b, 0xc9, 0xb3, 0xaa, 0x6c, 0x9c, 0x8b, 0x39, 0xfa, 0x00, 0x52, 0x26, 0xc1, 0x66, - 0xc3, 0xb2, 0x49, 0x36, 0xc9, 0x78, 0x73, 0x03, 0xbc, 0xdb, 0xe1, 0xe5, 0x28, 0xa7, 0x82, 0x28, - 0x3e, 0xf9, 0xab, 0xa0, 0x18, 0xd2, 0x4b, 0xbd, 0x05, 0x39, 0x16, 0x8e, 0x8f, 0xc9, 0x91, 0x1f, - 0x22, 0x56, 0x36, 0xc2, 0x8b, 0xf0, 0x08, 0x5e, 0xb9, 0xf0, 0xab, 0x08, 0xd9, 0x7b, 0x30, 0x63, - 0x93, 0x23, 0xbf, 0x3a, 0x10, 0xf2, 0x32, 0xea, 0x76, 0x0a, 0xd3, 0x7d, 0x5e, 0xd3, 0x76, 0xf4, - 0xd9, 0x54, 0xbf, 0x84, 0xff, 0x33, 0xf1, 0xcf, 0x1c, 0x5f, 0x5e, 0xbd, 0xa1, 0x07, 0x88, 0x1e, - 0x00, 0xf4, 0x4a, 0x0f, 0x0b, 0x63, 0xa6, 0x74, 0x57, 0x13, 0xc1, 0x0f, 0xea, 0x94, 0xc6, 0x0b, - 0x5b, 0x78, 0x06, 0x5b, 0xb8, 0x1e, 0x5e, 0x2f, 0x23, 0xe2, 0xa9, 0xfe, 0xa4, 0x00, 0x8a, 0x2e, - 0x2f, 0xb6, 0xb4, 0x09, 0x13, 0x07, 0xc1, 0x0b, 0x91, 0xa7, 0xf7, 0xae, 0xcc, 0xd3, 0xc0, 0xb5, - 0x2f, 0x47, 0xb9, 0x37, 0xfa, 0xf0, 0x02, 0xca, 0xd7, 0x86, 0x52, 0x72, 0xa5, 0x73, 0x98, 0x15, - 0x98, 0x89, 0x2c, 0x15, 0x33, 0x46, 0xb3, 0x7c, 0x13, 0x1e, 0x5b, 0x38, 0xcd, 0x99, 0x3c, 0xf5, - 0xa9, 0x12, 0x09, 0xb8, 0xdc, 0xb0, 0x7e, 0x81, 0x58, 0x79, 0xba, 0xdb, 0x29, 0x40, 0xe4, 0xe8, - 0x86, 0x8a, 0xa3, 0x35, 0x48, 0x07, 0x7f, 0xaa, 0x7e, 0xdb, 0x25, 0x2c, 0x75, 0xa7, 0x4b, 0x0b, - 0x97, 0xc5, 0x2e, 0x58, 0x7f, 0xbb, 0xed, 0x12, 0x23, 0x75, 0x20, 0xfe, 0xa9, 0x6f, 0x09, 0xb4, - 0x6d, 0xdc, 0x68, 0xb4, 0x63, 0x5f, 0xe6, 0x5f, 0x92, 0xe2, 0x0c, 0x85, 0xdb, 0xa8, 0x5b, 0xfa, - 0x08, 0xd2, 0x6d, 0x42, 0xab, 0xfc, 0xe0, 0xd9, 0xb6, 0xca, 0x5a, 0x70, 0x9a, 0x7f, 0x76, 0x0a, - 0x77, 0xeb, 0x96, 0xbf, 0xdb, 0xaa, 0x05, 0xbb, 0x10, 0x3d, 0x4d, 0xfc, 0x14, 0xa9, 0xb9, 0xa7, - 0x07, 0xbb, 0xa5, 0xda, 0x06, 0xd9, 0x31, 0x52, 0x6d, 0x42, 0x59, 0x26, 0xa1, 0x0a, 0xa4, 0x6c, - 0x47, 0x68, 0x8d, 0x8f, 0xa4, 0x75, 0xc3, 0x76, 0xb8, 0xd4, 0x27, 0x30, 0xb5, 0xd3, 0xf2, 0x3c, - 0x62, 0xfb, 0x42, 0x2f, 0x39, 0x92, 0xde, 0x4d, 0x21, 0xc2, 0x45, 0x3f, 0x85, 0x69, 0xd7, 0xa1, - 0xd4, 0xaa, 0x35, 0x88, 0x50, 0x9d, 0x18, 0x49, 0x75, 0x2a, 0x54, 0x91, 0xb2, 0x3c, 0x01, 0x76, - 0x3d, 0x42, 0x77, 0x9d, 0x86, 0x99, 0x9d, 0x1c, 0x4d, 0x96, 0xe5, 0x44, 0x28, 0x82, 0x1e, 0xc0, - 0xe4, 0x7e, 0xcb, 0xf1, 0x5a, 0xcd, 0xec, 0x8d, 0x91, 0xe4, 0x84, 0xb7, 0xba, 0x29, 0xca, 0xbe, - 0x81, 0x0f, 0xb7, 0xb0, 0x87, 0x9b, 0xb2, 0xe0, 0xe4, 0x20, 0x45, 0x5b, 0x35, 0xea, 0xe2, 0x1d, - 0xde, 0x34, 0xd3, 0x86, 0x7c, 0x46, 0x33, 0x30, 0xbe, 0x47, 0xda, 0x22, 0xd1, 0x83, 0xbf, 0xea, - 0x8a, 0x68, 0x72, 0x11, 0x19, 0x91, 0x74, 0xf3, 0x90, 0xf2, 0xf0, 0x61, 0xd5, 0xc4, 0x3e, 0x16, - 0x3a, 0x37, 0x3c, 0x7c, 0xb8, 0x81, 0x7d, 0x5c, 0xfa, 0x2d, 0x03, 0x13, 0xcc, 0x0b, 0x3d, 0x55, - 0x00, 0x7a, 0x43, 0x05, 0xd2, 0xae, 0xac, 0x2e, 0x03, 0x73, 0x49, 0x4e, 0x8f, 0x6d, 0xcf, 0xa1, - 0xd4, 0xa5, 0xaf, 0x7e, 0xff, 0xf7, 0x9b, 0xc4, 0x1d, 0xa4, 0xea, 0x97, 0x4c, 0x44, 0xbd, 0xa1, - 0x04, 0xfd, 0xac, 0x40, 0x6f, 0x28, 0x40, 0xc5, 0x78, 0x4b, 0x85, 0x64, 0x5a, 0x5c, 0x73, 0x01, - 0xf6, 0x0e, 0x03, 0x5b, 0x41, 0xcb, 0xc3, 0xc1, 0xf4, 0xe3, 0x68, 0x5b, 0x3c, 0x41, 0xdf, 0x2a, - 0x90, 0x96, 0x33, 0x06, 0x8a, 0x37, 0x48, 0xd0, 0x78, 0x9c, 0x03, 0xa3, 0x8b, 0x7a, 0x8f, 0x71, - 0xbe, 0x8a, 0x6e, 0x5f, 0xc6, 0x29, 0x47, 0x12, 0xf4, 0x83, 0x02, 0x29, 0xd9, 0xe4, 0xdf, 0x88, - 0x39, 0xdf, 0x70, 0xaa, 0xeb, 0x4d, 0x43, 0xea, 0x2a, 0x83, 0x5a, 0x46, 0xfa, 0x50, 0x28, 0xfd, - 0x38, 0x52, 0x08, 0x4f, 0xd0, 0xaf, 0x0a, 0xf4, 0x35, 0x65, 0x54, 0xba, 0x72, 0xe9, 0x0b, 0xa7, - 0x82, 0xdc, 0xca, 0xb5, 0x7c, 0x04, 0xf4, 0x9b, 0x0c, 0x7a, 0x09, 0x2d, 0x5e, 0x06, 0x1d, 0x4c, - 0x07, 0xc5, 0x10, 0xb7, 0x68, 0x99, 0xe8, 0x7b, 0x05, 0x26, 0x78, 0x6d, 0x19, 0xde, 0x85, 0xe5, - 0x01, 0x2f, 0xc5, 0x31, 0x15, 0x48, 0x6b, 0x0c, 0x69, 0x15, 0xbd, 0x7d, 0xcd, 0x38, 0xea, 0xbc, - 0xc7, 0xff, 0xa8, 0x40, 0x32, 0x10, 0x44, 0x8b, 0x31, 0x86, 0x04, 0x4e, 0x17, 0x7f, 0x9c, 0x50, - 0x37, 0x19, 0xdc, 0xfb, 0x68, 0x6d, 0x24, 0x38, 0xfd, 0x98, 0xb5, 0xe5, 0x13, 0x16, 0x44, 0xd6, - 0x1d, 0x87, 0x04, 0x31, 0xda, 0x78, 0x87, 0x04, 0xf1, 0x5c, 0xb3, 0x1d, 0x3d, 0x88, 0x3e, 0xa3, - 0xfa, 0x4e, 0x81, 0xb4, 0x2c, 0xa6, 0x43, 0x6e, 0x73, 0x7f, 0xed, 0x1e, 0x72, 0x9b, 0x07, 0x6a, - 0xf4, 0xf0, 0x72, 0xe8, 0xe1, 0xc3, 0xa2, 0xcb, 0x7c, 0xca, 0x95, 0xd3, 0x7f, 0xf2, 0x63, 0xa7, - 0xdd, 0xbc, 0xf2, 0xa2, 0x9b, 0x57, 0xfe, 0xee, 0xe6, 0x95, 0x27, 0x67, 0xf9, 0xb1, 0x17, 0x67, - 0xf9, 0xb1, 0x3f, 0xce, 0xf2, 0x63, 0x9f, 0xbf, 0x1e, 0x69, 0x3f, 0x81, 0x56, 0xb1, 0x81, 0x6b, - 0x94, 0xab, 0x1e, 0x45, 0x74, 0x59, 0x1f, 0xaa, 0x4d, 0xb2, 0x59, 0x7c, 0xe5, 0xbf, 0x00, 0x00, - 0x00, 0xff, 0xff, 0xb4, 0xd1, 0x58, 0x0c, 0x8a, 0x0f, 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 { - // Committees queries all committess of the committee module. - Committees(ctx context.Context, in *QueryCommitteesRequest, opts ...grpc.CallOption) (*QueryCommitteesResponse, error) - // Committee queries a committee based on committee ID. - Committee(ctx context.Context, in *QueryCommitteeRequest, opts ...grpc.CallOption) (*QueryCommitteeResponse, error) - // Proposals queries proposals based on committee ID. - Proposals(ctx context.Context, in *QueryProposalsRequest, opts ...grpc.CallOption) (*QueryProposalsResponse, error) - // Deposits queries a proposal based on proposal ID. - Proposal(ctx context.Context, in *QueryProposalRequest, opts ...grpc.CallOption) (*QueryProposalResponse, error) - // NextProposalID queries the next proposal ID of the committee module. - NextProposalID(ctx context.Context, in *QueryNextProposalIDRequest, opts ...grpc.CallOption) (*QueryNextProposalIDResponse, error) - // Votes queries all votes for a single proposal ID. - Votes(ctx context.Context, in *QueryVotesRequest, opts ...grpc.CallOption) (*QueryVotesResponse, error) - // Vote queries the vote of a single voter for a single proposal ID. - Vote(ctx context.Context, in *QueryVoteRequest, opts ...grpc.CallOption) (*QueryVoteResponse, error) - // Tally queries the tally of a single proposal ID. - Tally(ctx context.Context, in *QueryTallyRequest, opts ...grpc.CallOption) (*QueryTallyResponse, error) - // RawParams queries the raw params data of any subspace and key. - RawParams(ctx context.Context, in *QueryRawParamsRequest, opts ...grpc.CallOption) (*QueryRawParamsResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Committees(ctx context.Context, in *QueryCommitteesRequest, opts ...grpc.CallOption) (*QueryCommitteesResponse, error) { - out := new(QueryCommitteesResponse) - err := c.cc.Invoke(ctx, "/kava.committee.v1beta1.Query/Committees", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Committee(ctx context.Context, in *QueryCommitteeRequest, opts ...grpc.CallOption) (*QueryCommitteeResponse, error) { - out := new(QueryCommitteeResponse) - err := c.cc.Invoke(ctx, "/kava.committee.v1beta1.Query/Committee", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Proposals(ctx context.Context, in *QueryProposalsRequest, opts ...grpc.CallOption) (*QueryProposalsResponse, error) { - out := new(QueryProposalsResponse) - err := c.cc.Invoke(ctx, "/kava.committee.v1beta1.Query/Proposals", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Proposal(ctx context.Context, in *QueryProposalRequest, opts ...grpc.CallOption) (*QueryProposalResponse, error) { - out := new(QueryProposalResponse) - err := c.cc.Invoke(ctx, "/kava.committee.v1beta1.Query/Proposal", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) NextProposalID(ctx context.Context, in *QueryNextProposalIDRequest, opts ...grpc.CallOption) (*QueryNextProposalIDResponse, error) { - out := new(QueryNextProposalIDResponse) - err := c.cc.Invoke(ctx, "/kava.committee.v1beta1.Query/NextProposalID", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Votes(ctx context.Context, in *QueryVotesRequest, opts ...grpc.CallOption) (*QueryVotesResponse, error) { - out := new(QueryVotesResponse) - err := c.cc.Invoke(ctx, "/kava.committee.v1beta1.Query/Votes", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Vote(ctx context.Context, in *QueryVoteRequest, opts ...grpc.CallOption) (*QueryVoteResponse, error) { - out := new(QueryVoteResponse) - err := c.cc.Invoke(ctx, "/kava.committee.v1beta1.Query/Vote", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Tally(ctx context.Context, in *QueryTallyRequest, opts ...grpc.CallOption) (*QueryTallyResponse, error) { - out := new(QueryTallyResponse) - err := c.cc.Invoke(ctx, "/kava.committee.v1beta1.Query/Tally", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) RawParams(ctx context.Context, in *QueryRawParamsRequest, opts ...grpc.CallOption) (*QueryRawParamsResponse, error) { - out := new(QueryRawParamsResponse) - err := c.cc.Invoke(ctx, "/kava.committee.v1beta1.Query/RawParams", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Committees queries all committess of the committee module. - Committees(context.Context, *QueryCommitteesRequest) (*QueryCommitteesResponse, error) - // Committee queries a committee based on committee ID. - Committee(context.Context, *QueryCommitteeRequest) (*QueryCommitteeResponse, error) - // Proposals queries proposals based on committee ID. - Proposals(context.Context, *QueryProposalsRequest) (*QueryProposalsResponse, error) - // Deposits queries a proposal based on proposal ID. - Proposal(context.Context, *QueryProposalRequest) (*QueryProposalResponse, error) - // NextProposalID queries the next proposal ID of the committee module. - NextProposalID(context.Context, *QueryNextProposalIDRequest) (*QueryNextProposalIDResponse, error) - // Votes queries all votes for a single proposal ID. - Votes(context.Context, *QueryVotesRequest) (*QueryVotesResponse, error) - // Vote queries the vote of a single voter for a single proposal ID. - Vote(context.Context, *QueryVoteRequest) (*QueryVoteResponse, error) - // Tally queries the tally of a single proposal ID. - Tally(context.Context, *QueryTallyRequest) (*QueryTallyResponse, error) - // RawParams queries the raw params data of any subspace and key. - RawParams(context.Context, *QueryRawParamsRequest) (*QueryRawParamsResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Committees(ctx context.Context, req *QueryCommitteesRequest) (*QueryCommitteesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Committees not implemented") -} -func (*UnimplementedQueryServer) Committee(ctx context.Context, req *QueryCommitteeRequest) (*QueryCommitteeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Committee not implemented") -} -func (*UnimplementedQueryServer) Proposals(ctx context.Context, req *QueryProposalsRequest) (*QueryProposalsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Proposals not implemented") -} -func (*UnimplementedQueryServer) Proposal(ctx context.Context, req *QueryProposalRequest) (*QueryProposalResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Proposal not implemented") -} -func (*UnimplementedQueryServer) NextProposalID(ctx context.Context, req *QueryNextProposalIDRequest) (*QueryNextProposalIDResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method NextProposalID not implemented") -} -func (*UnimplementedQueryServer) Votes(ctx context.Context, req *QueryVotesRequest) (*QueryVotesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Votes not implemented") -} -func (*UnimplementedQueryServer) Vote(ctx context.Context, req *QueryVoteRequest) (*QueryVoteResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Vote not implemented") -} -func (*UnimplementedQueryServer) Tally(ctx context.Context, req *QueryTallyRequest) (*QueryTallyResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Tally not implemented") -} -func (*UnimplementedQueryServer) RawParams(ctx context.Context, req *QueryRawParamsRequest) (*QueryRawParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RawParams not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Committees_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryCommitteesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Committees(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.committee.v1beta1.Query/Committees", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Committees(ctx, req.(*QueryCommitteesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Committee_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryCommitteeRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Committee(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.committee.v1beta1.Query/Committee", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Committee(ctx, req.(*QueryCommitteeRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Proposals_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryProposalsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Proposals(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.committee.v1beta1.Query/Proposals", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Proposals(ctx, req.(*QueryProposalsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Proposal_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryProposalRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Proposal(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.committee.v1beta1.Query/Proposal", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Proposal(ctx, req.(*QueryProposalRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_NextProposalID_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryNextProposalIDRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).NextProposalID(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.committee.v1beta1.Query/NextProposalID", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).NextProposalID(ctx, req.(*QueryNextProposalIDRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Votes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryVotesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Votes(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.committee.v1beta1.Query/Votes", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Votes(ctx, req.(*QueryVotesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Vote_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryVoteRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Vote(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.committee.v1beta1.Query/Vote", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Vote(ctx, req.(*QueryVoteRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Tally_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTallyRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Tally(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.committee.v1beta1.Query/Tally", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Tally(ctx, req.(*QueryTallyRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_RawParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRawParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).RawParams(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.committee.v1beta1.Query/RawParams", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).RawParams(ctx, req.(*QueryRawParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.committee.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Committees", - Handler: _Query_Committees_Handler, - }, - { - MethodName: "Committee", - Handler: _Query_Committee_Handler, - }, - { - MethodName: "Proposals", - Handler: _Query_Proposals_Handler, - }, - { - MethodName: "Proposal", - Handler: _Query_Proposal_Handler, - }, - { - MethodName: "NextProposalID", - Handler: _Query_NextProposalID_Handler, - }, - { - MethodName: "Votes", - Handler: _Query_Votes_Handler, - }, - { - MethodName: "Vote", - Handler: _Query_Vote_Handler, - }, - { - MethodName: "Tally", - Handler: _Query_Tally_Handler, - }, - { - MethodName: "RawParams", - Handler: _Query_RawParams_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/committee/v1beta1/query.proto", -} - -func (m *QueryCommitteesRequest) 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 *QueryCommitteesRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCommitteesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryCommitteesResponse) 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 *QueryCommitteesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCommitteesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Committees) > 0 { - for iNdEx := len(m.Committees) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Committees[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 (m *QueryCommitteeRequest) 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 *QueryCommitteeRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCommitteeRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.CommitteeId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.CommitteeId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryCommitteeResponse) 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 *QueryCommitteeResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCommitteeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Committee != nil { - { - size, err := m.Committee.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 *QueryProposalsRequest) 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 *QueryProposalsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryProposalsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.CommitteeId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.CommitteeId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryProposalsResponse) 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 *QueryProposalsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryProposalsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Proposals) > 0 { - for iNdEx := len(m.Proposals) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Proposals[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 (m *QueryProposalRequest) 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 *QueryProposalRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryProposalRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.ProposalId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.ProposalId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryProposalResponse) 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 *QueryProposalResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryProposalResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - n2, err2 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Deadline, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Deadline):]) - if err2 != nil { - return 0, err2 - } - i -= n2 - i = encodeVarintQuery(dAtA, i, uint64(n2)) - i-- - dAtA[i] = 0x22 - if m.CommitteeID != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.CommitteeID)) - i-- - dAtA[i] = 0x18 - } - if m.ID != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.ID)) - i-- - dAtA[i] = 0x10 - } - if m.PubProposal != nil { - { - size, err := m.PubProposal.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 *QueryNextProposalIDRequest) 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 *QueryNextProposalIDRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryNextProposalIDRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryNextProposalIDResponse) 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 *QueryNextProposalIDResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryNextProposalIDResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.NextProposalID != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.NextProposalID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryVotesRequest) 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 *QueryVotesRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryVotesRequest) 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 m.ProposalId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.ProposalId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryVotesResponse) 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 *QueryVotesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryVotesResponse) 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.Votes) > 0 { - for iNdEx := len(m.Votes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Votes[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 (m *QueryVoteRequest) 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 *QueryVoteRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryVoteRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Voter) > 0 { - i -= len(m.Voter) - copy(dAtA[i:], m.Voter) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Voter))) - i-- - dAtA[i] = 0x12 - } - if m.ProposalId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.ProposalId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryVoteResponse) 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 *QueryVoteResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryVoteResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.VoteType != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.VoteType)) - i-- - dAtA[i] = 0x18 - } - if len(m.Voter) > 0 { - i -= len(m.Voter) - copy(dAtA[i:], m.Voter) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Voter))) - i-- - dAtA[i] = 0x12 - } - if m.ProposalID != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.ProposalID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryTallyRequest) 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 *QueryTallyRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTallyRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.ProposalId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.ProposalId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryTallyResponse) 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 *QueryTallyResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTallyResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Quorum.Size() - i -= size - if _, err := m.Quorum.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - { - size := m.VoteThreshold.Size() - i -= size - if _, err := m.VoteThreshold.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size := m.PossibleVotes.Size() - i -= size - if _, err := m.PossibleVotes.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.CurrentVotes.Size() - i -= size - if _, err := m.CurrentVotes.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.NoVotes.Size() - i -= size - if _, err := m.NoVotes.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.YesVotes.Size() - i -= size - if _, err := m.YesVotes.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.ProposalID != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.ProposalID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryRawParamsRequest) 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 *QueryRawParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRawParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Key) > 0 { - i -= len(m.Key) - copy(dAtA[i:], m.Key) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Key))) - i-- - dAtA[i] = 0x12 - } - if len(m.Subspace) > 0 { - i -= len(m.Subspace) - copy(dAtA[i:], m.Subspace) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Subspace))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryRawParamsResponse) 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 *QueryRawParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRawParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RawData) > 0 { - i -= len(m.RawData) - copy(dAtA[i:], m.RawData) - i = encodeVarintQuery(dAtA, i, uint64(len(m.RawData))) - 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 *QueryCommitteesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryCommitteesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Committees) > 0 { - for _, e := range m.Committees { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryCommitteeRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CommitteeId != 0 { - n += 1 + sovQuery(uint64(m.CommitteeId)) - } - return n -} - -func (m *QueryCommitteeResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Committee != nil { - l = m.Committee.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryProposalsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CommitteeId != 0 { - n += 1 + sovQuery(uint64(m.CommitteeId)) - } - return n -} - -func (m *QueryProposalsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Proposals) > 0 { - for _, e := range m.Proposals { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryProposalRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.ProposalId != 0 { - n += 1 + sovQuery(uint64(m.ProposalId)) - } - return n -} - -func (m *QueryProposalResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PubProposal != nil { - l = m.PubProposal.Size() - n += 1 + l + sovQuery(uint64(l)) - } - if m.ID != 0 { - n += 1 + sovQuery(uint64(m.ID)) - } - if m.CommitteeID != 0 { - n += 1 + sovQuery(uint64(m.CommitteeID)) - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Deadline) - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryNextProposalIDRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryNextProposalIDResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.NextProposalID != 0 { - n += 1 + sovQuery(uint64(m.NextProposalID)) - } - return n -} - -func (m *QueryVotesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.ProposalId != 0 { - n += 1 + sovQuery(uint64(m.ProposalId)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryVotesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Votes) > 0 { - for _, e := range m.Votes { - 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 (m *QueryVoteRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.ProposalId != 0 { - n += 1 + sovQuery(uint64(m.ProposalId)) - } - l = len(m.Voter) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryVoteResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.ProposalID != 0 { - n += 1 + sovQuery(uint64(m.ProposalID)) - } - l = len(m.Voter) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.VoteType != 0 { - n += 1 + sovQuery(uint64(m.VoteType)) - } - return n -} - -func (m *QueryTallyRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.ProposalId != 0 { - n += 1 + sovQuery(uint64(m.ProposalId)) - } - return n -} - -func (m *QueryTallyResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.ProposalID != 0 { - n += 1 + sovQuery(uint64(m.ProposalID)) - } - l = m.YesVotes.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.NoVotes.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.CurrentVotes.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.PossibleVotes.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.VoteThreshold.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.Quorum.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryRawParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Subspace) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Key) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryRawParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.RawData) - if l > 0 { - 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 *QueryCommitteesRequest) 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: QueryCommitteesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCommitteesRequest: 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 *QueryCommitteesResponse) 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: QueryCommitteesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCommitteesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Committees", 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.Committees = append(m.Committees, &types.Any{}) - if err := m.Committees[len(m.Committees)-1].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 *QueryCommitteeRequest) 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: QueryCommitteeRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCommitteeRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CommitteeId", wireType) - } - m.CommitteeId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CommitteeId |= 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 *QueryCommitteeResponse) 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: QueryCommitteeResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCommitteeResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Committee", 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.Committee == nil { - m.Committee = &types.Any{} - } - if err := m.Committee.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 *QueryProposalsRequest) 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: QueryProposalsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryProposalsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CommitteeId", wireType) - } - m.CommitteeId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CommitteeId |= 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 *QueryProposalsResponse) 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: QueryProposalsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryProposalsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Proposals", 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.Proposals = append(m.Proposals, QueryProposalResponse{}) - if err := m.Proposals[len(m.Proposals)-1].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 *QueryProposalRequest) 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: QueryProposalRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryProposalRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ProposalId", wireType) - } - m.ProposalId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ProposalId |= 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 *QueryProposalResponse) 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: QueryProposalResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryProposalResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PubProposal", 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.PubProposal == nil { - m.PubProposal = &types.Any{} - } - if err := m.PubProposal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - m.ID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CommitteeID", wireType) - } - m.CommitteeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CommitteeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deadline", 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 := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Deadline, 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 *QueryNextProposalIDRequest) 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: QueryNextProposalIDRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryNextProposalIDRequest: 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 *QueryNextProposalIDResponse) 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: QueryNextProposalIDResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryNextProposalIDResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field NextProposalID", wireType) - } - m.NextProposalID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.NextProposalID |= 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 *QueryVotesRequest) 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: QueryVotesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryVotesRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ProposalId", wireType) - } - m.ProposalId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ProposalId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - 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.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 *QueryVotesResponse) 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: QueryVotesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryVotesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Votes", 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.Votes = append(m.Votes, QueryVoteResponse{}) - if err := m.Votes[len(m.Votes)-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 (m *QueryVoteRequest) 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: QueryVoteRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryVoteRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ProposalId", wireType) - } - m.ProposalId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ProposalId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Voter", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Voter = string(dAtA[iNdEx:postIndex]) - 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 *QueryVoteResponse) 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: QueryVoteResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryVoteResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ProposalID", wireType) - } - m.ProposalID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ProposalID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Voter", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Voter = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field VoteType", wireType) - } - m.VoteType = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.VoteType |= VoteType(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 *QueryTallyRequest) 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: QueryTallyRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTallyRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ProposalId", wireType) - } - m.ProposalId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ProposalId |= 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 *QueryTallyResponse) 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: QueryTallyResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTallyResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ProposalID", wireType) - } - m.ProposalID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ProposalID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field YesVotes", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.YesVotes.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NoVotes", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.NoVotes.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CurrentVotes", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.CurrentVotes.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PossibleVotes", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.PossibleVotes.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field VoteThreshold", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.VoteThreshold.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Quorum", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Quorum.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 *QueryRawParamsRequest) 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: QueryRawParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRawParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Subspace", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Subspace = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Key = string(dAtA[iNdEx:postIndex]) - 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 *QueryRawParamsResponse) 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: QueryRawParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRawParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RawData", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RawData = string(dAtA[iNdEx:postIndex]) - 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/committee/types/query.pb.gw.go b/x/committee/types/query.pb.gw.go deleted file mode 100644 index 864960d8..00000000 --- a/x/committee/types/query.pb.gw.go +++ /dev/null @@ -1,929 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/committee/v1beta1/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_Committees_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCommitteesRequest - var metadata runtime.ServerMetadata - - msg, err := client.Committees(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Committees_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCommitteesRequest - var metadata runtime.ServerMetadata - - msg, err := server.Committees(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Committee_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCommitteeRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["committee_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "committee_id") - } - - protoReq.CommitteeId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "committee_id", err) - } - - msg, err := client.Committee(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Committee_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCommitteeRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["committee_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "committee_id") - } - - protoReq.CommitteeId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "committee_id", err) - } - - msg, err := server.Committee(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Proposals_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Proposals_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryProposalsRequest - 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_Proposals_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Proposals(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Proposals_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryProposalsRequest - 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_Proposals_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Proposals(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Proposal_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryProposalRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["proposal_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "proposal_id") - } - - protoReq.ProposalId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "proposal_id", err) - } - - msg, err := client.Proposal(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Proposal_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryProposalRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["proposal_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "proposal_id") - } - - protoReq.ProposalId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "proposal_id", err) - } - - msg, err := server.Proposal(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_NextProposalID_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryNextProposalIDRequest - var metadata runtime.ServerMetadata - - msg, err := client.NextProposalID(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_NextProposalID_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryNextProposalIDRequest - var metadata runtime.ServerMetadata - - msg, err := server.NextProposalID(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Votes_0 = &utilities.DoubleArray{Encoding: map[string]int{"proposal_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_Query_Votes_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryVotesRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["proposal_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "proposal_id") - } - - protoReq.ProposalId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "proposal_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Votes_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Votes(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Votes_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryVotesRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["proposal_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "proposal_id") - } - - protoReq.ProposalId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "proposal_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Votes_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Votes(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Vote_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryVoteRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["proposal_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "proposal_id") - } - - protoReq.ProposalId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "proposal_id", err) - } - - val, ok = pathParams["voter"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "voter") - } - - protoReq.Voter, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "voter", err) - } - - msg, err := client.Vote(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Vote_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryVoteRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["proposal_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "proposal_id") - } - - protoReq.ProposalId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "proposal_id", err) - } - - val, ok = pathParams["voter"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "voter") - } - - protoReq.Voter, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "voter", err) - } - - msg, err := server.Vote(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Tally_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTallyRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["proposal_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "proposal_id") - } - - protoReq.ProposalId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "proposal_id", err) - } - - msg, err := client.Tally(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Tally_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTallyRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["proposal_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "proposal_id") - } - - protoReq.ProposalId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "proposal_id", err) - } - - msg, err := server.Tally(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_RawParams_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_RawParams_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRawParamsRequest - 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_RawParams_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.RawParams(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_RawParams_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRawParamsRequest - 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_RawParams_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.RawParams(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_Committees_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_Committees_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_Committees_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Committee_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_Committee_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_Committee_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Proposals_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_Proposals_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_Proposals_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Proposal_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_Proposal_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_Proposal_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_NextProposalID_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_NextProposalID_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_NextProposalID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Votes_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_Votes_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_Votes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Vote_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_Vote_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_Vote_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Tally_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_Tally_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_Tally_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_RawParams_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_RawParams_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_RawParams_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_Committees_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_Committees_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_Committees_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Committee_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_Committee_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_Committee_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Proposals_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_Proposals_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_Proposals_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Proposal_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_Proposal_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_Proposal_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_NextProposalID_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_NextProposalID_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_NextProposalID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Votes_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_Votes_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_Votes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Vote_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_Vote_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_Vote_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Tally_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_Tally_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_Tally_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_RawParams_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_RawParams_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_RawParams_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Committees_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "committee", "v1beta1", "committees"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Committee_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"kava", "committee", "v1beta1", "committees", "committee_id"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Proposals_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "committee", "v1beta1", "proposals"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Proposal_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"kava", "committee", "v1beta1", "proposals", "proposal_id"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_NextProposalID_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "committee", "v1beta1", "next-proposal-id"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Votes_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"kava", "committee", "v1beta1", "proposals", "proposal_id", "votes"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Vote_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5, 1, 0, 4, 1, 5, 6}, []string{"kava", "committee", "v1beta1", "proposals", "proposal_id", "votes", "voter"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Tally_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"kava", "committee", "v1beta1", "proposals", "proposal_id", "tally"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_RawParams_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "committee", "v1beta1", "raw-params"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Committees_0 = runtime.ForwardResponseMessage - - forward_Query_Committee_0 = runtime.ForwardResponseMessage - - forward_Query_Proposals_0 = runtime.ForwardResponseMessage - - forward_Query_Proposal_0 = runtime.ForwardResponseMessage - - forward_Query_NextProposalID_0 = runtime.ForwardResponseMessage - - forward_Query_Votes_0 = runtime.ForwardResponseMessage - - forward_Query_Vote_0 = runtime.ForwardResponseMessage - - forward_Query_Tally_0 = runtime.ForwardResponseMessage - - forward_Query_RawParams_0 = runtime.ForwardResponseMessage -) diff --git a/x/committee/v1/client/cli/query.go b/x/committee/v1/client/cli/query.go new file mode 100644 index 00000000..cdb65c6d --- /dev/null +++ b/x/committee/v1/client/cli/query.go @@ -0,0 +1,87 @@ +package cli + +import ( + "context" + "fmt" + "strings" + + "github.com/spf13/cobra" + + "github.com/0glabs/0g-chain/x/committee/v1/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" +) + +// GetQueryCmd returns the cli query commands for the inflation module. +func GetQueryCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Querying commands for the committee module", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + cmd.AddCommand( + GetCurrentCommitteeID(), + GetRegisteredVoters(), + ) + + return cmd +} + +func GetCurrentCommitteeID() *cobra.Command { + cmd := &cobra.Command{ + Use: "current-committee-id", + Short: "Query the current committee ID", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + params := &types.QueryCurrentCommitteeIDRequest{} + res, err := queryClient.CurrentCommitteeID(context.Background(), params) + if err != nil { + return err + } + + return clientCtx.PrintString(fmt.Sprintf("%v\n", res.CurrentCommitteeID)) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +func GetRegisteredVoters() *cobra.Command { + cmd := &cobra.Command{ + Use: "registered-voters", + Short: "Query registered voters", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + params := &types.QueryRegisteredVotersRequest{} + res, err := queryClient.RegisteredVoters(context.Background(), params) + if err != nil { + return err + } + + return clientCtx.PrintString(fmt.Sprintf("%v\n", strings.Join(res.Voters, ","))) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/x/committee/v1/client/cli/tx.go b/x/committee/v1/client/cli/tx.go new file mode 100644 index 00000000..cc648b78 --- /dev/null +++ b/x/committee/v1/client/cli/tx.go @@ -0,0 +1,196 @@ +package cli + +import ( + "bufio" + "bytes" + "encoding/hex" + "errors" + "fmt" + "strconv" + + sdkmath "cosmossdk.io/math" + "github.com/0glabs/0g-chain/crypto/vrf" + "github.com/0glabs/0g-chain/x/committee/v1/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/tx" + sdkkr "github.com/cosmos/cosmos-sdk/crypto/keyring" + sdk "github.com/cosmos/cosmos-sdk/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + vrfalgo "github.com/coniks-sys/coniks-go/crypto/vrf" + "github.com/cosmos/cosmos-sdk/client/input" + "github.com/spf13/cobra" +) + +// 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, + } + cmd.AddCommand( + NewRegisterCmd(), + NewVoteCmd(), + ) + return cmd +} + +func NewRegisterCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "register", + Short: "Register a voter", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + // bypass the restriction of set keyring options + ctx := client.GetClientContextFromCmd(cmd).WithKeyringOptions(vrf.VrfOption()) + client.SetCmdClientContext(cmd, ctx) + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + kr := clientCtx.Keyring + // get account name by address + accAddr := clientCtx.GetFromAddress() + accRecord, err := kr.KeyByAddress(accAddr) + if err != nil { + // not found record by address in keyring + return nil + } + + // check voter account record exists + voterAccName := accRecord.Name + "-voter" + _, err = kr.Key(voterAccName) + if err == nil { + // account exists, ask for user confirmation + response, err2 := input.GetConfirmation(fmt.Sprintf("override the existing name %s", voterAccName), bufio.NewReader(clientCtx.Input), cmd.ErrOrStderr()) + if err2 != nil { + return err2 + } + + if !response { + return errors.New("aborted") + } + + err2 = kr.Delete(voterAccName) + if err2 != nil { + return err2 + } + } + + keyringAlgos, _ := kr.SupportedAlgorithms() + algo, err := sdkkr.NewSigningAlgoFromString("vrf", keyringAlgos) + if err != nil { + return err + } + + newRecord, err := kr.NewAccount(voterAccName, "", "", "", algo) + if err != nil { + return err + } + + pubKey, err := newRecord.GetPubKey() + if err != nil { + return err + } + + valAddr, err := sdk.ValAddressFromHex(hex.EncodeToString(clientCtx.GetFromAddress().Bytes())) + if err != nil { + return err + } + + msg := &types.MsgRegister{ + Voter: valAddr.String(), + Key: pubKey.Bytes(), + } + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + return cmd +} + +func NewVoteCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "vote committee-id", + Short: "Vote on a proposal", + Args: cobra.MinimumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + kr := clientCtx.Keyring + + // get account name by address + inAddr := clientCtx.GetFromAddress() + + valAddr, err := sdk.ValAddressFromHex(hex.EncodeToString(inAddr.Bytes())) + if err != nil { + return err + } + + inRecord, err := kr.KeyByAddress(inAddr) + if err != nil { + // not found record by address in keyring + return nil + } + + // check voter account record exists + voterAccName := inRecord.Name + "-voter" + voterRecord, err := kr.Key(voterAccName) + if err != nil { + // not found voter account + return err + } + sk := vrfalgo.PrivateKey(voterRecord.GetLocal().PrivKey.Value) + + committeeID, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return err + } + + votingStartHeight := types.DefaultVotingStartHeight + (committeeID-1)*types.DefaultVotingPeriod + + rsp, err := stakingtypes.NewQueryClient(clientCtx).HistoricalInfo(cmd.Context(), &stakingtypes.QueryHistoricalInfoRequest{Height: int64(votingStartHeight)}) + if err != nil { + return err + } + + var tokens sdkmath.Int + for _, val := range rsp.Hist.Valset { + thisValAddr := val.GetOperator() + if thisValAddr.Equals(valAddr) { + tokens = val.GetTokens() + } + } + + // 1_000 0AGI token / vote + numBallots := tokens.Quo(sdk.NewInt(1_000_000_000_000_000_000)).Quo(sdk.NewInt(1_000)).Uint64() + ballots := make([]*types.Ballot, numBallots) + for i := range ballots { + ballotID := uint64(i) + ballots[i] = &types.Ballot{ + ID: ballotID, + Content: sk.Compute(bytes.Join([][]byte{rsp.Hist.Header.LastCommitHash, types.Uint64ToBytes(ballotID)}, nil)), + } + } + + msg := &types.MsgVote{ + CommitteeID: committeeID, + Voter: valAddr.String(), + Ballots: ballots, + } + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + return cmd +} diff --git a/x/committee/v1/genesis.go b/x/committee/v1/genesis.go new file mode 100644 index 00000000..c369ff45 --- /dev/null +++ b/x/committee/v1/genesis.go @@ -0,0 +1,56 @@ +package committee + +import ( + "fmt" + + errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/0glabs/0g-chain/x/committee/v1/keeper" + "github.com/0glabs/0g-chain/x/committee/v1/types" +) + +// InitGenesis initializes the store state from a genesis state. +func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, gs types.GenesisState) { + if err := gs.Validate(); err != nil { + panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) + } + + params := gs.Params + err := keeper.SetParams(ctx, params) + if err != nil { + panic(errorsmod.Wrapf(err, "error setting params")) + } + + keeper.SetCurrentCommitteeID(ctx, gs.CurrentCommitteeID) + + for _, p := range gs.Committees { + keeper.SetCommittee(ctx, p) + } +} + +// ExportGenesis returns a GenesisState for a given context and keeper. +func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) *types.GenesisState { + startHeight, err := keeper.GetVotingStartHeight(ctx) + if err != nil { + panic(err) + } + + period, err := keeper.GetVotingPeriod(ctx) + if err != nil { + panic(err) + } + + currentID, err := keeper.GetCurrentCommitteeID(ctx) + if err != nil { + panic(err) + } + + return types.NewGenesisState( + keeper.GetParams(ctx), + startHeight, + period, + currentID, + keeper.GetCommittees(ctx), + ) +} diff --git a/x/committee/v1/keeper/abci.go b/x/committee/v1/keeper/abci.go new file mode 100644 index 00000000..5357c4e4 --- /dev/null +++ b/x/committee/v1/keeper/abci.go @@ -0,0 +1,72 @@ +package keeper + +import ( + "sort" + + abci "github.com/cometbft/cometbft/abci/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type Ballot struct { + voter sdk.ValAddress + content string +} + +func (k *Keeper) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { + committeeID, err := k.GetCurrentCommitteeID(ctx) + if err != nil { + // TODO: handle the case where committeeID is not available + return + } + committee, bz := k.GetCommittee(ctx, committeeID) + if !bz { + return + } + + if ctx.BlockHeight() >= int64(committee.StartHeight) { + // We are ready to accept votes for the next committee + if err := k.StoreNewCommittee(ctx, committee.StartHeight); err != nil { + return + } + } + + if ctx.BlockHeight() < int64(committee.EndHeight) { + return + } + + k.IncrementCurrentCommitteeID(ctx) + committee, bz = k.GetCommittee(ctx, committeeID+1) + if !bz { + return + } + + ballots := []Ballot{} + seen := make(map[string]struct{}) + for _, vote := range committee.Votes { + for _, ballot := range vote.Ballots { + ballot := Ballot{ + voter: vote.Voter, + content: string(ballot.Content), + } + if _, ok := seen[ballot.content]; ok { + continue + } + ballots = append(ballots, ballot) + seen[ballot.content] = struct{}{} + } + } + sort.Slice(ballots, func(i, j int) bool { + return ballots[i].content < ballots[j].content + }) + + committeeSize := k.GetParams(ctx).CommitteeSize + committee.Members = make([]sdk.ValAddress, committeeSize) + for i := 0; i < int(committeeSize); i = i + 1 { + committee.Members[i] = ballots[i].voter + } + + k.SetCommittee(ctx, committee) +} + +func (k *Keeper) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) { +} diff --git a/x/committee/v1/keeper/grpc_query.go b/x/committee/v1/keeper/grpc_query.go new file mode 100644 index 00000000..efb23909 --- /dev/null +++ b/x/committee/v1/keeper/grpc_query.go @@ -0,0 +1,35 @@ +package keeper + +import ( + "context" + + "github.com/0glabs/0g-chain/x/committee/v1/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var _ types.QueryServer = Keeper{} + +func (k Keeper) CurrentCommitteeID( + c context.Context, + _ *types.QueryCurrentCommitteeIDRequest, +) (*types.QueryCurrentCommitteeIDResponse, error) { + ctx := sdk.UnwrapSDKContext(c) + currentCommitteeID, err := k.GetCurrentCommitteeID(ctx) + if err != nil { + return nil, err + } + return &types.QueryCurrentCommitteeIDResponse{CurrentCommitteeID: currentCommitteeID}, nil +} + +func (k Keeper) RegisteredVoters( + c context.Context, + _ *types.QueryRegisteredVotersRequest, +) (*types.QueryRegisteredVotersResponse, error) { + ctx := sdk.UnwrapSDKContext(c) + voterAddrs := k.GetVoters(ctx) + voters := make([]string, len(voterAddrs)) + for i, voterAddr := range voterAddrs { + voters[i] = voterAddr.String() + } + return &types.QueryRegisteredVotersResponse{Voters: voters}, nil +} diff --git a/x/committee/v1/keeper/keeper.go b/x/committee/v1/keeper/keeper.go new file mode 100644 index 00000000..ab81d32a --- /dev/null +++ b/x/committee/v1/keeper/keeper.go @@ -0,0 +1,323 @@ +package keeper + +import ( + "fmt" + + errorsmod "cosmossdk.io/errors" + "github.com/cometbft/cometbft/libs/log" + "github.com/coniks-sys/coniks-go/crypto/vrf" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store/prefix" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/0glabs/0g-chain/x/committee/v1/types" +) + +// Keeper of the inflation store +type Keeper struct { + storeKey storetypes.StoreKey + cdc codec.BinaryCodec + stakingKeeper types.StakingKeeper +} + +// NewKeeper creates a new mint Keeper instance +func NewKeeper( + storeKey storetypes.StoreKey, + cdc codec.BinaryCodec, + stakingKeeper types.StakingKeeper, +) Keeper { + return Keeper{ + storeKey: storeKey, + cdc: cdc, + stakingKeeper: stakingKeeper, + } +} + +// Logger returns a module-specific logger. +func (k Keeper) Logger(ctx sdk.Context) log.Logger { + return ctx.Logger().With("module", "x/"+types.ModuleName) +} + +// ------------------------------------------ +// Committees +// ------------------------------------------ + +func (k Keeper) SetCurrentCommitteeID(ctx sdk.Context, id uint64) { + store := ctx.KVStore(k.storeKey) + store.Set(types.CurrentCommitteeIDKey, types.GetKeyFromID(id)) +} + +func (k Keeper) GetCurrentCommitteeID(ctx sdk.Context) (uint64, error) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.CurrentCommitteeIDKey) + if bz == nil { + return 0, errorsmod.Wrap(types.ErrInvalidGenesis, "current committee ID not set at genesis") + } + return types.Uint64FromBytes(bz), nil +} + +func (k Keeper) IncrementCurrentCommitteeID(ctx sdk.Context) error { + id, err := k.GetCurrentCommitteeID(ctx) + if err != nil { + return err + } + k.SetCurrentCommitteeID(ctx, id+1) + return nil +} + +func (k Keeper) SetVotingStartHeight(ctx sdk.Context, votingStartHeight uint64) { + store := ctx.KVStore(k.storeKey) + store.Set(types.VotingStartHeightKey, types.GetKeyFromID(votingStartHeight)) +} + +func (k Keeper) GetVotingStartHeight(ctx sdk.Context) (uint64, error) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.VotingStartHeightKey) + if bz == nil { + return 0, errorsmod.Wrap(types.ErrInvalidGenesis, "voting start height not set at genesis") + } + return types.Uint64FromBytes(bz), nil +} + +func (k Keeper) SetVotingPeriod(ctx sdk.Context, votingPeriod uint64) { + store := ctx.KVStore(k.storeKey) + store.Set(types.VotingPeriodKey, types.GetKeyFromID(votingPeriod)) +} + +func (k Keeper) GetVotingPeriod(ctx sdk.Context) (uint64, error) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.VotingPeriodKey) + if bz == nil { + return 0, errorsmod.Wrap(types.ErrInvalidGenesis, "voting period not set at genesis") + } + return types.Uint64FromBytes(bz), nil +} + +// StoreNewCommittee stores a committee, adding a new ID +func (k Keeper) StoreNewCommittee(ctx sdk.Context, votingStartHeight uint64) error { + currentCommitteeID, err := k.GetCurrentCommitteeID(ctx) + if err != nil { + return err + } + + votingPeriod, err := k.GetVotingPeriod(ctx) + if err != nil { + return err + } + com := types.Committee{ + ID: currentCommitteeID + 1, + VotingStartHeight: votingStartHeight, + StartHeight: votingStartHeight + votingPeriod, + EndHeight: votingStartHeight + votingPeriod*2, + Votes: []types.Vote{}, + Members: []sdk.ValAddress{}, + } + k.SetCommittee(ctx, com) + + return nil +} + +func (k Keeper) GetCommittee(ctx sdk.Context, committeeID uint64) (types.Committee, bool) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.CommitteeKeyPrefix) + bz := store.Get(types.GetKeyFromID(committeeID)) + if bz == nil { + return types.Committee{}, false + } + var com types.Committee + k.cdc.MustUnmarshal(bz, &com) + return com, true +} + +// SetCommittee puts a committee into the store. +func (k Keeper) SetCommittee(ctx sdk.Context, committee types.Committee) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.CommitteeKeyPrefix) + bz := k.cdc.MustMarshal(&committee) + store.Set(types.GetKeyFromID(committee.ID), bz) +} + +// // DeleteProposal removes a proposal from the store. +// func (k Keeper) DeleteProposal(ctx sdk.Context, proposalID uint64) { +// store := prefix.NewStore(ctx.KVStore(k.storeKey), types.ProposalKeyPrefix) +// store.Delete(types.GetKeyFromID(proposalID)) +// } + +// IterateProposals provides an iterator over all stored proposals. +// For each proposal, cb will be called. If cb returns true, the iterator will close and stop. +func (k Keeper) IterateCommittee(ctx sdk.Context, cb func(proposal types.Committee) (stop bool)) { + iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.CommitteeKeyPrefix) + + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + var committee types.Committee + k.cdc.MustUnmarshal(iterator.Value(), &committee) + if cb(committee) { + break + } + } +} + +func (k Keeper) GetCommittees(ctx sdk.Context) types.Committees { + results := types.Committees{} + k.IterateCommittee(ctx, func(prop types.Committee) bool { + results = append(results, prop) + return false + }) + return results +} + +// // DeleteProposalAndVotes removes a proposal and its associated votes. +// func (k Keeper) DeleteProposalAndVotes(ctx sdk.Context, proposalID uint64) { +// votes := k.GetVotesByProposal(ctx, proposalID) +// k.DeleteProposal(ctx, proposalID) +// for _, v := range votes { +// k.DeleteVote(ctx, v.ProposalID, v.Voter) +// } +// } + +// ------------------------------------------ +// Votes +// ------------------------------------------ + +// GetVote gets a vote from the store. +func (k Keeper) GetVote(ctx sdk.Context, epochID uint64, voter sdk.ValAddress) (types.Vote, bool) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.VoteKeyPrefix) + bz := store.Get(types.GetVoteKey(epochID, voter)) + if bz == nil { + return types.Vote{}, false + } + var vote types.Vote + k.cdc.MustUnmarshal(bz, &vote) + return vote, true +} + +// SetVote puts a vote into the store. +func (k Keeper) SetVote(ctx sdk.Context, vote types.Vote) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.VoteKeyPrefix) + bz := k.cdc.MustMarshal(&vote) + store.Set(types.GetVoteKey(vote.CommitteeID, vote.Voter), bz) +} + +// DeleteVote removes a Vote from the store. +func (k Keeper) DeleteVote(ctx sdk.Context, committeeID uint64, voter sdk.ValAddress) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.VoteKeyPrefix) + store.Delete(types.GetVoteKey(committeeID, voter)) +} + +// IterateVotes provides an iterator over all stored votes. +// For each vote, cb will be called. If cb returns true, the iterator will close and stop. +func (k Keeper) IterateVotes(ctx sdk.Context, cb func(vote types.Vote) (stop bool)) { + iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.VoteKeyPrefix) + + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + var vote types.Vote + k.cdc.MustUnmarshal(iterator.Value(), &vote) + + if cb(vote) { + break + } + } +} + +// GetVotes returns all stored votes. +func (k Keeper) GetVotes(ctx sdk.Context) []types.Vote { + results := []types.Vote{} + k.IterateVotes(ctx, func(vote types.Vote) bool { + results = append(results, vote) + return false + }) + return results +} + +// GetVotesByProposal returns all votes for one proposal. +func (k Keeper) GetVotesByCommittee(ctx sdk.Context, committeeID uint64) []types.Vote { + results := []types.Vote{} + iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), append(types.VoteKeyPrefix, types.GetKeyFromID(committeeID)...)) + + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + var vote types.Vote + k.cdc.MustUnmarshal(iterator.Value(), &vote) + results = append(results, vote) + } + + return results +} + +// ------------------------------------------ +// Voters +// ------------------------------------------ + +func (k Keeper) SetVoter(ctx sdk.Context, voter sdk.ValAddress, pk vrf.PublicKey) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.VoterKeyPrefix) + store.Set(types.GetVoterKey(voter), pk) + fmt.Printf("voterStoreKey: %v, publicKey: %v\n", types.GetVoterKey(voter), pk) +} + +func (k Keeper) IterateVoters(ctx sdk.Context, cb func(voter sdk.ValAddress, pk vrf.PublicKey) (stop bool)) { + iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.VoterKeyPrefix) + + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + if cb(sdk.ValAddress(iterator.Key()[1:]), vrf.PublicKey(iterator.Value())) { + break + } + } +} + +// GetVotes returns all stored voters +func (k Keeper) GetVoters(ctx sdk.Context) []sdk.ValAddress { + results := []sdk.ValAddress{} + k.IterateVoters(ctx, func(voter sdk.ValAddress, _ vrf.PublicKey) bool { + results = append(results, voter) + return false + }) + return results +} + +func (k Keeper) AddVoter(ctx sdk.Context, voter sdk.ValAddress, key []byte) error { + if len(key) != vrf.PublicKeySize { + return types.ErrInvalidPublicKey + } + + k.SetVoter(ctx, voter, vrf.PublicKey(key)) + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeRegister, + sdk.NewAttribute(types.AttributeKeyVoter, voter.String()), + // TODO: types.AttributeKeyPublicKey + ), + ) + + return nil +} + +func (k Keeper) AddVote(ctx sdk.Context, committeeID uint64, voter sdk.ValAddress, ballots []*types.Ballot) error { + // Validate + com, found := k.GetCommittee(ctx, committeeID) + if !found { + return errorsmod.Wrapf(types.ErrUnknownCommittee, "%d", committeeID) + } + if com.HasVotingEndedBy(ctx.BlockHeight()) { + return errorsmod.Wrapf(types.ErrProposalExpired, "%d ≥ %d", ctx.BlockHeight(), com.StartHeight) + } + + // TODO: verify if the voter is registered + // TODO: verify whether ballots are valid or not + + // Store vote, overwriting any prior vote + k.SetVote(ctx, types.NewVote(committeeID, voter, ballots)) + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeVote, + sdk.NewAttribute(types.AttributeKeyCommitteeID, fmt.Sprintf("%d", com.ID)), + sdk.NewAttribute(types.AttributeKeyVoter, voter.String()), + // TODO: types.AttributeKeyBallots + ), + ) + + return nil +} diff --git a/x/committee/v1/keeper/msg_server.go b/x/committee/v1/keeper/msg_server.go new file mode 100644 index 00000000..668031d1 --- /dev/null +++ b/x/committee/v1/keeper/msg_server.go @@ -0,0 +1,51 @@ +// Copyright Tharsis Labs Ltd.(Evmos) +// SPDX-License-Identifier:ENCL-1.0(https://github.com/evmos/evmos/blob/main/LICENSE) + +package keeper + +import ( + "context" + + "github.com/0glabs/0g-chain/x/committee/v1/types" + sdk "github.com/cosmos/cosmos-sdk/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +var _ types.MsgServer = &Keeper{} + +// Register handles MsgRegister messages +func (k Keeper) Register(goCtx context.Context, msg *types.MsgRegister) (*types.MsgRegisterResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + valAddr, err := sdk.ValAddressFromBech32(msg.Voter) + if err != nil { + return nil, err + } + + _, found := k.stakingKeeper.GetValidator(ctx, valAddr) + if !found { + return nil, stakingtypes.ErrNoValidatorFound + } + + if err := k.AddVoter(ctx, valAddr, msg.Key); err != nil { + return nil, err + } + + return &types.MsgRegisterResponse{}, nil +} + +// Vote handles MsgVote messages +func (k Keeper) Vote(goCtx context.Context, msg *types.MsgVote) (*types.MsgVoteResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + voter, err := sdk.ValAddressFromBech32(msg.Voter) + if err != nil { + return nil, err + } + + if err := k.AddVote(ctx, msg.CommitteeID, voter, msg.Ballots); err != nil { + return nil, err + } + + return &types.MsgVoteResponse{}, nil +} diff --git a/x/committee/v1/keeper/params.go b/x/committee/v1/keeper/params.go new file mode 100644 index 00000000..edbe3a20 --- /dev/null +++ b/x/committee/v1/keeper/params.go @@ -0,0 +1,29 @@ +package keeper + +import ( + "github.com/0glabs/0g-chain/x/committee/v1/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.ParamsKey) + if len(bz) == 0 { + return params + } + + k.cdc.MustUnmarshal(bz, ¶ms) + return params +} + +func (k Keeper) SetParams(ctx sdk.Context, params types.Params) error { + store := ctx.KVStore(k.storeKey) + bz, err := k.cdc.Marshal(¶ms) + if err != nil { + return err + } + + store.Set(types.ParamsKey, bz) + + return nil +} diff --git a/x/committee/v1/module.go b/x/committee/v1/module.go new file mode 100644 index 00000000..4b330ce0 --- /dev/null +++ b/x/committee/v1/module.go @@ -0,0 +1,171 @@ +package committee + +import ( + "context" + "encoding/json" + "fmt" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + + "github.com/0glabs/0g-chain/x/committee/v1/client/cli" + "github.com/0glabs/0g-chain/x/committee/v1/keeper" + "github.com/0glabs/0g-chain/x/committee/v1/types" +) + +// consensusVersion defines the current x/committee module consensus version. +const consensusVersion = 1 + +// type check to ensure the interface is properly implemented +var ( + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModule{} + _ module.BeginBlockAppModule = AppModule{} + _ module.EndBlockAppModule = AppModule{} +) + +// app module Basics object +type AppModuleBasic struct{} + +// Name returns the inflation module's name. +func (AppModuleBasic) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec registers the inflation module's types on the given LegacyAmino codec. +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} + +// ConsensusVersion returns the consensus state-breaking version for the module. +func (AppModuleBasic) ConsensusVersion() uint64 { + return consensusVersion +} + +// RegisterInterfaces registers interfaces and implementations of the incentives +// module. +func (AppModuleBasic) RegisterInterfaces(interfaceRegistry codectypes.InterfaceRegistry) { + types.RegisterInterfaces(interfaceRegistry) +} + +// DefaultGenesis returns default genesis state as raw bytes for the incentives +// module. +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { + return cdc.MustMarshalJSON(types.DefaultGenesisState()) +} + +// ValidateGenesis performs genesis state validation for the inflation module. +func (b AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { + var genesisState types.GenesisState + if err := cdc.UnmarshalJSON(bz, &genesisState); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return genesisState.Validate() +} + +// RegisterRESTRoutes performs a no-op as the inflation module doesn't expose REST +// endpoints +func (AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) {} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the inflation module. +func (b AppModuleBasic) RegisterGRPCGatewayRoutes(c client.Context, serveMux *runtime.ServeMux) { + if err := types.RegisterQueryHandlerClient(context.Background(), serveMux, types.NewQueryClient(c)); err != nil { + panic(err) + } +} + +// GetTxCmd returns the root tx command for the inflation module. +func (AppModuleBasic) GetTxCmd() *cobra.Command { return cli.GetTxCmd() } + +// GetQueryCmd returns no root query command for the inflation module. +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd() +} + +// ___________________________________________________________________________ + +// AppModule implements an application module for the inflation module. +type AppModule struct { + AppModuleBasic + keeper keeper.Keeper + sk *stakingkeeper.Keeper +} + +// NewAppModule creates a new AppModule Object +func NewAppModule( + k keeper.Keeper, + sk *stakingkeeper.Keeper, +) AppModule { + return AppModule{ + AppModuleBasic: AppModuleBasic{}, + keeper: k, + sk: sk, + } +} + +// Name returns the inflation module's name. +func (AppModule) Name() string { + return types.ModuleName +} + +// RegisterInvariants registers the inflation module invariants. +func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + +// 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(), am.keeper) + types.RegisterQueryServer(cfg.QueryServer(), am.keeper) +} + +func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { + am.keeper.BeginBlock(ctx, req) +} + +func (am AppModule) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) []abci.ValidatorUpdate { + am.keeper.EndBlock(ctx, req) + return []abci.ValidatorUpdate{} +} + +// InitGenesis performs genesis initialization for the inflation module. It returns +// no validator updates. +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { + var genesisState types.GenesisState + + cdc.MustUnmarshalJSON(data, &genesisState) + InitGenesis(ctx, am.keeper, genesisState) + return []abci.ValidatorUpdate{} +} + +// ExportGenesis returns the exported genesis state as raw bytes for the inflation +// module. +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { + gs := ExportGenesis(ctx, am.keeper) + return cdc.MustMarshalJSON(gs) +} + +// ___________________________________________________________________________ + +// AppModuleSimulation functions + +// GenerateGenesisState creates a randomized GenState of the inflation module. +func (am AppModule) GenerateGenesisState(_ *module.SimulationState) { +} + +// RegisterStoreDecoder registers a decoder for inflation module's types. +func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) { +} + +// WeightedOperations doesn't return any inflation module operation. +func (am AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { + return []simtypes.WeightedOperation{} +} diff --git a/x/committee/v1/types/codec.go b/x/committee/v1/types/codec.go new file mode 100644 index 00000000..288f2b89 --- /dev/null +++ b/x/committee/v1/types/codec.go @@ -0,0 +1,52 @@ +package types + +import ( + "github.com/0glabs/0g-chain/crypto/vrf" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/msgservice" +) + +var ( + amino = codec.NewLegacyAmino() + // ModuleCdc references the global evm module codec. Note, the codec should + // ONLY be used in certain instances of tests and for JSON encoding. + ModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) + + // AminoCdc is a amino codec created to support amino JSON compatible msgs. + AminoCdc = codec.NewAminoCodec(amino) +) + +const ( + // Amino names + registerName = "evmos/committee/MsgRegister" + voteName = "evmos/committee/MsgVote" +) + +// NOTE: This is required for the GetSignBytes function +func init() { + RegisterLegacyAminoCodec(amino) + amino.Seal() +} + +// RegisterInterfaces register implementations +func RegisterInterfaces(registry codectypes.InterfaceRegistry) { + registry.RegisterImplementations( + (*sdk.Msg)(nil), + &MsgRegister{}, + &MsgVote{}, + ) + + registry.RegisterImplementations((*cryptotypes.PubKey)(nil), &vrf.PubKey{}) + registry.RegisterImplementations((*cryptotypes.PrivKey)(nil), &vrf.PrivKey{}) + + msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +} + +// RegisterLegacyAminoCodec required for EIP-712 +func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + cdc.RegisterConcrete(&MsgRegister{}, registerName, nil) + cdc.RegisterConcrete(&MsgVote{}, voteName, nil) +} diff --git a/x/committee/v1/types/council.go b/x/committee/v1/types/council.go new file mode 100644 index 00000000..f879d6ed --- /dev/null +++ b/x/committee/v1/types/council.go @@ -0,0 +1,21 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type Committees []Committee +type Votes []Vote + +func (c Committee) HasVotingEndedBy(height int64) bool { + return height >= int64(c.StartHeight) +} + +// NewVote instantiates a new instance of Vote +func NewVote(committeeID uint64, voter sdk.ValAddress, ballots []*Ballot) Vote { + return Vote{ + CommitteeID: committeeID, + Voter: voter, + Ballots: ballots, + } +} diff --git a/x/committee/v1/types/epoch.go b/x/committee/v1/types/epoch.go new file mode 100644 index 00000000..d44612a1 --- /dev/null +++ b/x/committee/v1/types/epoch.go @@ -0,0 +1,3 @@ +package types + +type Epoch struct{} diff --git a/x/committee/types/errors.go b/x/committee/v1/types/errors.go similarity index 85% rename from x/committee/types/errors.go rename to x/committee/v1/types/errors.go index 82bcbcd8..9ee139fb 100644 --- a/x/committee/types/errors.go +++ b/x/committee/v1/types/errors.go @@ -14,4 +14,6 @@ var ( ErrUnknownSubspace = errorsmod.Register(ModuleName, 10, "subspace not found") ErrInvalidVoteType = errorsmod.Register(ModuleName, 11, "invalid vote type") ErrNotFoundProposalTally = errorsmod.Register(ModuleName, 12, "proposal tally not found") + ErrInvalidPublicKey = errorsmod.Register(ModuleName, 13, "invalid public key") + ErrInvalidValidatorAddress = errorsmod.Register(ModuleName, 14, "invalid validator address") ) diff --git a/x/committee/types/events.go b/x/committee/v1/types/events.go similarity index 59% rename from x/committee/types/events.go rename to x/committee/v1/types/events.go index 3cefe9f7..a8807b44 100644 --- a/x/committee/types/events.go +++ b/x/committee/v1/types/events.go @@ -2,17 +2,18 @@ package types // Module event types const ( - EventTypeProposalSubmit = "proposal_submit" - EventTypeProposalClose = "proposal_close" - EventTypeProposalVote = "proposal_vote" + EventTypeRegister = "register" + EventTypeVote = "vote" AttributeValueCategory = "committee" AttributeKeyCommitteeID = "committee_id" AttributeKeyProposalID = "proposal_id" - AttributeKeyDeadline = "deadline" + AttributeKeyVotingStartHeight = "voting_start_height" + AttributeKeyVotingEndHeight = "voting_end_height" AttributeKeyProposalCloseStatus = "status" AttributeKeyVoter = "voter" - AttributeKeyVote = "vote" + AttributeKeyBallots = "ballots" + AttributeKeyPublicKey = "public_key" AttributeKeyProposalOutcome = "proposal_outcome" AttributeKeyProposalTally = "proposal_tally" ) diff --git a/x/committee/v1/types/genesis.go b/x/committee/v1/types/genesis.go new file mode 100644 index 00000000..66fea4f3 --- /dev/null +++ b/x/committee/v1/types/genesis.go @@ -0,0 +1,42 @@ +package types + +const ( + DefaultVotingStartHeight = 1 + DefaultVotingPeriod = 200 +) + +// NewGenesisState returns a new genesis state object for the module. +func NewGenesisState(params Params, votingStartHeight uint64, votingPeriod uint64, currentCommitteeID uint64, committees Committees) *GenesisState { + return &GenesisState{ + Params: params, + VotingStartHeight: votingStartHeight, + VotingPeriod: votingPeriod, + CurrentCommitteeID: currentCommitteeID, + Committees: committees, + } +} + +// DefaultGenesisState returns the default genesis state for the module. +func DefaultGenesisState() *GenesisState { + return NewGenesisState( + Params{ + CommitteeSize: 1, + }, + DefaultVotingStartHeight, + DefaultVotingPeriod, + 1, + []Committee{ + { + ID: 1, + VotingStartHeight: DefaultVotingStartHeight, + StartHeight: DefaultVotingStartHeight + DefaultVotingPeriod, + EndHeight: DefaultVotingStartHeight + DefaultVotingPeriod*2, + Votes: Votes{}, + }}, + ) +} + +// Validate performs basic validation of genesis data. +func (gs GenesisState) Validate() error { + return nil +} diff --git a/x/issuance/types/genesis.pb.go b/x/committee/v1/types/genesis.pb.go similarity index 51% rename from x/issuance/types/genesis.pb.go rename to x/committee/v1/types/genesis.pb.go index 612b89c4..8ab49adf 100644 --- a/x/issuance/types/genesis.pb.go +++ b/x/committee/v1/types/genesis.pb.go @@ -1,27 +1,25 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/issuance/v1beta1/genesis.proto +// source: zgc/committee/v1/genesis.proto package types import ( fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/cosmos-sdk/codec/types" 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" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/durationpb" + _ "google.golang.org/protobuf/types/known/timestamppb" io "io" math "math" math_bits "math/bits" - time "time" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf -var _ = time.Kitchen // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. @@ -29,69 +27,15 @@ var _ = time.Kitchen // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package -// GenesisState defines the issuance module's genesis state. -type GenesisState struct { - // params defines all the parameters of the module. - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - Supplies []AssetSupply `protobuf:"bytes,2,rep,name=supplies,proto3" json:"supplies"` -} - -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_e567e34e5c078b96, []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) GetSupplies() []AssetSupply { - if m != nil { - return m.Supplies - } - return nil -} - -// Params defines the parameters for the issuance module. type Params struct { - Assets []Asset `protobuf:"bytes,1,rep,name=assets,proto3" json:"assets"` + CommitteeSize uint64 `protobuf:"varint,1,opt,name=committee_size,json=committeeSize,proto3" json:"committee_size,omitempty"` } -func (m *Params) Reset() { *m = Params{} } -func (*Params) ProtoMessage() {} +func (m *Params) Reset() { *m = Params{} } +func (m *Params) String() string { return proto.CompactTextString(m) } +func (*Params) ProtoMessage() {} func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_e567e34e5c078b96, []int{1} + return fileDescriptor_8ed77f46b627050b, []int{0} } func (m *Params) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -120,169 +64,34 @@ func (m *Params) XXX_DiscardUnknown() { var xxx_messageInfo_Params proto.InternalMessageInfo -func (m *Params) GetAssets() []Asset { +func (m *Params) GetCommitteeSize() uint64 { if m != nil { - return m.Assets - } - return nil -} - -// Asset type for assets in the issuance module -type Asset struct { - Owner string `protobuf:"bytes,1,opt,name=owner,proto3" json:"owner,omitempty"` - Denom string `protobuf:"bytes,2,opt,name=denom,proto3" json:"denom,omitempty"` - BlockedAddresses []string `protobuf:"bytes,3,rep,name=blocked_addresses,json=blockedAddresses,proto3" json:"blocked_addresses,omitempty"` - Paused bool `protobuf:"varint,4,opt,name=paused,proto3" json:"paused,omitempty"` - Blockable bool `protobuf:"varint,5,opt,name=blockable,proto3" json:"blockable,omitempty"` - RateLimit RateLimit `protobuf:"bytes,6,opt,name=rate_limit,json=rateLimit,proto3" json:"rate_limit"` -} - -func (m *Asset) Reset() { *m = Asset{} } -func (*Asset) ProtoMessage() {} -func (*Asset) Descriptor() ([]byte, []int) { - return fileDescriptor_e567e34e5c078b96, []int{2} -} -func (m *Asset) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Asset) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Asset.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 *Asset) XXX_Merge(src proto.Message) { - xxx_messageInfo_Asset.Merge(m, src) -} -func (m *Asset) XXX_Size() int { - return m.Size() -} -func (m *Asset) XXX_DiscardUnknown() { - xxx_messageInfo_Asset.DiscardUnknown(m) -} - -var xxx_messageInfo_Asset proto.InternalMessageInfo - -func (m *Asset) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *Asset) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *Asset) GetBlockedAddresses() []string { - if m != nil { - return m.BlockedAddresses - } - return nil -} - -func (m *Asset) GetPaused() bool { - if m != nil { - return m.Paused - } - return false -} - -func (m *Asset) GetBlockable() bool { - if m != nil { - return m.Blockable - } - return false -} - -func (m *Asset) GetRateLimit() RateLimit { - if m != nil { - return m.RateLimit - } - return RateLimit{} -} - -// RateLimit parameters for rate-limiting the supply of an issued asset -type RateLimit struct { - Active bool `protobuf:"varint,1,opt,name=active,proto3" json:"active,omitempty"` - Limit github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=limit,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"limit,omitempty"` - TimePeriod time.Duration `protobuf:"bytes,3,opt,name=time_period,json=timePeriod,proto3,stdduration" json:"time_period"` -} - -func (m *RateLimit) Reset() { *m = RateLimit{} } -func (m *RateLimit) String() string { return proto.CompactTextString(m) } -func (*RateLimit) ProtoMessage() {} -func (*RateLimit) Descriptor() ([]byte, []int) { - return fileDescriptor_e567e34e5c078b96, []int{3} -} -func (m *RateLimit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *RateLimit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_RateLimit.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 *RateLimit) XXX_Merge(src proto.Message) { - xxx_messageInfo_RateLimit.Merge(m, src) -} -func (m *RateLimit) XXX_Size() int { - return m.Size() -} -func (m *RateLimit) XXX_DiscardUnknown() { - xxx_messageInfo_RateLimit.DiscardUnknown(m) -} - -var xxx_messageInfo_RateLimit proto.InternalMessageInfo - -func (m *RateLimit) GetActive() bool { - if m != nil { - return m.Active - } - return false -} - -func (m *RateLimit) GetTimePeriod() time.Duration { - if m != nil { - return m.TimePeriod + return m.CommitteeSize } return 0 } -// AssetSupply contains information about an asset's rate-limited supply (the -// total supply of the asset is tracked in the top-level supply module) -type AssetSupply struct { - CurrentSupply types.Coin `protobuf:"bytes,1,opt,name=current_supply,json=currentSupply,proto3" json:"current_supply"` - TimeElapsed time.Duration `protobuf:"bytes,2,opt,name=time_elapsed,json=timeElapsed,proto3,stdduration" json:"time_elapsed"` +// GenesisState defines the committee module's genesis state. +type GenesisState struct { + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` + VotingStartHeight uint64 `protobuf:"varint,2,opt,name=voting_start_height,json=votingStartHeight,proto3" json:"voting_start_height,omitempty"` + VotingPeriod uint64 `protobuf:"varint,3,opt,name=voting_period,json=votingPeriod,proto3" json:"voting_period,omitempty"` + CurrentCommitteeID uint64 `protobuf:"varint,4,opt,name=current_committee_id,json=currentCommitteeId,proto3" json:"current_committee_id,omitempty"` + Committees []Committee `protobuf:"bytes,5,rep,name=committees,proto3" json:"committees"` } -func (m *AssetSupply) Reset() { *m = AssetSupply{} } -func (*AssetSupply) ProtoMessage() {} -func (*AssetSupply) Descriptor() ([]byte, []int) { - return fileDescriptor_e567e34e5c078b96, []int{4} +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_8ed77f46b627050b, []int{1} } -func (m *AssetSupply) XXX_Unmarshal(b []byte) error { +func (m *GenesisState) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } -func (m *AssetSupply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { +func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { - return xxx_messageInfo_AssetSupply.Marshal(b, m, deterministic) + return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) @@ -292,130 +101,243 @@ func (m *AssetSupply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) return b[:n], nil } } -func (m *AssetSupply) XXX_Merge(src proto.Message) { - xxx_messageInfo_AssetSupply.Merge(m, src) +func (m *GenesisState) XXX_Merge(src proto.Message) { + xxx_messageInfo_GenesisState.Merge(m, src) } -func (m *AssetSupply) XXX_Size() int { +func (m *GenesisState) XXX_Size() int { return m.Size() } -func (m *AssetSupply) XXX_DiscardUnknown() { - xxx_messageInfo_AssetSupply.DiscardUnknown(m) +func (m *GenesisState) XXX_DiscardUnknown() { + xxx_messageInfo_GenesisState.DiscardUnknown(m) } -var xxx_messageInfo_AssetSupply proto.InternalMessageInfo +var xxx_messageInfo_GenesisState proto.InternalMessageInfo -func (m *AssetSupply) GetCurrentSupply() types.Coin { - if m != nil { - return m.CurrentSupply +type Committee struct { + ID uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + VotingStartHeight uint64 `protobuf:"varint,2,opt,name=voting_start_height,json=votingStartHeight,proto3" json:"voting_start_height,omitempty"` + StartHeight uint64 `protobuf:"varint,3,opt,name=start_height,json=startHeight,proto3" json:"start_height,omitempty"` + EndHeight uint64 `protobuf:"varint,4,opt,name=end_height,json=endHeight,proto3" json:"end_height,omitempty"` + Votes []Vote `protobuf:"bytes,5,rep,name=votes,proto3" json:"votes"` + Members []github_com_cosmos_cosmos_sdk_types.ValAddress `protobuf:"bytes,6,rep,name=members,proto3,casttype=github.com/cosmos/cosmos-sdk/types.ValAddress" json:"members,omitempty"` +} + +func (m *Committee) Reset() { *m = Committee{} } +func (m *Committee) String() string { return proto.CompactTextString(m) } +func (*Committee) ProtoMessage() {} +func (*Committee) Descriptor() ([]byte, []int) { + return fileDescriptor_8ed77f46b627050b, []int{2} +} +func (m *Committee) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Committee) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Committee.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil } - return types.Coin{} +} +func (m *Committee) XXX_Merge(src proto.Message) { + xxx_messageInfo_Committee.Merge(m, src) +} +func (m *Committee) XXX_Size() int { + return m.Size() +} +func (m *Committee) XXX_DiscardUnknown() { + xxx_messageInfo_Committee.DiscardUnknown(m) } -func (m *AssetSupply) GetTimeElapsed() time.Duration { +var xxx_messageInfo_Committee proto.InternalMessageInfo + +func (m *Committee) GetID() uint64 { if m != nil { - return m.TimeElapsed + return m.ID } return 0 } -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.issuance.v1beta1.GenesisState") - proto.RegisterType((*Params)(nil), "kava.issuance.v1beta1.Params") - proto.RegisterType((*Asset)(nil), "kava.issuance.v1beta1.Asset") - proto.RegisterType((*RateLimit)(nil), "kava.issuance.v1beta1.RateLimit") - proto.RegisterType((*AssetSupply)(nil), "kava.issuance.v1beta1.AssetSupply") -} - -func init() { - proto.RegisterFile("kava/issuance/v1beta1/genesis.proto", fileDescriptor_e567e34e5c078b96) -} - -var fileDescriptor_e567e34e5c078b96 = []byte{ - // 590 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x53, 0x4f, 0x6f, 0xd3, 0x4e, - 0x10, 0x8d, 0x9b, 0x26, 0x4a, 0x36, 0xfd, 0xfd, 0x80, 0x55, 0x41, 0x6e, 0x55, 0x9c, 0x28, 0x48, - 0x28, 0x02, 0xba, 0x56, 0xcb, 0xad, 0x9c, 0x1a, 0x52, 0x10, 0x88, 0x43, 0xe5, 0x1e, 0x90, 0xb8, - 0x44, 0x6b, 0x7b, 0x30, 0xab, 0xda, 0x5e, 0xcb, 0xbb, 0x2e, 0xe4, 0x5b, 0xc0, 0xad, 0x47, 0x24, - 0xbe, 0x09, 0xa7, 0x1e, 0x7b, 0x44, 0x1c, 0x02, 0x4a, 0x6e, 0x7c, 0x0a, 0xb4, 0x7f, 0x92, 0xf4, - 0x40, 0x11, 0x27, 0xef, 0xcc, 0xbe, 0x37, 0x33, 0x6f, 0xfc, 0x16, 0xdd, 0x3b, 0xa5, 0x67, 0xd4, - 0x67, 0x42, 0x54, 0x34, 0x8f, 0xc0, 0x3f, 0xdb, 0x0b, 0x41, 0xd2, 0x3d, 0x3f, 0x81, 0x1c, 0x04, - 0x13, 0xa4, 0x28, 0xb9, 0xe4, 0xf8, 0xb6, 0x02, 0x91, 0x05, 0x88, 0x58, 0xd0, 0xb6, 0x17, 0x71, - 0x91, 0x71, 0xe1, 0x87, 0x54, 0xac, 0x98, 0x11, 0x67, 0xb9, 0xa1, 0x6d, 0x6f, 0x26, 0x3c, 0xe1, - 0xfa, 0xe8, 0xab, 0x93, 0xcd, 0x7a, 0x09, 0xe7, 0x49, 0x0a, 0xbe, 0x8e, 0xc2, 0xea, 0xad, 0x1f, - 0x57, 0x25, 0x95, 0x8c, 0x5b, 0x56, 0xff, 0x93, 0x83, 0x36, 0x9e, 0x9b, 0xf6, 0x27, 0x92, 0x4a, - 0xc0, 0x4f, 0x50, 0xb3, 0xa0, 0x25, 0xcd, 0x84, 0xeb, 0xf4, 0x9c, 0x41, 0x67, 0xff, 0x2e, 0xf9, - 0xe3, 0x38, 0xe4, 0x58, 0x83, 0x86, 0xeb, 0x17, 0xd3, 0x6e, 0x2d, 0xb0, 0x14, 0x3c, 0x42, 0x2d, - 0x51, 0x15, 0x45, 0xca, 0x40, 0xb8, 0x6b, 0xbd, 0xfa, 0xa0, 0xb3, 0xdf, 0xbf, 0x86, 0x7e, 0x28, - 0x04, 0xc8, 0x13, 0x85, 0x9d, 0xd8, 0x1a, 0x4b, 0x66, 0xff, 0x25, 0x6a, 0x9a, 0xea, 0xf8, 0x00, - 0x35, 0xa9, 0x02, 0xaa, 0x61, 0x54, 0xb5, 0x9d, 0xbf, 0x55, 0x5b, 0xcc, 0x62, 0x18, 0x07, 0xeb, - 0xe7, 0x9f, 0xbb, 0xb5, 0xfe, 0xdc, 0x41, 0x0d, 0x7d, 0x8b, 0x37, 0x51, 0x83, 0xbf, 0xcf, 0xa1, - 0xd4, 0xba, 0xda, 0x81, 0x09, 0x54, 0x36, 0x86, 0x9c, 0x67, 0xee, 0x9a, 0xc9, 0xea, 0x00, 0x3f, - 0x44, 0xb7, 0xc2, 0x94, 0x47, 0xa7, 0x10, 0x8f, 0x69, 0x1c, 0x97, 0x20, 0x04, 0x08, 0xb7, 0xde, - 0xab, 0x0f, 0xda, 0xc1, 0x4d, 0x7b, 0x71, 0xb8, 0xc8, 0xe3, 0x3b, 0x6a, 0x63, 0x95, 0x80, 0xd8, - 0x5d, 0xef, 0x39, 0x83, 0x56, 0x60, 0x23, 0xbc, 0x83, 0xda, 0x1a, 0x4b, 0xc3, 0x14, 0xdc, 0x86, - 0xbe, 0x5a, 0x25, 0xf0, 0x11, 0x42, 0x25, 0x95, 0x30, 0x4e, 0x59, 0xc6, 0xa4, 0xdb, 0xd4, 0xbb, - 0xee, 0x5d, 0x23, 0x2f, 0xa0, 0x12, 0x5e, 0x29, 0x9c, 0x95, 0xd8, 0x2e, 0x17, 0x09, 0xab, 0xf2, - 0xab, 0x83, 0xda, 0x4b, 0x90, 0x1a, 0x88, 0x46, 0x92, 0x9d, 0x81, 0x96, 0xda, 0x0a, 0x6c, 0x84, - 0x5f, 0xa3, 0x86, 0xe9, 0xa6, 0xb4, 0x6e, 0x0c, 0x0f, 0x55, 0xad, 0xef, 0xd3, 0xee, 0xfd, 0x84, - 0xc9, 0x77, 0x55, 0x48, 0x22, 0x9e, 0xf9, 0xd6, 0x63, 0xe6, 0xb3, 0x2b, 0xe2, 0x53, 0x5f, 0x4e, - 0x0a, 0x10, 0xe4, 0x45, 0x2e, 0x7f, 0x4d, 0xbb, 0x37, 0x34, 0xfd, 0x11, 0xcf, 0x98, 0x84, 0xac, - 0x90, 0x93, 0xc0, 0xd4, 0xc3, 0x23, 0xd4, 0x91, 0x2c, 0x83, 0x71, 0x01, 0x25, 0xe3, 0xb1, 0x5b, - 0xd7, 0x62, 0xb6, 0x88, 0xb1, 0x1e, 0x59, 0x58, 0x8f, 0x8c, 0xac, 0xf5, 0x86, 0x2d, 0xd5, 0xf9, - 0xfc, 0x47, 0xd7, 0x09, 0x90, 0xe2, 0x1d, 0x6b, 0x5a, 0xff, 0x8b, 0x83, 0x3a, 0x57, 0x6c, 0x81, - 0x9f, 0xa1, 0xff, 0xa3, 0xaa, 0x2c, 0x21, 0x97, 0x63, 0x6d, 0x8d, 0x89, 0x75, 0xe4, 0x16, 0x31, - 0xe3, 0x11, 0xf5, 0x12, 0x96, 0x3b, 0x7a, 0xca, 0x59, 0x6e, 0xd7, 0xf3, 0x9f, 0xa5, 0x2d, 0xeb, - 0x6c, 0xe8, 0xe9, 0x20, 0xa5, 0x85, 0xfa, 0x4b, 0x6b, 0xff, 0x3e, 0x9e, 0x96, 0x75, 0x64, 0x78, - 0x66, 0xd5, 0xc3, 0xd1, 0xc5, 0xcc, 0x73, 0x2e, 0x67, 0x9e, 0xf3, 0x73, 0xe6, 0x39, 0x1f, 0xe7, - 0x5e, 0xed, 0x72, 0xee, 0xd5, 0xbe, 0xcd, 0xbd, 0xda, 0x9b, 0x07, 0x57, 0xf6, 0xa8, 0xfe, 0xe3, - 0x6e, 0x4a, 0x43, 0xa1, 0x4f, 0xfe, 0x87, 0xd5, 0x9b, 0xd7, 0xfb, 0x0c, 0x9b, 0xba, 0xeb, 0xe3, - 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x3f, 0xa6, 0xf1, 0xda, 0x11, 0x04, 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 +func (m *Committee) GetVotingStartHeight() uint64 { + if m != nil { + return m.VotingStartHeight } - return dAtA[:n], nil + return 0 } -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.Supplies) > 0 { - for iNdEx := len(m.Supplies) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Supplies[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } +func (m *Committee) GetStartHeight() uint64 { + if m != nil { + return m.StartHeight } - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + return 0 +} + +func (m *Committee) GetEndHeight() uint64 { + if m != nil { + return m.EndHeight + } + return 0 +} + +func (m *Committee) GetVotes() []Vote { + if m != nil { + return m.Votes + } + return nil +} + +func (m *Committee) GetMembers() []github_com_cosmos_cosmos_sdk_types.ValAddress { + if m != nil { + return m.Members + } + return nil +} + +type Vote struct { + CommitteeID uint64 `protobuf:"varint,1,opt,name=committee_id,json=committeeId,proto3" json:"committee_id,omitempty"` + Voter github_com_cosmos_cosmos_sdk_types.ValAddress `protobuf:"bytes,2,opt,name=voter,proto3,casttype=github.com/cosmos/cosmos-sdk/types.ValAddress" json:"voter,omitempty"` + Ballots []*Ballot `protobuf:"bytes,3,rep,name=ballots,proto3" json:"ballots,omitempty"` +} + +func (m *Vote) Reset() { *m = Vote{} } +func (m *Vote) String() string { return proto.CompactTextString(m) } +func (*Vote) ProtoMessage() {} +func (*Vote) Descriptor() ([]byte, []int) { + return fileDescriptor_8ed77f46b627050b, []int{3} +} +func (m *Vote) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Vote) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Vote.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) if err != nil { - return 0, err + return nil, err } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) + return b[:n], nil } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil +} +func (m *Vote) XXX_Merge(src proto.Message) { + xxx_messageInfo_Vote.Merge(m, src) +} +func (m *Vote) XXX_Size() int { + return m.Size() +} +func (m *Vote) XXX_DiscardUnknown() { + xxx_messageInfo_Vote.DiscardUnknown(m) +} + +var xxx_messageInfo_Vote proto.InternalMessageInfo + +type Ballot struct { + ID uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Content []byte `protobuf:"bytes,2,opt,name=content,proto3" json:"content,omitempty"` +} + +func (m *Ballot) Reset() { *m = Ballot{} } +func (m *Ballot) String() string { return proto.CompactTextString(m) } +func (*Ballot) ProtoMessage() {} +func (*Ballot) Descriptor() ([]byte, []int) { + return fileDescriptor_8ed77f46b627050b, []int{4} +} +func (m *Ballot) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Ballot) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Ballot.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 *Ballot) XXX_Merge(src proto.Message) { + xxx_messageInfo_Ballot.Merge(m, src) +} +func (m *Ballot) XXX_Size() int { + return m.Size() +} +func (m *Ballot) XXX_DiscardUnknown() { + xxx_messageInfo_Ballot.DiscardUnknown(m) +} + +var xxx_messageInfo_Ballot proto.InternalMessageInfo + +func (m *Ballot) GetID() uint64 { + if m != nil { + return m.ID + } + return 0 +} + +func (m *Ballot) GetContent() []byte { + if m != nil { + return m.Content + } + return nil +} + +func init() { + proto.RegisterType((*Params)(nil), "zgc.committee.v1.Params") + proto.RegisterType((*GenesisState)(nil), "zgc.committee.v1.GenesisState") + proto.RegisterType((*Committee)(nil), "zgc.committee.v1.Committee") + proto.RegisterType((*Vote)(nil), "zgc.committee.v1.Vote") + proto.RegisterType((*Ballot)(nil), "zgc.committee.v1.Ballot") +} + +func init() { proto.RegisterFile("zgc/committee/v1/genesis.proto", fileDescriptor_8ed77f46b627050b) } + +var fileDescriptor_8ed77f46b627050b = []byte{ + // 596 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x94, 0x4d, 0x6e, 0xd3, 0x40, + 0x14, 0xc7, 0x63, 0x27, 0x75, 0xd5, 0x89, 0xcb, 0xc7, 0xb4, 0xaa, 0xdc, 0x22, 0xec, 0x12, 0x84, + 0x94, 0x4d, 0xec, 0x36, 0x48, 0x2c, 0xba, 0xab, 0x5b, 0x89, 0x64, 0x57, 0x39, 0x52, 0x17, 0x2c, + 0x88, 0xfc, 0x31, 0x4c, 0x46, 0xc4, 0x9e, 0xc8, 0x33, 0x89, 0x48, 0x4e, 0xc0, 0x92, 0x23, 0x70, + 0x01, 0x58, 0x71, 0x88, 0x2e, 0x2b, 0xc4, 0x82, 0x55, 0x84, 0x9c, 0x5b, 0xb0, 0x42, 0x99, 0xb1, + 0x4d, 0x92, 0xc2, 0x02, 0x89, 0x95, 0x3d, 0xef, 0xff, 0x9b, 0x37, 0xf3, 0x7f, 0xef, 0xd9, 0xc0, + 0x9c, 0xe1, 0xd0, 0x09, 0x69, 0x1c, 0x13, 0xce, 0x11, 0x72, 0x26, 0xa7, 0x0e, 0x46, 0x09, 0x62, + 0x84, 0xd9, 0xa3, 0x94, 0x72, 0x0a, 0x1f, 0xcc, 0x70, 0x68, 0x97, 0xba, 0x3d, 0x39, 0x3d, 0x3a, + 0x0c, 0x29, 0x8b, 0x29, 0xeb, 0x0b, 0xdd, 0x91, 0x0b, 0x09, 0x1f, 0xed, 0x63, 0x8a, 0xa9, 0x8c, + 0x2f, 0xdf, 0xf2, 0xe8, 0x21, 0xa6, 0x14, 0x0f, 0x91, 0x23, 0x56, 0xc1, 0xf8, 0x8d, 0xe3, 0x27, + 0xd3, 0x5c, 0xb2, 0x36, 0x25, 0x4e, 0x62, 0xc4, 0xb8, 0x1f, 0x8f, 0x24, 0xd0, 0x70, 0x80, 0x76, + 0xe5, 0xa7, 0x7e, 0xcc, 0xe0, 0x33, 0x70, 0xaf, 0xbc, 0x46, 0x9f, 0x91, 0x19, 0x32, 0x94, 0x63, + 0xa5, 0x59, 0xf3, 0x76, 0xcb, 0x68, 0x8f, 0xcc, 0x50, 0xe3, 0xb3, 0x0a, 0xf4, 0x97, 0xd2, 0x41, + 0x8f, 0xfb, 0x1c, 0xc1, 0x17, 0x40, 0x1b, 0x89, 0x0c, 0x82, 0xaf, 0xb7, 0x0d, 0x7b, 0xd3, 0x91, + 0x2d, 0x4f, 0x70, 0x6b, 0x37, 0x73, 0xab, 0xe2, 0xe5, 0x34, 0xb4, 0xc1, 0xde, 0x84, 0x72, 0x92, + 0xe0, 0x3e, 0xe3, 0x7e, 0xca, 0xfb, 0x03, 0x44, 0xf0, 0x80, 0x1b, 0xaa, 0x38, 0xf4, 0xa1, 0x94, + 0x7a, 0x4b, 0xa5, 0x23, 0x04, 0xf8, 0x14, 0xec, 0xe6, 0xfc, 0x08, 0xa5, 0x84, 0x46, 0x46, 0x55, + 0x90, 0xba, 0x0c, 0x5e, 0x89, 0x18, 0xec, 0x80, 0xfd, 0x70, 0x9c, 0xa6, 0x28, 0xe1, 0xfd, 0xdf, + 0x66, 0x48, 0x64, 0xd4, 0x96, 0xac, 0x7b, 0x90, 0xcd, 0x2d, 0x78, 0x21, 0xf5, 0x8b, 0x42, 0xee, + 0x5e, 0x7a, 0x30, 0xdc, 0x8c, 0x45, 0xf0, 0x1c, 0x80, 0x32, 0x03, 0x33, 0xb6, 0x8e, 0xab, 0xcd, + 0x7a, 0xfb, 0xd1, 0x5d, 0x6b, 0xe5, 0x96, 0xdc, 0xdd, 0xca, 0xa6, 0xb3, 0xda, 0xfb, 0x8f, 0x56, + 0xa5, 0xf1, 0x49, 0x05, 0x3b, 0x25, 0x05, 0x0f, 0x80, 0x4a, 0x22, 0x59, 0x59, 0x57, 0xcb, 0xe6, + 0x96, 0xda, 0xbd, 0xf4, 0x54, 0x12, 0xfd, 0x73, 0x35, 0x9e, 0x00, 0x7d, 0x0d, 0x94, 0xc5, 0xa8, + 0xb3, 0x15, 0xe4, 0x31, 0x00, 0x28, 0x89, 0x0a, 0x40, 0x54, 0xc0, 0xdb, 0x41, 0x49, 0x94, 0xcb, + 0x6d, 0xb0, 0x35, 0xa1, 0xbc, 0xf4, 0x76, 0x70, 0xd7, 0xdb, 0x35, 0xe5, 0x85, 0x2d, 0x89, 0xc2, + 0x00, 0x6c, 0xc7, 0x28, 0x0e, 0x50, 0xca, 0x0c, 0xed, 0xb8, 0xda, 0xd4, 0xdd, 0xce, 0xcf, 0xb9, + 0xd5, 0xc2, 0x84, 0x0f, 0xc6, 0xc1, 0x72, 0x6f, 0x3e, 0xad, 0xf9, 0xa3, 0xc5, 0xa2, 0xb7, 0x0e, + 0x9f, 0x8e, 0x10, 0xb3, 0xaf, 0xfd, 0xe1, 0x79, 0x14, 0xa5, 0x88, 0xb1, 0xaf, 0x5f, 0x5a, 0x7b, + 0xf9, 0x4c, 0xe7, 0x11, 0x77, 0xca, 0x11, 0xf3, 0x8a, 0xc4, 0x8d, 0x6f, 0x0a, 0xa8, 0x2d, 0x4f, + 0x86, 0x6d, 0xa0, 0xaf, 0xf5, 0x50, 0x16, 0xed, 0x7e, 0x36, 0xb7, 0xea, 0xab, 0xcd, 0xab, 0x87, + 0x2b, 0x5d, 0x7b, 0x2d, 0x4d, 0xa5, 0xa2, 0x70, 0xff, 0xf3, 0x7a, 0x32, 0x2d, 0x6c, 0x83, 0xed, + 0xc0, 0x1f, 0x0e, 0x29, 0x67, 0x46, 0x55, 0x94, 0xed, 0x0f, 0xd3, 0xee, 0x0a, 0xc0, 0x2b, 0xc0, + 0x7c, 0x0c, 0xce, 0x80, 0x26, 0x85, 0xbf, 0x8e, 0x80, 0x01, 0xb6, 0x43, 0x9a, 0x70, 0x94, 0xc8, + 0xb6, 0xeb, 0x5e, 0xb1, 0x74, 0xbb, 0x37, 0x99, 0xa9, 0xdc, 0x66, 0xa6, 0xf2, 0x23, 0x33, 0x95, + 0x0f, 0x0b, 0xb3, 0x72, 0xbb, 0x30, 0x2b, 0xdf, 0x17, 0x66, 0xe5, 0x95, 0xb3, 0x62, 0xee, 0x04, + 0x0f, 0xfd, 0x80, 0x39, 0x27, 0xb8, 0x15, 0x0e, 0x7c, 0x92, 0x38, 0xef, 0xd6, 0x7f, 0x3b, 0xc2, + 0x69, 0xa0, 0x89, 0xcf, 0xfe, 0xf9, 0xaf, 0x00, 0x00, 0x00, 0xff, 0xff, 0xfc, 0x35, 0x1d, 0xae, + 0x97, 0x04, 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { @@ -438,10 +360,38 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if len(m.Assets) > 0 { - for iNdEx := len(m.Assets) - 1; iNdEx >= 0; iNdEx-- { + if m.CommitteeSize != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.CommitteeSize)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +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.Committees) > 0 { + for iNdEx := len(m.Committees) - 1; iNdEx >= 0; iNdEx-- { { - size, err := m.Assets[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Committees[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -449,169 +399,26 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0xa + dAtA[i] = 0x2a } } - return len(dAtA) - i, nil -} - -func (m *Asset) 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 *Asset) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Asset) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.RateLimit.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - if m.Blockable { - i-- - if m.Blockable { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x28 - } - if m.Paused { - i-- - if m.Paused { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } + if m.CurrentCommitteeID != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.CurrentCommitteeID)) i-- dAtA[i] = 0x20 } - if len(m.BlockedAddresses) > 0 { - for iNdEx := len(m.BlockedAddresses) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.BlockedAddresses[iNdEx]) - copy(dAtA[i:], m.BlockedAddresses[iNdEx]) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.BlockedAddresses[iNdEx]))) - i-- - dAtA[i] = 0x1a - } - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.Denom))) + if m.VotingPeriod != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.VotingPeriod)) i-- - dAtA[i] = 0x12 + dAtA[i] = 0x18 } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.Owner))) + if m.VotingStartHeight != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.VotingStartHeight)) i-- - dAtA[i] = 0xa + dAtA[i] = 0x10 } - return len(dAtA) - i, nil -} - -func (m *RateLimit) 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 *RateLimit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *RateLimit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - n3, err3 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.TimePeriod, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.TimePeriod):]) - if err3 != nil { - return 0, err3 - } - i -= n3 - i = encodeVarintGenesis(dAtA, i, uint64(n3)) - i-- - dAtA[i] = 0x1a { - size := m.Limit.Size() - i -= size - if _, err := m.Limit.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.Active { - i-- - if m.Active { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *AssetSupply) 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 *AssetSupply) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AssetSupply) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - n4, err4 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.TimeElapsed, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.TimeElapsed):]) - if err4 != nil { - return 0, err4 - } - i -= n4 - i = encodeVarintGenesis(dAtA, i, uint64(n4)) - i-- - dAtA[i] = 0x12 - { - size, err := m.CurrentSupply.MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -623,6 +430,156 @@ func (m *AssetSupply) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *Committee) 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 *Committee) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Committee) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Members) > 0 { + for iNdEx := len(m.Members) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Members[iNdEx]) + copy(dAtA[i:], m.Members[iNdEx]) + i = encodeVarintGenesis(dAtA, i, uint64(len(m.Members[iNdEx]))) + i-- + dAtA[i] = 0x32 + } + } + if len(m.Votes) > 0 { + for iNdEx := len(m.Votes) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Votes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + } + if m.EndHeight != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.EndHeight)) + i-- + dAtA[i] = 0x20 + } + if m.StartHeight != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.StartHeight)) + i-- + dAtA[i] = 0x18 + } + if m.VotingStartHeight != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.VotingStartHeight)) + i-- + dAtA[i] = 0x10 + } + if m.ID != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.ID)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *Vote) 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 *Vote) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Vote) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Ballots) > 0 { + for iNdEx := len(m.Ballots) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Ballots[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if len(m.Voter) > 0 { + i -= len(m.Voter) + copy(dAtA[i:], m.Voter) + i = encodeVarintGenesis(dAtA, i, uint64(len(m.Voter))) + i-- + dAtA[i] = 0x12 + } + if m.CommitteeID != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.CommitteeID)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *Ballot) 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 *Ballot) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Ballot) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Content) > 0 { + i -= len(m.Content) + copy(dAtA[i:], m.Content) + i = encodeVarintGenesis(dAtA, i, uint64(len(m.Content))) + i-- + dAtA[i] = 0x12 + } + if m.ID != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.ID)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { offset -= sovGenesis(v) base := offset @@ -634,6 +591,18 @@ func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } +func (m *Params) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.CommitteeSize != 0 { + n += 1 + sovGenesis(uint64(m.CommitteeSize)) + } + return n +} + func (m *GenesisState) Size() (n int) { if m == nil { return 0 @@ -642,8 +611,17 @@ func (m *GenesisState) Size() (n int) { _ = l l = m.Params.Size() n += 1 + l + sovGenesis(uint64(l)) - if len(m.Supplies) > 0 { - for _, e := range m.Supplies { + if m.VotingStartHeight != 0 { + n += 1 + sovGenesis(uint64(m.VotingStartHeight)) + } + if m.VotingPeriod != 0 { + n += 1 + sovGenesis(uint64(m.VotingPeriod)) + } + if m.CurrentCommitteeID != 0 { + n += 1 + sovGenesis(uint64(m.CurrentCommitteeID)) + } + if len(m.Committees) > 0 { + for _, e := range m.Committees { l = e.Size() n += 1 + l + sovGenesis(uint64(l)) } @@ -651,14 +629,54 @@ func (m *GenesisState) Size() (n int) { return n } -func (m *Params) Size() (n int) { +func (m *Committee) Size() (n int) { if m == nil { return 0 } var l int _ = l - if len(m.Assets) > 0 { - for _, e := range m.Assets { + if m.ID != 0 { + n += 1 + sovGenesis(uint64(m.ID)) + } + if m.VotingStartHeight != 0 { + n += 1 + sovGenesis(uint64(m.VotingStartHeight)) + } + if m.StartHeight != 0 { + n += 1 + sovGenesis(uint64(m.StartHeight)) + } + if m.EndHeight != 0 { + n += 1 + sovGenesis(uint64(m.EndHeight)) + } + if len(m.Votes) > 0 { + for _, e := range m.Votes { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + if len(m.Members) > 0 { + for _, b := range m.Members { + l = len(b) + n += 1 + l + sovGenesis(uint64(l)) + } + } + return n +} + +func (m *Vote) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.CommitteeID != 0 { + n += 1 + sovGenesis(uint64(m.CommitteeID)) + } + l = len(m.Voter) + if l > 0 { + n += 1 + l + sovGenesis(uint64(l)) + } + if len(m.Ballots) > 0 { + for _, e := range m.Ballots { l = e.Size() n += 1 + l + sovGenesis(uint64(l)) } @@ -666,63 +684,19 @@ func (m *Params) Size() (n int) { return n } -func (m *Asset) Size() (n int) { +func (m *Ballot) Size() (n int) { if m == nil { return 0 } var l int _ = l - l = len(m.Owner) + if m.ID != 0 { + n += 1 + sovGenesis(uint64(m.ID)) + } + l = len(m.Content) if l > 0 { n += 1 + l + sovGenesis(uint64(l)) } - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - if len(m.BlockedAddresses) > 0 { - for _, s := range m.BlockedAddresses { - l = len(s) - n += 1 + l + sovGenesis(uint64(l)) - } - } - if m.Paused { - n += 2 - } - if m.Blockable { - n += 2 - } - l = m.RateLimit.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *RateLimit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Active { - n += 2 - } - l = m.Limit.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.TimePeriod) - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *AssetSupply) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.CurrentSupply.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.TimeElapsed) - n += 1 + l + sovGenesis(uint64(l)) return n } @@ -732,6 +706,75 @@ func sovGenesis(x uint64) (n int) { func sozGenesis(x uint64) (n int) { return sovGenesis(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 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: 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 { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CommitteeSize", wireType) + } + m.CommitteeSize = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CommitteeSize |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + 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 (m *GenesisState) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -795,10 +838,10 @@ func (m *GenesisState) Unmarshal(dAtA []byte) error { } iNdEx = postIndex case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Supplies", wireType) + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field VotingStartHeight", wireType) } - var msglen int + m.VotingStartHeight = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis @@ -808,229 +851,16 @@ func (m *GenesisState) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + m.VotingStartHeight |= uint64(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.Supplies = append(m.Supplies, AssetSupply{}) - if err := m.Supplies[len(m.Supplies)-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 (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 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: 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 { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Assets", 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.Assets = append(m.Assets, Asset{}) - if err := m.Assets[len(m.Assets)-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 (m *Asset) 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: Asset: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Asset: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BlockedAddresses", wireType) + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field VotingPeriod", wireType) } - var stringLen uint64 + m.VotingPeriod = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis @@ -1040,29 +870,16 @@ func (m *Asset) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + m.VotingPeriod |= uint64(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.BlockedAddresses = append(m.BlockedAddresses, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex case 4: if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Paused", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field CurrentCommitteeID", wireType) } - var v int + m.CurrentCommitteeID = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis @@ -1072,35 +889,14 @@ func (m *Asset) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - v |= int(b&0x7F) << shift + m.CurrentCommitteeID |= uint64(b&0x7F) << shift if b < 0x80 { break } } - m.Paused = bool(v != 0) case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Blockable", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Blockable = bool(v != 0) - case 6: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RateLimit", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Committees", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -1127,7 +923,8 @@ func (m *Asset) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.RateLimit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Committees = append(m.Committees, Committee{}) + if err := m.Committees[len(m.Committees)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -1152,7 +949,7 @@ func (m *Asset) Unmarshal(dAtA []byte) error { } return nil } -func (m *RateLimit) Unmarshal(dAtA []byte) error { +func (m *Committee) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -1175,17 +972,17 @@ func (m *RateLimit) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: RateLimit: wiretype end group for non-group") + return fmt.Errorf("proto: Committee: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: RateLimit: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: Committee: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Active", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) } - var v int + m.ID = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis @@ -1195,15 +992,105 @@ func (m *RateLimit) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - v |= int(b&0x7F) << shift + m.ID |= uint64(b&0x7F) << shift if b < 0x80 { break } } - m.Active = bool(v != 0) case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field VotingStartHeight", wireType) + } + m.VotingStartHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.VotingStartHeight |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field StartHeight", wireType) + } + m.StartHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.StartHeight |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field EndHeight", wireType) + } + m.EndHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.EndHeight |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Votes", 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.Votes = append(m.Votes, Vote{}) + if err := m.Votes[len(m.Votes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Members", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { @@ -1230,13 +1117,115 @@ func (m *RateLimit) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.Limit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Members = append(m.Members, make([]byte, postIndex-iNdEx)) + copy(m.Members[len(m.Members)-1], dAtA[iNdEx:postIndex]) + 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 (m *Vote) 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: Vote: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Vote: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CommitteeID", wireType) + } + m.CommitteeID = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CommitteeID |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Voter", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Voter = append(m.Voter[:0], dAtA[iNdEx:postIndex]...) + if m.Voter == nil { + m.Voter = []byte{} + } iNdEx = postIndex case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TimePeriod", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Ballots", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -1263,7 +1252,8 @@ func (m *RateLimit) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.TimePeriod, dAtA[iNdEx:postIndex]); err != nil { + m.Ballots = append(m.Ballots, &Ballot{}) + if err := m.Ballots[len(m.Ballots)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -1288,7 +1278,7 @@ func (m *RateLimit) Unmarshal(dAtA []byte) error { } return nil } -func (m *AssetSupply) Unmarshal(dAtA []byte) error { +func (m *Ballot) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -1311,17 +1301,17 @@ func (m *AssetSupply) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: AssetSupply: wiretype end group for non-group") + return fmt.Errorf("proto: Ballot: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: AssetSupply: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: Ballot: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CurrentSupply", wireType) + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) } - var msglen int + m.ID = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis @@ -1331,30 +1321,16 @@ func (m *AssetSupply) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + m.ID |= uint64(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.CurrentSupply.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TimeElapsed", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Content", wireType) } - var msglen int + var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis @@ -1364,23 +1340,24 @@ func (m *AssetSupply) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + if byteLen < 0 { return ErrInvalidLengthGenesis } - postIndex := iNdEx + msglen + postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } - if err := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.TimeElapsed, dAtA[iNdEx:postIndex]); err != nil { - return err + m.Content = append(m.Content[:0], dAtA[iNdEx:postIndex]...) + if m.Content == nil { + m.Content = []byte{} } iNdEx = postIndex default: diff --git a/x/committee/types/expected_keepers.go b/x/committee/v1/types/interfaces.go similarity index 67% rename from x/committee/types/expected_keepers.go rename to x/committee/v1/types/interfaces.go index d4352e6a..c48ad7f0 100644 --- a/x/committee/types/expected_keepers.go +++ b/x/committee/v1/types/interfaces.go @@ -3,13 +3,9 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) -type ParamKeeper interface { - GetSubspace(string) (paramstypes.Subspace, bool) -} - // AccountKeeper defines the expected account keeper type AccountKeeper interface { GetAccount(sdk.Context, sdk.AccAddress) authtypes.AccountI @@ -20,3 +16,8 @@ type BankKeeper interface { GetSupply(ctx sdk.Context, denom string) sdk.Coin GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin } + +type StakingKeeper interface { + BondDenom(ctx sdk.Context) (res string) + GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool) +} diff --git a/x/committee/types/keys.go b/x/committee/v1/types/keys.go similarity index 59% rename from x/committee/types/keys.go rename to x/committee/v1/types/keys.go index 3888a98f..3a55aa92 100644 --- a/x/committee/types/keys.go +++ b/x/committee/v1/types/keys.go @@ -12,34 +12,35 @@ const ( // StoreKey Top level store key where all module items will be stored StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default name for parameter store - DefaultParamspace = ModuleName ) // Key prefixes var ( CommitteeKeyPrefix = []byte{0x00} // prefix for keys that store committees - ProposalKeyPrefix = []byte{0x01} // prefix for keys that store proposals - VoteKeyPrefix = []byte{0x02} // prefix for keys that store votes + VoteKeyPrefix = []byte{0x01} // prefix for keys that store votes + VoterKeyPrefix = []byte{0x02} // prefix for keys that store voters - NextProposalIDKey = []byte{0x03} // key for the next proposal id + ParamsKey = []byte{0x03} + VotingStartHeightKey = []byte{0x04} + VotingPeriodKey = []byte{0x05} + CurrentCommitteeIDKey = []byte{0x06} ) // GetKeyFromID returns the bytes to use as a key for a uint64 id func GetKeyFromID(id uint64) []byte { - return uint64ToBytes(id) + return Uint64ToBytes(id) } -func GetVoteKey(proposalID uint64, voter sdk.AccAddress) []byte { - return append(GetKeyFromID(proposalID), voter.Bytes()...) +func GetVoteKey(committeeID uint64, voter sdk.ValAddress) []byte { + return append(GetKeyFromID(committeeID), voter.Bytes()...) +} + +func GetVoterKey(voter sdk.ValAddress) []byte { + return voter.Bytes() } // Uint64ToBytes converts a uint64 into fixed length bytes for use in store keys. -func uint64ToBytes(id uint64) []byte { +func Uint64ToBytes(id uint64) []byte { bz := make([]byte, 8) binary.BigEndian.PutUint64(bz, uint64(id)) return bz diff --git a/x/committee/v1/types/msg.go b/x/committee/v1/types/msg.go new file mode 100644 index 00000000..640cdf6f --- /dev/null +++ b/x/committee/v1/types/msg.go @@ -0,0 +1,65 @@ +package types + +import ( + "encoding/hex" + + "github.com/coniks-sys/coniks-go/crypto/vrf" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var _, _ sdk.Msg = &MsgRegister{}, &MsgVote{} + +// GetSigners returns the expected signers for a MsgRegister message. +func (msg *MsgRegister) GetSigners() []sdk.AccAddress { + valAddr, err := sdk.ValAddressFromBech32(msg.Voter) + if err != nil { + panic(err) + } + accAddr, err := sdk.AccAddressFromHexUnsafe(hex.EncodeToString(valAddr.Bytes())) + if err != nil { + panic(err) + } + return []sdk.AccAddress{accAddr} +} + +// ValidateBasic does a sanity check of the provided data +func (msg *MsgRegister) ValidateBasic() error { + if _, err := sdk.ValAddressFromBech32(msg.Voter); err != nil { + return ErrInvalidValidatorAddress + } + if len(msg.Key) != vrf.PublicKeySize { + return ErrInvalidPublicKey + } + return nil +} + +// GetSignBytes implements the LegacyMsg interface. +func (msg MsgRegister) GetSignBytes() []byte { + return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&msg)) +} + +// GetSigners returns the expected signers for a MsgVote message. +func (msg *MsgVote) GetSigners() []sdk.AccAddress { + valAddr, err := sdk.ValAddressFromBech32(msg.Voter) + if err != nil { + panic(err) + } + accAddr, err := sdk.AccAddressFromHexUnsafe(hex.EncodeToString(valAddr.Bytes())) + if err != nil { + panic(err) + } + return []sdk.AccAddress{accAddr} +} + +// ValidateBasic does a sanity check of the provided data +func (msg *MsgVote) ValidateBasic() error { + if _, err := sdk.ValAddressFromBech32(msg.Voter); err != nil { + return ErrInvalidValidatorAddress + } + return nil +} + +// GetSignBytes implements the LegacyMsg interface. +func (msg MsgVote) GetSignBytes() []byte { + return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&msg)) +} diff --git a/x/committee/v1/types/query.pb.go b/x/committee/v1/types/query.pb.go new file mode 100644 index 00000000..9d78029f --- /dev/null +++ b/x/committee/v1/types/query.pb.go @@ -0,0 +1,839 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: zgc/committee/v1/query.proto + +package types + +import ( + context "context" + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/cosmos-sdk/codec/types" + _ "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" + _ "google.golang.org/protobuf/types/known/timestamppb" + 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 QueryCurrentCommitteeIDRequest struct { +} + +func (m *QueryCurrentCommitteeIDRequest) Reset() { *m = QueryCurrentCommitteeIDRequest{} } +func (m *QueryCurrentCommitteeIDRequest) String() string { return proto.CompactTextString(m) } +func (*QueryCurrentCommitteeIDRequest) ProtoMessage() {} +func (*QueryCurrentCommitteeIDRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_e1eb280fe137a977, []int{0} +} +func (m *QueryCurrentCommitteeIDRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryCurrentCommitteeIDRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryCurrentCommitteeIDRequest.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 *QueryCurrentCommitteeIDRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryCurrentCommitteeIDRequest.Merge(m, src) +} +func (m *QueryCurrentCommitteeIDRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryCurrentCommitteeIDRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryCurrentCommitteeIDRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryCurrentCommitteeIDRequest proto.InternalMessageInfo + +type QueryCurrentCommitteeIDResponse struct { + CurrentCommitteeID uint64 `protobuf:"varint,1,opt,name=current_committee_id,json=currentCommitteeId,proto3" json:"current_committee_id,omitempty"` +} + +func (m *QueryCurrentCommitteeIDResponse) Reset() { *m = QueryCurrentCommitteeIDResponse{} } +func (m *QueryCurrentCommitteeIDResponse) String() string { return proto.CompactTextString(m) } +func (*QueryCurrentCommitteeIDResponse) ProtoMessage() {} +func (*QueryCurrentCommitteeIDResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_e1eb280fe137a977, []int{1} +} +func (m *QueryCurrentCommitteeIDResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryCurrentCommitteeIDResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryCurrentCommitteeIDResponse.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 *QueryCurrentCommitteeIDResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryCurrentCommitteeIDResponse.Merge(m, src) +} +func (m *QueryCurrentCommitteeIDResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryCurrentCommitteeIDResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryCurrentCommitteeIDResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryCurrentCommitteeIDResponse proto.InternalMessageInfo + +type QueryRegisteredVotersRequest struct { +} + +func (m *QueryRegisteredVotersRequest) Reset() { *m = QueryRegisteredVotersRequest{} } +func (m *QueryRegisteredVotersRequest) String() string { return proto.CompactTextString(m) } +func (*QueryRegisteredVotersRequest) ProtoMessage() {} +func (*QueryRegisteredVotersRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_e1eb280fe137a977, []int{2} +} +func (m *QueryRegisteredVotersRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryRegisteredVotersRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryRegisteredVotersRequest.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 *QueryRegisteredVotersRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryRegisteredVotersRequest.Merge(m, src) +} +func (m *QueryRegisteredVotersRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryRegisteredVotersRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryRegisteredVotersRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryRegisteredVotersRequest proto.InternalMessageInfo + +type QueryRegisteredVotersResponse struct { + Voters []string `protobuf:"bytes,1,rep,name=voters,proto3" json:"voters,omitempty"` +} + +func (m *QueryRegisteredVotersResponse) Reset() { *m = QueryRegisteredVotersResponse{} } +func (m *QueryRegisteredVotersResponse) String() string { return proto.CompactTextString(m) } +func (*QueryRegisteredVotersResponse) ProtoMessage() {} +func (*QueryRegisteredVotersResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_e1eb280fe137a977, []int{3} +} +func (m *QueryRegisteredVotersResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryRegisteredVotersResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryRegisteredVotersResponse.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 *QueryRegisteredVotersResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryRegisteredVotersResponse.Merge(m, src) +} +func (m *QueryRegisteredVotersResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryRegisteredVotersResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryRegisteredVotersResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryRegisteredVotersResponse proto.InternalMessageInfo + +func init() { + proto.RegisterType((*QueryCurrentCommitteeIDRequest)(nil), "zgc.committee.v1.QueryCurrentCommitteeIDRequest") + proto.RegisterType((*QueryCurrentCommitteeIDResponse)(nil), "zgc.committee.v1.QueryCurrentCommitteeIDResponse") + proto.RegisterType((*QueryRegisteredVotersRequest)(nil), "zgc.committee.v1.QueryRegisteredVotersRequest") + proto.RegisterType((*QueryRegisteredVotersResponse)(nil), "zgc.committee.v1.QueryRegisteredVotersResponse") +} + +func init() { proto.RegisterFile("zgc/committee/v1/query.proto", fileDescriptor_e1eb280fe137a977) } + +var fileDescriptor_e1eb280fe137a977 = []byte{ + // 425 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x52, 0x3f, 0x6f, 0xd3, 0x40, + 0x14, 0xf7, 0x15, 0xa8, 0xc4, 0x4d, 0xd5, 0xa9, 0xaa, 0x5a, 0x2b, 0x5c, 0x22, 0x2f, 0x14, 0x84, + 0x7d, 0x4e, 0x19, 0xd8, 0x5b, 0x06, 0x18, 0x18, 0xc8, 0xc0, 0xc0, 0x12, 0xf9, 0xcf, 0xe3, 0x7a, + 0xa2, 0xbe, 0x73, 0x7d, 0xe7, 0x88, 0x76, 0xe4, 0x13, 0x20, 0xf1, 0x15, 0x58, 0xf9, 0x1e, 0x19, + 0x23, 0xb1, 0x30, 0x45, 0xe0, 0xf0, 0x41, 0x50, 0xec, 0x8b, 0xa5, 0x98, 0x18, 0xc1, 0xe6, 0xf7, + 0xfb, 0xf3, 0xde, 0xef, 0xde, 0x33, 0x1e, 0xdc, 0xf2, 0x84, 0x25, 0x2a, 0xcb, 0x84, 0x31, 0x00, + 0x6c, 0x36, 0x66, 0xd7, 0x25, 0x14, 0x37, 0x41, 0x5e, 0x28, 0xa3, 0xc8, 0xc1, 0x2d, 0x4f, 0x82, + 0x96, 0x0d, 0x66, 0x63, 0xf7, 0x24, 0x51, 0x3a, 0x53, 0x7a, 0x5a, 0xf3, 0xac, 0x29, 0x1a, 0xb1, + 0x7b, 0xc8, 0x15, 0x57, 0x0d, 0xbe, 0xfe, 0xb2, 0xe8, 0x80, 0x2b, 0xc5, 0xaf, 0x80, 0x45, 0xb9, + 0x60, 0x91, 0x94, 0xca, 0x44, 0x46, 0x28, 0xb9, 0xf1, 0x9c, 0x58, 0xb6, 0xae, 0xe2, 0xf2, 0x1d, + 0x8b, 0xa4, 0x9d, 0xed, 0x0e, 0xbb, 0x94, 0x11, 0x19, 0x68, 0x13, 0x65, 0xb9, 0x15, 0xd0, 0x3f, + 0xa2, 0x73, 0x90, 0xa0, 0x85, 0xed, 0xed, 0x8d, 0x30, 0x7d, 0xbd, 0x7e, 0xcb, 0x45, 0x59, 0x14, + 0x20, 0xcd, 0xc5, 0x46, 0xf9, 0xf2, 0xf9, 0x04, 0xae, 0x4b, 0xd0, 0xc6, 0x7b, 0x8f, 0x87, 0xbd, + 0x0a, 0x9d, 0x2b, 0xa9, 0x81, 0xbc, 0xc0, 0x87, 0x49, 0xc3, 0x4e, 0xdb, 0x51, 0x53, 0x91, 0x1e, + 0xa3, 0x11, 0x3a, 0xbd, 0x7b, 0x7e, 0x54, 0x2d, 0x87, 0x64, 0x87, 0x9b, 0x24, 0x5d, 0x2c, 0xf5, + 0x28, 0x1e, 0xd4, 0xc3, 0x26, 0xc0, 0x85, 0x36, 0x50, 0x40, 0xfa, 0x46, 0x19, 0x28, 0xf4, 0x26, + 0xcc, 0x33, 0xfc, 0xa0, 0x87, 0xb7, 0x51, 0x8e, 0xf0, 0xfe, 0xac, 0x46, 0x8e, 0xd1, 0xe8, 0xce, + 0xe9, 0xfd, 0x89, 0xad, 0xce, 0x96, 0x7b, 0xf8, 0x5e, 0xed, 0x24, 0x5f, 0x11, 0xde, 0x91, 0x86, + 0x84, 0x41, 0xf7, 0x8c, 0xc1, 0xdf, 0x17, 0xe3, 0x8e, 0xff, 0xc3, 0xd1, 0xa4, 0xf3, 0xce, 0x3e, + 0x7e, 0xfb, 0xf5, 0x79, 0xef, 0x09, 0x79, 0xcc, 0x42, 0x9e, 0x5c, 0x46, 0x42, 0x6e, 0x9f, 0xc6, + 0x2e, 0xc4, 0x6f, 0x41, 0x5f, 0xa4, 0xe4, 0x0b, 0xc2, 0x07, 0xdd, 0xe7, 0x92, 0xa0, 0x67, 0x76, + 0xcf, 0xde, 0x5c, 0xf6, 0xcf, 0x7a, 0x9b, 0x94, 0xd5, 0x49, 0x1f, 0x91, 0x87, 0xbb, 0x93, 0x16, + 0xad, 0xcf, 0x6f, 0x16, 0x7c, 0xfe, 0x6a, 0xfe, 0x93, 0x3a, 0xf3, 0x8a, 0xa2, 0x45, 0x45, 0xd1, + 0x8f, 0x8a, 0xa2, 0x4f, 0x2b, 0xea, 0x2c, 0x56, 0xd4, 0xf9, 0xbe, 0xa2, 0xce, 0x5b, 0xc6, 0x85, + 0xb9, 0x2c, 0xe3, 0x75, 0x02, 0x16, 0xf2, 0xab, 0x28, 0xd6, 0x2c, 0xe4, 0x7e, 0xd3, 0xf8, 0xc3, + 0x76, 0x6b, 0x73, 0x93, 0x83, 0x8e, 0xf7, 0xeb, 0xdf, 0xf3, 0xe9, 0xef, 0x00, 0x00, 0x00, 0xff, + 0xff, 0xbc, 0x1f, 0xba, 0xac, 0x7b, 0x03, 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 { + CurrentCommitteeID(ctx context.Context, in *QueryCurrentCommitteeIDRequest, opts ...grpc.CallOption) (*QueryCurrentCommitteeIDResponse, error) + RegisteredVoters(ctx context.Context, in *QueryRegisteredVotersRequest, opts ...grpc.CallOption) (*QueryRegisteredVotersResponse, error) +} + +type queryClient struct { + cc grpc1.ClientConn +} + +func NewQueryClient(cc grpc1.ClientConn) QueryClient { + return &queryClient{cc} +} + +func (c *queryClient) CurrentCommitteeID(ctx context.Context, in *QueryCurrentCommitteeIDRequest, opts ...grpc.CallOption) (*QueryCurrentCommitteeIDResponse, error) { + out := new(QueryCurrentCommitteeIDResponse) + err := c.cc.Invoke(ctx, "/zgc.committee.v1.Query/CurrentCommitteeID", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) RegisteredVoters(ctx context.Context, in *QueryRegisteredVotersRequest, opts ...grpc.CallOption) (*QueryRegisteredVotersResponse, error) { + out := new(QueryRegisteredVotersResponse) + err := c.cc.Invoke(ctx, "/zgc.committee.v1.Query/RegisteredVoters", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +type QueryServer interface { + CurrentCommitteeID(context.Context, *QueryCurrentCommitteeIDRequest) (*QueryCurrentCommitteeIDResponse, error) + RegisteredVoters(context.Context, *QueryRegisteredVotersRequest) (*QueryRegisteredVotersResponse, error) +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct { +} + +func (*UnimplementedQueryServer) CurrentCommitteeID(ctx context.Context, req *QueryCurrentCommitteeIDRequest) (*QueryCurrentCommitteeIDResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method CurrentCommitteeID not implemented") +} +func (*UnimplementedQueryServer) RegisteredVoters(ctx context.Context, req *QueryRegisteredVotersRequest) (*QueryRegisteredVotersResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method RegisteredVoters not implemented") +} + +func RegisterQueryServer(s grpc1.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +func _Query_CurrentCommitteeID_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryCurrentCommitteeIDRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).CurrentCommitteeID(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/zgc.committee.v1.Query/CurrentCommitteeID", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).CurrentCommitteeID(ctx, req.(*QueryCurrentCommitteeIDRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_RegisteredVoters_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryRegisteredVotersRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).RegisteredVoters(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/zgc.committee.v1.Query/RegisteredVoters", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).RegisteredVoters(ctx, req.(*QueryRegisteredVotersRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "zgc.committee.v1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "CurrentCommitteeID", + Handler: _Query_CurrentCommitteeID_Handler, + }, + { + MethodName: "RegisteredVoters", + Handler: _Query_RegisteredVoters_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "zgc/committee/v1/query.proto", +} + +func (m *QueryCurrentCommitteeIDRequest) 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 *QueryCurrentCommitteeIDRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryCurrentCommitteeIDRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *QueryCurrentCommitteeIDResponse) 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 *QueryCurrentCommitteeIDResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryCurrentCommitteeIDResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.CurrentCommitteeID != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.CurrentCommitteeID)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *QueryRegisteredVotersRequest) 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 *QueryRegisteredVotersRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryRegisteredVotersRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *QueryRegisteredVotersResponse) 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 *QueryRegisteredVotersResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryRegisteredVotersResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Voters) > 0 { + for iNdEx := len(m.Voters) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Voters[iNdEx]) + copy(dAtA[i:], m.Voters[iNdEx]) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Voters[iNdEx]))) + 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 *QueryCurrentCommitteeIDRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *QueryCurrentCommitteeIDResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.CurrentCommitteeID != 0 { + n += 1 + sovQuery(uint64(m.CurrentCommitteeID)) + } + return n +} + +func (m *QueryRegisteredVotersRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *QueryRegisteredVotersResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Voters) > 0 { + for _, s := range m.Voters { + l = len(s) + 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 *QueryCurrentCommitteeIDRequest) 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: QueryCurrentCommitteeIDRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryCurrentCommitteeIDRequest: 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 *QueryCurrentCommitteeIDResponse) 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: QueryCurrentCommitteeIDResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryCurrentCommitteeIDResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CurrentCommitteeID", wireType) + } + m.CurrentCommitteeID = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CurrentCommitteeID |= 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 *QueryRegisteredVotersRequest) 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: QueryRegisteredVotersRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryRegisteredVotersRequest: 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 *QueryRegisteredVotersResponse) 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: QueryRegisteredVotersResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryRegisteredVotersResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Voters", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + 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 ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Voters = append(m.Voters, string(dAtA[iNdEx:postIndex])) + 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/liquid/types/query.pb.gw.go b/x/committee/v1/types/query.pb.gw.go similarity index 63% rename from x/liquid/types/query.pb.gw.go rename to x/committee/v1/types/query.pb.gw.go index b9134b62..acb545c0 100644 --- a/x/liquid/types/query.pb.gw.go +++ b/x/committee/v1/types/query.pb.gw.go @@ -1,5 +1,5 @@ // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/liquid/v1beta1/query.proto +// source: zgc/committee/v1/query.proto /* Package types is a reverse proxy. @@ -33,74 +33,38 @@ var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage var _ = metadata.Join -func request_Query_DelegatedBalance_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDelegatedBalanceRequest +func request_Query_CurrentCommitteeID_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryCurrentCommitteeIDRequest var metadata runtime.ServerMetadata - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["delegator"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "delegator") - } - - protoReq.Delegator, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "delegator", err) - } - - msg, err := client.DelegatedBalance(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + msg, err := client.CurrentCommitteeID(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } -func local_request_Query_DelegatedBalance_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDelegatedBalanceRequest +func local_request_Query_CurrentCommitteeID_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryCurrentCommitteeIDRequest var metadata runtime.ServerMetadata - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["delegator"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "delegator") - } - - protoReq.Delegator, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "delegator", err) - } - - msg, err := server.DelegatedBalance(ctx, &protoReq) + msg, err := server.CurrentCommitteeID(ctx, &protoReq) return msg, metadata, err } -func request_Query_TotalSupply_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalSupplyRequest +func request_Query_RegisteredVoters_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryRegisteredVotersRequest var metadata runtime.ServerMetadata - msg, err := client.TotalSupply(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + msg, err := client.RegisteredVoters(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } -func local_request_Query_TotalSupply_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalSupplyRequest +func local_request_Query_RegisteredVoters_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryRegisteredVotersRequest var metadata runtime.ServerMetadata - msg, err := server.TotalSupply(ctx, &protoReq) + msg, err := server.RegisteredVoters(ctx, &protoReq) return msg, metadata, err } @@ -111,7 +75,7 @@ func local_request_Query_TotalSupply_0(ctx context.Context, marshaler runtime.Ma // 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_DelegatedBalance_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_CurrentCommitteeID_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -122,7 +86,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_DelegatedBalance_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_CurrentCommitteeID_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 { @@ -130,11 +94,11 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_DelegatedBalance_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_CurrentCommitteeID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_TotalSupply_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_RegisteredVoters_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -145,7 +109,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_TotalSupply_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_RegisteredVoters_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 { @@ -153,7 +117,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_TotalSupply_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_RegisteredVoters_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) @@ -198,7 +162,7 @@ func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc // "QueryClient" to call the correct interceptors. func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - mux.Handle("GET", pattern_Query_DelegatedBalance_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_CurrentCommitteeID_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) @@ -207,18 +171,18 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_DelegatedBalance_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_CurrentCommitteeID_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_DelegatedBalance_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_CurrentCommitteeID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_TotalSupply_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_RegisteredVoters_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) @@ -227,14 +191,14 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_TotalSupply_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_RegisteredVoters_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_TotalSupply_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_RegisteredVoters_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) @@ -242,13 +206,13 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } var ( - pattern_Query_DelegatedBalance_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"kava", "liquid", "v1beta1", "delegated_balance", "delegator"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_CurrentCommitteeID_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"0gchain", "committee", "v1", "current-committee-id"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_TotalSupply_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "liquid", "v1beta1", "total_supply"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_RegisteredVoters_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"0gchain", "committee", "v1", "registered-voters"}, "", runtime.AssumeColonVerbOpt(false))) ) var ( - forward_Query_DelegatedBalance_0 = runtime.ForwardResponseMessage + forward_Query_CurrentCommitteeID_0 = runtime.ForwardResponseMessage - forward_Query_TotalSupply_0 = runtime.ForwardResponseMessage + forward_Query_RegisteredVoters_0 = runtime.ForwardResponseMessage ) diff --git a/x/committee/types/tx.pb.go b/x/committee/v1/types/tx.pb.go similarity index 59% rename from x/committee/types/tx.pb.go rename to x/committee/v1/types/tx.pb.go index 7a3570e3..5f9d335a 100644 --- a/x/committee/types/tx.pb.go +++ b/x/committee/v1/types/tx.pb.go @@ -1,5 +1,5 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/committee/v1beta1/tx.proto +// source: zgc/committee/v1/tx.proto package types @@ -7,7 +7,7 @@ import ( context "context" fmt "fmt" _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/codec/types" + _ "github.com/cosmos/cosmos-sdk/codec/types" _ "github.com/cosmos/gogoproto/gogoproto" grpc1 "github.com/cosmos/gogoproto/grpc" proto "github.com/cosmos/gogoproto/proto" @@ -30,25 +30,23 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package -// MsgSubmitProposal is used by committee members to create a new proposal that they can vote on. -type MsgSubmitProposal struct { - PubProposal *types.Any `protobuf:"bytes,1,opt,name=pub_proposal,json=pubProposal,proto3" json:"pub_proposal,omitempty"` - Proposer string `protobuf:"bytes,2,opt,name=proposer,proto3" json:"proposer,omitempty"` - CommitteeID uint64 `protobuf:"varint,3,opt,name=committee_id,json=committeeId,proto3" json:"committee_id,omitempty"` +type MsgRegister struct { + Voter string `protobuf:"bytes,1,opt,name=voter,proto3" json:"voter,omitempty"` + Key []byte `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"` } -func (m *MsgSubmitProposal) Reset() { *m = MsgSubmitProposal{} } -func (m *MsgSubmitProposal) String() string { return proto.CompactTextString(m) } -func (*MsgSubmitProposal) ProtoMessage() {} -func (*MsgSubmitProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_3f3857845b071606, []int{0} +func (m *MsgRegister) Reset() { *m = MsgRegister{} } +func (m *MsgRegister) String() string { return proto.CompactTextString(m) } +func (*MsgRegister) ProtoMessage() {} +func (*MsgRegister) Descriptor() ([]byte, []int) { + return fileDescriptor_ea97a64f78abecc0, []int{0} } -func (m *MsgSubmitProposal) XXX_Unmarshal(b []byte) error { +func (m *MsgRegister) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } -func (m *MsgSubmitProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { +func (m *MsgRegister) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { - return xxx_messageInfo_MsgSubmitProposal.Marshal(b, m, deterministic) + return xxx_messageInfo_MsgRegister.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) @@ -58,35 +56,33 @@ func (m *MsgSubmitProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, e return b[:n], nil } } -func (m *MsgSubmitProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSubmitProposal.Merge(m, src) +func (m *MsgRegister) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgRegister.Merge(m, src) } -func (m *MsgSubmitProposal) XXX_Size() int { +func (m *MsgRegister) XXX_Size() int { return m.Size() } -func (m *MsgSubmitProposal) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSubmitProposal.DiscardUnknown(m) +func (m *MsgRegister) XXX_DiscardUnknown() { + xxx_messageInfo_MsgRegister.DiscardUnknown(m) } -var xxx_messageInfo_MsgSubmitProposal proto.InternalMessageInfo +var xxx_messageInfo_MsgRegister proto.InternalMessageInfo -// MsgSubmitProposalResponse defines the SubmitProposal response type -type MsgSubmitProposalResponse struct { - ProposalID uint64 `protobuf:"varint,1,opt,name=proposal_id,json=proposalId,proto3" json:"proposal_id,omitempty"` +type MsgRegisterResponse struct { } -func (m *MsgSubmitProposalResponse) Reset() { *m = MsgSubmitProposalResponse{} } -func (m *MsgSubmitProposalResponse) String() string { return proto.CompactTextString(m) } -func (*MsgSubmitProposalResponse) ProtoMessage() {} -func (*MsgSubmitProposalResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3f3857845b071606, []int{1} +func (m *MsgRegisterResponse) Reset() { *m = MsgRegisterResponse{} } +func (m *MsgRegisterResponse) String() string { return proto.CompactTextString(m) } +func (*MsgRegisterResponse) ProtoMessage() {} +func (*MsgRegisterResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_ea97a64f78abecc0, []int{1} } -func (m *MsgSubmitProposalResponse) XXX_Unmarshal(b []byte) error { +func (m *MsgRegisterResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } -func (m *MsgSubmitProposalResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { +func (m *MsgRegisterResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { - return xxx_messageInfo_MsgSubmitProposalResponse.Marshal(b, m, deterministic) + return xxx_messageInfo_MsgRegisterResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) @@ -96,30 +92,29 @@ func (m *MsgSubmitProposalResponse) XXX_Marshal(b []byte, deterministic bool) ([ return b[:n], nil } } -func (m *MsgSubmitProposalResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSubmitProposalResponse.Merge(m, src) +func (m *MsgRegisterResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgRegisterResponse.Merge(m, src) } -func (m *MsgSubmitProposalResponse) XXX_Size() int { +func (m *MsgRegisterResponse) XXX_Size() int { return m.Size() } -func (m *MsgSubmitProposalResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSubmitProposalResponse.DiscardUnknown(m) +func (m *MsgRegisterResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgRegisterResponse.DiscardUnknown(m) } -var xxx_messageInfo_MsgSubmitProposalResponse proto.InternalMessageInfo +var xxx_messageInfo_MsgRegisterResponse proto.InternalMessageInfo -// MsgVote is submitted by committee members to vote on proposals. type MsgVote struct { - ProposalID uint64 `protobuf:"varint,1,opt,name=proposal_id,json=proposalId,proto3" json:"proposal_id,omitempty"` - Voter string `protobuf:"bytes,2,opt,name=voter,proto3" json:"voter,omitempty"` - VoteType VoteType `protobuf:"varint,3,opt,name=vote_type,json=voteType,proto3,enum=kava.committee.v1beta1.VoteType" json:"vote_type,omitempty"` + CommitteeID uint64 `protobuf:"varint,1,opt,name=committee_id,json=committeeId,proto3" json:"committee_id,omitempty"` + Voter string `protobuf:"bytes,2,opt,name=voter,proto3" json:"voter,omitempty"` + Ballots []*Ballot `protobuf:"bytes,3,rep,name=ballots,proto3" json:"ballots,omitempty"` } func (m *MsgVote) Reset() { *m = MsgVote{} } func (m *MsgVote) String() string { return proto.CompactTextString(m) } func (*MsgVote) ProtoMessage() {} func (*MsgVote) Descriptor() ([]byte, []int) { - return fileDescriptor_3f3857845b071606, []int{2} + return fileDescriptor_ea97a64f78abecc0, []int{2} } func (m *MsgVote) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -148,7 +143,6 @@ func (m *MsgVote) XXX_DiscardUnknown() { var xxx_messageInfo_MsgVote proto.InternalMessageInfo -// MsgVoteResponse defines the Vote response type type MsgVoteResponse struct { } @@ -156,7 +150,7 @@ func (m *MsgVoteResponse) Reset() { *m = MsgVoteResponse{} } func (m *MsgVoteResponse) String() string { return proto.CompactTextString(m) } func (*MsgVoteResponse) ProtoMessage() {} func (*MsgVoteResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3f3857845b071606, []int{3} + return fileDescriptor_ea97a64f78abecc0, []int{3} } func (m *MsgVoteResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -186,45 +180,40 @@ func (m *MsgVoteResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgVoteResponse proto.InternalMessageInfo func init() { - proto.RegisterType((*MsgSubmitProposal)(nil), "kava.committee.v1beta1.MsgSubmitProposal") - proto.RegisterType((*MsgSubmitProposalResponse)(nil), "kava.committee.v1beta1.MsgSubmitProposalResponse") - proto.RegisterType((*MsgVote)(nil), "kava.committee.v1beta1.MsgVote") - proto.RegisterType((*MsgVoteResponse)(nil), "kava.committee.v1beta1.MsgVoteResponse") + proto.RegisterType((*MsgRegister)(nil), "zgc.committee.v1.MsgRegister") + proto.RegisterType((*MsgRegisterResponse)(nil), "zgc.committee.v1.MsgRegisterResponse") + proto.RegisterType((*MsgVote)(nil), "zgc.committee.v1.MsgVote") + proto.RegisterType((*MsgVoteResponse)(nil), "zgc.committee.v1.MsgVoteResponse") } -func init() { proto.RegisterFile("kava/committee/v1beta1/tx.proto", fileDescriptor_3f3857845b071606) } +func init() { proto.RegisterFile("zgc/committee/v1/tx.proto", fileDescriptor_ea97a64f78abecc0) } -var fileDescriptor_3f3857845b071606 = []byte{ - // 455 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x92, 0xcf, 0x6e, 0xd3, 0x40, - 0x10, 0xc6, 0xb3, 0xb4, 0x40, 0x3b, 0xae, 0x52, 0xd5, 0x8a, 0x50, 0xe2, 0x83, 0x13, 0x45, 0x48, - 0x04, 0xa1, 0xee, 0x2a, 0xe1, 0xcc, 0x81, 0xb4, 0x17, 0x4b, 0x44, 0xaa, 0x0c, 0x02, 0x89, 0x4b, - 0x64, 0x37, 0xcb, 0x62, 0x91, 0x78, 0xac, 0xec, 0xda, 0xaa, 0x9f, 0x02, 0x1e, 0x86, 0x23, 0x77, - 0x2a, 0x4e, 0x3d, 0x72, 0xaa, 0xc0, 0x79, 0x11, 0xb4, 0xb6, 0xd7, 0x42, 0x94, 0xf0, 0xe7, 0x36, - 0x33, 0xfe, 0xcd, 0x37, 0xdf, 0x8c, 0x17, 0xfa, 0xef, 0x82, 0x2c, 0x60, 0xe7, 0xb8, 0x5a, 0x45, - 0x4a, 0x71, 0xce, 0xb2, 0x71, 0xc8, 0x55, 0x30, 0x66, 0xea, 0x82, 0x26, 0x6b, 0x54, 0x68, 0xdf, - 0xd3, 0x00, 0x6d, 0x00, 0x5a, 0x03, 0x4e, 0xef, 0x1c, 0xe5, 0x0a, 0xe5, 0xbc, 0xa4, 0x58, 0x95, - 0x54, 0x2d, 0x4e, 0x47, 0xa0, 0xc0, 0xaa, 0xae, 0xa3, 0xba, 0xda, 0x13, 0x88, 0x62, 0xc9, 0x59, - 0x99, 0x85, 0xe9, 0x1b, 0x16, 0xc4, 0x79, 0xfd, 0xe9, 0xfe, 0x16, 0x13, 0x82, 0xc7, 0x5c, 0x46, - 0xb5, 0xec, 0xf0, 0x13, 0x81, 0xa3, 0x99, 0x14, 0xcf, 0xd3, 0x70, 0x15, 0xa9, 0xb3, 0x35, 0x26, - 0x28, 0x83, 0xa5, 0xfd, 0x0a, 0x0e, 0x92, 0x34, 0xd4, 0x36, 0xca, 0xbc, 0x4b, 0x06, 0x64, 0x64, - 0x4d, 0x3a, 0xb4, 0x9a, 0x46, 0xcd, 0x34, 0xfa, 0x34, 0xce, 0xa7, 0xee, 0x97, 0x8f, 0xc7, 0x4e, - 0x6d, 0x55, 0x60, 0x66, 0x76, 0xa1, 0x27, 0x18, 0x2b, 0x1e, 0x2b, 0xdf, 0x4a, 0xd2, 0xb0, 0x11, - 0x76, 0x60, 0xaf, 0x12, 0xe5, 0xeb, 0xee, 0xad, 0x01, 0x19, 0xed, 0xfb, 0x4d, 0x6e, 0x4f, 0xe0, - 0xa0, 0x71, 0x3b, 0x8f, 0x16, 0xdd, 0x9d, 0x01, 0x19, 0xed, 0x4e, 0x0f, 0x8b, 0xeb, 0xbe, 0x75, - 0x62, 0xea, 0xde, 0xa9, 0x6f, 0x35, 0x90, 0xb7, 0x18, 0x3e, 0x83, 0xde, 0x0d, 0xf7, 0x3e, 0x97, - 0x09, 0xc6, 0x92, 0xdb, 0x0c, 0x2c, 0xb3, 0x81, 0xd6, 0x23, 0xa5, 0x5e, 0xbb, 0xb8, 0xee, 0x83, - 0x41, 0xbd, 0x53, 0x1f, 0x0c, 0xe2, 0x2d, 0x86, 0xef, 0x09, 0xdc, 0x9d, 0x49, 0xf1, 0x12, 0xd5, - 0xff, 0x37, 0xdb, 0x1d, 0xb8, 0x9d, 0xa1, 0x6a, 0xf6, 0xaa, 0x12, 0xfb, 0x09, 0xec, 0xeb, 0x60, - 0xae, 0xf2, 0x84, 0x97, 0x1b, 0xb5, 0x27, 0x03, 0xfa, 0xfb, 0xbf, 0x4f, 0xf5, 0xdc, 0x17, 0x79, - 0xc2, 0xfd, 0xbd, 0xac, 0x8e, 0x86, 0x47, 0x70, 0x58, 0x1b, 0x32, 0x5b, 0x4d, 0x3e, 0x13, 0xd8, - 0x99, 0x49, 0x61, 0xc7, 0xd0, 0xfe, 0xe5, 0xaf, 0x3d, 0xdc, 0x26, 0x7c, 0xe3, 0x44, 0xce, 0xf8, - 0x9f, 0xd1, 0xe6, 0x9a, 0x67, 0xb0, 0x5b, 0x1e, 0xa6, 0xff, 0x87, 0x56, 0x0d, 0x38, 0x0f, 0xfe, - 0x02, 0x18, 0xc5, 0xa9, 0x77, 0xf9, 0xdd, 0x6d, 0x5d, 0x16, 0x2e, 0xb9, 0x2a, 0x5c, 0xf2, 0xad, - 0x70, 0xc9, 0x87, 0x8d, 0xdb, 0xba, 0xda, 0xb8, 0xad, 0xaf, 0x1b, 0xb7, 0xf5, 0xfa, 0x91, 0x88, - 0xd4, 0xdb, 0x34, 0xd4, 0x3a, 0x4c, 0x0b, 0x1e, 0x2f, 0x83, 0x50, 0x96, 0x11, 0xbb, 0xf8, 0xe9, - 0x59, 0xeb, 0xc3, 0xca, 0xf0, 0x4e, 0xf9, 0x24, 0x1f, 0xff, 0x08, 0x00, 0x00, 0xff, 0xff, 0xe5, - 0x91, 0xbf, 0x3d, 0x7a, 0x03, 0x00, 0x00, +var fileDescriptor_ea97a64f78abecc0 = []byte{ + // 377 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x52, 0x4d, 0x8e, 0xda, 0x30, + 0x18, 0x8d, 0x09, 0x2d, 0xad, 0x83, 0x04, 0x4d, 0xa9, 0x94, 0x44, 0xaa, 0x4b, 0x23, 0x55, 0x62, + 0xd3, 0x18, 0x52, 0xf5, 0x02, 0x94, 0x0d, 0x8b, 0x48, 0x55, 0x16, 0x5d, 0x74, 0x83, 0x92, 0xe0, + 0x9a, 0xa8, 0x21, 0x46, 0xd8, 0x20, 0xe0, 0x02, 0xb3, 0x9d, 0x0b, 0xcc, 0x7d, 0x58, 0xb2, 0x9c, + 0xd5, 0x68, 0x26, 0x5c, 0x64, 0x94, 0xdf, 0x41, 0x30, 0x33, 0xbb, 0xef, 0xfb, 0xde, 0xf3, 0x7b, + 0xdf, 0xb3, 0x0d, 0xf5, 0x1d, 0x0d, 0x70, 0xc0, 0xe6, 0xf3, 0x50, 0x08, 0x42, 0xf0, 0x7a, 0x80, + 0xc5, 0xc6, 0x5a, 0x2c, 0x99, 0x60, 0x6a, 0x7b, 0x47, 0x03, 0xab, 0x82, 0xac, 0xf5, 0xc0, 0xd0, + 0x03, 0xc6, 0xe7, 0x8c, 0x4f, 0x32, 0x1c, 0xe7, 0x4d, 0x4e, 0x36, 0x3a, 0x94, 0x51, 0x96, 0xcf, + 0xd3, 0xaa, 0x98, 0xea, 0x94, 0x31, 0x1a, 0x11, 0x9c, 0x75, 0xfe, 0xea, 0x1f, 0xf6, 0xe2, 0x6d, + 0x01, 0xa1, 0x0b, 0x63, 0x4a, 0x62, 0xc2, 0xc3, 0x42, 0xd0, 0xfc, 0x09, 0x15, 0x87, 0x53, 0x97, + 0xd0, 0x90, 0x0b, 0xb2, 0x54, 0x3b, 0xf0, 0xcd, 0x9a, 0x09, 0xb2, 0xd4, 0x40, 0x17, 0xf4, 0xde, + 0xbb, 0x79, 0xa3, 0xb6, 0xa1, 0xfc, 0x9f, 0x6c, 0xb5, 0x5a, 0x17, 0xf4, 0x9a, 0x6e, 0x5a, 0x9a, + 0x9f, 0xe0, 0xc7, 0x93, 0x63, 0x2e, 0xe1, 0x0b, 0x16, 0x73, 0x62, 0x5e, 0x01, 0xd8, 0x70, 0x38, + 0xfd, 0xc3, 0x04, 0x51, 0x6d, 0xd8, 0xac, 0x7c, 0x27, 0xe1, 0x34, 0x53, 0xac, 0x0f, 0x5b, 0xc9, + 0xdd, 0x17, 0xe5, 0x57, 0x39, 0x1f, 0x8f, 0x5c, 0xa5, 0x22, 0x8d, 0xa7, 0x4f, 0xf6, 0xb5, 0x53, + 0x7b, 0x1b, 0x36, 0x7c, 0x2f, 0x8a, 0x98, 0xe0, 0x9a, 0xdc, 0x95, 0x7b, 0x8a, 0xad, 0x59, 0xe7, + 0x77, 0x66, 0x0d, 0x33, 0x82, 0x5b, 0x12, 0xcd, 0x0f, 0xb0, 0x55, 0x2c, 0x52, 0x2e, 0x67, 0xdf, + 0x00, 0x28, 0x3b, 0x9c, 0xaa, 0xbf, 0xe1, 0xbb, 0x2a, 0xef, 0xe7, 0x4b, 0xa5, 0x93, 0x5c, 0xc6, + 0xb7, 0x57, 0xe1, 0x52, 0x59, 0x1d, 0xc1, 0x7a, 0x16, 0x59, 0x7f, 0x96, 0x9e, 0x42, 0xc6, 0xd7, + 0x17, 0xa1, 0x52, 0x65, 0xe8, 0xec, 0x1f, 0x90, 0xb4, 0x4f, 0x10, 0x38, 0x24, 0x08, 0xdc, 0x27, + 0x08, 0x5c, 0x1f, 0x91, 0x74, 0x38, 0x22, 0xe9, 0xf6, 0x88, 0xa4, 0xbf, 0x98, 0x86, 0x62, 0xb6, + 0xf2, 0x53, 0x09, 0xdc, 0xa7, 0x91, 0xe7, 0x73, 0xdc, 0xa7, 0xdf, 0x83, 0x99, 0x17, 0xc6, 0x78, + 0x73, 0xf6, 0xb5, 0xb6, 0x0b, 0xc2, 0xfd, 0xb7, 0xd9, 0x03, 0xff, 0x78, 0x0c, 0x00, 0x00, 0xff, + 0xff, 0xec, 0xc0, 0x4c, 0xa8, 0x7b, 0x02, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -239,9 +228,7 @@ const _ = grpc.SupportPackageIsVersion4 // // 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 { - // SubmitProposal defines a method for submitting a committee proposal - SubmitProposal(ctx context.Context, in *MsgSubmitProposal, opts ...grpc.CallOption) (*MsgSubmitProposalResponse, error) - // Vote defines a method for voting on a proposal + Register(ctx context.Context, in *MsgRegister, opts ...grpc.CallOption) (*MsgRegisterResponse, error) Vote(ctx context.Context, in *MsgVote, opts ...grpc.CallOption) (*MsgVoteResponse, error) } @@ -253,9 +240,9 @@ func NewMsgClient(cc grpc1.ClientConn) MsgClient { return &msgClient{cc} } -func (c *msgClient) SubmitProposal(ctx context.Context, in *MsgSubmitProposal, opts ...grpc.CallOption) (*MsgSubmitProposalResponse, error) { - out := new(MsgSubmitProposalResponse) - err := c.cc.Invoke(ctx, "/kava.committee.v1beta1.Msg/SubmitProposal", in, out, opts...) +func (c *msgClient) Register(ctx context.Context, in *MsgRegister, opts ...grpc.CallOption) (*MsgRegisterResponse, error) { + out := new(MsgRegisterResponse) + err := c.cc.Invoke(ctx, "/zgc.committee.v1.Msg/Register", in, out, opts...) if err != nil { return nil, err } @@ -264,7 +251,7 @@ func (c *msgClient) SubmitProposal(ctx context.Context, in *MsgSubmitProposal, o func (c *msgClient) Vote(ctx context.Context, in *MsgVote, opts ...grpc.CallOption) (*MsgVoteResponse, error) { out := new(MsgVoteResponse) - err := c.cc.Invoke(ctx, "/kava.committee.v1beta1.Msg/Vote", in, out, opts...) + err := c.cc.Invoke(ctx, "/zgc.committee.v1.Msg/Vote", in, out, opts...) if err != nil { return nil, err } @@ -273,9 +260,7 @@ func (c *msgClient) Vote(ctx context.Context, in *MsgVote, opts ...grpc.CallOpti // MsgServer is the server API for Msg service. type MsgServer interface { - // SubmitProposal defines a method for submitting a committee proposal - SubmitProposal(context.Context, *MsgSubmitProposal) (*MsgSubmitProposalResponse, error) - // Vote defines a method for voting on a proposal + Register(context.Context, *MsgRegister) (*MsgRegisterResponse, error) Vote(context.Context, *MsgVote) (*MsgVoteResponse, error) } @@ -283,8 +268,8 @@ type MsgServer interface { type UnimplementedMsgServer struct { } -func (*UnimplementedMsgServer) SubmitProposal(ctx context.Context, req *MsgSubmitProposal) (*MsgSubmitProposalResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SubmitProposal not implemented") +func (*UnimplementedMsgServer) Register(ctx context.Context, req *MsgRegister) (*MsgRegisterResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Register not implemented") } func (*UnimplementedMsgServer) Vote(ctx context.Context, req *MsgVote) (*MsgVoteResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Vote not implemented") @@ -294,20 +279,20 @@ func RegisterMsgServer(s grpc1.Server, srv MsgServer) { s.RegisterService(&_Msg_serviceDesc, srv) } -func _Msg_SubmitProposal_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgSubmitProposal) +func _Msg_Register_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgRegister) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return srv.(MsgServer).SubmitProposal(ctx, in) + return srv.(MsgServer).Register(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/kava.committee.v1beta1.Msg/SubmitProposal", + FullMethod: "/zgc.committee.v1.Msg/Register", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).SubmitProposal(ctx, req.(*MsgSubmitProposal)) + return srv.(MsgServer).Register(ctx, req.(*MsgRegister)) } return interceptor(ctx, in, info, handler) } @@ -322,7 +307,7 @@ func _Msg_Vote_Handler(srv interface{}, ctx context.Context, dec func(interface{ } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/kava.committee.v1beta1.Msg/Vote", + FullMethod: "/zgc.committee.v1.Msg/Vote", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MsgServer).Vote(ctx, req.(*MsgVote)) @@ -331,12 +316,12 @@ func _Msg_Vote_Handler(srv interface{}, ctx context.Context, dec func(interface{ } var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.committee.v1beta1.Msg", + ServiceName: "zgc.committee.v1.Msg", HandlerType: (*MsgServer)(nil), Methods: []grpc.MethodDesc{ { - MethodName: "SubmitProposal", - Handler: _Msg_SubmitProposal_Handler, + MethodName: "Register", + Handler: _Msg_Register_Handler, }, { MethodName: "Vote", @@ -344,10 +329,10 @@ var _Msg_serviceDesc = grpc.ServiceDesc{ }, }, Streams: []grpc.StreamDesc{}, - Metadata: "kava/committee/v1beta1/tx.proto", + Metadata: "zgc/committee/v1/tx.proto", } -func (m *MsgSubmitProposal) Marshal() (dAtA []byte, err error) { +func (m *MsgRegister) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -357,44 +342,34 @@ func (m *MsgSubmitProposal) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *MsgSubmitProposal) MarshalTo(dAtA []byte) (int, error) { +func (m *MsgRegister) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *MsgSubmitProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *MsgRegister) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if m.CommitteeID != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.CommitteeID)) - i-- - dAtA[i] = 0x18 - } - if len(m.Proposer) > 0 { - i -= len(m.Proposer) - copy(dAtA[i:], m.Proposer) - i = encodeVarintTx(dAtA, i, uint64(len(m.Proposer))) + if len(m.Key) > 0 { + i -= len(m.Key) + copy(dAtA[i:], m.Key) + i = encodeVarintTx(dAtA, i, uint64(len(m.Key))) i-- dAtA[i] = 0x12 } - if m.PubProposal != nil { - { - size, err := m.PubProposal.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } + if len(m.Voter) > 0 { + i -= len(m.Voter) + copy(dAtA[i:], m.Voter) + i = encodeVarintTx(dAtA, i, uint64(len(m.Voter))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } -func (m *MsgSubmitProposalResponse) Marshal() (dAtA []byte, err error) { +func (m *MsgRegisterResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -404,21 +379,16 @@ func (m *MsgSubmitProposalResponse) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *MsgSubmitProposalResponse) MarshalTo(dAtA []byte) (int, error) { +func (m *MsgRegisterResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *MsgSubmitProposalResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *MsgRegisterResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if m.ProposalID != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.ProposalID)) - i-- - dAtA[i] = 0x8 - } return len(dAtA) - i, nil } @@ -442,10 +412,19 @@ func (m *MsgVote) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if m.VoteType != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.VoteType)) - i-- - dAtA[i] = 0x18 + if len(m.Ballots) > 0 { + for iNdEx := len(m.Ballots) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Ballots[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } } if len(m.Voter) > 0 { i -= len(m.Voter) @@ -454,8 +433,8 @@ func (m *MsgVote) MarshalToSizedBuffer(dAtA []byte) (int, error) { i-- dAtA[i] = 0x12 } - if m.ProposalID != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.ProposalID)) + if m.CommitteeID != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.CommitteeID)) i-- dAtA[i] = 0x8 } @@ -496,35 +475,29 @@ func encodeVarintTx(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } -func (m *MsgSubmitProposal) Size() (n int) { +func (m *MsgRegister) Size() (n int) { if m == nil { return 0 } var l int _ = l - if m.PubProposal != nil { - l = m.PubProposal.Size() - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Proposer) + l = len(m.Voter) if l > 0 { n += 1 + l + sovTx(uint64(l)) } - if m.CommitteeID != 0 { - n += 1 + sovTx(uint64(m.CommitteeID)) + l = len(m.Key) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) } return n } -func (m *MsgSubmitProposalResponse) Size() (n int) { +func (m *MsgRegisterResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l - if m.ProposalID != 0 { - n += 1 + sovTx(uint64(m.ProposalID)) - } return n } @@ -534,15 +507,18 @@ func (m *MsgVote) Size() (n int) { } var l int _ = l - if m.ProposalID != 0 { - n += 1 + sovTx(uint64(m.ProposalID)) + if m.CommitteeID != 0 { + n += 1 + sovTx(uint64(m.CommitteeID)) } l = len(m.Voter) if l > 0 { n += 1 + l + sovTx(uint64(l)) } - if m.VoteType != 0 { - n += 1 + sovTx(uint64(m.VoteType)) + if len(m.Ballots) > 0 { + for _, e := range m.Ballots { + l = e.Size() + n += 1 + l + sovTx(uint64(l)) + } } return n } @@ -562,7 +538,7 @@ func sovTx(x uint64) (n int) { func sozTx(x uint64) (n int) { return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } -func (m *MsgSubmitProposal) Unmarshal(dAtA []byte) error { +func (m *MsgRegister) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -585,51 +561,15 @@ func (m *MsgSubmitProposal) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgSubmitProposal: wiretype end group for non-group") + return fmt.Errorf("proto: MsgRegister: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSubmitProposal: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: MsgRegister: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PubProposal", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.PubProposal == nil { - m.PubProposal = &types.Any{} - } - if err := m.PubProposal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Proposer", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Voter", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -657,13 +597,13 @@ func (m *MsgSubmitProposal) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Proposer = string(dAtA[iNdEx:postIndex]) + m.Voter = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CommitteeID", wireType) + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) } - m.CommitteeID = 0 + var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -673,11 +613,26 @@ func (m *MsgSubmitProposal) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.CommitteeID |= uint64(b&0x7F) << shift + byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } + if byteLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...) + if m.Key == nil { + m.Key = []byte{} + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) @@ -699,7 +654,7 @@ func (m *MsgSubmitProposal) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgSubmitProposalResponse) Unmarshal(dAtA []byte) error { +func (m *MsgRegisterResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -722,31 +677,12 @@ func (m *MsgSubmitProposalResponse) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgSubmitProposalResponse: wiretype end group for non-group") + return fmt.Errorf("proto: MsgRegisterResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSubmitProposalResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: MsgRegisterResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ProposalID", wireType) - } - m.ProposalID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ProposalID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) @@ -799,9 +735,9 @@ func (m *MsgVote) Unmarshal(dAtA []byte) error { switch fieldNum { case 1: if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ProposalID", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field CommitteeID", wireType) } - m.ProposalID = 0 + m.CommitteeID = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -811,7 +747,7 @@ func (m *MsgVote) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.ProposalID |= uint64(b&0x7F) << shift + m.CommitteeID |= uint64(b&0x7F) << shift if b < 0x80 { break } @@ -849,10 +785,10 @@ func (m *MsgVote) Unmarshal(dAtA []byte) error { m.Voter = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field VoteType", wireType) + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Ballots", wireType) } - m.VoteType = 0 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -862,11 +798,26 @@ func (m *MsgVote) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.VoteType |= VoteType(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Ballots = append(m.Ballots, &Ballot{}) + if err := m.Ballots[len(m.Ballots)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) diff --git a/x/community/abci.go b/x/community/abci.go deleted file mode 100644 index b20aeafd..00000000 --- a/x/community/abci.go +++ /dev/null @@ -1,20 +0,0 @@ -package community - -import ( - "time" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/community/keeper" - "github.com/kava-labs/kava/x/community/types" -) - -// BeginBlocker runs the community module begin blocker logic. -func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - - // This exact call order is required to allow payout on the upgrade block - k.CheckAndDisableMintAndKavaDistInflation(ctx) - k.PayoutAccumulatedStakingRewards(ctx) -} diff --git a/x/community/abci_test.go b/x/community/abci_test.go deleted file mode 100644 index c74938bd..00000000 --- a/x/community/abci_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package community_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/community" - "github.com/kava-labs/kava/x/community/types" - "github.com/stretchr/testify/require" -) - -func TestABCIStakingRewardsArePaidOutOnDisableInflationBlock(t *testing.T) { - app.SetSDKConfig() - tApp := app.NewTestApp() - tApp.InitializeFromGenesisStates() - keeper := tApp.GetCommunityKeeper() - accountKeeper := tApp.GetAccountKeeper() - bankKeeper := tApp.GetBankKeeper() - - // a block that runs after addition of the disable inflation code on chain - // but before the disable inflation time - initialBlockTime := time.Now() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: initialBlockTime}) - - poolAcc := accountKeeper.GetModuleAccount(ctx, types.ModuleName) - feeCollectorAcc := accountKeeper.GetModuleAccount(ctx, authtypes.FeeCollectorName) - - disableTime := initialBlockTime.Add(9 * time.Second) - - // set state - params, _ := keeper.GetParams(ctx) - params.UpgradeTimeDisableInflation = disableTime - params.UpgradeTimeSetStakingRewardsPerSecond = sdkmath.LegacyNewDec(1000000) // 1 KAVA - params.StakingRewardsPerSecond = sdkmath.LegacyZeroDec() - keeper.SetParams(ctx, params) - - // fund community pool account - tApp.FundAccount(ctx, poolAcc.GetAddress(), sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10000000)))) // 10 KAVA - initialFeeCollectorBalance := bankKeeper.GetBalance(ctx, feeCollectorAcc.GetAddress(), "ukava").Amount - - // run one block - community.BeginBlocker(ctx, keeper) - - // assert that staking rewards in parameters are still set to zero - params, found := keeper.GetParams(ctx) - require.True(t, found) - require.Equal(t, sdkmath.LegacyZeroDec(), params.StakingRewardsPerSecond) - - // assert no rewards are given yet - rewards := bankKeeper.GetBalance(ctx, feeCollectorAcc.GetAddress(), "ukava").Amount.Sub(initialFeeCollectorBalance) - require.Equal(t, sdkmath.ZeroInt(), rewards) - - // new block when disable inflation runs, 10 seconds from initial block for easy math - blockTime := disableTime.Add(1 * time.Second) - ctx = tApp.NewContext(true, tmproto.Header{Height: ctx.BlockHeight() + 1, Time: blockTime}) - - // run the next block - community.BeginBlocker(ctx, keeper) - - // assert that staking rewards have been set and disable inflation time is zero - params, found = keeper.GetParams(ctx) - require.True(t, found) - require.True(t, params.UpgradeTimeDisableInflation.IsZero()) - require.Equal(t, sdkmath.LegacyNewDec(1000000), params.StakingRewardsPerSecond) - - // assert that 10 KAVA has been distributed in rewards - rewards = bankKeeper.GetBalance(ctx, feeCollectorAcc.GetAddress(), "ukava").Amount.Sub(initialFeeCollectorBalance) - require.Equal(t, sdkmath.NewInt(10000000).String(), rewards.String()) -} diff --git a/x/community/client/cli/query.go b/x/community/client/cli/query.go deleted file mode 100644 index 527aceb6..00000000 --- a/x/community/client/cli/query.go +++ /dev/null @@ -1,107 +0,0 @@ -package cli - -import ( - "context" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - - "github.com/kava-labs/kava/x/community/types" -) - -// GetQueryCmd returns the cli query commands for the community module. -func GetQueryCmd() *cobra.Command { - communityQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the community module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - commands := []*cobra.Command{ - getCmdQueryParams(), - getCmdQueryBalance(), - getCmdQueryAnnualizedRewards(), - } - - for _, cmd := range commands { - flags.AddQueryFlagsToCmd(cmd) - } - - communityQueryCmd.AddCommand(commands...) - - return communityQueryCmd -} - -func getCmdQueryParams() *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: "get the community module parameters", - Long: "Get the current community module parameters.", - 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(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } -} - -// getCmdQueryBalance implements a command to return the current community pool balance. -func getCmdQueryBalance() *cobra.Command { - return &cobra.Command{ - Use: "balance", - Short: "Query the current balance of the community module account", - 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.Balance(cmd.Context(), &types.QueryBalanceRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -// getCmdQueryAnnualizedRewards implements a command to return the current annualized rewards. -func getCmdQueryAnnualizedRewards() *cobra.Command { - return &cobra.Command{ - Use: "annualized-rewards", - Short: "Query a current calculation of annualized rewards for the chain.", - 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.AnnualizedRewards(cmd.Context(), &types.QueryAnnualizedRewardsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} diff --git a/x/community/client/cli/tx.go b/x/community/client/cli/tx.go deleted file mode 100644 index a140c12c..00000000 --- a/x/community/client/cli/tx.go +++ /dev/null @@ -1,210 +0,0 @@ -package cli - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - "github.com/kava-labs/kava/x/community/client/utils" - "github.com/kava-labs/kava/x/community/types" -) - -const ( - flagDeposit = "deposit" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - communityTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "community module transactions subcommands", - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - getCmdFundCommunityPool(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - communityTxCmd.AddCommand(cmds...) - - return communityTxCmd -} - -func getCmdFundCommunityPool() *cobra.Command { - return &cobra.Command{ - Use: "fund-community-pool [coins]", - Short: "funds the community pool", - Long: "Fund community pool removes the listed coins from the sender's account and send them to the community module account.", - Args: cobra.ExactArgs(1), - Example: fmt.Sprintf( - `%s tx %s fund-community-module 10000000ukava --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - coins, err := sdk.ParseCoinsNormalized(args[0]) - if err != nil { - return err - } - - msg := types.NewMsgFundCommunityPool(clientCtx.GetFromAddress(), coins) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -// NewCmdSubmitCommunityPoolLendDepositProposal implements the command to submit a community-pool lend deposit proposal -func NewCmdSubmitCommunityPoolLendDepositProposal() *cobra.Command { - cmd := &cobra.Command{ - Use: "community-pool-lend-deposit [proposal-file]", - Args: cobra.ExactArgs(1), - Short: "Submit a community pool lend deposit proposal", - Long: strings.TrimSpace( - fmt.Sprintf(`Submit a community pool lend deposit proposal along with an initial deposit. -The proposal details must be supplied via a JSON file. -Note that --deposit below is the initial proposal deposit submitted along with the proposal. -Example: -$ %s tx gov submit-proposal community-pool-lend-deposit --deposit 1000000000ukava --from= -Where proposal.json contains: -{ - "title": "Community Pool Deposit", - "description": "Deposit some KAVA from community pool!", - "amount": [ - { - "denom": "ukava", - "amount": "100000000000" - } - ] -} -`, - version.AppName, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - // parse proposal - proposal, err := utils.ParseCommunityPoolLendDepositProposal(clientCtx.Codec, args[0]) - if err != nil { - return err - } - - deposit, err := parseInitialDeposit(cmd) - if err != nil { - return err - } - - from := clientCtx.GetFromAddress() - msg, err := govv1beta1.NewMsgSubmitProposal(&proposal, deposit, from) - if err != nil { - return err - } - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - cmd.Flags().String(flagDeposit, "", "Initial deposit for the proposal") - - return cmd -} - -// NewCmdSubmitCommunityPoolLendWithdrawProposal implements the command to submit a community-pool lend withdraw proposal -func NewCmdSubmitCommunityPoolLendWithdrawProposal() *cobra.Command { - cmd := &cobra.Command{ - Use: "community-pool-lend-withdraw [proposal-file]", - Args: cobra.ExactArgs(1), - Short: "Submit a community pool lend withdraw proposal", - Long: strings.TrimSpace( - fmt.Sprintf(`Submit a community pool lend withdraw proposal along with an initial deposit. -The proposal details must be supplied via a JSON file. -Note that --deposit below is the initial proposal deposit submitted along with the proposal. -Example: -$ %s tx gov submit-proposal community-pool-lend-withdraw --deposit 1000000000ukava --from= -Where proposal.json contains: -{ - "title": "Community Pool Withdrawal", - "description": "Withdraw some KAVA from community pool!", - "amount": [ - { - "denom": "ukava", - "amount": "100000000000" - } - ] -} -`, - version.AppName, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - // parse proposal - proposal, err := utils.ParseCommunityPoolLendWithdrawProposal(clientCtx.Codec, args[0]) - if err != nil { - return err - } - - deposit, err := parseInitialDeposit(cmd) - if err != nil { - return err - } - from := clientCtx.GetFromAddress() - msg, err := govv1beta1.NewMsgSubmitProposal(&proposal, deposit, from) - if err != nil { - return err - } - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - cmd.Flags().String(flagDeposit, "", "Initial deposit for the proposal") - - return cmd -} - -func parseInitialDeposit(cmd *cobra.Command) (sdk.Coins, error) { - // parse initial deposit - depositStr, err := cmd.Flags().GetString(flagDeposit) - if err != nil { - return nil, fmt.Errorf("no initial deposit found. did you set --deposit? %s", err) - } - deposit, err := sdk.ParseCoinsNormalized(depositStr) - if err != nil { - return nil, fmt.Errorf("unable to parse deposit: %s", err) - } - if !deposit.IsValid() || deposit.IsZero() { - return nil, fmt.Errorf("no initial deposit set, use --deposit flag") - } - return deposit, nil -} diff --git a/x/community/client/proposal_handler.go b/x/community/client/proposal_handler.go deleted file mode 100644 index f1a0dfa1..00000000 --- a/x/community/client/proposal_handler.go +++ /dev/null @@ -1,17 +0,0 @@ -package client - -import ( - govclient "github.com/cosmos/cosmos-sdk/x/gov/client" - - "github.com/kava-labs/kava/x/community/client/cli" -) - -// community-pool deposit/withdraw lend proposal handlers -var ( - LendDepositProposalHandler = govclient.NewProposalHandler( - cli.NewCmdSubmitCommunityPoolLendDepositProposal, - ) - LendWithdrawProposalHandler = govclient.NewProposalHandler( - cli.NewCmdSubmitCommunityPoolLendWithdrawProposal, - ) -) diff --git a/x/community/client/utils/utils.go b/x/community/client/utils/utils.go deleted file mode 100644 index 5b409a88..00000000 --- a/x/community/client/utils/utils.go +++ /dev/null @@ -1,39 +0,0 @@ -package utils - -import ( - "os" - - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/kava-labs/kava/x/community/types" -) - -// ParseCommunityPoolLendDepositProposal reads a JSON file and parses it to a CommunityPoolLendDepositProposal -func ParseCommunityPoolLendDepositProposal( - cdc codec.JSONCodec, - proposalFile string, -) (types.CommunityPoolLendDepositProposal, error) { - proposal := types.CommunityPoolLendDepositProposal{} - contents, err := os.ReadFile(proposalFile) - if err != nil { - return proposal, err - } - - err = cdc.UnmarshalJSON(contents, &proposal) - return proposal, err -} - -// ParseCommunityPoolLendWithdrawProposal reads a JSON file and parses it to a CommunityPoolLendWithdrawProposal -func ParseCommunityPoolLendWithdrawProposal( - cdc codec.JSONCodec, - proposalFile string, -) (types.CommunityPoolLendWithdrawProposal, error) { - proposal := types.CommunityPoolLendWithdrawProposal{} - contents, err := os.ReadFile(proposalFile) - if err != nil { - return proposal, err - } - - err = cdc.UnmarshalJSON(contents, &proposal) - return proposal, err -} diff --git a/x/community/client/utils/utils_test.go b/x/community/client/utils/utils_test.go deleted file mode 100644 index 1088c832..00000000 --- a/x/community/client/utils/utils_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package utils_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/community/client/utils" -) - -func TestParseDepositProposal(t *testing.T) { - cdc := codec.NewAminoCodec(codec.NewLegacyAmino()) - okJSON := testutil.WriteToNewTempFile(t, ` -{ - "title": "Community Pool Lend Deposit", - "description": "Deposit some KAVA from community pool to Lend!", - "amount": [ - { - "denom": "ukava", - "amount": "100000000000" - } - ] -} -`) - proposal, err := utils.ParseCommunityPoolLendDepositProposal(cdc, okJSON.Name()) - require.NoError(t, err) - - expectedAmount, err := sdk.ParseCoinsNormalized("100000000000ukava") - require.NoError(t, err) - - require.Equal(t, "Community Pool Lend Deposit", proposal.Title) - require.Equal(t, "Deposit some KAVA from community pool to Lend!", proposal.Description) - require.Equal(t, expectedAmount, proposal.Amount) -} - -func TestParseWithdrawProposal(t *testing.T) { - cdc := codec.NewAminoCodec(codec.NewLegacyAmino()) - okJSON := testutil.WriteToNewTempFile(t, ` -{ - "title": "Community Pool Lend Withdraw", - "description": "Withdraw some KAVA from community pool to Lend!", - "amount": [ - { - "denom": "ukava", - "amount": "100000000000" - } - ] -} -`) - proposal, err := utils.ParseCommunityPoolLendWithdrawProposal(cdc, okJSON.Name()) - require.NoError(t, err) - - expectedAmount, err := sdk.ParseCoinsNormalized("100000000000ukava") - require.NoError(t, err) - - require.Equal(t, "Community Pool Lend Withdraw", proposal.Title) - require.Equal(t, "Withdraw some KAVA from community pool to Lend!", proposal.Description) - require.Equal(t, expectedAmount, proposal.Amount) -} - -func TestParseFileNoExists(t *testing.T) { - cdc := codec.NewAminoCodec(codec.NewLegacyAmino()) - _, err := utils.ParseCommunityPoolLendDepositProposal(cdc, "not-a-file.json") - require.ErrorContains(t, err, "no such file or directory") - _, err = utils.ParseCommunityPoolLendWithdrawProposal(cdc, "not-a-file.json") - require.ErrorContains(t, err, "no such file or directory") -} - -func TestParseFileMalformed(t *testing.T) { - cdc := codec.NewAminoCodec(codec.NewLegacyAmino()) - malformed := testutil.WriteToNewTempFile(t, ` -{ - "title": "I'm malformed b/c there's no closing quote, - "description": "A description", - "amount": [{"denom": "ukava", "amount": "100000000000"}] -} -`) - _, err := utils.ParseCommunityPoolLendDepositProposal(cdc, malformed.Name()) - require.ErrorContains(t, err, "invalid character") - _, err = utils.ParseCommunityPoolLendWithdrawProposal(cdc, malformed.Name()) - require.ErrorContains(t, err, "invalid character") -} diff --git a/x/community/disable_inflation_abci_test.go b/x/community/disable_inflation_abci_test.go deleted file mode 100644 index 67c387c7..00000000 --- a/x/community/disable_inflation_abci_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package community_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/community" - "github.com/kava-labs/kava/x/community/keeper" - "github.com/kava-labs/kava/x/community/testutil" -) - -func TestABCIDisableInflation(t *testing.T) { - testFunc := func(ctx sdk.Context, k keeper.Keeper) { - community.BeginBlocker(ctx, k) - } - suite.Run(t, testutil.NewDisableInflationTestSuite(testFunc)) -} diff --git a/x/community/genesis.go b/x/community/genesis.go deleted file mode 100644 index e359fc49..00000000 --- a/x/community/genesis.go +++ /dev/null @@ -1,34 +0,0 @@ -// the community module has no genesis state but must init its module account on init -package community - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/community/keeper" - "github.com/kava-labs/kava/x/community/types" -) - -// InitGenesis initializes the community module account and stores the genesis state -func InitGenesis(ctx sdk.Context, k keeper.Keeper, ak types.AccountKeeper, gs types.GenesisState) { - // check if the module account exists - if moduleAcc := ak.GetModuleAccount(ctx, types.ModuleAccountName); moduleAcc == nil { - panic(fmt.Sprintf("%s module account has not been set", types.ModuleAccountName)) - } - - k.SetParams(ctx, gs.Params) - k.SetStakingRewardsState(ctx, gs.StakingRewardsState) -} - -// ExportGenesis exports the store to a genesis state -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { - params, found := k.GetParams(ctx) - if !found { - params = types.Params{} - } - - stakingRewardsState := k.GetStakingRewardsState(ctx) - - return types.NewGenesisState(params, stakingRewardsState) -} diff --git a/x/community/genesis_test.go b/x/community/genesis_test.go deleted file mode 100644 index 1a8a2589..00000000 --- a/x/community/genesis_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package community_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - "github.com/kava-labs/kava/x/community" - "github.com/kava-labs/kava/x/community/testutil" - "github.com/kava-labs/kava/x/community/types" -) - -type genesisTestSuite struct { - testutil.Suite -} - -func (suite *genesisTestSuite) SetupTest() { - suite.Suite.SetupTest() -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(genesisTestSuite)) -} - -func (suite *genesisTestSuite) TestInitGenesis() { - - accountKeeper := suite.App.GetAccountKeeper() - - genesisState := types.NewGenesisState( - types.NewParams( - time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - sdkmath.LegacyNewDec(1000), - sdkmath.LegacyNewDec(1000), - ), - types.NewStakingRewardsState( - time.Date(1997, 1, 1, 0, 0, 0, 0, time.UTC), - sdkmath.LegacyMustNewDecFromStr("0.100000000000000000"), - ), - ) - - suite.NotPanics(func() { - community.InitGenesis(suite.Ctx, suite.Keeper, accountKeeper, genesisState) - }) - - // check for module account this way b/c GetModuleAccount creates if not existing. - acc := accountKeeper.GetAccount(suite.Ctx, suite.MaccAddress) - suite.NotNil(acc) - _, ok := acc.(authtypes.ModuleAccountI) - suite.True(ok) - - keeper := suite.App.GetCommunityKeeper() - storedParams, found := keeper.GetParams(suite.Ctx) - suite.True(found) - suite.Equal(genesisState.Params, storedParams) - - stakingRewardsState := keeper.GetStakingRewardsState(suite.Ctx) - suite.Equal(genesisState.StakingRewardsState, stakingRewardsState) -} - -func (suite *genesisTestSuite) TestExportGenesis() { - params := types.NewParams( - time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - sdkmath.LegacyNewDec(1000), - sdkmath.LegacyNewDec(1000), - ) - suite.Keeper.SetParams(suite.Ctx, params) - - stakingRewardsState := types.NewStakingRewardsState( - time.Date(1997, 1, 1, 0, 0, 0, 0, time.UTC), - sdkmath.LegacyMustNewDecFromStr("0.100000000000000000"), - ) - suite.Keeper.SetStakingRewardsState(suite.Ctx, stakingRewardsState) - - genesisState := community.ExportGenesis(suite.Ctx, suite.Keeper) - - suite.Equal(params, genesisState.Params) - suite.Equal(stakingRewardsState, genesisState.StakingRewardsState) -} - -func (suite *genesisTestSuite) TestInitExportIsLossless() { - genesisState := types.NewGenesisState( - types.NewParams( - time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - sdkmath.LegacyNewDec(1000), - sdkmath.LegacyNewDec(1000), - ), - types.NewStakingRewardsState( - time.Date(1997, 1, 1, 0, 0, 0, 0, time.UTC), - sdkmath.LegacyMustNewDecFromStr("0.100000000000000000"), - ), - ) - - community.InitGenesis(suite.Ctx, suite.Keeper, suite.App.GetAccountKeeper(), genesisState) - exportedState := community.ExportGenesis(suite.Ctx, suite.Keeper) - - suite.Equal(genesisState, exportedState) -} diff --git a/x/community/handler.go b/x/community/handler.go deleted file mode 100644 index 45cf024b..00000000 --- a/x/community/handler.go +++ /dev/null @@ -1,29 +0,0 @@ -package community - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - "github.com/kava-labs/kava/x/community/keeper" - "github.com/kava-labs/kava/x/community/types" -) - -// NewCommunityPoolProposalHandler handles x/community proposals. -func NewCommunityPoolProposalHandler(k keeper.Keeper) govv1beta1.Handler { - return func(ctx sdk.Context, content govv1beta1.Content) error { - switch c := content.(type) { - case *types.CommunityCDPRepayDebtProposal: - return keeper.HandleCommunityCDPRepayDebtProposal(ctx, k, c) - case *types.CommunityCDPWithdrawCollateralProposal: - return keeper.HandleCommunityCDPWithdrawCollateralProposal(ctx, k, c) - case *types.CommunityPoolLendDepositProposal: - return keeper.HandleCommunityPoolLendDepositProposal(ctx, k, c) - case *types.CommunityPoolLendWithdrawProposal: - return keeper.HandleCommunityPoolLendWithdrawProposal(ctx, k, c) - default: - return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized community proposal content type: %T", c) - } - } -} diff --git a/x/community/keeper/consolidate.go b/x/community/keeper/consolidate.go deleted file mode 100644 index 41115785..00000000 --- a/x/community/keeper/consolidate.go +++ /dev/null @@ -1,104 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/community/types" - - kavadisttypes "github.com/kava-labs/kava/x/kavadist/types" - - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" -) - -// StartCommunityFundConsolidation consolidates the community funds from -// x/distribution and x/kavadist into the x/community module account -func (k Keeper) StartCommunityFundConsolidation(ctx sdk.Context) error { - logger := k.Logger(ctx) - logger.Info("community fund consolidation upgrade started") - - // Consolidate x/distribution community pool - if err := k.consolidateCommunityDistribution(ctx); err != nil { - return err - } - - // Consolidate x/kavadist account - if err := k.consolidateCommunityKavadist(ctx); err != nil { - return err - } - - // Log new x/community balance - communityCoins := k.GetModuleAccountBalance(ctx) - logger.Info(fmt.Sprintf("community funds consolidated, x/community balance is now %s", communityCoins)) - - return nil -} - -// consolidateCommunityDistribution transfers all coins from the x/distribution -// community pool to the x/community module account -func (k Keeper) consolidateCommunityDistribution(ctx sdk.Context) error { - logger := k.Logger(ctx) - - // Get community coins with leftover leftoverDust - truncatedCoins, leftoverDust := k.distrKeeper. - GetFeePoolCommunityCoins(ctx). - TruncateDecimal() - - // Transfer to x/community - err := k.bankKeeper.SendCoinsFromModuleToModule( - ctx, - distrtypes.ModuleName, // sender - types.ModuleName, // recipient - truncatedCoins, - ) - if err != nil { - return fmt.Errorf("failed to transfer x/distribution coins to x/community: %w", err) - } - - logger.Info(fmt.Sprintf("transferred %s from x/distribution to x/community", truncatedCoins)) - - // Set x/distribution community pool to remaining dust amounts - feePool := k.distrKeeper.GetFeePool(ctx) - feePool.CommunityPool = leftoverDust - k.distrKeeper.SetFeePool(ctx, feePool) - - logger.Info(fmt.Sprintf("remaining x/distribution community pool dust: %s", leftoverDust)) - - return nil -} - -// consolidateCommunityKavadist transfers all coins from the x/kavadist module -// account to the x/community module account -func (k Keeper) consolidateCommunityKavadist(ctx sdk.Context) error { - logger := k.Logger(ctx) - - kavadistAcc := k.accountKeeper.GetModuleAccount(ctx, kavadisttypes.KavaDistMacc) - transferCoins := k.bankKeeper.GetAllBalances(ctx, kavadistAcc.GetAddress()) - - // Remove ukava from transfer coins - ony transfer non-ukava coins - found, kavaCoins := transferCoins.Find("ukava") - if found { - transferCoins = transferCoins.Sub(kavaCoins) - } - - // Transfer remaining coins to x/community - err := k.bankKeeper.SendCoinsFromModuleToModule( - ctx, - kavadisttypes.ModuleName, // sender - types.ModuleName, // recipient - transferCoins, - ) - if err != nil { - return fmt.Errorf("failed to transfer x/kavadist coins to x/community: %w", err) - } - - kavadistRemainingCoins := k.bankKeeper.GetAllBalances(ctx, kavadistAcc.GetAddress()) - - logger.Info(fmt.Sprintf( - "transferred %s from x/kavadist to x/community, remaining x/kavadist balance: %s", - transferCoins, - kavadistRemainingCoins, - )) - - return nil -} diff --git a/x/community/keeper/disable_inflation.go b/x/community/keeper/disable_inflation.go deleted file mode 100644 index 1a88f53b..00000000 --- a/x/community/keeper/disable_inflation.go +++ /dev/null @@ -1,83 +0,0 @@ -package keeper - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/community/types" -) - -// CheckAndDisableMintAndKavaDistInflation compares the disable inflation time and block time, -// and disables inflation if time is set and before block time. Inflation time is reset, -// so this method is safe to call more than once. -func (k Keeper) CheckAndDisableMintAndKavaDistInflation(ctx sdk.Context) { - // panic if params are not found since this can only be reached if chain state is corrupted or method is ran at an invalid height - params := k.mustGetParams(ctx) - - // if disable inflation time is in the future or zero there is nothing to do, so return - if params.UpgradeTimeDisableInflation.IsZero() || params.UpgradeTimeDisableInflation.After(ctx.BlockTime()) { - return - } - - logger := k.Logger(ctx) - logger.Info("disable inflation upgrade started") - - // run disable inflation logic - k.disableInflation(ctx) - k.disableCommunityTax(ctx) - - logger.Info("disable inflation upgrade finished successfully!") - - // reset disable inflation time to ensure next call is a no-op - params.UpgradeTimeDisableInflation = time.Time{} - // set staking rewards to provided intial value - params.StakingRewardsPerSecond = params.UpgradeTimeSetStakingRewardsPerSecond - k.SetParams(ctx, params) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeInflationStop, - sdk.NewAttribute( - types.AttributeKeyInflationDisableTime, - ctx.BlockTime().Format(time.RFC3339), - ), - ), - ) - - if err := k.StartCommunityFundConsolidation(ctx); err != nil { - panic(err) - } -} - -// TODO: double check this is correct method for disabling inflation in kavadist without -// affecting rewards. In addition, inflation periods in kavadist should be removed. -func (k Keeper) disableInflation(ctx sdk.Context) { - logger := k.Logger(ctx) - - // set x/min inflation to 0 - mintParams := k.mintKeeper.GetParams(ctx) - mintParams.InflationMin = sdk.ZeroDec() - mintParams.InflationMax = sdk.ZeroDec() - if err := k.mintKeeper.SetParams(ctx, mintParams); err != nil { - panic(err) - } - logger.Info("x/mint inflation set to 0") - - // disable kavadist inflation - kavadistParams := k.kavadistKeeper.GetParams(ctx) - kavadistParams.Active = false - k.kavadistKeeper.SetParams(ctx, kavadistParams) - logger.Info("x/kavadist inflation disabled") -} - -// disableCommunityTax sets x/distribution Params.CommunityTax to 0 -func (k Keeper) disableCommunityTax(ctx sdk.Context) { - logger := k.Logger(ctx) - - distrParams := k.distrKeeper.GetParams(ctx) - distrParams.CommunityTax = sdk.ZeroDec() - if err := k.distrKeeper.SetParams(ctx, distrParams); err != nil { - panic(err) - } - logger.Info("x/distribution community tax set to 0") -} diff --git a/x/community/keeper/disable_inflation_test.go b/x/community/keeper/disable_inflation_test.go deleted file mode 100644 index 94e19097..00000000 --- a/x/community/keeper/disable_inflation_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/community/keeper" - "github.com/kava-labs/kava/x/community/testutil" -) - -func TestKeeperDisableInflation(t *testing.T) { - testFunc := func(ctx sdk.Context, k keeper.Keeper) { - k.CheckAndDisableMintAndKavaDistInflation(ctx) - } - suite.Run(t, testutil.NewDisableInflationTestSuite(testFunc)) -} diff --git a/x/community/keeper/grpc_query.go b/x/community/keeper/grpc_query.go deleted file mode 100644 index 44d58e6c..00000000 --- a/x/community/keeper/grpc_query.go +++ /dev/null @@ -1,99 +0,0 @@ -package keeper - -import ( - "context" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/kava-labs/kava/x/community/types" -) - -type queryServer struct { - keeper Keeper -} - -var _ types.QueryServer = queryServer{} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -// Params implements the gRPC service handler for querying x/community params. -func (s queryServer) Params(c context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - params, found := s.keeper.GetParams(ctx) - if !found { - return nil, status.Error(codes.NotFound, "params not found") - } - - return &types.QueryParamsResponse{ - Params: params, - }, nil -} - -// Balance implements the gRPC service handler for querying x/community balance. -func (s queryServer) Balance(c context.Context, _ *types.QueryBalanceRequest) (*types.QueryBalanceResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - return &types.QueryBalanceResponse{ - Coins: s.keeper.GetModuleAccountBalance(ctx), - }, nil -} - -// CommunityPool queries the community pool coins -func (s queryServer) TotalBalance( - c context.Context, - req *types.QueryTotalBalanceRequest, -) (*types.QueryTotalBalanceResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - // x/distribution community pool balance - nativePoolBalance := s.keeper.distrKeeper.GetFeePoolCommunityCoins(ctx) - - // x/community pool balance - communityPoolBalance := s.keeper.GetModuleAccountBalance(ctx) - - totalBalance := nativePoolBalance.Add(sdk.NewDecCoinsFromCoins(communityPoolBalance...)...) - - return &types.QueryTotalBalanceResponse{ - Pool: totalBalance, - }, nil -} - -// AnnualizedRewards calculates the annualized rewards for the chain. -func (s queryServer) AnnualizedRewards( - c context.Context, - req *types.QueryAnnualizedRewardsRequest, -) (*types.QueryAnnualizedRewardsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - // staking rewards come from one of two sources depending on if inflation is enabled or not. - // at any given time, only one source will contribute to the staking rewards. the other will be zero. - // this method adds both sources together so it is accurate in both cases. - - params := s.keeper.mustGetParams(ctx) - bondDenom := s.keeper.stakingKeeper.BondDenom(ctx) - - totalSupply := s.keeper.bankKeeper.GetSupply(ctx, bondDenom).Amount - totalBonded := s.keeper.stakingKeeper.TotalBondedTokens(ctx) - rewardsPerSecond := params.StakingRewardsPerSecond - // need to convert these from sdk.Dec to sdkmath.LegacyDec - inflationRate := convertDecToLegacyDec(s.keeper.mintKeeper.GetMinter(ctx).Inflation) - communityTax := convertDecToLegacyDec(s.keeper.distrKeeper.GetCommunityTax(ctx)) - - return &types.QueryAnnualizedRewardsResponse{ - StakingRewards: CalculateStakingAnnualPercentage(totalSupply, totalBonded, inflationRate, communityTax, rewardsPerSecond), - }, nil -} - -// convertDecToLegacyDec is a helper method for converting between new and old Dec types -// current version of cosmos-sdk in this repo uses sdk.Dec -// this module uses sdkmath.LegacyDec in its parameters -// TODO: remove me after upgrade to cosmos-sdk v50 (LegacyDec is everywhere) -func convertDecToLegacyDec(in sdk.Dec) sdkmath.LegacyDec { - return sdkmath.LegacyNewDecFromBigIntWithPrec(in.BigInt(), sdk.Precision) -} diff --git a/x/community/keeper/grpc_query_test.go b/x/community/keeper/grpc_query_test.go deleted file mode 100644 index 6a4b9b28..00000000 --- a/x/community/keeper/grpc_query_test.go +++ /dev/null @@ -1,292 +0,0 @@ -package keeper_test - -import ( - "context" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/community/keeper" - "github.com/kava-labs/kava/x/community/testutil" - "github.com/kava-labs/kava/x/community/types" -) - -type grpcQueryTestSuite struct { - testutil.Suite - - queryClient types.QueryClient -} - -func (suite *grpcQueryTestSuite) SetupTest() { - suite.Suite.SetupTest() - - queryHelper := baseapp.NewQueryServerTestHelper(suite.Ctx, suite.App.InterfaceRegistry()) - types.RegisterQueryServer(queryHelper, keeper.NewQueryServerImpl(suite.Keeper)) - - suite.queryClient = types.NewQueryClient(queryHelper) -} - -func TestGrpcQueryTestSuite(t *testing.T) { - suite.Run(t, new(grpcQueryTestSuite)) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryParams() { - p := types.NewParams( - time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - sdkmath.LegacyNewDec(1000), - sdkmath.LegacyNewDec(1000), - ) - suite.Keeper.SetParams(suite.Ctx, p) - - res, err := suite.queryClient.Params(context.Background(), &types.QueryParamsRequest{}) - suite.Require().NoError(err) - suite.Equal( - types.QueryParamsResponse{ - Params: p, - }, - *res, - ) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryBalance() { - var expCoins sdk.Coins - - testCases := []struct { - name string - setup func() - }{ - { - name: "handles response with no balance", - setup: func() { expCoins = sdk.Coins{} }, - }, - { - name: "handles response with balance", - setup: func() { - expCoins = sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100)), - sdk.NewCoin("usdx", sdkmath.NewInt(1000)), - ) - suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, expCoins) - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - tc.setup() - res, err := suite.queryClient.Balance(context.Background(), &types.QueryBalanceRequest{}) - suite.Require().NoError(err) - suite.Require().True(expCoins.IsEqual(res.Coins)) - }) - } -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalBalance() { - var expCoins sdk.DecCoins - - testCases := []struct { - name string - setup func() - }{ - { - name: "handles response with no balance", - setup: func() { expCoins = sdk.DecCoins{} }, - }, - { - name: "handles response with balance", - setup: func() { - expCoins = sdk.NewDecCoins( - sdk.NewDecCoin("ukava", sdkmath.NewInt(100)), - sdk.NewDecCoin("usdx", sdkmath.NewInt(1000)), - ) - - coins, _ := expCoins.TruncateDecimal() - - suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, coins) - }, - }, - { - name: "handles response with both x/community + x/distribution balance", - setup: func() { - decCoins1 := sdk.NewDecCoins( - sdk.NewDecCoin("ukava", sdkmath.NewInt(100)), - sdk.NewDecCoin("usdx", sdkmath.NewInt(1000)), - ) - - coins, _ := decCoins1.TruncateDecimal() - - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, coins) - suite.Require().NoError(err) - - decCoins2 := sdk.NewDecCoins( - sdk.NewDecCoin("ukava", sdkmath.NewInt(100)), - sdk.NewDecCoin("usdc", sdkmath.NewInt(1000)), - ) - - // Add to x/distribution community pool (just state, not actual coins) - dk := suite.App.GetDistrKeeper() - feePool := dk.GetFeePool(suite.Ctx) - feePool.CommunityPool = feePool.CommunityPool.Add(decCoins2...) - dk.SetFeePool(suite.Ctx, feePool) - - expCoins = decCoins1.Add(decCoins2...) - }, - }, - { - name: "handles response with only x/distribution balance", - setup: func() { - expCoins = sdk.NewDecCoins( - sdk.NewDecCoin("ukava", sdkmath.NewInt(100)), - sdk.NewDecCoin("usdc", sdkmath.NewInt(1000)), - ) - - // Add to x/distribution community pool (just state, not actual coins) - dk := suite.App.GetDistrKeeper() - feePool := dk.GetFeePool(suite.Ctx) - feePool.CommunityPool = feePool.CommunityPool.Add(expCoins...) - dk.SetFeePool(suite.Ctx, feePool) - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - tc.setup() - res, err := suite.queryClient.TotalBalance(context.Background(), &types.QueryTotalBalanceRequest{}) - suite.Require().NoError(err) - suite.Require().True(expCoins.IsEqual(res.Pool)) - }) - } -} - -// NOTE: this test makes use of the fact that there is always an initial 1e6 bonded tokens -// To adjust the bonded ratio, it adjusts the total supply by minting tokens. -func (suite *grpcQueryTestSuite) TestGrpcQueryAnnualizedRewards() { - bondedTokens := sdkmath.NewInt(1e6) - testCases := []struct { - name string - bondedRatio sdk.Dec - inflation sdk.Dec - rewardsPerSec sdkmath.LegacyDec - communityTax sdk.Dec - expectedRate sdkmath.LegacyDec - }{ - { - name: "sanity check: no inflation, no rewards => 0%", - bondedRatio: sdk.MustNewDecFromStr("0.3456"), - inflation: sdk.ZeroDec(), - rewardsPerSec: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyZeroDec(), - }, - { - name: "inflation sanity check: 100% inflation, 100% bonded => 100%", - bondedRatio: sdk.OneDec(), - inflation: sdk.OneDec(), - rewardsPerSec: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyOneDec(), - }, - { - name: "inflation sanity check: 100% community tax => 0%", - bondedRatio: sdk.OneDec(), - inflation: sdk.OneDec(), - communityTax: sdk.OneDec(), - rewardsPerSec: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyZeroDec(), - }, - { - name: "rewards per second sanity check: (totalBonded/SecondsPerYear) rps => 100%", - bondedRatio: sdk.OneDec(), // bonded tokens are constant in this test. ratio has no affect. - inflation: sdk.ZeroDec(), - rewardsPerSec: sdkmath.LegacyNewDecFromInt(bondedTokens).QuoInt(sdkmath.NewInt(keeper.SecondsPerYear)), - // expect ~100% - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.999999999999999984"), - }, - { - name: "inflation enabled: realistic example", - bondedRatio: sdk.MustNewDecFromStr("0.148"), - inflation: sdk.MustNewDecFromStr("0.595"), - communityTax: sdk.MustNewDecFromStr("0.9495"), - rewardsPerSec: sdkmath.LegacyZeroDec(), - // expect ~20.23% - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.203023625910000000"), - }, - { - name: "inflation disabled: simple example", - bondedRatio: sdk.OneDec(), // bonded tokens are constant in this test. ratio has no affect. - inflation: sdk.ZeroDec(), - rewardsPerSec: sdkmath.LegacyMustNewDecFromStr("0.01"), - // 1e6 bonded tokens => seconds per year / bonded tokens = 31.536 - // expect 31.536% - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.31536"), - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - // set inflation - mk := suite.App.GetMintKeeper() - minter := mk.GetMinter(suite.Ctx) - minter.Inflation = tc.inflation - mk.SetMinter(suite.Ctx, minter) - - // set community tax - communityTax := sdk.ZeroDec() - if !tc.communityTax.IsNil() { - communityTax = tc.communityTax - } - dk := suite.App.GetDistrKeeper() - distParams := dk.GetParams(suite.Ctx) - distParams.CommunityTax = communityTax - dk.SetParams(suite.Ctx, distParams) - - // set staking rewards per second - ck := suite.App.GetCommunityKeeper() - commParams, _ := ck.GetParams(suite.Ctx) - commParams.StakingRewardsPerSecond = tc.rewardsPerSec - ck.SetParams(suite.Ctx, commParams) - - // set bonded tokens - suite.adjustBondedRatio(tc.bondedRatio) - - // query for annualized rewards - res, err := suite.queryClient.AnnualizedRewards(suite.Ctx, &types.QueryAnnualizedRewardsRequest{}) - // verify results match expected - suite.Require().NoError(err) - suite.Equal(tc.expectedRate, res.StakingRewards) - }) - } -} - -// adjustBondRatio changes the ratio of bonded coins -// it leverages the fact that there is a constant number of bonded tokens -// and adjusts the total supply to make change the bonded ratio. -// returns the new total supply of the bond denom -func (suite *grpcQueryTestSuite) adjustBondedRatio(desiredRatio sdk.Dec) sdkmath.Int { - // from the InitGenesis validator - bondedTokens := sdkmath.NewInt(1e6) - bondDenom := suite.App.GetStakingKeeper().BondDenom(suite.Ctx) - - // first, burn all non-delegated coins (bonded ratio = 100%) - suite.App.DeleteGenesisValidatorCoins(suite.T(), suite.Ctx) - - if desiredRatio.Equal(sdk.OneDec()) { - return bondedTokens - } - - // mint new tokens to adjust the bond ratio - newTotalSupply := sdk.NewDecFromInt(bondedTokens).Quo(desiredRatio).TruncateInt() - coinsToMint := newTotalSupply.Sub(bondedTokens) - err := suite.App.FundAccount(suite.Ctx, app.RandomAddress(), sdk.NewCoins(sdk.NewCoin(bondDenom, coinsToMint))) - suite.Require().NoError(err) - - return newTotalSupply -} diff --git a/x/community/keeper/keeper.go b/x/community/keeper/keeper.go deleted file mode 100644 index 585afaca..00000000 --- a/x/community/keeper/keeper.go +++ /dev/null @@ -1,132 +0,0 @@ -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" - - "github.com/kava-labs/kava/x/community/types" -) - -// Keeper of the community store -type Keeper struct { - key storetypes.StoreKey - cdc codec.Codec - - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - cdpKeeper types.CdpKeeper - distrKeeper types.DistributionKeeper - hardKeeper types.HardKeeper - moduleAddress sdk.AccAddress - mintKeeper types.MintKeeper - kavadistKeeper types.KavadistKeeper - stakingKeeper types.StakingKeeper - - // the address capable of executing a MsgUpdateParams message. Typically, this - // should be the x/gov module account. - authority sdk.AccAddress - - legacyCommunityPoolAddress sdk.AccAddress -} - -// NewKeeper creates a new community Keeper instance -func NewKeeper( - cdc codec.Codec, - key storetypes.StoreKey, - ak types.AccountKeeper, - bk types.BankKeeper, - ck types.CdpKeeper, - dk types.DistributionKeeper, - hk types.HardKeeper, - mk types.MintKeeper, - kk types.KavadistKeeper, - sk types.StakingKeeper, - authority sdk.AccAddress, -) Keeper { - // ensure community module account is set - addr := ak.GetModuleAddress(types.ModuleAccountName) - if addr == nil { - panic(fmt.Sprintf("%s module account has not been set", types.ModuleAccountName)) - } - legacyAddr := ak.GetModuleAddress(types.LegacyCommunityPoolModuleName) - if addr == nil { - panic("legacy community pool address not found") - } - if err := sdk.VerifyAddressFormat(authority); err != nil { - panic(fmt.Sprintf("invalid authority address: %s", err)) - } - - return Keeper{ - key: key, - cdc: cdc, - - accountKeeper: ak, - bankKeeper: bk, - cdpKeeper: ck, - distrKeeper: dk, - hardKeeper: hk, - mintKeeper: mk, - kavadistKeeper: kk, - stakingKeeper: sk, - moduleAddress: addr, - - authority: authority, - legacyCommunityPoolAddress: legacyAddr, - } -} - -// GetAuthority returns the x/community module's authority. -func (k Keeper) GetAuthority() sdk.AccAddress { - return k.authority -} - -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", "x/"+types.ModuleName) -} - -// GetModuleAccountBalance returns all the coins held by the community module account -func (k Keeper) GetModuleAccountBalance(ctx sdk.Context) sdk.Coins { - return k.bankKeeper.GetAllBalances(ctx, k.moduleAddress) -} - -// FundCommunityPool transfers coins from the sender to the community module account. -func (k Keeper) FundCommunityPool(ctx sdk.Context, sender sdk.AccAddress, amount sdk.Coins) error { - return k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleAccountName, amount) -} - -// DistributeFromCommunityPool transfers coins from the community pool to recipient. -func (k Keeper) DistributeFromCommunityPool(ctx sdk.Context, recipient sdk.AccAddress, amount sdk.Coins) error { - return k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, recipient, amount) -} - -// GetStakingRewardsState returns the staking reward state or the default state if not set -func (k Keeper) GetStakingRewardsState(ctx sdk.Context) types.StakingRewardsState { - store := ctx.KVStore(k.key) - - b := store.Get(types.StakingRewardsStateKey) - if b == nil { - return types.DefaultStakingRewardsState() - } - - state := types.StakingRewardsState{} - k.cdc.MustUnmarshal(b, &state) - - return state -} - -// SetStakingRewardsState validates and sets the staking rewards state in the store -func (k Keeper) SetStakingRewardsState(ctx sdk.Context, state types.StakingRewardsState) { - if err := state.Validate(); err != nil { - panic(fmt.Sprintf("invalid state: %s", err)) - } - - store := ctx.KVStore(k.key) - b := k.cdc.MustMarshal(&state) - - store.Set(types.StakingRewardsStateKey, b) -} diff --git a/x/community/keeper/keeper_test.go b/x/community/keeper/keeper_test.go deleted file mode 100644 index f3d8d7d6..00000000 --- a/x/community/keeper/keeper_test.go +++ /dev/null @@ -1,188 +0,0 @@ -package keeper_test - -import ( - "strings" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/community/keeper" - "github.com/kava-labs/kava/x/community/testutil" - "github.com/kava-labs/kava/x/community/types" -) - -// Test suite used for all keeper tests -type KeeperTestSuite struct { - testutil.Suite -} - -// The default state used by each test -func (suite *KeeperTestSuite) SetupTest() { - suite.Suite.SetupTest() -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} - -func (suite *KeeperTestSuite) TestCommunityPool() { - suite.SetupTest() - maccAddr := suite.App.GetAccountKeeper().GetModuleAddress(types.ModuleAccountName) - - funds := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10000)), - sdk.NewCoin("usdx", sdkmath.NewInt(100)), - ) - sender := suite.CreateFundedAccount(funds) - - suite.Run("FundCommunityPool", func() { - err := suite.Keeper.FundCommunityPool(suite.Ctx, sender, funds) - suite.Require().NoError(err) - - // check that community pool received balance - suite.App.CheckBalance(suite.T(), suite.Ctx, maccAddr, funds) - suite.Equal(funds, suite.Keeper.GetModuleAccountBalance(suite.Ctx)) - // check that sender had balance deducted - suite.App.CheckBalance(suite.T(), suite.Ctx, sender, sdk.NewCoins()) - }) - - // send it back - suite.Run("DistributeFromCommunityPool - valid", func() { - err := suite.Keeper.DistributeFromCommunityPool(suite.Ctx, sender, funds) - suite.Require().NoError(err) - - // community pool has funds deducted - suite.App.CheckBalance(suite.T(), suite.Ctx, maccAddr, sdk.NewCoins()) - suite.Equal(sdk.NewCoins(), suite.Keeper.GetModuleAccountBalance(suite.Ctx)) - // receiver receives the funds - suite.App.CheckBalance(suite.T(), suite.Ctx, sender, funds) - }) - - // can't send more than we have! - suite.Run("DistributeFromCommunityPool - insufficient funds", func() { - suite.Equal(sdk.NewCoins(), suite.Keeper.GetModuleAccountBalance(suite.Ctx)) - err := suite.Keeper.DistributeFromCommunityPool(suite.Ctx, sender, funds) - suite.Require().ErrorContains(err, "insufficient funds") - }) -} - -func (suite *KeeperTestSuite) TestGetAndSetStakingRewardsState() { - keeper := suite.Keeper - - defaultParams := keeper.GetStakingRewardsState(suite.Ctx) - suite.Equal(time.Time{}, defaultParams.LastAccumulationTime, "expected default returned accumulation time to be zero") - suite.Equal(sdkmath.LegacyZeroDec(), defaultParams.LastTruncationError, "expected default truncation error to be zero") - - suite.NotPanics(func() { keeper.SetStakingRewardsState(suite.Ctx, defaultParams) }, "expected setting default state to not panic") - - invalidParams := defaultParams - invalidParams.LastTruncationError = sdkmath.LegacyDec{} - - suite.Panics(func() { keeper.SetStakingRewardsState(suite.Ctx, invalidParams) }, "expected setting invalid state to panic") - - validParams := defaultParams - validParams.LastAccumulationTime = time.Date(2023, 9, 29, 11, 42, 53, 123456789, time.UTC) - validParams.LastTruncationError = sdkmath.LegacyMustNewDecFromStr("0.50000000000000000") - - suite.NotPanics(func() { keeper.SetStakingRewardsState(suite.Ctx, validParams) }, "expected setting valid state to not panic") - - suite.Equal(validParams, keeper.GetStakingRewardsState(suite.Ctx), "expected fetched state to equal set state") -} - -func (suite *KeeperTestSuite) TestGetAuthority_Default() { - suite.Equal( - authtypes.NewModuleAddress(govtypes.ModuleName), - suite.Keeper.GetAuthority(), - "expected fetched authority to equal x/gov address", - ) -} - -func (suite *KeeperTestSuite) TestGetAuthority_Any() { - tests := []struct { - name string - authority sdk.AccAddress - }{ - { - name: "gov", - authority: authtypes.NewModuleAddress(govtypes.ModuleName), - }, - { - name: "random", - authority: sdk.AccAddress("random"), - }, - } - - for _, tc := range tests { - suite.Run(tc.name, func() { - suite.NotPanics(func() { - suite.Keeper = keeper.NewKeeper( - suite.App.AppCodec(), - suite.App.GetKVStoreKey(types.StoreKey), - suite.App.GetAccountKeeper(), - suite.App.GetBankKeeper(), - suite.App.GetCDPKeeper(), - suite.App.GetDistrKeeper(), - suite.App.GetHardKeeper(), - suite.App.GetMintKeeper(), - suite.App.GetKavadistKeeper(), - suite.App.GetStakingKeeper(), - tc.authority, - ) - }) - - suite.Equalf( - tc.authority, - suite.Keeper.GetAuthority(), - "expected fetched authority to equal %s address", - tc.authority, - ) - }) - } -} - -func (suite *KeeperTestSuite) TestNewKeeper_InvalidAuthority() { - tests := []struct { - name string - authority sdk.AccAddress - panicStr string - }{ - { - name: "empty", - authority: sdk.AccAddress{}, - panicStr: "invalid authority address: addresses cannot be empty: unknown address", - }, - { - name: "too long", - authority: sdk.AccAddress(strings.Repeat("a", address.MaxAddrLen+1)), - panicStr: "invalid authority address: address max length is 255, got 256: unknown address", - }, - } - - for _, tc := range tests { - suite.Run(tc.name, func() { - suite.PanicsWithValue( - tc.panicStr, - func() { - suite.Keeper = keeper.NewKeeper( - suite.App.AppCodec(), - suite.App.GetKVStoreKey(types.StoreKey), - suite.App.GetAccountKeeper(), - suite.App.GetBankKeeper(), - suite.App.GetCDPKeeper(), - suite.App.GetDistrKeeper(), - suite.App.GetHardKeeper(), - suite.App.GetMintKeeper(), - suite.App.GetKavadistKeeper(), - suite.App.GetStakingKeeper(), - tc.authority, - ) - }) - }) - } -} diff --git a/x/community/keeper/migrations.go b/x/community/keeper/migrations.go deleted file mode 100644 index 036c56fe..00000000 --- a/x/community/keeper/migrations.go +++ /dev/null @@ -1,27 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - v2 "github.com/kava-labs/kava/x/community/migrations/v2" -) - -// Migrator is a struct for handling in-place store migrations. -type Migrator struct { - keeper Keeper -} - -// NewMigrator returns a new Migrator. -func NewMigrator(keeper Keeper) Migrator { - return Migrator{ - keeper: keeper, - } -} - -// Migrate1to2 migrates from version 1 to 2. -func (m Migrator) Migrate1to2(ctx sdk.Context) error { - return v2.Migrate( - ctx, - ctx.KVStore(m.keeper.key), - m.keeper.cdc, - ) -} diff --git a/x/community/keeper/msg_server.go b/x/community/keeper/msg_server.go deleted file mode 100644 index e3945c96..00000000 --- a/x/community/keeper/msg_server.go +++ /dev/null @@ -1,76 +0,0 @@ -package keeper - -import ( - "context" - - "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - - "github.com/kava-labs/kava/x/community/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the community MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -// FundCommunityPool handles FundCommunityPool msgs. -func (s msgServer) FundCommunityPool(goCtx context.Context, msg *types.MsgFundCommunityPool) (*types.MsgFundCommunityPoolResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - - // above validation will fail if depositor is invalid - depositor := sdk.MustAccAddressFromBech32(msg.Depositor) - - if err := s.keeper.FundCommunityPool(ctx, depositor, msg.Amount); err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeyAction, types.AttributeValueFundCommunityPool), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Depositor), - sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), - ), - ) - - return &types.MsgFundCommunityPoolResponse{}, nil -} - -// UpdateParams handles UpdateParams msgs. -func (s msgServer) UpdateParams( - goCtx context.Context, - msg *types.MsgUpdateParams, -) (*types.MsgUpdateParamsResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if s.keeper.GetAuthority().String() != msg.Authority { - return nil, errors.Wrapf( - govtypes.ErrInvalidSigner, - "invalid authority; expected %s, got %s", - s.keeper.GetAuthority(), - msg.Authority, - ) - } - - if err := msg.Params.Validate(); err != nil { - return nil, errors.Wrap(types.ErrInvalidParams, err.Error()) - } - - s.keeper.SetParams(ctx, msg.Params) - - return &types.MsgUpdateParamsResponse{}, nil -} diff --git a/x/community/keeper/msg_server_test.go b/x/community/keeper/msg_server_test.go deleted file mode 100644 index 63095161..00000000 --- a/x/community/keeper/msg_server_test.go +++ /dev/null @@ -1,170 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/community/keeper" - "github.com/kava-labs/kava/x/community/testutil" - "github.com/kava-labs/kava/x/community/types" -) - -type msgServerTestSuite struct { - testutil.Suite - - communityPool sdk.AccAddress - msgServer types.MsgServer -} - -func (suite *msgServerTestSuite) SetupTest() { - suite.Suite.SetupTest() - - suite.communityPool = suite.App.GetAccountKeeper().GetModuleAddress(types.ModuleAccountName) - suite.msgServer = keeper.NewMsgServerImpl(suite.Keeper) -} - -func TestMsgServerTestSuite(t *testing.T) { - suite.Run(t, new(msgServerTestSuite)) -} - -func (suite *msgServerTestSuite) TestMsgFundCommunityPool() { - singleCoin := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(2e6))) - multipleCoins := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(3e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(1e7)), - ) - testCases := []struct { - name string - setup func() *types.MsgFundCommunityPool - expectedBalance sdk.Coins - shouldPass bool - }{ - { - name: "valid funding of single coin", - setup: func() *types.MsgFundCommunityPool { - sender := app.RandomAddress() - suite.App.FundAccount(suite.Ctx, sender, singleCoin) - return &types.MsgFundCommunityPool{ - Amount: singleCoin, - Depositor: sender.String(), - } - }, - expectedBalance: singleCoin, - shouldPass: true, - }, - { - name: "valid funding of multiple coins", - setup: func() *types.MsgFundCommunityPool { - sender := app.RandomAddress() - suite.App.FundAccount(suite.Ctx, sender, multipleCoins) - return &types.MsgFundCommunityPool{ - Amount: multipleCoins, - Depositor: sender.String(), - } - }, - expectedBalance: multipleCoins, - shouldPass: true, - }, - { - name: "invalid - failing message validation", - setup: func() *types.MsgFundCommunityPool { - return &types.MsgFundCommunityPool{ - Amount: sdk.NewCoins(), - Depositor: app.RandomAddress().String(), - } - }, - expectedBalance: sdk.NewCoins(), - shouldPass: false, - }, - { - name: "invalid - failing tx, insufficient funds", - setup: func() *types.MsgFundCommunityPool { - return &types.MsgFundCommunityPool{ - Amount: singleCoin, - Depositor: app.RandomAddress().String(), - } - }, - expectedBalance: sdk.NewCoins(), - shouldPass: false, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - msg := tc.setup() - _, err := suite.msgServer.FundCommunityPool(sdk.WrapSDKContext(suite.Ctx), msg) - if tc.shouldPass { - suite.NoError(err) - } else { - suite.Error(err) - } - - balance := suite.Keeper.GetModuleAccountBalance(suite.Ctx) - suite.App.CheckBalance(suite.T(), suite.Ctx, suite.communityPool, balance) - }) - } -} - -func (suite *msgServerTestSuite) TestMsgUpdateParams() { - govAddr := authtypes.NewModuleAddress(govtypes.ModuleName) - - testCases := []struct { - name string - msg types.MsgUpdateParams - expectedError error - }{ - { - name: "valid", - msg: types.MsgUpdateParams{ - Authority: govAddr.String(), - Params: types.DefaultParams(), - }, - expectedError: nil, - }, - { - name: "invalid - bad authority", - msg: types.MsgUpdateParams{ - Authority: sdk.AccAddress{1, 2, 3}.String(), - Params: types.DefaultParams(), - }, - expectedError: govtypes.ErrInvalidSigner, - }, - { - name: "invalid - empty authority", - msg: types.MsgUpdateParams{ - Authority: "", - Params: types.DefaultParams(), - }, - expectedError: govtypes.ErrInvalidSigner, - }, - { - name: "invalid - parameters", - msg: types.MsgUpdateParams{ - Authority: govAddr.String(), - Params: types.Params{}, - }, - expectedError: types.ErrInvalidParams, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - _, err := suite.msgServer.UpdateParams(sdk.WrapSDKContext(suite.Ctx), &tc.msg) - if tc.expectedError == nil { - suite.NoError(err) - } else { - suite.ErrorIs(err, tc.expectedError) - } - }) - } -} diff --git a/x/community/keeper/params.go b/x/community/keeper/params.go deleted file mode 100644 index 9819af33..00000000 --- a/x/community/keeper/params.go +++ /dev/null @@ -1,45 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/community/types" -) - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) (types.Params, bool) { - store := ctx.KVStore(k.key) - - bz := store.Get(types.ParamsKey) - if bz == nil { - return types.Params{}, false - } - - params := types.Params{} - k.cdc.MustUnmarshal(bz, ¶ms) - - return params, true -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - if err := params.Validate(); err != nil { - panic(fmt.Sprintf("invalid params: %s", err)) - } - - store := ctx.KVStore(k.key) - bz := k.cdc.MustMarshal(¶ms) - - store.Set(types.ParamsKey, bz) -} - -func (k Keeper) mustGetParams(ctx sdk.Context) types.Params { - params, found := k.GetParams(ctx) - if !found { - panic("invalid state: module parameters not found") - } - - return params -} diff --git a/x/community/keeper/params_test.go b/x/community/keeper/params_test.go deleted file mode 100644 index 7dff215e..00000000 --- a/x/community/keeper/params_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/community/keeper" - "github.com/kava-labs/kava/x/community/types" -) - -// Test suite used for all store tests -type StoreTestSuite struct { - suite.Suite - - App app.TestApp - Ctx sdk.Context - Keeper keeper.Keeper -} - -// The default state used by each test -func (suite *StoreTestSuite) SetupTest() { - app.SetSDKConfig() - suite.App = app.NewTestApp() - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - suite.Keeper = suite.App.GetCommunityKeeper() -} - -func TestStoreTestSuite(t *testing.T) { - suite.Run(t, new(StoreTestSuite)) -} - -func (suite *StoreTestSuite) TestGetSetParams() { - suite.Run("get params returns not found on empty store", func() { - _, found := suite.Keeper.GetParams(suite.Ctx) - suite.Require().False(found) - }) - - suite.Run("set params cannot store invalid params", func() { - invalid := types.Params{UpgradeTimeDisableInflation: time.Date(-1, 1, 1, 0, 0, 0, 0, time.UTC)} - suite.Panics(func() { - suite.Keeper.SetParams(suite.Ctx, invalid) - }) - }) - - suite.Run("get params returns stored params", func() { - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) - - storedParams, found := suite.Keeper.GetParams(suite.Ctx) - suite.True(found) - suite.Equal(types.DefaultParams(), storedParams) - }) - - suite.Run("set overwrite previous value", func() { - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) - - params := types.NewParams( - time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - sdkmath.LegacyNewDec(1000), - sdkmath.LegacyNewDec(1000), - ) - suite.Keeper.SetParams(suite.Ctx, params) - - storedParams, found := suite.Keeper.GetParams(suite.Ctx) - suite.True(found) - suite.NotEqual(params, types.DefaultParams()) - suite.Equal(params, storedParams) - }) -} diff --git a/x/community/keeper/proposal_handler.go b/x/community/keeper/proposal_handler.go deleted file mode 100644 index f6366b5a..00000000 --- a/x/community/keeper/proposal_handler.go +++ /dev/null @@ -1,41 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/community/types" -) - -// HandleCommunityPoolLendDepositProposal is a handler for executing a passed community pool lend deposit proposal. -func HandleCommunityPoolLendDepositProposal(ctx sdk.Context, k Keeper, p *types.CommunityPoolLendDepositProposal) error { - // move funds from community pool to x/community so hard position is held by this module. - err := k.distrKeeper.DistributeFromFeePool(ctx, p.Amount, k.moduleAddress) - if err != nil { - return err - } - // deposit funds into hard - return k.hardKeeper.Deposit(ctx, k.moduleAddress, p.Amount) -} - -// HandleCommunityPoolLendWithdrawProposal is a handler for executing a passed community pool lend withdraw proposal. -func HandleCommunityPoolLendWithdrawProposal(ctx sdk.Context, k Keeper, p *types.CommunityPoolLendWithdrawProposal) error { - // withdraw funds from x/hard to this module account - return k.hardKeeper.Withdraw(ctx, k.moduleAddress, p.Amount) -} - -// HandleCommunityCDPRepayDebtProposal is a handler for executing a passed community pool cdp repay debt proposal. -func HandleCommunityCDPRepayDebtProposal(ctx sdk.Context, k Keeper, p *types.CommunityCDPRepayDebtProposal) error { - // make debt repayment - return k.cdpKeeper.RepayPrincipal(ctx, k.moduleAddress, p.CollateralType, p.Payment) -} - -// HandleCommunityCDPWithdrawCollateralProposal is a handler for executing a -// passed community pool cdp withdraw collateral proposal. -func HandleCommunityCDPWithdrawCollateralProposal( - ctx sdk.Context, - k Keeper, - p *types.CommunityCDPWithdrawCollateralProposal, -) error { - // withdraw collateral - return k.cdpKeeper.WithdrawCollateral(ctx, k.moduleAddress, k.moduleAddress, p.Collateral, p.CollateralType) -} diff --git a/x/community/keeper/proposal_handler_test.go b/x/community/keeper/proposal_handler_test.go deleted file mode 100644 index 7f6a6f54..00000000 --- a/x/community/keeper/proposal_handler_test.go +++ /dev/null @@ -1,562 +0,0 @@ -package keeper_test - -import ( - "fmt" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - abcitypes "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - cdpkeeper "github.com/kava-labs/kava/x/cdp/keeper" - "github.com/kava-labs/kava/x/community/keeper" - "github.com/kava-labs/kava/x/community/testutil" - "github.com/kava-labs/kava/x/community/types" - hardkeeper "github.com/kava-labs/kava/x/hard/keeper" - hardtypes "github.com/kava-labs/kava/x/hard/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -const chainID = app.TestChainId - -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } -func ukava(amt int64) sdk.Coins { - return sdk.NewCoins(c("ukava", amt)) -} - -func usdx(amt int64) sdk.Coins { - return sdk.NewCoins(c("usdx", amt)) -} - -func otherdenom(amt int64) sdk.Coins { - return sdk.NewCoins(c("other-denom", amt)) -} - -type proposalTestSuite struct { - suite.Suite - - App app.TestApp - Ctx sdk.Context - Keeper keeper.Keeper - MaccAddress sdk.AccAddress - - cdpKeeper cdpkeeper.Keeper - hardKeeper hardkeeper.Keeper -} - -func TestProposalTestSuite(t *testing.T) { - suite.Run(t, new(proposalTestSuite)) -} - -func (suite *proposalTestSuite) SetupTest() { - app.SetSDKConfig() - - genTime := tmtime.Now() - - hardGS, pricefeedGS := testutil.NewLendGenesisBuilder(). - WithMarket("ukava", "kava:usd", sdk.OneDec()). - WithMarket("usdx", "usdx:usd", sdk.OneDec()). - Build() - - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{ - Height: 1, - Time: genTime, - ChainID: chainID, - }) - - // Set UpgradeTimeDisableInflation to far future to not influence module - // account balances - params := types.Params{ - UpgradeTimeDisableInflation: time.Now().Add(100000 * time.Hour), - StakingRewardsPerSecond: sdkmath.LegacyNewDec(0), - } - communityGs := types.NewGenesisState(params, types.DefaultStakingRewardsState()) - - tApp.InitializeFromGenesisStatesWithTimeAndChainID( - genTime, chainID, - app.GenesisState{hardtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&communityGs)}, - testutil.NewCDPGenState(tApp.AppCodec(), "ukava", "kava", sdk.NewDec(2)), - ) - - suite.App = tApp - suite.Ctx = ctx - suite.Keeper = tApp.GetCommunityKeeper() - suite.MaccAddress = tApp.GetAccountKeeper().GetModuleAddress(types.ModuleAccountName) - suite.cdpKeeper = suite.App.GetCDPKeeper() - suite.hardKeeper = suite.App.GetHardKeeper() - - // give the community pool some funds - // ukava - suite.FundCommunityPool(ukava(2e10)) - // usdx - suite.FundCommunityPool(usdx(2e10)) - // other-denom - suite.FundCommunityPool(otherdenom(1e10)) -} - -func (suite *proposalTestSuite) NextBlock() { - newTime := suite.Ctx.BlockTime().Add(6 * time.Second) - newHeight := suite.Ctx.BlockHeight() + 1 - - suite.App.EndBlocker(suite.Ctx, abcitypes.RequestEndBlock{}) - suite.Ctx = suite.Ctx.WithBlockTime(newTime).WithBlockHeight(newHeight).WithChainID(chainID) - suite.App.BeginBlocker(suite.Ctx, abcitypes.RequestBeginBlock{}) -} - -func (suite *proposalTestSuite) FundCommunityPool(coins sdk.Coins) { - // mint to ephemeral account - ephemeralAcc := app.RandomAddress() - suite.NoError(suite.App.FundAccount(suite.Ctx, ephemeralAcc, coins)) - // fund community pool with newly minted coins - suite.NoError(suite.App.GetDistrKeeper().FundCommunityPool(suite.Ctx, coins, ephemeralAcc)) -} - -func (suite *proposalTestSuite) GetCommunityPoolBalance() sdk.Coins { - ak := suite.App.GetAccountKeeper() - bk := suite.App.GetBankKeeper() - - addr := ak.GetModuleAddress(types.ModuleAccountName) - - // Return x/community module account balance, no longer using x/distribution community pool - return bk.GetAllBalances(suite.Ctx, addr) -} - -func (suite *proposalTestSuite) CheckCommunityPoolBalance(expected sdk.Coins) { - actual := suite.GetCommunityPoolBalance() - // check that balance is expected - suite.True(expected.IsEqual(actual), fmt.Sprintf("unexpected balance in community pool\nexpected: %s\nactual: %s", expected, actual)) -} - -func (suite *proposalTestSuite) TestCommunityLendDepositProposal() { - testCases := []struct { - name string - proposals []*types.CommunityPoolLendDepositProposal - expectedErr string - expectedDeposits []sdk.Coins - }{ - { - name: "valid - one proposal, one denom", - proposals: []*types.CommunityPoolLendDepositProposal{ - {Amount: ukava(1e8)}, - }, - expectedErr: "", - expectedDeposits: []sdk.Coins{ukava(1e8)}, - }, - { - name: "valid - one proposal, multiple denoms", - proposals: []*types.CommunityPoolLendDepositProposal{ - {Amount: ukava(1e8).Add(usdx(1e8)...)}, - }, - expectedErr: "", - expectedDeposits: []sdk.Coins{ukava(1e8).Add(usdx(1e8)...)}, - }, - { - name: "valid - multiple proposals, same denom", - proposals: []*types.CommunityPoolLendDepositProposal{ - {Amount: ukava(1e8)}, - {Amount: ukava(1e9)}, - }, - expectedErr: "", - expectedDeposits: []sdk.Coins{ukava(1e8 + 1e9)}, - }, - { - name: "valid - multiple proposals, different denoms", - proposals: []*types.CommunityPoolLendDepositProposal{ - {Amount: ukava(1e8)}, - {Amount: usdx(1e8)}, - }, - expectedErr: "", - expectedDeposits: []sdk.Coins{ukava(1e8).Add(usdx(1e8)...)}, - }, - { - name: "invalid - insufficient balance", - proposals: []*types.CommunityPoolLendDepositProposal{ - { - Description: "more coins than i have!", - Amount: ukava(1e11), - }, - }, - expectedErr: "community pool does not have sufficient coins to distribute", - expectedDeposits: []sdk.Coins{}, - }, - { - name: "invalid - invalid lend deposit (unsupported denom)", - proposals: []*types.CommunityPoolLendDepositProposal{ - {Amount: otherdenom(1e9)}, - }, - expectedErr: "invalid deposit denom", - expectedDeposits: []sdk.Coins{}, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - for _, proposal := range tc.proposals { - err := keeper.HandleCommunityPoolLendDepositProposal(suite.Ctx, suite.Keeper, proposal) - if tc.expectedErr == "" { - suite.NoError(err) - } else { - suite.ErrorContains(err, tc.expectedErr) - } - } - - deposits := suite.hardKeeper.GetDepositsByUser(suite.Ctx, suite.MaccAddress) - suite.Len(deposits, len(tc.expectedDeposits), "expected a deposit to lend") - for _, amt := range tc.expectedDeposits { - suite.Equal(amt, deposits[0].Amount, "expected amount to match") - } - }) - } -} - -func (suite *proposalTestSuite) TestCommunityLendWithdrawProposal() { - testCases := []struct { - name string - initialDeposit sdk.Coins - proposals []*types.CommunityPoolLendWithdrawProposal - expectedErr string - expectedWithdrawal sdk.Coins - }{ - { - // in the week it would take a proposal to pass, the position would have grown - // to withdraw the entire position, it'd be safest to set a very high withdraw - name: "valid - requesting withdrawal of more than total will withdraw all", - initialDeposit: ukava(1e9), - proposals: []*types.CommunityPoolLendWithdrawProposal{ - {Amount: ukava(1e12)}, - }, - expectedErr: "", - expectedWithdrawal: ukava(1e9), - }, - { - name: "valid - single proposal, single denom, full withdrawal", - initialDeposit: ukava(1e9), - proposals: []*types.CommunityPoolLendWithdrawProposal{ - {Amount: ukava(1e9)}, - }, - expectedErr: "", - expectedWithdrawal: ukava(1e9), - }, - { - name: "valid - single proposal, multiple denoms, full withdrawal", - initialDeposit: ukava(1e9).Add(usdx(1e9)...), - proposals: []*types.CommunityPoolLendWithdrawProposal{ - {Amount: ukava(1e9).Add(usdx(1e9)...)}, - }, - expectedErr: "", - expectedWithdrawal: ukava(1e9).Add(usdx(1e9)...), - }, - { - name: "valid - single proposal, partial withdrawal", - initialDeposit: ukava(1e9).Add(usdx(1e9)...), - proposals: []*types.CommunityPoolLendWithdrawProposal{ - {Amount: ukava(1e8).Add(usdx(1e9)...)}, - }, - expectedErr: "", - expectedWithdrawal: ukava(1e8).Add(usdx(1e9)...), - }, - { - name: "valid - multiple proposals, full withdrawal", - initialDeposit: ukava(1e9).Add(usdx(1e9)...), - proposals: []*types.CommunityPoolLendWithdrawProposal{ - {Amount: ukava(1e9)}, - {Amount: usdx(1e9)}, - }, - expectedErr: "", - expectedWithdrawal: ukava(1e9).Add(usdx(1e9)...), - }, - { - name: "valid - multiple proposals, partial withdrawal", - initialDeposit: ukava(1e9).Add(usdx(1e9)...), - proposals: []*types.CommunityPoolLendWithdrawProposal{ - {Amount: ukava(1e8)}, - {Amount: usdx(1e8)}, - }, - expectedErr: "", - expectedWithdrawal: ukava(1e8).Add(usdx(1e8)...), - }, - { - name: "invalid - nonexistent position, has no deposits", - initialDeposit: sdk.NewCoins(), - proposals: []*types.CommunityPoolLendWithdrawProposal{ - {Amount: ukava(1e8)}, - }, - expectedErr: "deposit not found", - expectedWithdrawal: sdk.NewCoins(), - }, - { - name: "invalid - nonexistent position, has deposits of different denom", - initialDeposit: ukava(1e8), - proposals: []*types.CommunityPoolLendWithdrawProposal{ - {Amount: usdx(1e8)}, - }, - expectedErr: "no coins of this type deposited", - expectedWithdrawal: sdk.NewCoins(), - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - // Disable minting, so that the community pool balance doesn't change - // during the test - this is because staking denom is "ukava" and no - // longer "stake" which has an initial and changing balance instead - // of just 0 - suite.App.SetInflation(suite.Ctx, sdk.ZeroDec()) - - // setup initial deposit - if !tc.initialDeposit.IsZero() { - deposit := types.NewCommunityPoolLendDepositProposal("initial deposit", "has coins", tc.initialDeposit) - err := keeper.HandleCommunityPoolLendDepositProposal(suite.Ctx, suite.Keeper, deposit) - suite.NoError(err, "unexpected error while seeding lend deposit") - } - - beforeBalance := suite.GetCommunityPoolBalance() - - // run the proposals - for i, proposal := range tc.proposals { - fmt.Println("submitting proposal ", i, " ", suite.Ctx.ChainID()) - err := keeper.HandleCommunityPoolLendWithdrawProposal(suite.Ctx, suite.Keeper, proposal) - if tc.expectedErr == "" { - suite.NoError(err) - } else { - suite.ErrorContains(err, tc.expectedErr) - } - - suite.NextBlock() - } - - // expect funds to be removed from hard deposit - expectedRemaining := tc.initialDeposit.Sub(tc.expectedWithdrawal...) - deposits := suite.hardKeeper.GetDepositsByUser(suite.Ctx, suite.MaccAddress) - if expectedRemaining.IsZero() { - suite.Len(deposits, 0, "expected all deposits to be withdrawn") - } else { - suite.Len(deposits, 1, "expected user to have remaining deposit") - suite.Equal(expectedRemaining, deposits[0].Amount) - } - - // expect funds to be distributed back to community pool - suite.CheckCommunityPoolBalance(beforeBalance.Add(tc.expectedWithdrawal...)) - }) - } -} - -// expectation: funds in the community module will be used to repay cdps. -// if collateral is returned, it stays in the community module. -func (suite *proposalTestSuite) TestCommunityCDPRepayDebtProposal() { - initialModuleFunds := ukava(2e10).Add(otherdenom(1e9)...) - collateralType := "kava-a" - type debt struct { - collateral sdk.Coin - principal sdk.Coin - } - testcases := []struct { - name string - initialDebt *debt - proposal *types.CommunityCDPRepayDebtProposal - expectedErr string - expectedRepaid sdk.Coin - }{ - { - name: "valid - paid in full", - initialDebt: &debt{c("ukava", 1e10), c("usdx", 1e9)}, - proposal: types.NewCommunityCDPRepayDebtProposal( - "repaying my debts in full", - "title says it all", - collateralType, - c("usdx", 1e9), - ), - expectedErr: "", - expectedRepaid: c("usdx", 1e9), - }, - { - name: "valid - partial payment", - initialDebt: &debt{c("ukava", 1e10), c("usdx", 1e9)}, - proposal: types.NewCommunityCDPRepayDebtProposal( - "title goes here", - "description goes here", - collateralType, - c("usdx", 1e8), - ), - expectedErr: "", - expectedRepaid: c("usdx", 1e8), - }, - { - name: "invalid - insufficient funds", - initialDebt: &debt{c("ukava", 1e10), c("usdx", 1e9)}, - proposal: types.NewCommunityCDPRepayDebtProposal( - "title goes here", - "description goes here", - collateralType, - c("usdx", 1e10), // <-- more usdx than we have - ), - expectedErr: "insufficient balance", - expectedRepaid: c("usdx", 0), - }, - } - - for _, tc := range testcases { - suite.Run(tc.name, func() { - var err error - suite.SetupTest() - - // setup the community module with some initial funds - err = suite.App.FundModuleAccount(suite.Ctx, types.ModuleAccountName, initialModuleFunds) - suite.NoError(err, "failed to initially fund module account for cdp creation") - - // setup initial debt position - err = suite.cdpKeeper.AddCdp(suite.Ctx, suite.MaccAddress, tc.initialDebt.collateral, tc.initialDebt.principal, collateralType) - suite.NoError(err, "unexpected error while creating initial cdp") - - balanceBefore := suite.Keeper.GetModuleAccountBalance(suite.Ctx) - - // submit proposal - err = keeper.HandleCommunityCDPRepayDebtProposal(suite.Ctx, suite.Keeper, tc.proposal) - if tc.expectedErr == "" { - suite.NoError(err) - } else { - suite.ErrorContains(err, tc.expectedErr) - } - suite.NextBlock() - - cdps := suite.cdpKeeper.GetAllCdpsByCollateralType(suite.Ctx, collateralType) - expectedRemainingPrincipal := tc.initialDebt.principal.Sub(tc.expectedRepaid) - fullyRepaid := expectedRemainingPrincipal.IsZero() - - // expect repayment funds to be deducted from community module account - expectedModuleBalance := balanceBefore.Sub(tc.expectedRepaid) - // when fully repaid, the position is closed and collateral is returned. - if fullyRepaid { - suite.Len(cdps, 0, "expected position to have been closed on payment") - // expect balance to include recouped collateral - expectedModuleBalance = expectedModuleBalance.Add(tc.initialDebt.collateral) - } else { - suite.Len(cdps, 1, "expected debt position to remain open") - suite.Equal(suite.MaccAddress, cdps[0].Owner, "sanity check: unexpected owner") - // check the remaining principle on the cdp - suite.Equal(expectedRemainingPrincipal, cdps[0].Principal) - } - - // verify the balance changed as expected - moduleBalanceAfter := suite.Keeper.GetModuleAccountBalance(suite.Ctx) - suite.True(expectedModuleBalance.IsEqual(moduleBalanceAfter), "module balance changed unexpectedly") - }) - } -} - -// expectation: funds in the community module used as cdp collateral will be -// withdrawn and stays in the community module. -func (suite *proposalTestSuite) TestCommunityCDPWithdrawCollateralProposal() { - initialModuleFunds := ukava(2e10).Add(otherdenom(1e9)...) - collateralType := "kava-a" - type debt struct { - collateral sdk.Coin - principal sdk.Coin - } - testcases := []struct { - name string - initialDebt *debt - proposal *types.CommunityCDPWithdrawCollateralProposal - expectedErr string - expectedWithdrawn sdk.Coin - }{ - { - name: "valid - withdrawing max collateral", - initialDebt: &debt{ - c("ukava", 1e10), - c("usdx", 1e9), - }, - proposal: types.NewCommunityCDPWithdrawCollateralProposal( - "withdrawing max collateral", - "i might get liquidated", - collateralType, - c("ukava", 8e9-1), // Withdraw all collateral except 2*principal-1 amount - ), - expectedErr: "", - expectedWithdrawn: c("ukava", 8e9-1), - }, - { - name: "valid - withdrawing partial collateral", - initialDebt: &debt{ - c("ukava", 1e10), - c("usdx", 1e9), - }, - proposal: types.NewCommunityCDPWithdrawCollateralProposal( - "title goes here", - "description goes here", - collateralType, - c("ukava", 1e9), - ), - expectedErr: "", - expectedWithdrawn: c("ukava", 1e9), - }, - { - name: "invalid - withdrawing too much collateral", - initialDebt: &debt{ - c("ukava", 1e10), - c("usdx", 1e9), - }, - proposal: types.NewCommunityCDPWithdrawCollateralProposal( - "title goes here", - "description goes here", - collateralType, - c("ukava", 9e9), // <-- would be under collateralized - ), - expectedErr: "proposed collateral ratio is below liquidation ratio", - expectedWithdrawn: c("ukava", 0), - }, - } - - for _, tc := range testcases { - suite.Run(tc.name, func() { - var err error - suite.SetupTest() - - // setup the community module with some initial funds - err = suite.App.FundModuleAccount(suite.Ctx, types.ModuleAccountName, initialModuleFunds) - suite.NoError(err, "failed to initially fund module account for cdp creation") - - // setup initial debt position - err = suite.cdpKeeper.AddCdp(suite.Ctx, suite.MaccAddress, tc.initialDebt.collateral, tc.initialDebt.principal, collateralType) - suite.NoError(err, "unexpected error while creating initial cdp") - - balanceBefore := suite.Keeper.GetModuleAccountBalance(suite.Ctx) - - // submit proposal - err = keeper.HandleCommunityCDPWithdrawCollateralProposal(suite.Ctx, suite.Keeper, tc.proposal) - if tc.expectedErr == "" { - suite.NoError(err) - } else { - suite.Require().ErrorContains(err, tc.expectedErr) - } - suite.NextBlock() - - cdps := suite.cdpKeeper.GetAllCdpsByCollateralType(suite.Ctx, collateralType) - expectedRemainingCollateral := tc.initialDebt.collateral.Sub(tc.expectedWithdrawn) - - // expect withdrawn funds to add to community module account - expectedModuleBalance := balanceBefore.Add(tc.expectedWithdrawn) - - suite.Len(cdps, 1, "expected debt position to remain open") - suite.Equal(suite.MaccAddress, cdps[0].Owner, "sanity check: unexpected owner") - // check the remaining principle on the cdp - suite.Equal(expectedRemainingCollateral, cdps[0].Collateral) - - // verify the balance changed as expected - moduleBalanceAfter := suite.Keeper.GetModuleAccountBalance(suite.Ctx) - suite.True(expectedModuleBalance.IsEqual(moduleBalanceAfter), "module balance changed unexpectedly") - }) - } -} diff --git a/x/community/keeper/rewards.go b/x/community/keeper/rewards.go deleted file mode 100644 index 1f9198a3..00000000 --- a/x/community/keeper/rewards.go +++ /dev/null @@ -1,27 +0,0 @@ -package keeper - -import ( - sdkmath "cosmossdk.io/math" -) - -const SecondsPerYear = 365 * 24 * 3600 - -// CalculateStakingAnnualPercentage returns the annualized staking reward rate. -// It assumes that staking comes from one of two sources depending on if inflation is enabled or not. -func CalculateStakingAnnualPercentage(totalSupply, totalBonded sdkmath.Int, inflationRate, communityTax, rewardsPerSecond sdkmath.LegacyDec) sdkmath.LegacyDec { - // no rewards are given if no tokens are bonded, in addition avoid division by zero - if totalBonded.IsZero() { - return sdkmath.LegacyZeroDec() - } - - // the percent of inflationRate * totalSupply tokens that are distributed to stakers - percentInflationDistributedToStakers := sdkmath.LegacyOneDec().Sub(communityTax) - - // the total amount of tokens distributed to stakers in a year - amountGivenPerYear := inflationRate. - MulInt(totalSupply).Mul(percentInflationDistributedToStakers). // portion provided by inflation via mint & distribution modules - Add(rewardsPerSecond.Mul(sdkmath.LegacyNewDec(SecondsPerYear))) // portion provided by community module - - // divide by total bonded tokens to get the percent return - return amountGivenPerYear.QuoInt(totalBonded) -} diff --git a/x/community/keeper/rewards_test.go b/x/community/keeper/rewards_test.go deleted file mode 100644 index 8aed1f76..00000000 --- a/x/community/keeper/rewards_test.go +++ /dev/null @@ -1,189 +0,0 @@ -package keeper_test - -import ( - "math/big" - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/community/keeper" -) - -func TestStakingRewardsCalculator(t *testing.T) { - hugeInflation := new(big.Int).Exp(big.NewInt(2), big.NewInt(205), nil) - hugeRewardsPerSec := new(big.Int).Exp(big.NewInt(2), big.NewInt(230), nil) - - testCases := []struct { - name string - totalSupply sdkmath.Int - totalBonded sdkmath.Int - inflation sdkmath.LegacyDec - communityTax sdkmath.LegacyDec - perSecReward sdkmath.LegacyDec - expectedRate sdkmath.LegacyDec - }{ - { - name: "no inflation, no rewards per sec -> 0%", - totalSupply: sdkmath.ZeroInt(), - totalBonded: sdkmath.ZeroInt(), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyZeroDec(), - }, - // - // - // inflation-only - // - // - { - name: "inflation only: no bonded tokens -> 0%", - totalSupply: sdk.NewInt(42), - totalBonded: sdkmath.ZeroInt(), - inflation: sdkmath.LegacyOneDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyZeroDec(), - }, - { - name: "inflation only: 0% inflation -> 0%", - totalSupply: sdk.NewInt(123), - totalBonded: sdkmath.NewInt(45), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyZeroDec(), - }, - { - name: "inflation only: 100% bonded w/ 100% inflation -> 100%", - totalSupply: sdk.NewInt(42), - totalBonded: sdk.NewInt(42), - inflation: sdkmath.LegacyOneDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyOneDec(), - }, - { - name: "inflation only: 100% community tax -> 0%", - totalSupply: sdk.NewInt(123), - totalBonded: sdkmath.NewInt(45), - inflation: sdkmath.LegacyMustNewDecFromStr("0.853"), - communityTax: sdkmath.LegacyOneDec(), - perSecReward: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyZeroDec(), - }, - { - name: "inflation only: Oct 2023 case", - totalSupply: sdk.NewInt(857570000e6), - totalBonded: sdk.NewInt(127680000e6), - inflation: sdkmath.LegacyMustNewDecFromStr("0.595"), - communityTax: sdkmath.LegacyMustNewDecFromStr("0.9495"), - perSecReward: sdkmath.LegacyZeroDec(), - // expect 20.18% staking reward - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.201815746984649122"), // verified manually - }, - { - name: "inflation only: low inflation", - totalSupply: sdk.NewInt(857570000e6), - totalBonded: sdk.NewInt(127680000e6), - inflation: sdkmath.LegacyMustNewDecFromStr("0.0000000001"), - communityTax: sdkmath.LegacyMustNewDecFromStr("0.9495"), - perSecReward: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.000000000033918612"), // verified manually, rounded would be 0.000000000033918613 - }, - { - name: "inflation only: absurdly high inflation", - totalSupply: sdk.NewInt(857570000e6), - totalBonded: sdk.NewInt(127680000e6), - inflation: sdkmath.LegacyNewDecFromBigInt(hugeInflation), // 2^205. a higher exponent than this overflows. - communityTax: sdkmath.LegacyMustNewDecFromStr("0.9495"), - perSecReward: sdkmath.LegacyZeroDec(), - // https://www.wolframalpha.com/input?i=%282%5E205%29+*+%281+-+0.9495%29+*+%28857570000e6+%2F127680000e6%29 - expectedRate: sdkmath.LegacyMustNewDecFromStr("17441635052648297161685283657196753398188161373334495592570113.113824561403508771"), // verified manually, would round up - }, - // - // - // rewards-only - // - // - { - name: "rps only: no bonded tokens -> 0%", - totalSupply: sdk.NewInt(42), - totalBonded: sdkmath.ZeroInt(), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyMustNewDecFromStr("1234567.123456"), - expectedRate: sdkmath.LegacyZeroDec(), - }, - { - name: "rps only: rps = total bonded / seconds in year -> basically 100%", - totalSupply: sdk.NewInt(12345), - totalBonded: sdkmath.NewInt(1234), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyNewDec(1234).Quo(sdkmath.LegacyNewDec(keeper.SecondsPerYear)), - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.999999999999987228"), // <-- for 6-decimal token, this is negligible rounding - }, - { - name: "rps only: 10M kava / year rewards", - totalSupply: sdk.NewInt(870950000e6), - totalBonded: sdkmath.NewInt(130380000e6), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyMustNewDecFromStr("317097.919837645865043125"), // 10 million kava per year - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.076698880196349133"), // verified manually - }, - { - name: "rps only: 25M kava / year rewards", - totalSupply: sdk.NewInt(870950000e6), - totalBonded: sdkmath.NewInt(130380000e6), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyMustNewDecFromStr("792744.799594114662607813"), // 25 million kava per year - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.191747200490872833"), // verified manually - }, - { - name: "rps only: too much kava / year rewards", - totalSupply: sdk.NewInt(870950000e6), - totalBonded: sdkmath.NewInt(130380000e6), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyNewDecFromBigInt(hugeRewardsPerSec), // 2^230. a higher exponent than this overflows. - // https://www.wolframalpha.com/input?i=%28%28365+*+24+*+3600%29+%2F+130380000e6%29+*+%282%5E230%29 - expectedRate: sdkmath.LegacyMustNewDecFromStr("417344440850566075319340506352140425426634017001007267992800590.431305795858260469"), // verified manually - }, - { - name: "rps only: low kava / year rewards", - totalSupply: sdk.NewInt(870950000e6), - totalBonded: sdkmath.NewInt(130380000e6), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyMustNewDecFromStr("0.1"), - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.000000024187758858"), // verified manually, rounded would be 0.000000024187758859 - }, - { - name: "rps only: 1 ukava / year rewards", - totalSupply: sdk.NewInt(870950000e6), - totalBonded: sdkmath.NewInt(130380000e6), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyMustNewDecFromStr("0.000000031709791984"), // 1 ukava per year - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.000000000000007669"), // verified manually, rounded would be 0.000000000000007670 - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - rewardRate := keeper.CalculateStakingAnnualPercentage( - tc.totalSupply, - tc.totalBonded, - tc.inflation, - tc.communityTax, - tc.perSecReward) - require.Equal(t, tc.expectedRate, rewardRate) - }) - } -} diff --git a/x/community/keeper/staking.go b/x/community/keeper/staking.go deleted file mode 100644 index 52101a11..00000000 --- a/x/community/keeper/staking.go +++ /dev/null @@ -1,98 +0,0 @@ -package keeper - -import ( - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/kava-labs/kava/x/community/types" -) - -const nanosecondsInOneSecond = int64(1000000000) - -// PayoutAccumulatedStakingRewards calculates and transfers taking rewards to the fee collector address -func (k Keeper) PayoutAccumulatedStakingRewards(ctx sdk.Context) { - // get module parameters which define the amount of rewards to payout per second - params := k.mustGetParams(ctx) - currentBlockTime := ctx.BlockTime() - state := k.GetStakingRewardsState(ctx) - - // we have un-initialized state -- set accumulation time and exit since there is nothing to do - if state.LastAccumulationTime.IsZero() { - state.LastAccumulationTime = currentBlockTime - - k.SetStakingRewardsState(ctx, state) - - return - } - - // get the denom for staking - stakingRewardDenom := k.stakingKeeper.BondDenom(ctx) - - // we fetch the community pool balance to ensure only accumulate rewards up to the current balance - communityPoolBalance := sdkmath.LegacyNewDecFromInt(k.bankKeeper.GetBalance(ctx, k.moduleAddress, stakingRewardDenom).Amount) - - // calculate staking reward payout capped to community pool balance - truncatedRewards, truncationError := calculateStakingRewards( - currentBlockTime, - state.LastAccumulationTime, - state.LastTruncationError, - params.StakingRewardsPerSecond, - communityPoolBalance, - ) - - // only payout if the truncated rewards are non-zero - if !truncatedRewards.IsZero() { - transferAmount := sdk.NewCoins(sdk.NewCoin(stakingRewardDenom, truncatedRewards)) - - if err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleAccountName, authtypes.FeeCollectorName, transferAmount); err != nil { - // we check for a valid balance and rewards can never be negative so panic since this will only - // occur in cases where the chain is running in an invalid state - panic(err) - } - - // emit event with amount transferred - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeStakingRewardsPaid, - sdk.NewAttribute(types.AttributeKeyStakingRewardAmount, transferAmount.String()), - ), - ) - - } - - // update accumulation state - state.LastAccumulationTime = currentBlockTime - // if the community pool balance is zero, this also resets the truncation error - state.LastTruncationError = truncationError - - // save state - k.SetStakingRewardsState(ctx, state) -} - -// calculateStakingRewards takes the currentBlockTime, state of last accumulation, rewards per second, and the community pool balance -// in order to calculate the total payout since the last accumulation time. It returns the truncated payout amount and the truncation error. -func calculateStakingRewards(currentBlockTime, lastAccumulationTime time.Time, lastTruncationError, stakingRewardsPerSecond, communityPoolBalance sdkmath.LegacyDec) (sdkmath.Int, sdkmath.LegacyDec) { - // we get the duration since we last accumulated, then use nanoseconds for full precision available - durationSinceLastPayout := currentBlockTime.Sub(lastAccumulationTime) - nanosecondsSinceLastPayout := sdkmath.LegacyNewDec(durationSinceLastPayout.Nanoseconds()) - - // We multiply by nanoseconds first, then divide by conversion to avoid loss of precision. - // This multiplication is also tested against very large values so we are safe from overflow - // in normal operations. - accumulatedRewards := nanosecondsSinceLastPayout.Mul(stakingRewardsPerSecond).QuoInt64(nanosecondsInOneSecond) - // Ensure we add any error from previous truncations - accumulatedRewards = accumulatedRewards.Add(lastTruncationError) - - if communityPoolBalance.LT(accumulatedRewards) { - accumulatedRewards = communityPoolBalance - } - - // we truncate since we can only transfer whole units - truncatedRewards := accumulatedRewards.TruncateDec() - // the truncation error to carry over to the next accumulation - truncationError := accumulatedRewards.Sub(truncatedRewards) - - return truncatedRewards.TruncateInt(), truncationError -} diff --git a/x/community/keeper/staking_test.go b/x/community/keeper/staking_test.go deleted file mode 100644 index 5b02f044..00000000 --- a/x/community/keeper/staking_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/community/keeper" - "github.com/kava-labs/kava/x/community/testutil" -) - -func TestKeeperPayoutAccumulatedStakingRewards(t *testing.T) { - testFunc := func(ctx sdk.Context, k keeper.Keeper) { - k.PayoutAccumulatedStakingRewards(ctx) - } - suite.Run(t, testutil.NewStakingRewardsTestSuite(testFunc)) -} diff --git a/x/community/migrations/v2/store.go b/x/community/migrations/v2/store.go deleted file mode 100644 index 34907dfd..00000000 --- a/x/community/migrations/v2/store.go +++ /dev/null @@ -1,35 +0,0 @@ -package v2 - -import ( - "time" - - storetypes "github.com/cosmos/cosmos-sdk/store/types" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/community/types" -) - -// Migrate migrates the x/community module state from the consensus version 1 to -// version 2. Specifically, sets new parameters in the module state. -func Migrate( - ctx sdk.Context, - store storetypes.KVStore, - cdc codec.BinaryCodec, -) error { - params := types.NewParams( - time.Time{}, - sdkmath.LegacyNewDec(0), - sdkmath.LegacyNewDec(0), - ) - - if err := params.Validate(); err != nil { - return err - } - - bz := cdc.MustMarshal(¶ms) - store.Set(types.ParamsKey, bz) - - return nil -} diff --git a/x/community/migrations/v2/store_test.go b/x/community/migrations/v2/store_test.go deleted file mode 100644 index 6c8deb2c..00000000 --- a/x/community/migrations/v2/store_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package v2_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/app" - v2 "github.com/kava-labs/kava/x/community/migrations/v2" - "github.com/kava-labs/kava/x/community/types" -) - -func TestMigrateStore(t *testing.T) { - tApp := app.NewTestApp() - cdc := tApp.AppCodec() - storeKey := sdk.NewKVStoreKey("community") - ctx := testutil.DefaultContext(storeKey, sdk.NewTransientStoreKey("transient_test")) - store := ctx.KVStore(storeKey) - - require.Nil( - t, - store.Get(types.ParamsKey), - "params shouldn't exist in store before migration", - ) - - require.NoError(t, v2.Migrate(ctx, store, cdc)) - - paramsBytes := store.Get(types.ParamsKey) - require.NotNil(t, paramsBytes, "params should be in store after migration") - - var params types.Params - cdc.MustUnmarshal(paramsBytes, ¶ms) - - t.Logf("params: %+v", params) - - require.Equal( - t, - types.NewParams( - time.Time{}, - sdkmath.LegacyNewDec(0), - sdkmath.LegacyNewDec(0), - ), - params, - "params should be correct after migration", - ) -} diff --git a/x/community/module.go b/x/community/module.go deleted file mode 100644 index 83eaef6e..00000000 --- a/x/community/module.go +++ /dev/null @@ -1,148 +0,0 @@ -package community - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/kava-labs/kava/x/community/client/cli" - "github.com/kava-labs/kava/x/community/keeper" - "github.com/kava-labs/kava/x/community/types" -) - -// ConsensusVersion defines the current module consensus version. -const ConsensusVersion = 2 - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name returns the module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -// Deprecated: unused but necessary to fulfill AppModuleBasic interface -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - gs := types.DefaultGenesisState() - return cdc.MustMarshalJSON(&gs) -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) - if err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// GetTxCmd returns the root tx command for the module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, ak types.AccountKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: ak, - } -} - -// Name module name -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// RegisterInvariants register module invariants -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) - - m := keeper.NewMigrator(am.keeper) - if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil { - panic(fmt.Sprintf("failed to migrate x/community from version 1 to 2: %v", err)) - } -} - -// InitGenesis module init-genesis -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { - var genState types.GenesisState - cdc.MustUnmarshalJSON(gs, &genState) - - InitGenesis(ctx, am.keeper, am.accountKeeper, genState) - return []abci.ValidatorUpdate{} -} - -// ExportGenesis module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(&gs) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { - BeginBlocker(ctx, am.keeper) -} - -// EndBlock module end-block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/community/module_test.go b/x/community/module_test.go deleted file mode 100644 index 4e74874a..00000000 --- a/x/community/module_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package community_test - -import ( - "testing" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/require" - - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/community/types" -) - -func TestItCreatesModuleAccountOnInitBlock(t *testing.T) { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - tApp.InitializeFromGenesisStates() - - accKeeper := tApp.GetAccountKeeper() - acc := accKeeper.GetAccount(ctx, authtypes.NewModuleAddress(types.ModuleName)) - require.NotNil(t, acc) -} diff --git a/x/community/spec/01_concepts.md b/x/community/spec/01_concepts.md deleted file mode 100644 index 8a520410..00000000 --- a/x/community/spec/01_concepts.md +++ /dev/null @@ -1,37 +0,0 @@ - - -# Concepts - -## Community Pool - -The x/community module contains the community pool funds and provides proposal -handlers to manage community pool funds. - -### Funding - -The x/community module account can be funded by any account sending a -community/FundCommunityPool message. These funds may be deposited/withdrawn to -lend via the CommunityPoolLendDepositProposal & -CommunityPoolLendWithdrawProposal. - -### Rewards - -Rewards payout behavior for staking depends on the module parameters, and will -change based on the "switchover" time parameter `upgrade_time_disable_inflation`. - -If the current block is *before* the switchover time and the -`staking_rewards_per_second` parameter is set to 0, no staking rewards will be -paid from the `x/community` module and will continue to come from other modules -such as `x/mint` and `x/distribution`. - -On the first block after the switchover time, the `staking_rewards_per_second` -parameter is updated to reflect the parameter -`upgrade_time_set_staking_rewards_per_second`, and staking rewards are paid out -every block from the community pool, instead of from minted coins from `x/mint` -and `x/kavadist`. The payout is calculated with the `staking_rewards_per_second` -parameter. - -In addition to these payout changes, inflation in `x/mint` and `x/kavadist` is -disabled after the switchover time. diff --git a/x/community/spec/02_state.md b/x/community/spec/02_state.md deleted file mode 100644 index b2dbcb2a..00000000 --- a/x/community/spec/02_state.md +++ /dev/null @@ -1,75 +0,0 @@ - - -# State - -## Parameters and Genesis State - -`Params` define the module parameters, containing the information required to -set the current staking rewards per second at a future date. When the -`upgrade_time_disable_inflation` time is reached, `staking_rewards_per_second` -will be set to `upgrade_time_set_staking_rewards_per_second`. - -```protobuf -// Params defines the parameters of the community module. -message Params { - option (gogoproto.equal) = true; - - // upgrade_time_disable_inflation is the time at which to disable mint and kavadist module inflation. - // If set to 0, inflation will be disabled from block 1. - google.protobuf.Timestamp upgrade_time_disable_inflation = 1 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - - // staking_rewards_per_second is the amount paid out to delegators each block from the community account - string staking_rewards_per_second = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", - (gogoproto.nullable) = false - ]; - - // upgrade_time_set_staking_rewards_per_second is the initial staking_rewards_per_second to set - // and use when the disable inflation time is reached - string upgrade_time_set_staking_rewards_per_second = 3 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", - (gogoproto.nullable) = false - ]; -} -``` - -`GenesisState` defines the state that must be persisted when the blockchain -stops/restarts in order for normal function of the module to resume. It contains -the parameters and staking rewards state to keep track of payout between blocks. - -```protobuf -// GenesisState defines the community module's genesis state. -message GenesisState { - // params defines all the parameters related to commmunity - Params params = 1 [(gogoproto.nullable) = false]; - - // StakingRewardsState stores the internal staking reward data required to - // track staking rewards across blocks - StakingRewardsState staking_rewards_state = 2 [(gogoproto.nullable) = false]; -} - -// StakingRewardsState represents the state of staking reward accumulation between blocks. -message StakingRewardsState { - // last_accumulation_time represents the last block time which rewards where calculated and distributed. - // This may be zero to signal accumulation should start on the next interval. - google.protobuf.Timestamp last_accumulation_time = 1 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - - // accumulated_truncation_error represents the sum of previous errors due to truncation on payout - // This value will always be on the interval [0, 1). - string last_truncation_error = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", - (gogoproto.nullable) = false - ]; -} -``` diff --git a/x/community/spec/03_messages.md b/x/community/spec/03_messages.md deleted file mode 100644 index 90ecc05b..00000000 --- a/x/community/spec/03_messages.md +++ /dev/null @@ -1,22 +0,0 @@ - - -# Messages - -## FundCommunityPool - -Send coins directly from the sender to the community module account. - -The transaction fails if the amount cannot be transferred from the sender to the community module account. - -https://github.com/Kava-Labs/kava/blob/1d36429fe34cc5829d636d73b7c34751a925791b/proto/kava/community/v1beta1/tx.proto#L21-L30 - -## UpdateParams - -Update module parameters via gov proposal. - -The transaction fails if the message is not submitted through a gov proposal. -The message `authority` must be the x/gov module account address. - -https://github.com/Kava-Labs/kava/blob/1d36429fe34cc5829d636d73b7c34751a925791b/proto/kava/community/v1beta1/tx.proto#L35-L44 diff --git a/x/community/spec/04_events.md b/x/community/spec/04_events.md deleted file mode 100644 index 367693fd..00000000 --- a/x/community/spec/04_events.md +++ /dev/null @@ -1,53 +0,0 @@ - - -# Events - -The community module emits the following events: - -## Handlers - -### MsgFundCommunityPool - -| Type | Attribute Key | Attribute Value | -| ------- | ------------- | ------------------- | -| message | module | community | -| message | action | fund_community_pool | -| message | sender | {senderAddress} | -| message | amount | {amountCoins} | - -## Keeper events - -In addition to handlers events, the bank keeper will produce events when the -following methods are called (or any method which ends up calling them) - -### CheckAndDisableMintAndKavaDistInflation - -```json -{ - "type": "inflation_stop", - "attributes": [ - { - "key": "inflation_disable_time", - "value": "{{RFC3339 formatted time inflation was disabled}}", - "index": true - } - ] -} -``` - -### PayoutAccumulatedStakingRewards - -```json -{ - "type": "staking_rewards_paid", - "attributes": [ - { - "key": "staking_reward_amount", - "value": "{{sdk.Coins being paid to validators}}", - "index": true - } - ] -} -``` diff --git a/x/community/spec/05_params.md b/x/community/spec/05_params.md deleted file mode 100644 index e046e236..00000000 --- a/x/community/spec/05_params.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# Parameters - -The community module contains the following parameters: - -| Key | Type | Example | -| ------------------------------------------- | ------------- | ---------------------- | -| upgrade_time_disable_inflation | string (time) | "2023-11-01T00:00:00Z" | -| staking_rewards_per_second | string | "744191" | -| upgrade_time_set_staking_rewards_per_second | string | "0" | diff --git a/x/community/spec/README.md b/x/community/spec/README.md deleted file mode 100644 index 16b3a581..00000000 --- a/x/community/spec/README.md +++ /dev/null @@ -1,19 +0,0 @@ - - -# `community` - - - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** - -## Abstract - -`x/community` is an implementation of a Cosmos SDK Module that provides governance for the community pool of funds controlled by Kava DAO. diff --git a/x/community/staking_rewards_abci_test.go b/x/community/staking_rewards_abci_test.go deleted file mode 100644 index d943170e..00000000 --- a/x/community/staking_rewards_abci_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package community_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/community" - "github.com/kava-labs/kava/x/community/keeper" - "github.com/kava-labs/kava/x/community/testutil" - "github.com/stretchr/testify/suite" -) - -func TestABCIPayoutAccumulatedStakingRewards(t *testing.T) { - testFunc := func(ctx sdk.Context, k keeper.Keeper) { - community.BeginBlocker(ctx, k) - } - suite.Run(t, testutil.NewStakingRewardsTestSuite(testFunc)) -} diff --git a/x/community/testutil/cdp_genesis.go b/x/community/testutil/cdp_genesis.go deleted file mode 100644 index 3b4ef80d..00000000 --- a/x/community/testutil/cdp_genesis.go +++ /dev/null @@ -1,57 +0,0 @@ -package testutil - -import ( - "time" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - cdptypes "github.com/kava-labs/kava/x/cdp/types" -) - -func NewCDPGenState(cdc codec.JSONCodec, denom, asset string, liquidationRatio sdk.Dec) app.GenesisState { - cdpGenesis := cdptypes.GenesisState{ - Params: cdptypes.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - SurplusAuctionThreshold: cdptypes.DefaultSurplusThreshold, - SurplusAuctionLot: cdptypes.DefaultSurplusLot, - DebtAuctionThreshold: cdptypes.DefaultDebtThreshold, - DebtAuctionLot: cdptypes.DefaultDebtLot, - LiquidationBlockInterval: cdptypes.DefaultBeginBlockerExecutionBlockInterval, - CollateralParams: cdptypes.CollateralParams{ - { - Denom: denom, - Type: asset + "-a", - LiquidationRatio: liquidationRatio, - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdk.NewInt(100), - SpotMarketID: asset + ":usd", - LiquidationMarketID: asset + ":usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - CheckCollateralizationIndexCount: sdk.NewInt(10), - ConversionFactor: sdk.NewInt(6), - }, - }, - DebtParam: cdptypes.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdk.NewInt(6), - DebtFloor: sdk.NewInt(10000000), - }, - }, - StartingCdpID: cdptypes.DefaultCdpStartingID, - DebtDenom: cdptypes.DefaultDebtDenom, - GovDenom: cdptypes.DefaultGovDenom, - CDPs: cdptypes.CDPs{}, - PreviousAccumulationTimes: cdptypes.GenesisAccumulationTimes{ - cdptypes.NewGenesisAccumulationTime(asset+"-a", time.Time{}, sdk.OneDec()), - }, - TotalPrincipals: cdptypes.GenesisTotalPrincipals{ - cdptypes.NewGenesisTotalPrincipal(asset+"-a", sdk.ZeroInt()), - }, - } - return app.GenesisState{cdptypes.ModuleName: cdc.MustMarshalJSON(&cdpGenesis)} -} diff --git a/x/community/testutil/consolidate.go b/x/community/testutil/consolidate.go deleted file mode 100644 index 51ec6a5f..00000000 --- a/x/community/testutil/consolidate.go +++ /dev/null @@ -1,180 +0,0 @@ -package testutil - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/kava-labs/kava/app" - types "github.com/kava-labs/kava/x/community/types" - kavadisttypes "github.com/kava-labs/kava/x/kavadist/types" -) - -func (suite *disableInflationTestSuite) TestStartCommunityFundConsolidation() { - tests := []struct { - name string - initialFeePoolCoins sdk.DecCoins - initialKavadistBalance sdk.Coins - }{ - { - "basic test with both balances and dust", - sdk.NewDecCoins( - sdk.NewDecCoinFromDec("ukava", sdk.NewDecWithPrec(123456, 2)), - sdk.NewDecCoinFromDec("usdx", sdk.NewDecWithPrec(654321, 3)), - ), - sdk.NewCoins( - sdk.NewInt64Coin("ukava", 10_000), - sdk.NewInt64Coin("usdx", 10_000), - ), - }, - { - "empty x/distribution feepool", - sdk.DecCoins(nil), - sdk.NewCoins( - sdk.NewInt64Coin("ukava", 10_000), - sdk.NewInt64Coin("usdx", 10_000), - ), - }, - { - "empty x/kavadist balance", - sdk.NewDecCoins( - sdk.NewDecCoinFromDec("ukava", sdk.NewDecWithPrec(123456, 2)), - sdk.NewDecCoinFromDec("usdx", sdk.NewDecWithPrec(654321, 3)), - ), - sdk.Coins{}, - }, - { - "both x/distribution feepool and x/kavadist balance empty", - sdk.DecCoins(nil), - sdk.Coins{}, - }, - } - - for _, tc := range tests { - suite.Run(tc.name, func() { - suite.SetupTest() - ak := suite.App.GetAccountKeeper() - - initialFeePool := distrtypes.FeePool{ - CommunityPool: tc.initialFeePoolCoins, - } - - initialFeePoolCoins, initialFeePoolDust := initialFeePool.CommunityPool.TruncateDecimal() - - // More coins than initial feepool/communitypool - fundCoins := sdk.NewCoins( - sdk.NewInt64Coin("ukava", 10_000), - sdk.NewInt64Coin("usdx", 10_000), - ) - - // Always fund x/distribution with enough coins to cover feepool - err := suite.App.FundModuleAccount( - suite.Ctx, - distrtypes.ModuleName, - fundCoins, - ) - suite.NoError(err, "x/distribution account should be funded without error") - - err = suite.App.FundModuleAccount( - suite.Ctx, - kavadisttypes.ModuleName, - tc.initialKavadistBalance, - ) - suite.NoError(err, "x/kavadist account should be funded without error") - - suite.App.GetDistrKeeper().SetFeePool(suite.Ctx, initialFeePool) - - // Ensure the feepool was set before migration - feePoolBefore := suite.App.GetDistrKeeper().GetFeePool(suite.Ctx) - suite.Equal(initialFeePool, feePoolBefore, "initial feepool should be set") - communityBalanceBefore := suite.App.GetCommunityKeeper().GetModuleAccountBalance(suite.Ctx) - - kavadistAcc := ak.GetModuleAccount(suite.Ctx, kavadisttypes.KavaDistMacc) - kavaDistCoinsBefore := suite.App.GetBankKeeper().GetAllBalances(suite.Ctx, kavadistAcc.GetAddress()) - suite.Equal( - tc.initialKavadistBalance, - kavaDistCoinsBefore, - "x/kavadist balance should be funded", - ) - - expectedKavaDistCoins := sdk.NewCoins(sdk.NewCoin("ukava", kavaDistCoinsBefore.AmountOf("ukava"))) - - // ------------- - // Run upgrade - - params, found := suite.Keeper.GetParams(suite.Ctx) - suite.Require().True(found) - params.UpgradeTimeDisableInflation = suite.Ctx.BlockTime().Add(-time.Minute) - suite.Keeper.SetParams(suite.Ctx, params) - - err = suite.Keeper.StartCommunityFundConsolidation(suite.Ctx) - suite.NoError(err, "consolidation should not error") - - // ------------- - // Check results - suite.Run("module balances after consolidation should moved", func() { - feePoolAfter := suite.App.GetDistrKeeper().GetFeePool(suite.Ctx) - suite.Equal( - initialFeePoolDust, - feePoolAfter.CommunityPool, - "x/distribution community pool should be sent to x/community", - ) - - kavaDistCoinsAfter := suite.App.GetBankKeeper().GetAllBalances(suite.Ctx, kavadistAcc.GetAddress()) - suite.Equal( - expectedKavaDistCoins, - kavaDistCoinsAfter, - "x/kavadist balance should ony contain ukava", - ) - - totalExpectedCommunityPoolCoins := communityBalanceBefore. - Add(initialFeePoolCoins...). // x/distribution fee pool - Add(tc.initialKavadistBalance...) // x/kavadist module balance - - communityBalanceAfter := suite.App.GetCommunityKeeper().GetModuleAccountBalance(suite.Ctx) - - // Use .IsAllGTE to avoid types.Coins(nil) vs types.Coins{} mismatch - suite.Truef( - totalExpectedCommunityPoolCoins.IsAllGTE(communityBalanceAfter), - "x/community balance should be increased by the truncated x/distribution community pool, got %s, expected %s", - communityBalanceAfter, - totalExpectedCommunityPoolCoins, - ) - }) - - suite.Run("bank transfer events should be emitted", func() { - communityAcc := ak.GetModuleAccount(suite.Ctx, types.ModuleAccountName) - distributionAcc := ak.GetModuleAccount(suite.Ctx, distrtypes.ModuleName) - kavadistAcc := ak.GetModuleAccount(suite.Ctx, kavadisttypes.KavaDistMacc) - - events := suite.Ctx.EventManager().Events() - - suite.NoError( - app.EventsContains( - events, - sdk.NewEvent( - banktypes.EventTypeTransfer, - sdk.NewAttribute(banktypes.AttributeKeyRecipient, communityAcc.GetAddress().String()), - sdk.NewAttribute(banktypes.AttributeKeySender, distributionAcc.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, initialFeePoolCoins.String()), - ), - ), - ) - - suite.NoError( - app.EventsContains( - events, - sdk.NewEvent( - banktypes.EventTypeTransfer, - sdk.NewAttribute(banktypes.AttributeKeyRecipient, communityAcc.GetAddress().String()), - sdk.NewAttribute(banktypes.AttributeKeySender, kavadistAcc.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, kavaDistCoinsBefore.Sub(expectedKavaDistCoins...).String()), - ), - ), - ) - }) - }) - } -} diff --git a/x/community/testutil/disable_inflation.go b/x/community/testutil/disable_inflation.go deleted file mode 100644 index 4d37cc73..00000000 --- a/x/community/testutil/disable_inflation.go +++ /dev/null @@ -1,203 +0,0 @@ -package testutil - -import ( - "time" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/community" - "github.com/kava-labs/kava/x/community/keeper" - "github.com/kava-labs/kava/x/community/types" - kavadisttypes "github.com/kava-labs/kava/x/kavadist/types" -) - -type testFunc func(sdk.Context, keeper.Keeper) - -// Test suite used for all abci inflation tests -type disableInflationTestSuite struct { - suite.Suite - - App app.TestApp - Ctx sdk.Context - Keeper keeper.Keeper - - genesisMintState *minttypes.GenesisState - genesisKavadistState *kavadisttypes.GenesisState - genesisDistrState *distrtypes.GenesisState - - testFunc testFunc -} - -func NewDisableInflationTestSuite(tf testFunc) *disableInflationTestSuite { - suite := &disableInflationTestSuite{} - suite.testFunc = tf - return suite -} - -// The default state used by each test -func (suite *disableInflationTestSuite) SetupTest() { - app.SetSDKConfig() - tApp := app.NewTestApp() - suite.App = tApp - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - suite.Keeper = suite.App.GetCommunityKeeper() - - // Set up x/mint and x/kavadist gen state - mintGen := minttypes.DefaultGenesisState() - mintGen.Params.InflationMax = sdk.NewDecWithPrec(595, 3) - mintGen.Params.InflationMin = sdk.NewDecWithPrec(595, 3) - suite.genesisMintState = mintGen - - kavadistGen := kavadisttypes.DefaultGenesisState() - kavadistGen.Params.Active = true - suite.genesisKavadistState = kavadistGen - - distrGen := distrtypes.DefaultGenesisState() - distrGen.Params.CommunityTax = sdk.MustNewDecFromStr("0.949500000000000000") - suite.genesisDistrState = distrGen - - appCodec := tApp.AppCodec() - suite.App.InitializeFromGenesisStates( - app.GenesisState{minttypes.ModuleName: appCodec.MustMarshalJSON(mintGen)}, - app.GenesisState{kavadisttypes.ModuleName: appCodec.MustMarshalJSON(kavadistGen)}, - app.GenesisState{distrtypes.ModuleName: appCodec.MustMarshalJSON(distrGen)}, - ) -} - -func (suite *disableInflationTestSuite) TestDisableInflation() { - validateState := func(upgraded bool, expectedDisableTime time.Time, originalStakingRewards sdkmath.LegacyDec, setStakingRewards sdkmath.LegacyDec, msg string) { - params, found := suite.Keeper.GetParams(suite.Ctx) - suite.Require().True(found) - mintParams := suite.App.GetMintKeeper().GetParams(suite.Ctx) - kavadistParams := suite.App.GetKavadistKeeper().GetParams(suite.Ctx) - distrParams := suite.App.GetDistrKeeper().GetParams(suite.Ctx) - - disableTimeMsg := "expected inflation disable time to match" - expectedMintState := suite.genesisMintState - expectedKavadistState := suite.genesisKavadistState - expectedDistrState := suite.genesisDistrState - expectedStakingRewards := originalStakingRewards - msgSuffix := "before upgrade" - - // The state expected after upgrade time is reached - if upgraded { - // Disable upgrade time is reset when run. - // - // This allows the time to be set and run again if required. - // In addition, with zero time not upgrading, achieves idempotence - // without extra logic or state. - expectedDisableTime = time.Time{} - disableTimeMsg = "expected inflation disable time to be reset" - expectedStakingRewards = setStakingRewards - - expectedMintState.Params.InflationMin = sdk.ZeroDec() - expectedMintState.Params.InflationMax = sdk.ZeroDec() - - expectedKavadistState.Params.Active = false - - expectedDistrState.Params.CommunityTax = sdk.ZeroDec() - - msgSuffix = "after upgrade" - - suite.Require().NoError( - app.EventsContains( - suite.Ctx.EventManager().Events(), - sdk.NewEvent( - types.EventTypeInflationStop, - sdk.NewAttribute( - types.AttributeKeyInflationDisableTime, - suite.Ctx.BlockTime().Format(time.RFC3339), - ), - ), - )) - } - - suite.Require().Equal(expectedMintState.Params.InflationMin, mintParams.InflationMin, msg+": expected mint inflation min to match state "+msgSuffix) - suite.Require().Equal(expectedMintState.Params.InflationMax, mintParams.InflationMax, msg+": expected mint inflation max to match state "+msgSuffix) - suite.Require().Equal(expectedKavadistState.Params.Active, kavadistParams.Active, msg+":expected kavadist active flag match state "+msgSuffix) - suite.Require().Equal(expectedDistrState.Params.CommunityTax, distrParams.CommunityTax, msg+":expected x/distribution community tax to match state "+msgSuffix) - suite.Require().Equal(expectedDisableTime, params.UpgradeTimeDisableInflation, msg+": "+disableTimeMsg) - - // we always check staking rewards per second matches the passed in expectation - suite.Require().Equal(expectedStakingRewards, params.StakingRewardsPerSecond, msg+": "+"staking rewards per second to match "+msgSuffix) - // we don't modify or zero out the initial rewards per second for upgrade time - suite.Require().Equal(setStakingRewards, params.UpgradeTimeSetStakingRewardsPerSecond, msg+": "+"set staking rewards per second to match "+msgSuffix) - } - - blockTime := suite.Ctx.BlockTime() - testCases := []struct { - name string - upgradeTime time.Time - setStakingRewards sdkmath.LegacyDec - shouldUpgrade bool - }{ - {"zero upgrade time -- should not upgrade", time.Time{}, sdkmath.LegacyNewDec(1001), false}, - {"upgrade time in future -- should not upgrade", blockTime.Add(1 * time.Second), sdkmath.LegacyNewDec(1002), false}, - {"upgrade time in past -- should upgrade", blockTime.Add(-1 * time.Second), sdkmath.LegacyNewDec(1003), true}, - {"upgrade time equal to block time -- should upgrade", blockTime, sdkmath.LegacyNewDec(1004), true}, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - params, found := suite.Keeper.GetParams(suite.Ctx) - suite.Require().True(found) - - // these should not match in order to assure assertions test correct behavior - suite.Require().NotEqual(params.StakingRewardsPerSecond, tc.setStakingRewards, "set staking rewards can not match initial staking rewards") - - // ensure state is as we expect before running upgrade or updating time - validateState(false, time.Time{}, params.StakingRewardsPerSecond, params.UpgradeTimeSetStakingRewardsPerSecond, "initial state") - - // set inflation disable time - params.UpgradeTimeDisableInflation = tc.upgradeTime - // set upgrade time set staking rewards per second - params.UpgradeTimeSetStakingRewardsPerSecond = tc.setStakingRewards - suite.Keeper.SetParams(suite.Ctx, params) - - // run test function - suite.testFunc(suite.Ctx, suite.Keeper) - - // run assertions to ensure upgrade did or did not run - validateState(tc.shouldUpgrade, tc.upgradeTime, params.StakingRewardsPerSecond, tc.setStakingRewards, "first begin blocker run") - - // test idempotence only if upgrade should have been ran - if tc.shouldUpgrade { - // reset mint and kavadist state to their initial values - err := suite.App.GetMintKeeper().SetParams(suite.Ctx, suite.genesisMintState.Params) - suite.Require().NoError(err) - suite.App.GetKavadistKeeper().SetParams(suite.Ctx, suite.genesisKavadistState.Params) - - // modify staking rewards per second to ensure they are not overridden again - params, found := suite.Keeper.GetParams(suite.Ctx) - suite.Require().True(found) - params.StakingRewardsPerSecond = params.StakingRewardsPerSecond.Add(sdkmath.LegacyOneDec()) - suite.Keeper.SetParams(suite.Ctx, params) - - // run begin blocker again - community.BeginBlocker(suite.Ctx, suite.Keeper) - - // ensure begin blocker is idempotent and never runs twice - validateState(false, time.Time{}, params.StakingRewardsPerSecond, tc.setStakingRewards, "second begin blocker run") - } - }) - } -} - -func (suite *disableInflationTestSuite) TestPanicsOnMissingParameters() { - suite.SetupTest() - - store := suite.Ctx.KVStore(suite.App.GetKVStoreKey(types.StoreKey)) - store.Delete(types.ParamsKey) - - suite.PanicsWithValue("invalid state: module parameters not found", func() { - suite.testFunc(suite.Ctx, suite.Keeper) - }) -} diff --git a/x/community/testutil/main.go b/x/community/testutil/main.go deleted file mode 100644 index 1016b68e..00000000 --- a/x/community/testutil/main.go +++ /dev/null @@ -1,47 +0,0 @@ -package testutil - -import ( - "github.com/stretchr/testify/suite" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/community/keeper" - "github.com/kava-labs/kava/x/community/types" -) - -// Test suite used for all community tests -type Suite struct { - suite.Suite - App app.TestApp - Ctx sdk.Context - Keeper keeper.Keeper - - MaccAddress sdk.AccAddress -} - -// The default state used by each test -func (suite *Suite) SetupTest() { - app.SetSDKConfig() - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - suite.App = tApp.InitializeFromGenesisStates() - - suite.Ctx = ctx - suite.Keeper = tApp.GetCommunityKeeper() - communityPoolAddress := tApp.GetAccountKeeper().GetModuleAddress(types.ModuleAccountName) - // hello, greppers! - suite.Equal("kava17d2wax0zhjrrecvaszuyxdf5wcu5a0p4qlx3t5", communityPoolAddress.String()) - suite.MaccAddress = communityPoolAddress -} - -// CreateFundedAccount creates a random account and mints `coins` to it. -func (suite *Suite) CreateFundedAccount(coins sdk.Coins) sdk.AccAddress { - addr := app.RandomAddress() - err := suite.App.FundAccount(suite.Ctx, addr, coins) - suite.Require().NoError(err) - return addr -} diff --git a/x/community/testutil/pricefeed_genesis_builder.go b/x/community/testutil/pricefeed_genesis_builder.go deleted file mode 100644 index e0a2e37c..00000000 --- a/x/community/testutil/pricefeed_genesis_builder.go +++ /dev/null @@ -1,61 +0,0 @@ -package testutil - -import ( - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - hardtypes "github.com/kava-labs/kava/x/hard/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -// lendGenesisBuilder builds the Hard and Pricefeed genesis states for setting up Kava Lend -type lendGenesisBuilder struct { - hardMarkets []hardtypes.MoneyMarket - pfMarkets []pricefeedtypes.Market - prices []pricefeedtypes.PostedPrice -} - -func NewLendGenesisBuilder() lendGenesisBuilder { - return lendGenesisBuilder{} -} - -func (b lendGenesisBuilder) Build() (hardtypes.GenesisState, pricefeedtypes.GenesisState) { - hardGS := hardtypes.DefaultGenesisState() - hardGS.Params.MoneyMarkets = b.hardMarkets - - pricefeedGS := pricefeedtypes.DefaultGenesisState() - pricefeedGS.Params.Markets = b.pfMarkets - pricefeedGS.PostedPrices = b.prices - return hardGS, pricefeedGS -} - -func (b lendGenesisBuilder) WithMarket(denom, spotMarketId string, price sdk.Dec) lendGenesisBuilder { - // add hard money market - b.hardMarkets = append(b.hardMarkets, - hardtypes.NewMoneyMarket( - denom, - hardtypes.NewBorrowLimit(false, sdk.NewDec(1e15), sdk.MustNewDecFromStr("0.6")), - spotMarketId, - sdkmath.NewInt(1e6), - hardtypes.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), - sdk.MustNewDecFromStr("0.05"), - sdk.ZeroDec(), - ), - ) - - // add pricefeed - b.pfMarkets = append(b.pfMarkets, - pricefeedtypes.Market{MarketID: spotMarketId, BaseAsset: denom, QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - ) - b.prices = append(b.prices, - pricefeedtypes.PostedPrice{ - MarketID: spotMarketId, - OracleAddress: sdk.AccAddress{}, - Price: price, - Expiry: time.Now().Add(100 * time.Hour), - }, - ) - - return b -} diff --git a/x/community/testutil/staking_rewards.go b/x/community/testutil/staking_rewards.go deleted file mode 100644 index dbecab2c..00000000 --- a/x/community/testutil/staking_rewards.go +++ /dev/null @@ -1,421 +0,0 @@ -package testutil - -import ( - "fmt" - "math" - "math/rand" - "time" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/community" - "github.com/kava-labs/kava/x/community/keeper" - "github.com/kava-labs/kava/x/community/types" -) - -// StakingRewardsTestSuite tests staking rewards per second logic -type stakingRewardsTestSuite struct { - suite.Suite - - App app.TestApp - Keeper keeper.Keeper - - testFunc testFunc -} - -func NewStakingRewardsTestSuite(tf testFunc) *stakingRewardsTestSuite { - suite := &stakingRewardsTestSuite{} - suite.testFunc = tf - return suite -} - -// The default state used by each test -func (suite *stakingRewardsTestSuite) SetupTest() { - app.SetSDKConfig() - - tApp := app.NewTestApp() - tApp.InitializeFromGenesisStates() - - suite.App = tApp - suite.Keeper = suite.App.GetCommunityKeeper() -} - -func (suite *stakingRewardsTestSuite) TestStakingRewards() { - testCases := []struct { - // name of subtest - name string - - // block time of first block - periodStart time.Time - // block time of last block - periodEnd time.Time - - // block time n will be periodStart + rand(range_min...range_max)*(n-1) up to periodEnd - blockTimeRangeMin float64 - blockTimeRangeMax float64 - - // rewards per second to set in state - rewardsPerSecond sdkmath.LegacyDec - - // the amount of ukava to mint and transfer to the community pool - // to use to pay for rewards - communityPoolFunds sdkmath.Int - - // how many total rewards are expected to be accumulated in ukava - expectedRewardsTotal sdkmath.Int - }{ - // ** These take a long time to run ** - //{ - // name: "one year with 0.5 to 1 second block times", - // periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - // periodEnd: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC), - // blockTimeRangeMin: 0.5, - // blockTimeRangeMax: 1, - // rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("1585489.599188229325215626"), - // expectedRewardsTotal: sdkmath.NewInt(49999999999999), // 50 million KAVA per year - //}, - //{ - // name: "one year with 5.5 to 6.5 second blocktimes", - // periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - // periodEnd: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC), - // blockTimeRangeMin: 5.5, - // blockTimeRangeMax: 6.5, - // rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("1585489.599188229325215626"), // 50 million kava per year - // communityPoolFunds: sdkmath.NewInt(50000000000000), - // expectedRewardsTotal: sdkmath.NewInt(49999999999999), // truncation results in 1 ukava error - //}, - // - // - // One Day of blocks with different block time variations - // - // - { - name: "one day with sub-second block times and 50 million KAVA per year", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 0.1, - blockTimeRangeMax: 1, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("1585489.599188229325215626"), // 50 million kava per year - communityPoolFunds: sdkmath.NewInt(200000000000), - expectedRewardsTotal: sdkmath.NewInt(136986301369), // 50 million / 365 days - 1 ukava - - }, - { - name: "one day with 5.5 to 6.5 second block times and 50 million KAVA per year", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 5.5, - blockTimeRangeMax: 6.5, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("1585489.599188229325215626"), // 50 million kava per year - communityPoolFunds: sdkmath.NewInt(200000000000), - expectedRewardsTotal: sdkmath.NewInt(136986301369), // 50 million / 365 days - 1 ukava - }, - // - // - // Total time span under 1 second - // - // - { - name: "single 6.9 second time span and 25 million KAVA per year", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 1, 0, 0, 6, 900000000, time.UTC), - blockTimeRangeMin: 10, // forces only two blocks -- one time span - blockTimeRangeMax: 10, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("792744.799594114662607813"), // 25 million kava per year - communityPoolFunds: sdkmath.NewInt(10000000), - expectedRewardsTotal: sdkmath.NewInt(5469939), // per second rate * 6.9 - }, - { - name: "multiple blocks across sub-second time span nd 10 million KAVA per year", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 1, 0, 0, 0, 800000000, time.UTC), - blockTimeRangeMin: 0.1, // multiple blocks in a sub-second time span - blockTimeRangeMax: 0.2, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("317097.919837645865043125"), // 10 million kava per year - communityPoolFunds: sdkmath.NewInt(300000), - expectedRewardsTotal: sdkmath.NewInt(253678), // per second rate * 0.8 - }, - // - // - // Variations of community pool balance - // - // - { - name: "community pool exact funds -- should spend community to zero and not panic", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 5.5, - blockTimeRangeMax: 6.2, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("317097.919837645865043125"), // 10 million kava per year - communityPoolFunds: sdkmath.NewInt(27397260273), - expectedRewardsTotal: sdkmath.NewInt(27397260273), - }, - { - name: "community pool under funded -- should spend community pool to down to zero and not panic", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 5.5, - blockTimeRangeMax: 6.5, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("1585489.599188229325215626"), // 25 million kava per year - communityPoolFunds: sdkmath.NewInt(100000000000), // under funded - expectedRewardsTotal: sdkmath.NewInt(100000000000), // rewards max is the community pool balance - }, - { - name: "community pool no funds -- should pay zero rewards and not panic", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 5.5, - blockTimeRangeMax: 6.5, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("792744.799594114662607813"), // 25 million kava per year - communityPoolFunds: sdkmath.NewInt(0), - expectedRewardsTotal: sdkmath.NewInt(0), - }, - // - // - // Disabled - // - // - { - name: "zero rewards per second results in zero rewards paid", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 5.5, - blockTimeRangeMax: 6.5, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("0.000000000000000000"), // 25 million kava per year - communityPoolFunds: sdkmath.NewInt(100000000000000), - expectedRewardsTotal: sdkmath.NewInt(0), - }, - // - // - // Test underlying calculations are safe and overflow/underflow bounds are reasonable - // - // - { - name: "does not overflow with extremely large per second value and extremely large single block durations", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2033, 1, 1, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 315619200, // a single 10 year long block in seconds (w/ 3 leap years) - blockTimeRangeMax: 315619200, // a single 10 year long block in seconds (w/ 3 leap years) - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("100000000000000000000000000.000000000000000000"), // 100 million kava per second in 18 decimal form - communityPoolFunds: newIntFromString("40000000000000000000000000000000000"), - expectedRewardsTotal: newIntFromString("31561920000000000000000000000000000"), // 10 years worth of rewards (with three leap years) - }, - { - name: "able to accumulate decimal ukava units across blocks", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 5.5, - blockTimeRangeMax: 6.5, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("0.100000000000000000"), // blocks are not long enough to accumulate a single ukava with this rate - communityPoolFunds: sdkmath.NewInt(10000), - expectedRewardsTotal: sdkmath.NewInt(8640), - }, - { - name: "down to 1 ukava per year can be accumulated -- we are safe from underflow at reasonably small values", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 60, // large block times speed up this test case - blockTimeRangeMax: 120, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("0.000000031709791984"), - communityPoolFunds: sdkmath.NewInt(1), - expectedRewardsTotal: sdkmath.NewInt(1), - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - // keepers - keeper := suite.Keeper - accountKeeper := suite.App.GetAccountKeeper() - bankKeeper := suite.App.GetBankKeeper() - - // initial context at height 1 - height := int64(1) - blockTime := tc.periodStart - ctx := suite.App.NewContext(true, tmproto.Header{Height: height, Time: blockTime}) - - // ensure community pool balance matches the test expectations - poolAcc := accountKeeper.GetModuleAccount(ctx, types.ModuleName) - // community pool balance should start at zero - suite.Require().True(bankKeeper.GetBalance(ctx, poolAcc.GetAddress(), "ukava").Amount.IsZero(), "expected community pool to start with zero coins in test genesis") - // fund withexact amount from test case - suite.App.FundAccount(ctx, poolAcc.GetAddress(), sdk.NewCoins(sdk.NewCoin("ukava", tc.communityPoolFunds))) - - // get starting balance of fee collector to substract later in case this is non-zero in genesis - feeCollectorAcc := accountKeeper.GetModuleAccount(ctx, authtypes.FeeCollectorName) - initialFeeCollectorBalance := bankKeeper.GetBalance(ctx, feeCollectorAcc.GetAddress(), "ukava").Amount - - // set rewards per second in state - params, found := keeper.GetParams(ctx) - suite.Require().True(found) - params.StakingRewardsPerSecond = tc.rewardsPerSecond - keeper.SetParams(ctx, params) - - stakingRewardEvents := sdk.Events{} - - for { - // run community begin blocker logic - suite.testFunc(ctx, keeper) - - // accumulate event rewards from events - stakingRewardEvents = append(stakingRewardEvents, filterStakingRewardEvents(ctx.EventManager().Events())...) - - // exit loop if we are at last block - if blockTime.Equal(tc.periodEnd) { - break - } - - // create random block duration in nanoseconds - randomBlockDurationInSeconds := tc.blockTimeRangeMin + rand.Float64()*(tc.blockTimeRangeMax-tc.blockTimeRangeMin) - nextBlockDuration := time.Duration(randomBlockDurationInSeconds * math.Pow10(9)) - - // move to next block by incrementing height, adding random duration, and settings new context - height++ - blockTime = blockTime.Add(nextBlockDuration) - // set last block to exact end of period if we go past - if blockTime.After(tc.periodEnd) { - blockTime = tc.periodEnd - } - ctx = suite.App.NewContext(true, tmproto.Header{Height: height, Time: blockTime}) - } - - endingFeeCollectorBalance := bankKeeper.GetBalance(ctx, feeCollectorAcc.GetAddress(), "ukava").Amount - feeCollectorBalanceAdded := endingFeeCollectorBalance.Sub(initialFeeCollectorBalance) - - // assert fee pool was payed the correct rewards - suite.Equal(tc.expectedRewardsTotal.String(), feeCollectorBalanceAdded.String(), "expected fee collector balance to match") - - if tc.expectedRewardsTotal.IsZero() { - suite.Equal(0, len(stakingRewardEvents), "expected no events to be emitted") - } else { - // we add up all reward coin events - eventCoins := getRewardCoinsFromEvents(stakingRewardEvents) - - // assert events emitted match expected rewards - suite.Equal( - tc.expectedRewardsTotal.String(), - eventCoins.AmountOf("ukava").String(), - "expected event coins to match", - ) - } - - // assert the community pool deducted the same amount - expectedCommunityPoolBalance := tc.communityPoolFunds.Sub(tc.expectedRewardsTotal) - actualCommunityPoolBalance := bankKeeper.GetBalance(ctx, poolAcc.GetAddress(), "ukava").Amount - suite.Equal(expectedCommunityPoolBalance.String(), actualCommunityPoolBalance.String(), "expected community pool balance to match") - }) - } - -} - -func (suite *stakingRewardsTestSuite) TestStakingRewardsDoNotAccumulateWhenPoolIsDrained() { - app := suite.App - keeper := suite.Keeper - accountKeeper := suite.App.GetAccountKeeper() - bankKeeper := suite.App.GetBankKeeper() - - // first block - blockTime := time.Now() - ctx := app.NewContext(true, tmproto.Header{Height: 1, Time: blockTime}) - - poolAcc := accountKeeper.GetModuleAccount(ctx, types.ModuleName) - feeCollectorAcc := accountKeeper.GetModuleAccount(ctx, authtypes.FeeCollectorName) - - // set state to pay staking rewards - params, _ := keeper.GetParams(ctx) - // we set a decimal amount that ensures after 10 seconds we overspend the community pool - // with enough truncation error that we would have an ending balance of 20.000001 if it was - // carried over after the pool run out of funds - params.StakingRewardsPerSecond = sdkmath.LegacyMustNewDecFromStr("1000000.099999999999999999") // > 1 KAVA per second - keeper.SetParams(ctx, params) - - // fund community pool account - app.FundAccount(ctx, poolAcc.GetAddress(), sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10000000)))) // 10 KAVA - initialFeeCollectorBalance := bankKeeper.GetBalance(ctx, feeCollectorAcc.GetAddress(), "ukava").Amount - - // run first block (no rewards hapeen on first block) - community.BeginBlocker(ctx, keeper) - - // run second block 10 seconds in future and spend all community pool rewards - blockTime = blockTime.Add(10 * time.Second) - ctx = app.NewContext(true, tmproto.Header{Height: 2, Time: blockTime}) - community.BeginBlocker(ctx, keeper) - - // run third block 10 seconds in future which no rewards will be paid - blockTime = blockTime.Add(10 * time.Second) - ctx = app.NewContext(true, tmproto.Header{Height: 3, Time: blockTime}) - community.BeginBlocker(ctx, keeper) - - // run fourth block 10 seconds in future which no rewards will be paid - blockTime = blockTime.Add(10 * time.Second) - ctx = app.NewContext(true, tmproto.Header{Height: 4, Time: blockTime}) - community.BeginBlocker(ctx, keeper) - - // refund the community pool with 100 KAVA -- plenty of funds - app.FundAccount(ctx, poolAcc.GetAddress(), sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100000000)))) // 100 KAVA - - // run fifth block 10 seconds in future which no rewards will be paid - blockTime = blockTime.Add(10 * time.Second) - ctx = app.NewContext(true, tmproto.Header{Height: 5, Time: blockTime}) - community.BeginBlocker(ctx, keeper) - - // assert that only 20 total KAVA has been distributed in rewards - // and blocks where community pool had d - rewards := bankKeeper.GetBalance(ctx, feeCollectorAcc.GetAddress(), "ukava").Amount.Sub(initialFeeCollectorBalance) - suite.Require().Equal(sdkmath.NewInt(20000000).String(), rewards.String()) -} - -func (suite *stakingRewardsTestSuite) TestPanicsOnMissingParameters() { - suite.SetupTest() - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: time.Now()}) - store := ctx.KVStore(suite.App.GetKVStoreKey(types.StoreKey)) - store.Delete(types.ParamsKey) - - suite.PanicsWithValue("invalid state: module parameters not found", func() { - suite.testFunc(ctx, suite.Keeper) - }) -} - -// newIntFromString returns a new sdkmath.Int from a string -func newIntFromString(str string) sdkmath.Int { - num, ok := sdkmath.NewIntFromString(str) - if !ok { - panic(fmt.Sprintf("overflow creating Int from %s", str)) - } - return num -} - -func filterStakingRewardEvents(events sdk.Events) (rewardEvents sdk.Events) { - for _, event := range events { - if event.Type == types.EventTypeStakingRewardsPaid { - rewardEvents = append(rewardEvents, event) - } - } - - return -} - -func getRewardCoinsFromEvents(events sdk.Events) sdk.Coins { - coins := sdk.NewCoins() - - for _, event := range events { - if event.Type == types.EventTypeStakingRewardsPaid { - rewards, err := sdk.ParseCoinNormalized(string(event.Attributes[0].Value)) - if err != nil { - panic(err) - } - - coins = coins.Add(rewards) - } - } - - return coins -} diff --git a/x/community/types/codec.go b/x/community/types/codec.go deleted file mode 100644 index 9c20c18f..00000000 --- a/x/community/types/codec.go +++ /dev/null @@ -1,54 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/legacy" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - legacy.RegisterAminoMsg(cdc, &MsgFundCommunityPool{}, "community/MsgFundCommunityPool") - legacy.RegisterAminoMsg(cdc, &MsgUpdateParams{}, "community/MsgUpdateParams") - - cdc.RegisterConcrete(&CommunityPoolLendDepositProposal{}, "kava/CommunityPoolLendDepositProposal", nil) - cdc.RegisterConcrete(&CommunityPoolLendWithdrawProposal{}, "kava/CommunityPoolLendWithdrawProposal", nil) - cdc.RegisterConcrete(&CommunityCDPRepayDebtProposal{}, "kava/CommunityCDPRepayDebtProposal", nil) - cdc.RegisterConcrete(&CommunityCDPWithdrawCollateralProposal{}, "kava/CommunityCDPWithdrawCollateralProposal", nil) -} - -// RegisterInterfaces registers proto messages under their interfaces for unmarshalling, -// in addition to registering the msg service for handling tx msgs. -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgFundCommunityPool{}, - &MsgUpdateParams{}, - ) - registry.RegisterImplementations((*govv1beta1.Content)(nil), - &CommunityPoolLendDepositProposal{}, - &CommunityPoolLendWithdrawProposal{}, - &CommunityCDPRepayDebtProposal{}, - &CommunityCDPWithdrawCollateralProposal{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/community/types/errors.go b/x/community/types/errors.go deleted file mode 100644 index 64f4b109..00000000 --- a/x/community/types/errors.go +++ /dev/null @@ -1,5 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -var ErrInvalidParams = errorsmod.Register(ModuleName, 1, "invalid params") diff --git a/x/community/types/events.go b/x/community/types/events.go deleted file mode 100644 index c9c0d126..00000000 --- a/x/community/types/events.go +++ /dev/null @@ -1,13 +0,0 @@ -package types - -// Community module event types -const ( - EventTypeInflationStop = "inflation_stop" - EventTypeStakingRewardsPaid = "staking_rewards_paid" - - AttributeKeyStakingRewardAmount = "staking_reward_amount" - AttributeKeyInflationDisableTime = "inflation_disable_time" - - AttributeValueFundCommunityPool = "fund_community_pool" - AttributeValueCategory = ModuleName -) diff --git a/x/community/types/expected_keepers.go b/x/community/types/expected_keepers.go deleted file mode 100644 index 468b4efc..00000000 --- a/x/community/types/expected_keepers.go +++ /dev/null @@ -1,69 +0,0 @@ -package types - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - kavadisttypes "github.com/kava-labs/kava/x/kavadist/types" -) - -// AccountKeeper defines the contract required for account APIs. -type AccountKeeper interface { - GetModuleAccount(ctx sdk.Context, moduleName string) authtypes.ModuleAccountI - GetModuleAddress(name string) sdk.AccAddress -} - -// BankKeeper defines the contract needed to be fulfilled for banking dependencies. -type BankKeeper interface { - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error - - GetSupply(ctx sdk.Context, denom string) sdk.Coin -} - -// CdpKeeper defines the contract needed to be fulfilled for cdp dependencies. -type CdpKeeper interface { - RepayPrincipal(ctx sdk.Context, owner sdk.AccAddress, collateralType string, payment sdk.Coin) error - WithdrawCollateral(ctx sdk.Context, owner, depositor sdk.AccAddress, collateral sdk.Coin, collateralType string) error -} - -// HardKeeper defines the contract needed to be fulfilled for Kava Lend dependencies. -type HardKeeper interface { - Deposit(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error - Withdraw(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error -} - -// DistributionKeeper defines the contract needed to be fulfilled for distribution dependencies. -type DistributionKeeper interface { - DistributeFromFeePool(ctx sdk.Context, amount sdk.Coins, receiveAddr sdk.AccAddress) error - FundCommunityPool(ctx sdk.Context, amount sdk.Coins, sender sdk.AccAddress) error - GetFeePoolCommunityCoins(ctx sdk.Context) sdk.DecCoins - GetFeePool(ctx sdk.Context) distrtypes.FeePool - SetFeePool(ctx sdk.Context, feePool distrtypes.FeePool) - GetParams(ctx sdk.Context) distrtypes.Params - SetParams(ctx sdk.Context, params distrtypes.Params) error - GetCommunityTax(ctx sdk.Context) sdk.Dec -} - -type MintKeeper interface { - GetParams(ctx sdk.Context) (params minttypes.Params) - SetParams(ctx sdk.Context, params minttypes.Params) error - GetMinter(ctx sdk.Context) (minter minttypes.Minter) -} - -type KavadistKeeper interface { - GetParams(ctx sdk.Context) (params kavadisttypes.Params) - SetParams(ctx sdk.Context, params kavadisttypes.Params) -} - -// StakingKeeper expected interface for the staking keeper -type StakingKeeper interface { - BondDenom(ctx sdk.Context) string - TotalBondedTokens(ctx sdk.Context) sdkmath.Int -} diff --git a/x/community/types/genesis.go b/x/community/types/genesis.go deleted file mode 100644 index 2d75fdec..00000000 --- a/x/community/types/genesis.go +++ /dev/null @@ -1,26 +0,0 @@ -package types - -// NewGenesisState returns a new genesis state object -func NewGenesisState(params Params, stakingRewardsState StakingRewardsState) GenesisState { - return GenesisState{ - Params: params, - StakingRewardsState: stakingRewardsState, - } -} - -// DefaultGenesisState returns default genesis state -func DefaultGenesisState() GenesisState { - return NewGenesisState( - DefaultParams(), - DefaultStakingRewardsState(), - ) -} - -// Validate checks the params are valid -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - - return gs.StakingRewardsState.Validate() -} diff --git a/x/community/types/genesis.pb.go b/x/community/types/genesis.pb.go deleted file mode 100644 index 7f4674c0..00000000 --- a/x/community/types/genesis.pb.go +++ /dev/null @@ -1,382 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/community/v1beta1/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 community module's genesis state. -type GenesisState struct { - // params defines all the parameters related to commmunity - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - // StakingRewardsState stores the internal staking reward data required to - // track staking rewards across blocks - StakingRewardsState StakingRewardsState `protobuf:"bytes,2,opt,name=staking_rewards_state,json=stakingRewardsState,proto3" json:"staking_rewards_state"` -} - -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_ccf84d82ea3861e0, []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) GetStakingRewardsState() StakingRewardsState { - if m != nil { - return m.StakingRewardsState - } - return StakingRewardsState{} -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.community.v1beta1.GenesisState") -} - -func init() { - proto.RegisterFile("kava/community/v1beta1/genesis.proto", fileDescriptor_ccf84d82ea3861e0) -} - -var fileDescriptor_ccf84d82ea3861e0 = []byte{ - // 255 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xc9, 0x4e, 0x2c, 0x4b, - 0xd4, 0x4f, 0xce, 0xcf, 0xcd, 0x2d, 0xcd, 0xcb, 0x2c, 0xa9, 0xd4, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, - 0x49, 0x34, 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, - 0x17, 0x12, 0x03, 0xa9, 0xd2, 0x83, 0xab, 0xd2, 0x83, 0xaa, 0x92, 0x12, 0x49, 0xcf, 0x4f, 0xcf, - 0x07, 0x2b, 0xd1, 0x07, 0xb1, 0x20, 0xaa, 0xa5, 0x94, 0x71, 0x98, 0x59, 0x90, 0x58, 0x94, 0x98, - 0x0b, 0x35, 0x52, 0x0a, 0x97, 0xc5, 0xc5, 0x25, 0x89, 0xd9, 0x99, 0x79, 0xe9, 0x10, 0x55, 0x4a, - 0x9b, 0x19, 0xb9, 0x78, 0xdc, 0x21, 0x4e, 0x09, 0x2e, 0x49, 0x2c, 0x49, 0x15, 0xb2, 0xe1, 0x62, - 0x83, 0x18, 0x23, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0x6d, 0x24, 0xa7, 0x87, 0xdd, 0x69, 0x7a, 0x01, - 0x60, 0x55, 0x4e, 0x2c, 0x27, 0xee, 0xc9, 0x33, 0x04, 0x41, 0xf5, 0x08, 0xa5, 0x72, 0x89, 0x42, - 0xcd, 0x8f, 0x2f, 0x4a, 0x2d, 0x4f, 0x2c, 0x4a, 0x29, 0x8e, 0x2f, 0x06, 0x19, 0x2b, 0xc1, 0x04, - 0x36, 0x4c, 0x1b, 0x97, 0x61, 0xc1, 0x10, 0x4d, 0x41, 0x10, 0x3d, 0x60, 0x97, 0x40, 0x4d, 0x16, - 0x2e, 0xc6, 0x22, 0xe5, 0x7a, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, - 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0xda, - 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x20, 0x2b, 0xf4, 0x41, 0x76, 0xe9, 0xe6, 0x24, 0x26, 0x15, - 0x83, 0x59, 0xfa, 0x15, 0x48, 0x81, 0x51, 0x52, 0x59, 0x90, 0x5a, 0x9c, 0xc4, 0x06, 0x0e, 0x03, - 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xc5, 0x84, 0x31, 0x9f, 0xa4, 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 - { - size, err := m.StakingRewardsState.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)) - l = m.StakingRewardsState.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 StakingRewardsState", 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.StakingRewardsState.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/community/types/genesis_test.go b/x/community/types/genesis_test.go deleted file mode 100644 index 124364a2..00000000 --- a/x/community/types/genesis_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/kava-labs/kava/x/community/types" -) - -func TestDefaultGenesisState(t *testing.T) { - defaultGen := types.DefaultGenesisState() - - require.NoError(t, defaultGen.Validate()) - require.Equal(t, types.DefaultParams(), defaultGen.Params) - require.Equal(t, types.DefaultStakingRewardsState(), defaultGen.StakingRewardsState) -} - -func TestGenesisState_ValidateParams(t *testing.T) { - for _, tc := range paramTestCases { - t.Run(tc.name, func(t *testing.T) { - genState := types.DefaultGenesisState() - genState.Params = tc.params - - err := genState.Validate() - - if tc.expectedErr == "" { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), tc.expectedErr) - } - }) - } -} - -func TestGenesisState_ValidateStakingRewardsState(t *testing.T) { - for _, tc := range stakingRewardsStateTestCases { - t.Run(tc.name, func(t *testing.T) { - genState := types.DefaultGenesisState() - genState.StakingRewardsState = tc.stakingRewardsState - - err := genState.Validate() - - if tc.expectedErr == "" { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), tc.expectedErr) - } - }) - } -} diff --git a/x/community/types/keys.go b/x/community/types/keys.go deleted file mode 100644 index dc6f0a35..00000000 --- a/x/community/types/keys.go +++ /dev/null @@ -1,28 +0,0 @@ -package types - -const ( - // module name - ModuleName = "community" - - // ModuleAccountName is the name of the module's account - ModuleAccountName = ModuleName - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey is the top-level router key for the module - RouterKey = ModuleName - - // Query endpoints supported by community - QueryBalance = "balance" - - // LegacyCommunityPoolModuleName is the module account name used by the legacy community pool - // It is used to determine the address of the old community pool to be returned with the legacy balance. - LegacyCommunityPoolModuleName = "distribution" -) - -// key prefixes for store -var ( - ParamsKey = []byte{0x01} - StakingRewardsStateKey = []byte{0x02} -) diff --git a/x/community/types/msg.go b/x/community/types/msg.go deleted file mode 100644 index ff04fb6a..00000000 --- a/x/community/types/msg.go +++ /dev/null @@ -1,102 +0,0 @@ -package types - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" -) - -// ensure Msg interface compliance at compile time -var ( - _ sdk.Msg = &MsgFundCommunityPool{} - _ legacytx.LegacyMsg = &MsgFundCommunityPool{} - _ sdk.Msg = &MsgUpdateParams{} - _ legacytx.LegacyMsg = &MsgUpdateParams{} -) - -// NewMsgFundCommunityPool returns a new MsgFundCommunityPool -func NewMsgFundCommunityPool(depositor sdk.AccAddress, amount sdk.Coins) MsgFundCommunityPool { - return MsgFundCommunityPool{ - Depositor: depositor.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgFundCommunityPool) Route() string { return ModuleName } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgFundCommunityPool) Type() string { return sdk.MsgTypeURL(&msg) } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgFundCommunityPool) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if msg.Amount.IsAnyNil() || !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "'%s'", msg.Amount) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgFundCommunityPool) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgFundCommunityPool) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - panic(err) - } - return []sdk.AccAddress{depositor} -} - -// NewMsgUpdateParams returns a new MsgUpdateParams -func NewMsgUpdateParams(authority sdk.AccAddress, params Params) MsgUpdateParams { - return MsgUpdateParams{ - Authority: authority.String(), - Params: params, - } -} - -// Route return the message type used for routing the message. -func (msg MsgUpdateParams) Route() string { return ModuleName } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgUpdateParams) Type() string { return sdk.MsgTypeURL(&msg) } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgUpdateParams) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Authority) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if err := msg.Params.Validate(); err != nil { - return errorsmod.Wrap(ErrInvalidParams, err.Error()) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgUpdateParams) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgUpdateParams) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Authority) - if err != nil { - panic(err) - } - return []sdk.AccAddress{depositor} -} diff --git a/x/community/types/msg_test.go b/x/community/types/msg_test.go deleted file mode 100644 index 5629e40f..00000000 --- a/x/community/types/msg_test.go +++ /dev/null @@ -1,163 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/community/types" -) - -func TestFundCommunityPool_ValidateBasic(t *testing.T) { - validCoins := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewIntFromUint64(1e6)), - sdk.NewCoin("some-denom", sdkmath.NewIntFromUint64(1e4)), - ) - testCases := []struct { - name string - shouldPass bool - message types.MsgFundCommunityPool - }{ - { - name: "valid message", - shouldPass: true, - message: types.NewMsgFundCommunityPool(app.RandomAddress(), validCoins), - }, - { - name: "invalid - bad depositor", - shouldPass: false, - message: types.MsgFundCommunityPool{ - Depositor: "not-an-address", - Amount: validCoins, - }, - }, - { - name: "invalid - empty coins", - shouldPass: false, - message: types.MsgFundCommunityPool{ - Depositor: app.RandomAddress().String(), - Amount: sdk.NewCoins(), - }, - }, - { - name: "invalid - nil coins", - shouldPass: false, - message: types.MsgFundCommunityPool{ - Depositor: app.RandomAddress().String(), - Amount: nil, - }, - }, - { - name: "invalid - zero coins", - shouldPass: false, - message: types.MsgFundCommunityPool{ - Depositor: app.RandomAddress().String(), - Amount: sdk.NewCoins( - sdk.NewCoin("ukava", sdk.ZeroInt()), - ), - }, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.message.ValidateBasic() - if tc.shouldPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } -} - -func TestMsgUpdateParams_ValidateBasic(t *testing.T) { - testCases := []struct { - name string - message types.MsgUpdateParams - expectedErr error - }{ - { - name: "valid message", - message: types.NewMsgUpdateParams(app.RandomAddress(), types.DefaultParams()), - expectedErr: nil, - }, - { - name: "invalid - bad authority", - message: types.MsgUpdateParams{ - Authority: "not-an-address", - Params: types.DefaultParams(), - }, - expectedErr: sdkerrors.ErrInvalidAddress, - }, - { - name: "invalid - empty authority", - message: types.MsgUpdateParams{ - Authority: "", - Params: types.DefaultParams(), - }, - expectedErr: sdkerrors.ErrInvalidAddress, - }, - { - name: "invalid - invalid params", - message: types.MsgUpdateParams{ - Authority: app.RandomAddress().String(), - Params: types.Params{}, - }, - expectedErr: types.ErrInvalidParams, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.message.ValidateBasic() - if tc.expectedErr == nil { - require.NoError(t, err) - } else { - require.ErrorIs(t, err, tc.expectedErr) - } - }) - } -} - -func TestFundCommunityPool_GetSigners(t *testing.T) { - t.Run("valid", func(t *testing.T) { - address := app.RandomAddress() - signers := types.MsgFundCommunityPool{ - Depositor: address.String(), - }.GetSigners() - require.Len(t, signers, 1) - require.Equal(t, address, signers[0]) - }) - - t.Run("panics when depositor is invalid", func(t *testing.T) { - require.Panics(t, func() { - types.MsgFundCommunityPool{ - Depositor: "not-an-address", - }.GetSigners() - }) - }) -} - -func TestMsgUpdateParams_GetSigners(t *testing.T) { - t.Run("valid", func(t *testing.T) { - address := app.RandomAddress() - signers := types.MsgUpdateParams{ - Authority: address.String(), - }.GetSigners() - require.Len(t, signers, 1) - require.Equal(t, address, signers[0]) - }) - - t.Run("panics when depositor is invalid", func(t *testing.T) { - require.Panics(t, func() { - types.MsgUpdateParams{ - Authority: "not-an-address", - }.GetSigners() - }) - }) -} diff --git a/x/community/types/params.go b/x/community/types/params.go deleted file mode 100644 index f6fd1aef..00000000 --- a/x/community/types/params.go +++ /dev/null @@ -1,65 +0,0 @@ -package types - -import ( - fmt "fmt" - "time" - - sdkmath "cosmossdk.io/math" -) - -var ( - DefaultUpgradeTimeDisableInflation = time.Time{} - // DefaultStakingRewardsPerSecond is zero and should be set by genesis or upgrade - DefaultStakingRewardsPerSecond = sdkmath.LegacyNewDec(0) - // DefaultStakingRewardsPerSecond is zero and should be set by genesis or upgrade - DefaultUpgradeTimeSetStakingRewardsPerSecond = sdkmath.LegacyNewDec(0) -) - -// NewParams returns a new params object -func NewParams( - upgradeTime time.Time, - stakingRewardsPerSecond sdkmath.LegacyDec, - upgradeTimeSetstakingRewardsPerSecond sdkmath.LegacyDec, -) Params { - return Params{ - UpgradeTimeDisableInflation: upgradeTime, - StakingRewardsPerSecond: stakingRewardsPerSecond, - UpgradeTimeSetStakingRewardsPerSecond: upgradeTimeSetstakingRewardsPerSecond, - } -} - -// DefaultParams returns default params -func DefaultParams() Params { - return NewParams( - DefaultUpgradeTimeDisableInflation, - DefaultStakingRewardsPerSecond, - DefaultUpgradeTimeSetStakingRewardsPerSecond, - ) -} - -// Validate checks the params are valid -func (p Params) Validate() error { - // p.UpgradeTimeDisableInflation.IsZero() is a valid state. It's taken to mean inflation will be disabled on the block 1. - - if err := validateDecNotNilNonNegative(p.StakingRewardsPerSecond, "StakingRewardsPerSecond"); err != nil { - return err - } - - if err := validateDecNotNilNonNegative(p.UpgradeTimeSetStakingRewardsPerSecond, "UpgradeTimeSetStakingRewardsPerSecond"); err != nil { - return err - } - - return nil -} - -func validateDecNotNilNonNegative(value sdkmath.LegacyDec, name string) error { - if value.IsNil() { - return fmt.Errorf("%s should not be nil", name) - } - - if value.IsNegative() { - return fmt.Errorf("%s should not be negative: %s", name, value) - } - - return nil -} diff --git a/x/community/types/params.pb.go b/x/community/types/params.pb.go deleted file mode 100644 index d84bf309..00000000 --- a/x/community/types/params.pb.go +++ /dev/null @@ -1,468 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/community/v1beta1/params.proto - -package types - -import ( - cosmossdk_io_math "cosmossdk.io/math" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 of the community module. -type Params struct { - // upgrade_time_disable_inflation is the time at which to disable mint and kavadist module inflation. - // If set to 0, inflation will be disabled from block 1. - UpgradeTimeDisableInflation time.Time `protobuf:"bytes,1,opt,name=upgrade_time_disable_inflation,json=upgradeTimeDisableInflation,proto3,stdtime" json:"upgrade_time_disable_inflation"` - // staking_rewards_per_second is the amount paid out to delegators each block from the community account - StakingRewardsPerSecond cosmossdk_io_math.LegacyDec `protobuf:"bytes,2,opt,name=staking_rewards_per_second,json=stakingRewardsPerSecond,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"staking_rewards_per_second"` - // upgrade_time_set_staking_rewards_per_second is the initial staking_rewards_per_second to set - // and use when the disable inflation time is reached - UpgradeTimeSetStakingRewardsPerSecond cosmossdk_io_math.LegacyDec `protobuf:"bytes,3,opt,name=upgrade_time_set_staking_rewards_per_second,json=upgradeTimeSetStakingRewardsPerSecond,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"upgrade_time_set_staking_rewards_per_second"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_0a48475520900507, []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 (m *Params) GetUpgradeTimeDisableInflation() time.Time { - if m != nil { - return m.UpgradeTimeDisableInflation - } - return time.Time{} -} - -func init() { - proto.RegisterType((*Params)(nil), "kava.community.v1beta1.Params") -} - -func init() { - proto.RegisterFile("kava/community/v1beta1/params.proto", fileDescriptor_0a48475520900507) -} - -var fileDescriptor_0a48475520900507 = []byte{ - // 386 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x92, 0x41, 0x4b, 0xe3, 0x40, - 0x14, 0x80, 0x33, 0xdd, 0xa5, 0xec, 0x66, 0x6f, 0x61, 0xd9, 0xad, 0x29, 0x24, 0x45, 0x11, 0x0a, - 0xa5, 0x33, 0x54, 0x6f, 0x1e, 0x4b, 0x3d, 0x08, 0x1e, 0x4a, 0xeb, 0xc9, 0xcb, 0x30, 0x49, 0xa6, - 0xd3, 0xa1, 0x49, 0x26, 0x64, 0x26, 0xd5, 0xfe, 0x08, 0xa1, 0x3f, 0xc1, 0x1f, 0xe1, 0x8f, 0xe8, - 0xb1, 0x78, 0x12, 0x0f, 0x55, 0xda, 0x8b, 0x7f, 0xc1, 0x9b, 0x24, 0x93, 0x4a, 0x05, 0xf1, 0xe0, - 0xed, 0xbd, 0x97, 0x2f, 0xdf, 0xbc, 0x37, 0xf3, 0xcc, 0x83, 0x09, 0x99, 0x12, 0xe4, 0x8b, 0x28, - 0xca, 0x62, 0xae, 0x66, 0x68, 0xda, 0xf1, 0xa8, 0x22, 0x1d, 0x94, 0x90, 0x94, 0x44, 0x12, 0x26, - 0xa9, 0x50, 0xc2, 0xfa, 0x97, 0x43, 0xf0, 0x1d, 0x82, 0x25, 0x64, 0xef, 0xf9, 0x42, 0x46, 0x42, - 0xe2, 0x82, 0x42, 0x3a, 0xd1, 0xbf, 0xd8, 0x7f, 0x99, 0x60, 0x42, 0xd7, 0xf3, 0xa8, 0xac, 0xba, - 0x4c, 0x08, 0x16, 0x52, 0x54, 0x64, 0x5e, 0x36, 0x42, 0x8a, 0x47, 0x54, 0x2a, 0x12, 0x25, 0x1a, - 0xd8, 0x7f, 0xad, 0x98, 0xd5, 0x7e, 0x71, 0xb4, 0xc5, 0x4d, 0x27, 0x4b, 0x58, 0x4a, 0x02, 0x8a, - 0x73, 0x0a, 0x07, 0x5c, 0x12, 0x2f, 0xa4, 0x98, 0xc7, 0xa3, 0x90, 0x28, 0x2e, 0xe2, 0x1a, 0x68, - 0x80, 0xe6, 0x9f, 0x23, 0x1b, 0x6a, 0x29, 0xdc, 0x4a, 0xe1, 0xc5, 0x56, 0xda, 0xfd, 0xb5, 0x58, - 0xb9, 0xc6, 0xfc, 0xc9, 0x05, 0x83, 0x7a, 0xe9, 0xca, 0xbf, 0xf5, 0xb4, 0xe9, 0x6c, 0x2b, 0xb2, - 0x62, 0xd3, 0x96, 0x8a, 0x4c, 0x78, 0xcc, 0x70, 0x4a, 0xaf, 0x48, 0x1a, 0x48, 0x9c, 0xd0, 0x14, - 0x4b, 0xea, 0x8b, 0x38, 0xa8, 0x55, 0x1a, 0xa0, 0xf9, 0xbb, 0xdb, 0xc9, 0x55, 0x8f, 0x2b, 0xb7, - 0xae, 0xc7, 0x94, 0xc1, 0x04, 0x72, 0x81, 0x22, 0xa2, 0xc6, 0xf0, 0x9c, 0x32, 0xe2, 0xcf, 0x7a, - 0xd4, 0xbf, 0xbf, 0x6b, 0x9b, 0xe5, 0x2d, 0xf4, 0xa8, 0x3f, 0xf8, 0x5f, 0x4a, 0x07, 0xda, 0xd9, - 0xa7, 0xe9, 0xb0, 0x30, 0x5a, 0x37, 0xc0, 0x6c, 0x7d, 0x98, 0x4d, 0x52, 0x85, 0xbf, 0xe8, 0xe0, - 0xc7, 0x77, 0x3b, 0x38, 0xdc, 0x99, 0x7a, 0x48, 0xd5, 0xf0, 0xf3, 0x7e, 0x4e, 0x7e, 0xbe, 0xdc, - 0xba, 0xa0, 0x7b, 0xba, 0x58, 0x3b, 0x60, 0xb9, 0x76, 0xc0, 0xf3, 0xda, 0x01, 0xf3, 0x8d, 0x63, - 0x2c, 0x37, 0x8e, 0xf1, 0xb0, 0x71, 0x8c, 0xcb, 0x16, 0xe3, 0x6a, 0x9c, 0x79, 0xf9, 0x06, 0xa0, - 0x7c, 0x15, 0xda, 0x21, 0xf1, 0x64, 0x11, 0xa1, 0xeb, 0x9d, 0xdd, 0x51, 0xb3, 0x84, 0x4a, 0xaf, - 0x5a, 0xbc, 0xc3, 0xf1, 0x5b, 0x00, 0x00, 0x00, 0xff, 0xff, 0x19, 0x03, 0x78, 0xe5, 0x5a, 0x02, - 0x00, 0x00, -} - -func (this *Params) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*Params) - if !ok { - that2, ok := that.(Params) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if !this.UpgradeTimeDisableInflation.Equal(that1.UpgradeTimeDisableInflation) { - return false - } - if !this.StakingRewardsPerSecond.Equal(that1.StakingRewardsPerSecond) { - return false - } - if !this.UpgradeTimeSetStakingRewardsPerSecond.Equal(that1.UpgradeTimeSetStakingRewardsPerSecond) { - return false - } - return true -} -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 - { - size := m.UpgradeTimeSetStakingRewardsPerSecond.Size() - i -= size - if _, err := m.UpgradeTimeSetStakingRewardsPerSecond.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.StakingRewardsPerSecond.Size() - i -= size - if _, err := m.StakingRewardsPerSecond.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.UpgradeTimeDisableInflation, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.UpgradeTimeDisableInflation):]) - if err1 != nil { - return 0, err1 - } - i -= n1 - i = encodeVarintParams(dAtA, i, uint64(n1)) - i-- - dAtA[i] = 0xa - 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 - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.UpgradeTimeDisableInflation) - n += 1 + l + sovParams(uint64(l)) - l = m.StakingRewardsPerSecond.Size() - n += 1 + l + sovParams(uint64(l)) - l = m.UpgradeTimeSetStakingRewardsPerSecond.Size() - n += 1 + l + sovParams(uint64(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 { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UpgradeTimeDisableInflation", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.UpgradeTimeDisableInflation, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StakingRewardsPerSecond", 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 - } - if err := m.StakingRewardsPerSecond.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UpgradeTimeSetStakingRewardsPerSecond", 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 - } - if err := m.UpgradeTimeSetStakingRewardsPerSecond.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - 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/community/types/params_test.go b/x/community/types/params_test.go deleted file mode 100644 index c9017c13..00000000 --- a/x/community/types/params_test.go +++ /dev/null @@ -1,103 +0,0 @@ -package types_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - "github.com/kava-labs/kava/x/community/types" -) - -type paramTestCase struct { - name string - params types.Params - expectedErr string -} - -var paramTestCases = []paramTestCase{ - { - name: "default params are valid", - params: types.DefaultParams(), - expectedErr: "", - }, - { - name: "valid params", - params: types.Params{ - UpgradeTimeDisableInflation: time.Time{}, - StakingRewardsPerSecond: sdkmath.LegacyNewDec(1000), - UpgradeTimeSetStakingRewardsPerSecond: sdkmath.LegacyNewDec(1000), - }, - expectedErr: "", - }, - { - name: "rewards per second are allowed to be zero", - params: types.Params{ - UpgradeTimeDisableInflation: time.Time{}, - StakingRewardsPerSecond: sdkmath.LegacyNewDec(0), - UpgradeTimeSetStakingRewardsPerSecond: sdkmath.LegacyNewDec(1000), - }, - expectedErr: "", - }, - { - name: "nil rewards per second", - params: types.Params{ - UpgradeTimeDisableInflation: time.Time{}, - StakingRewardsPerSecond: sdkmath.LegacyDec{}, - UpgradeTimeSetStakingRewardsPerSecond: sdkmath.LegacyNewDec(1000), - }, - expectedErr: "StakingRewardsPerSecond should not be nil", - }, - { - name: "negative rewards per second", - params: types.Params{ - UpgradeTimeDisableInflation: time.Time{}, - StakingRewardsPerSecond: sdkmath.LegacyNewDec(-5), - UpgradeTimeSetStakingRewardsPerSecond: sdkmath.LegacyNewDec(1000), - }, - expectedErr: "StakingRewardsPerSecond should not be negative", - }, - { - name: "upgrade time set rewards per second are allowed to be zero", - params: types.Params{ - UpgradeTimeDisableInflation: time.Time{}, - StakingRewardsPerSecond: sdkmath.LegacyNewDec(1000), - UpgradeTimeSetStakingRewardsPerSecond: sdkmath.LegacyNewDec(0), - }, - expectedErr: "", - }, - { - name: "nil upgrade time set rewards per second", - params: types.Params{ - UpgradeTimeDisableInflation: time.Time{}, - StakingRewardsPerSecond: sdkmath.LegacyNewDec(1000), - UpgradeTimeSetStakingRewardsPerSecond: sdkmath.LegacyDec{}, - }, - expectedErr: "UpgradeTimeSetStakingRewardsPerSecond should not be nil", - }, - { - name: "upgrade time set negative rewards per second", - params: types.Params{ - UpgradeTimeDisableInflation: time.Time{}, - StakingRewardsPerSecond: sdkmath.LegacyNewDec(1000), - UpgradeTimeSetStakingRewardsPerSecond: sdkmath.LegacyNewDec(-5), - }, - expectedErr: "UpgradeTimeSetStakingRewardsPerSecond should not be negative", - }, -} - -func TestParamsValidate(t *testing.T) { - for _, tc := range paramTestCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.params.Validate() - - if tc.expectedErr == "" { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), tc.expectedErr) - } - }) - } -} diff --git a/x/community/types/proposal.go b/x/community/types/proposal.go deleted file mode 100644 index 9000fc29..00000000 --- a/x/community/types/proposal.go +++ /dev/null @@ -1,259 +0,0 @@ -package types - -import ( - "errors" - fmt "fmt" - "strings" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - govcodec "github.com/cosmos/cosmos-sdk/x/gov/codec" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -const ( - // ProposalTypeCommunityPoolLendDeposit defines the type for a CommunityPoolLendDepositProposal - ProposalTypeCommunityPoolLendDeposit = "CommunityPoolLendDeposit" - // ProposalTypeCommunityPoolLendWithdraw defines the type for a CommunityPoolLendDepositProposal - ProposalTypeCommunityPoolLendWithdraw = "CommunityPoolLendWithdraw" - // ProposalTypeCommunityCDPRepayDebt defines the type for a CommunityCDPRepayDebtProposal - ProposalTypeCommunityCDPRepayDebt = "CommunityCDPRepayDebt" - // ProposalTypeCommunityCDPWithdrawCollateral defines the type for a CommunityCDPWithdrawCollateralProposal - ProposalTypeCommunityCDPWithdrawCollateral = "CommunityCDPWithdrawCollateral" -) - -// Assert CommunityPoolLendDepositProposal implements govtypes.Content at compile-time -var ( - _ govv1beta1.Content = &CommunityPoolLendDepositProposal{} - _ govv1beta1.Content = &CommunityPoolLendWithdrawProposal{} - _ govv1beta1.Content = &CommunityCDPRepayDebtProposal{} - _ govv1beta1.Content = &CommunityCDPWithdrawCollateralProposal{} -) - -func init() { - govv1beta1.RegisterProposalType(ProposalTypeCommunityPoolLendDeposit) - govcodec.ModuleCdc.Amino.RegisterConcrete(&CommunityPoolLendDepositProposal{}, "kava/CommunityPoolLendDepositProposal", nil) - govv1beta1.RegisterProposalType(ProposalTypeCommunityPoolLendWithdraw) - govcodec.ModuleCdc.Amino.RegisterConcrete(&CommunityPoolLendWithdrawProposal{}, "kava/CommunityPoolLendWithdrawProposal", nil) - govv1beta1.RegisterProposalType(ProposalTypeCommunityCDPRepayDebt) - govcodec.ModuleCdc.Amino.RegisterConcrete(&CommunityCDPRepayDebtProposal{}, "kava/CommunityCDPRepayDebtProposal", nil) - govv1beta1.RegisterProposalType(ProposalTypeCommunityCDPWithdrawCollateral) - govcodec.ModuleCdc.Amino.RegisterConcrete(&CommunityCDPWithdrawCollateralProposal{}, "kava/CommunityCDPWithdrawCollateralProposal", nil) -} - -////////////////// -// Lend Proposals -////////////////// - -// NewCommunityPoolLendDepositProposal creates a new community pool deposit proposal. -func NewCommunityPoolLendDepositProposal(title, description string, amount sdk.Coins) *CommunityPoolLendDepositProposal { - return &CommunityPoolLendDepositProposal{ - Title: title, - Description: description, - Amount: amount, - } -} - -// GetTitle returns the title of a community pool lend deposit proposal. -func (p *CommunityPoolLendDepositProposal) GetTitle() string { return p.Title } - -// GetDescription returns the description of a community pool lend deposit proposal. -func (p *CommunityPoolLendDepositProposal) GetDescription() string { return p.Description } - -// GetDescription returns the routing key of a community pool lend deposit proposal. -func (p *CommunityPoolLendDepositProposal) ProposalRoute() string { return ModuleName } - -// ProposalType returns the type of a community pool lend deposit proposal. -func (p *CommunityPoolLendDepositProposal) ProposalType() string { - return ProposalTypeCommunityPoolLendDeposit -} - -// String implements fmt.Stringer -func (p *CommunityPoolLendDepositProposal) String() string { - var b strings.Builder - b.WriteString(fmt.Sprintf(`Community Pool Lend Deposit Proposal: - Title: %s - Description: %s - Amount: %s -`, p.Title, p.Description, p.Amount)) - return b.String() -} - -// ValidateBasic stateless validation of a community pool lend deposit proposal. -func (p *CommunityPoolLendDepositProposal) ValidateBasic() error { - if err := govv1beta1.ValidateAbstract(p); err != nil { - return err - } - // ensure the proposal has valid amount - if !p.Amount.IsValid() || p.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "deposit amount %s", p.Amount) - } - return p.Amount.Validate() -} - -// NewCommunityPoolLendWithdrawProposal creates a new community pool lend withdraw proposal. -func NewCommunityPoolLendWithdrawProposal(title, description string, amount sdk.Coins) *CommunityPoolLendWithdrawProposal { - return &CommunityPoolLendWithdrawProposal{ - Title: title, - Description: description, - Amount: amount, - } -} - -// GetTitle returns the title of a community pool withdraw proposal. -func (p *CommunityPoolLendWithdrawProposal) GetTitle() string { return p.Title } - -// GetDescription returns the description of a community pool withdraw proposal. -func (p *CommunityPoolLendWithdrawProposal) GetDescription() string { return p.Description } - -// GetDescription returns the routing key of a community pool withdraw proposal. -func (p *CommunityPoolLendWithdrawProposal) ProposalRoute() string { return ModuleName } - -// ProposalType returns the type of a community pool withdraw proposal. -func (p *CommunityPoolLendWithdrawProposal) ProposalType() string { - return ProposalTypeCommunityPoolLendWithdraw -} - -// String implements fmt.Stringer -func (p *CommunityPoolLendWithdrawProposal) String() string { - var b strings.Builder - b.WriteString(fmt.Sprintf(`Community Pool Lend Withdraw Proposal: - Title: %s - Description: %s - Amount: %s -`, p.Title, p.Description, p.Amount)) - return b.String() -} - -// ValidateBasic stateless validation of a community pool withdraw proposal. -func (p *CommunityPoolLendWithdrawProposal) ValidateBasic() error { - if err := govv1beta1.ValidateAbstract(p); err != nil { - return err - } - // ensure the proposal has valid amount - if !p.Amount.IsValid() || p.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "withdraw amount %s", p.Amount) - } - return p.Amount.Validate() -} - -///////////////// -// CDP Proposals -///////////////// - -// NewCommunityCDPRepayDebtProposal creates a new community pool cdp debt repay proposal. -func NewCommunityCDPRepayDebtProposal( - title string, - description string, - collateralType string, - payment sdk.Coin, -) *CommunityCDPRepayDebtProposal { - return &CommunityCDPRepayDebtProposal{ - Title: title, - Description: description, - CollateralType: collateralType, - Payment: payment, - } -} - -// GetTitle returns the title of the proposal. -func (p *CommunityCDPRepayDebtProposal) GetTitle() string { return p.Title } - -// GetDescription returns the description of the proposal. -func (p *CommunityCDPRepayDebtProposal) GetDescription() string { return p.Description } - -// GetDescription returns the routing key of the proposal. -func (p *CommunityCDPRepayDebtProposal) ProposalRoute() string { return ModuleName } - -// ProposalType returns the type of the proposal. -func (p *CommunityCDPRepayDebtProposal) ProposalType() string { - return ProposalTypeCommunityCDPRepayDebt -} - -// String implements fmt.Stringer -func (p *CommunityCDPRepayDebtProposal) String() string { - var b strings.Builder - b.WriteString(fmt.Sprintf(`Community CDP Repay Debt Proposal: - Title: %s - Description: %s - Collateral Type: %s - Payment: %s -`, p.Title, p.Description, p.CollateralType, p.Payment)) - return b.String() -} - -// ValidateBasic stateless validation of the proposal. -func (p *CommunityCDPRepayDebtProposal) ValidateBasic() error { - if err := govv1beta1.ValidateAbstract(p); err != nil { - return err - } - // ensure collateral type is set - if strings.TrimSpace(p.CollateralType) == "" { - return errors.New("cdp collateral type cannot be blank") - } - // ensure the proposal has payment amount - if !p.Payment.IsValid() || p.Payment.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "payment amount %s", p.Payment) - } - return nil -} - -// NewCommunityCDPRepayDebtProposal creates a new community pool cdp debt repay proposal. -func NewCommunityCDPWithdrawCollateralProposal( - title string, - description string, - collateralType string, - collateral sdk.Coin, -) *CommunityCDPWithdrawCollateralProposal { - return &CommunityCDPWithdrawCollateralProposal{ - Title: title, - Description: description, - CollateralType: collateralType, - Collateral: collateral, - } -} - -// GetTitle returns the title of the proposal. -func (p *CommunityCDPWithdrawCollateralProposal) GetTitle() string { return p.Title } - -// GetDescription returns the description of the proposal. -func (p *CommunityCDPWithdrawCollateralProposal) GetDescription() string { return p.Description } - -// GetDescription returns the routing key of the proposal. -func (p *CommunityCDPWithdrawCollateralProposal) ProposalRoute() string { return ModuleName } - -// ProposalType returns the type of the proposal. -func (p *CommunityCDPWithdrawCollateralProposal) ProposalType() string { - return ProposalTypeCommunityCDPWithdrawCollateral -} - -// String implements fmt.Stringer -func (p *CommunityCDPWithdrawCollateralProposal) String() string { - var b strings.Builder - b.WriteString(fmt.Sprintf(`Community CDP Withdraw Collateral Proposal: - Title: %s - Description: %s - Collateral Type: %s - Collateral: %s -`, p.Title, p.Description, p.CollateralType, p.Collateral)) - return b.String() -} - -// ValidateBasic stateless validation of the proposal. -func (p *CommunityCDPWithdrawCollateralProposal) ValidateBasic() error { - if err := govv1beta1.ValidateAbstract(p); err != nil { - return err - } - - // ensure collateral type is set - if strings.TrimSpace(p.CollateralType) == "" { - return errors.New("cdp collateral type cannot be blank") - } - - // ensure the proposal has collateral amount - if !p.Collateral.IsValid() || p.Collateral.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "collateral amount %s", p.Collateral) - } - return nil -} diff --git a/x/community/types/proposal.pb.go b/x/community/types/proposal.pb.go deleted file mode 100644 index 81c9f67d..00000000 --- a/x/community/types/proposal.pb.go +++ /dev/null @@ -1,1288 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/community/v1beta1/proposal.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 - -// CommunityPoolLendDepositProposal deposits from the community pool into lend -type CommunityPoolLendDepositProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *CommunityPoolLendDepositProposal) Reset() { *m = CommunityPoolLendDepositProposal{} } -func (*CommunityPoolLendDepositProposal) ProtoMessage() {} -func (*CommunityPoolLendDepositProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_64aa83b2ed448ec1, []int{0} -} -func (m *CommunityPoolLendDepositProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolLendDepositProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolLendDepositProposal.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 *CommunityPoolLendDepositProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolLendDepositProposal.Merge(m, src) -} -func (m *CommunityPoolLendDepositProposal) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolLendDepositProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolLendDepositProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolLendDepositProposal proto.InternalMessageInfo - -// CommunityPoolLendWithdrawProposal withdraws a lend position back to the community pool -type CommunityPoolLendWithdrawProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *CommunityPoolLendWithdrawProposal) Reset() { *m = CommunityPoolLendWithdrawProposal{} } -func (*CommunityPoolLendWithdrawProposal) ProtoMessage() {} -func (*CommunityPoolLendWithdrawProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_64aa83b2ed448ec1, []int{1} -} -func (m *CommunityPoolLendWithdrawProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolLendWithdrawProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolLendWithdrawProposal.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 *CommunityPoolLendWithdrawProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolLendWithdrawProposal.Merge(m, src) -} -func (m *CommunityPoolLendWithdrawProposal) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolLendWithdrawProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolLendWithdrawProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolLendWithdrawProposal proto.InternalMessageInfo - -// CommunityCDPRepayDebtProposal repays a cdp debt position owned by the community module -// This proposal exists primarily to allow committees to repay community module cdp debts. -type CommunityCDPRepayDebtProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - CollateralType string `protobuf:"bytes,3,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Payment types.Coin `protobuf:"bytes,4,opt,name=payment,proto3" json:"payment"` -} - -func (m *CommunityCDPRepayDebtProposal) Reset() { *m = CommunityCDPRepayDebtProposal{} } -func (*CommunityCDPRepayDebtProposal) ProtoMessage() {} -func (*CommunityCDPRepayDebtProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_64aa83b2ed448ec1, []int{2} -} -func (m *CommunityCDPRepayDebtProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityCDPRepayDebtProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityCDPRepayDebtProposal.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 *CommunityCDPRepayDebtProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityCDPRepayDebtProposal.Merge(m, src) -} -func (m *CommunityCDPRepayDebtProposal) XXX_Size() int { - return m.Size() -} -func (m *CommunityCDPRepayDebtProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityCDPRepayDebtProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityCDPRepayDebtProposal proto.InternalMessageInfo - -// CommunityCDPWithdrawCollateralProposal withdraws cdp collateral owned by the community module -// This proposal exists primarily to allow committees to withdraw community module cdp collateral. -type CommunityCDPWithdrawCollateralProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - CollateralType string `protobuf:"bytes,3,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Collateral types.Coin `protobuf:"bytes,4,opt,name=collateral,proto3" json:"collateral"` -} - -func (m *CommunityCDPWithdrawCollateralProposal) Reset() { - *m = CommunityCDPWithdrawCollateralProposal{} -} -func (*CommunityCDPWithdrawCollateralProposal) ProtoMessage() {} -func (*CommunityCDPWithdrawCollateralProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_64aa83b2ed448ec1, []int{3} -} -func (m *CommunityCDPWithdrawCollateralProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityCDPWithdrawCollateralProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityCDPWithdrawCollateralProposal.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 *CommunityCDPWithdrawCollateralProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityCDPWithdrawCollateralProposal.Merge(m, src) -} -func (m *CommunityCDPWithdrawCollateralProposal) XXX_Size() int { - return m.Size() -} -func (m *CommunityCDPWithdrawCollateralProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityCDPWithdrawCollateralProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityCDPWithdrawCollateralProposal proto.InternalMessageInfo - -func init() { - proto.RegisterType((*CommunityPoolLendDepositProposal)(nil), "kava.community.v1beta1.CommunityPoolLendDepositProposal") - proto.RegisterType((*CommunityPoolLendWithdrawProposal)(nil), "kava.community.v1beta1.CommunityPoolLendWithdrawProposal") - proto.RegisterType((*CommunityCDPRepayDebtProposal)(nil), "kava.community.v1beta1.CommunityCDPRepayDebtProposal") - proto.RegisterType((*CommunityCDPWithdrawCollateralProposal)(nil), "kava.community.v1beta1.CommunityCDPWithdrawCollateralProposal") -} - -func init() { - proto.RegisterFile("kava/community/v1beta1/proposal.proto", fileDescriptor_64aa83b2ed448ec1) -} - -var fileDescriptor_64aa83b2ed448ec1 = []byte{ - // 419 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x93, 0x3f, 0x0b, 0xd3, 0x40, - 0x18, 0xc6, 0x73, 0xb6, 0x56, 0xbd, 0x82, 0x42, 0x28, 0x12, 0x0b, 0x26, 0xb1, 0xa0, 0x16, 0xa4, - 0x39, 0xab, 0x93, 0x2e, 0x42, 0x53, 0x37, 0x87, 0x12, 0x04, 0xc1, 0x45, 0x2e, 0xc9, 0xd1, 0x1e, - 0x4d, 0xf2, 0x1e, 0xb9, 0x6b, 0x35, 0xdf, 0xc0, 0xd1, 0xd1, 0xb1, 0xb3, 0xdf, 0x43, 0xa8, 0x4e, - 0x1d, 0x1c, 0x9c, 0x54, 0xda, 0x2f, 0x22, 0xf9, 0xdb, 0x80, 0x20, 0x82, 0x20, 0x38, 0xe5, 0xcd, - 0x7b, 0xcf, 0x7b, 0xf7, 0xfc, 0x78, 0x78, 0xf1, 0xed, 0x35, 0xdd, 0x52, 0x12, 0x40, 0x1c, 0x6f, - 0x12, 0xae, 0x32, 0xb2, 0x9d, 0xfa, 0x4c, 0xd1, 0x29, 0x11, 0x29, 0x08, 0x90, 0x34, 0x72, 0x44, - 0x0a, 0x0a, 0xf4, 0xeb, 0xb9, 0xcc, 0x69, 0x64, 0x4e, 0x25, 0x1b, 0x9a, 0x01, 0xc8, 0x18, 0x24, - 0xf1, 0xa9, 0x64, 0xcd, 0x6c, 0x00, 0x3c, 0x29, 0xe7, 0x86, 0x83, 0x25, 0x2c, 0xa1, 0x28, 0x49, - 0x5e, 0x95, 0xdd, 0xd1, 0x27, 0x84, 0x6d, 0xb7, 0xbe, 0x6b, 0x01, 0x10, 0x3d, 0x63, 0x49, 0x38, - 0x67, 0x02, 0x24, 0x57, 0x8b, 0xea, 0x61, 0x7d, 0x80, 0x2f, 0x2a, 0xae, 0x22, 0x66, 0x20, 0x1b, - 0x8d, 0xaf, 0x78, 0xe5, 0x8f, 0x6e, 0xe3, 0x7e, 0xc8, 0x64, 0x90, 0x72, 0xa1, 0x38, 0x24, 0xc6, - 0x85, 0xe2, 0xac, 0xdd, 0xd2, 0x03, 0xdc, 0xa3, 0x31, 0x6c, 0x12, 0x65, 0x74, 0xec, 0xce, 0xb8, - 0xff, 0xe0, 0x86, 0x53, 0x7a, 0x74, 0x72, 0x8f, 0xb5, 0x71, 0xc7, 0x05, 0x9e, 0xcc, 0xee, 0xef, - 0xbf, 0x59, 0xda, 0x87, 0xef, 0xd6, 0x78, 0xc9, 0xd5, 0x6a, 0xe3, 0xe7, 0x7c, 0xa4, 0x02, 0x2a, - 0x3f, 0x13, 0x19, 0xae, 0x89, 0xca, 0x04, 0x93, 0xc5, 0x80, 0xf4, 0xaa, 0xab, 0x1f, 0x5f, 0x7e, - 0xbb, 0xb3, 0xb4, 0xf7, 0x3b, 0x4b, 0x1b, 0x7d, 0x46, 0xf8, 0xd6, 0x2f, 0x2c, 0x2f, 0xb8, 0x5a, - 0x85, 0x29, 0x7d, 0xfd, 0xbf, 0xc1, 0x7c, 0x44, 0xf8, 0x66, 0x03, 0xe3, 0xce, 0x17, 0x1e, 0x13, - 0x34, 0x9b, 0x33, 0xff, 0xef, 0x53, 0xb9, 0x8b, 0xaf, 0x05, 0x10, 0x45, 0x54, 0xb1, 0x94, 0x46, - 0xaf, 0x72, 0x17, 0x46, 0xa7, 0x50, 0x5d, 0x3d, 0xb7, 0x9f, 0x67, 0x82, 0xe9, 0x8f, 0xf0, 0x25, - 0x41, 0xb3, 0x98, 0x25, 0xca, 0xe8, 0xda, 0xe8, 0xf7, 0xc8, 0xdd, 0x1c, 0xd9, 0xab, 0xf5, 0x2d, - 0x8e, 0x2f, 0x08, 0xdf, 0x69, 0x73, 0xd4, 0x79, 0xb8, 0xcd, 0x5b, 0xff, 0x0e, 0xe8, 0x09, 0xc6, - 0xe7, 0xce, 0x9f, 0x32, 0xb5, 0x46, 0xce, 0x58, 0xb3, 0xa7, 0xfb, 0xa3, 0x89, 0x0e, 0x47, 0x13, - 0xfd, 0x38, 0x9a, 0xe8, 0xdd, 0xc9, 0xd4, 0x0e, 0x27, 0x53, 0xfb, 0x7a, 0x32, 0xb5, 0x97, 0xf7, - 0x5a, 0xa1, 0xe7, 0xab, 0x3a, 0x89, 0xa8, 0x2f, 0x8b, 0x8a, 0xbc, 0x69, 0x6d, 0x77, 0x91, 0xbe, - 0xdf, 0x2b, 0xb6, 0xf0, 0xe1, 0xcf, 0x00, 0x00, 0x00, 0xff, 0xff, 0xef, 0x58, 0xb9, 0x21, 0xfc, - 0x03, 0x00, 0x00, -} - -func (m *CommunityPoolLendDepositProposal) 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 *CommunityPoolLendDepositProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolLendDepositProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CommunityPoolLendWithdrawProposal) 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 *CommunityPoolLendWithdrawProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolLendWithdrawProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CommunityCDPRepayDebtProposal) 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 *CommunityCDPRepayDebtProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityCDPRepayDebtProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Payment.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintProposal(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CommunityCDPWithdrawCollateralProposal) 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 *CommunityCDPWithdrawCollateralProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityCDPWithdrawCollateralProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Collateral.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintProposal(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintProposal(dAtA []byte, offset int, v uint64) int { - offset -= sovProposal(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *CommunityPoolLendDepositProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func (m *CommunityPoolLendWithdrawProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func (m *CommunityCDPRepayDebtProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = m.Payment.Size() - n += 1 + l + sovProposal(uint64(l)) - return n -} - -func (m *CommunityCDPWithdrawCollateralProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = m.Collateral.Size() - n += 1 + l + sovProposal(uint64(l)) - return n -} - -func sovProposal(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozProposal(x uint64) (n int) { - return sovProposal(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *CommunityPoolLendDepositProposal) 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 ErrIntOverflowProposal - } - 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: CommunityPoolLendDepositProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolLendDepositProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityPoolLendWithdrawProposal) 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 ErrIntOverflowProposal - } - 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: CommunityPoolLendWithdrawProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolLendWithdrawProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityCDPRepayDebtProposal) 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 ErrIntOverflowProposal - } - 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: CommunityCDPRepayDebtProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityCDPRepayDebtProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Payment", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Payment.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityCDPWithdrawCollateralProposal) 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 ErrIntOverflowProposal - } - 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: CommunityCDPWithdrawCollateralProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityCDPWithdrawCollateralProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Collateral", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Collateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipProposal(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, ErrIntOverflowProposal - } - 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, ErrIntOverflowProposal - } - 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, ErrIntOverflowProposal - } - 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, ErrInvalidLengthProposal - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupProposal - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthProposal - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthProposal = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowProposal = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupProposal = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/community/types/proposal_test.go b/x/community/types/proposal_test.go deleted file mode 100644 index 384fcf53..00000000 --- a/x/community/types/proposal_test.go +++ /dev/null @@ -1,330 +0,0 @@ -package types_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/kava-labs/kava/x/community/types" -) - -func TestLendProposals_ValidateBasic(t *testing.T) { - // each proposalData is tested with Deposit and Withdraw proposals - type proposalData struct { - Title string - Description string - Amount sdk.Coins - } - testCases := []struct { - name string - proposal proposalData - expectedErr string - }{ - { - name: "valid proposal", - proposal: proposalData{ - Title: "I'm a lend proposal", - Description: "I interact with lend", - Amount: sdk.NewCoins(sdk.NewInt64Coin("ukava", 1e10)), - }, - expectedErr: "", - }, - { - name: "invalid - fails gov validation", - proposal: proposalData{ - Description: "I have no title.", - }, - expectedErr: "invalid proposal content", - }, - { - name: "invalid - nil coins", - proposal: proposalData{ - Title: "Error profoundly", - Description: "My coins are nil", - Amount: nil, - }, - expectedErr: "invalid coins", - }, - { - name: "invalid - empty coins", - proposal: proposalData{ - Title: "Error profoundly", - Description: "My coins are empty", - Amount: sdk.NewCoins(), - }, - expectedErr: "invalid coins", - }, - { - name: "invalid - zero coins", - proposal: proposalData{ - Title: "Error profoundly", - Description: "My coins are zero", - Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdk.ZeroInt())), - }, - expectedErr: "invalid coins", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - t.Run("CommunityPoolLendDepositProposal", func(t *testing.T) { - deposit := types.NewCommunityPoolLendDepositProposal( - tc.proposal.Title, - tc.proposal.Description, - tc.proposal.Amount, - ) - err := deposit.ValidateBasic() - if tc.expectedErr != "" { - require.ErrorContains(t, err, tc.expectedErr) - return - } - - require.NoError(t, err) - require.Equal(t, deposit.Title, deposit.GetTitle()) - require.Equal(t, deposit.Description, deposit.GetDescription()) - require.Equal(t, types.ModuleName, deposit.ProposalRoute()) - require.Equal(t, types.ProposalTypeCommunityPoolLendDeposit, deposit.ProposalType()) - }) - - t.Run("CommunityPoolLendWithdrawProposal", func(t *testing.T) { - withdrawl := types.NewCommunityPoolLendWithdrawProposal( - tc.proposal.Title, - tc.proposal.Description, - tc.proposal.Amount, - ) - err := withdrawl.ValidateBasic() - if tc.expectedErr != "" { - require.ErrorContains(t, err, tc.expectedErr) - return - } - - require.NoError(t, err) - require.Equal(t, withdrawl.Title, withdrawl.GetTitle()) - require.Equal(t, withdrawl.Description, withdrawl.GetDescription()) - require.Equal(t, types.ModuleName, withdrawl.ProposalRoute()) - require.Equal(t, types.ProposalTypeCommunityPoolLendWithdraw, withdrawl.ProposalType()) - }) - }) - } -} - -func TestCommunityPoolLendDepositProposal_Stringer(t *testing.T) { - proposal := types.NewCommunityPoolLendDepositProposal( - "Title", - "Description", - sdk.NewCoins(sdk.NewInt64Coin("ukava", 42)), - ) - require.Equal(t, `Community Pool Lend Deposit Proposal: - Title: Title - Description: Description - Amount: 42ukava -`, proposal.String()) -} - -func TestCommunityPoolLendWithdrawProposal_Stringer(t *testing.T) { - proposal := types.NewCommunityPoolLendWithdrawProposal( - "Title", - "Description", - sdk.NewCoins(sdk.NewInt64Coin("ukava", 42)), - ) - require.Equal(t, `Community Pool Lend Withdraw Proposal: - Title: Title - Description: Description - Amount: 42ukava -`, proposal.String()) -} - -func TestCommunityCDPRepayDebtProposal_ValidateBasic(t *testing.T) { - type proposalData struct { - Title string - Description string - CollateralType string - Payment sdk.Coin - } - testCases := []struct { - name string - proposal proposalData - expectedErr string - }{ - { - name: "valid proposal", - proposal: proposalData{ - Title: "Repay my debt plz", - Description: "I interact with cdp", - CollateralType: "type-a", - Payment: sdk.NewInt64Coin("ukava", 1e6), - }, - expectedErr: "", - }, - { - name: "invalid - fails gov validation", - proposal: proposalData{ - Description: "I have no title.", - }, - expectedErr: "invalid proposal content", - }, - { - name: "invalid - empty collateral type", - proposal: proposalData{ - Title: "Error profoundly", - Description: "I have no collateral type", - }, - expectedErr: "collateral type cannot be blank", - }, - { - name: "invalid - empty coins", - proposal: proposalData{ - Title: "Error profoundly", - Description: "My coins are empty", - CollateralType: "type-a", - Payment: sdk.Coin{}, - }, - expectedErr: "invalid coins", - }, - { - name: "invalid - zero coins", - proposal: proposalData{ - Title: "Error profoundly", - Description: "My coins are zero", - CollateralType: "type-a", - Payment: sdk.NewInt64Coin("ukava", 0), - }, - expectedErr: "invalid coins", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - repayDebt := types.NewCommunityCDPRepayDebtProposal( - tc.proposal.Title, - tc.proposal.Description, - tc.proposal.CollateralType, - tc.proposal.Payment, - ) - err := repayDebt.ValidateBasic() - if tc.expectedErr != "" { - require.ErrorContains(t, err, tc.expectedErr) - return - } - - require.NoError(t, err) - require.Equal(t, repayDebt.Title, repayDebt.GetTitle()) - require.Equal(t, repayDebt.Description, repayDebt.GetDescription()) - require.Equal(t, types.ModuleName, repayDebt.ProposalRoute()) - require.Equal(t, types.ProposalTypeCommunityCDPRepayDebt, repayDebt.ProposalType()) - }) - } -} - -func TestCommunityCDPRepayDebtProposal_Stringer(t *testing.T) { - proposal := types.NewCommunityCDPRepayDebtProposal( - "title", - "description", - "collateral-type", - sdk.NewInt64Coin("ukava", 42), - ) - require.Equal(t, `Community CDP Repay Debt Proposal: - Title: title - Description: description - Collateral Type: collateral-type - Payment: 42ukava -`, proposal.String()) -} - -func TestCommunityCDPWithdrawCollateralProposal_ValidateBasic(t *testing.T) { - type proposalData struct { - Title string - Description string - CollateralType string - Collateral sdk.Coin - } - testCases := []struct { - name string - proposal proposalData - expectedErr string - }{ - { - name: "valid proposal", - proposal: proposalData{ - Title: "withdraw my collateral plz", - Description: "I interact with cdp", - CollateralType: "type-a", - Collateral: sdk.NewInt64Coin("ukava", 1e6), - }, - expectedErr: "", - }, - { - name: "invalid - fails gov validation", - proposal: proposalData{ - Description: "I have no title.", - }, - expectedErr: "invalid proposal content", - }, - { - name: "invalid - empty collateral type", - proposal: proposalData{ - Title: "Error profoundly", - Description: "I have no collateral type", - }, - expectedErr: "collateral type cannot be blank", - }, - { - name: "invalid - empty coins", - proposal: proposalData{ - Title: "Error profoundly", - Description: "My coins are empty", - CollateralType: "type-a", - Collateral: sdk.Coin{}, - }, - expectedErr: "invalid coins", - }, - { - name: "invalid - zero coins", - proposal: proposalData{ - Title: "Error profoundly", - Description: "My coins are zero", - CollateralType: "type-a", - Collateral: sdk.NewInt64Coin("ukava", 0), - }, - expectedErr: "invalid coins", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - repayDebt := types.NewCommunityCDPWithdrawCollateralProposal( - tc.proposal.Title, - tc.proposal.Description, - tc.proposal.CollateralType, - tc.proposal.Collateral, - ) - err := repayDebt.ValidateBasic() - if tc.expectedErr != "" { - require.ErrorContains(t, err, tc.expectedErr) - return - } - - require.NoError(t, err) - require.Equal(t, repayDebt.Title, repayDebt.GetTitle()) - require.Equal(t, repayDebt.Description, repayDebt.GetDescription()) - require.Equal(t, types.ModuleName, repayDebt.ProposalRoute()) - require.Equal(t, types.ProposalTypeCommunityCDPWithdrawCollateral, repayDebt.ProposalType()) - }) - } -} - -func TestCommunityCDPWithdrawCollateralProposal_Stringer(t *testing.T) { - proposal := types.NewCommunityCDPWithdrawCollateralProposal( - "title", - "description", - "collateral-type", - sdk.NewInt64Coin("ukava", 42), - ) - require.Equal(t, `Community CDP Withdraw Collateral Proposal: - Title: title - Description: description - Collateral Type: collateral-type - Collateral: 42ukava -`, proposal.String()) -} diff --git a/x/community/types/query.pb.go b/x/community/types/query.pb.go deleted file mode 100644 index c1451fd4..00000000 --- a/x/community/types/query.pb.go +++ /dev/null @@ -1,1573 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/community/v1beta1/query.proto - -package types - -import ( - context "context" - cosmossdk_io_math "cosmossdk.io/math" - 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" - 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 - -// QueryParams defines the request type for querying x/community params. -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_f236f06c43149273, []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 defines the response type for querying x/community params. -type QueryParamsResponse struct { - // params represents the community module parameters - 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_f236f06c43149273, []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{} -} - -// QueryBalanceRequest defines the request type for querying x/community balance. -type QueryBalanceRequest struct { -} - -func (m *QueryBalanceRequest) Reset() { *m = QueryBalanceRequest{} } -func (m *QueryBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*QueryBalanceRequest) ProtoMessage() {} -func (*QueryBalanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_f236f06c43149273, []int{2} -} -func (m *QueryBalanceRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryBalanceRequest.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 *QueryBalanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryBalanceRequest.Merge(m, src) -} -func (m *QueryBalanceRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryBalanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryBalanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryBalanceRequest proto.InternalMessageInfo - -// QueryBalanceResponse defines the response type for querying x/community balance. -type QueryBalanceResponse struct { - Coins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=coins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"coins"` -} - -func (m *QueryBalanceResponse) Reset() { *m = QueryBalanceResponse{} } -func (m *QueryBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*QueryBalanceResponse) ProtoMessage() {} -func (*QueryBalanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_f236f06c43149273, []int{3} -} -func (m *QueryBalanceResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryBalanceResponse.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 *QueryBalanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryBalanceResponse.Merge(m, src) -} -func (m *QueryBalanceResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryBalanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryBalanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryBalanceResponse proto.InternalMessageInfo - -func (m *QueryBalanceResponse) GetCoins() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Coins - } - return nil -} - -// QueryTotalBalanceRequest defines the request type for querying total community pool balance. -type QueryTotalBalanceRequest struct { -} - -func (m *QueryTotalBalanceRequest) Reset() { *m = QueryTotalBalanceRequest{} } -func (m *QueryTotalBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalBalanceRequest) ProtoMessage() {} -func (*QueryTotalBalanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_f236f06c43149273, []int{4} -} -func (m *QueryTotalBalanceRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalBalanceRequest.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 *QueryTotalBalanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalBalanceRequest.Merge(m, src) -} -func (m *QueryTotalBalanceRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalBalanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalBalanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalBalanceRequest proto.InternalMessageInfo - -// QueryTotalBalanceResponse defines the response type for querying total -// community pool balance. This matches the x/distribution CommunityPool query response. -type QueryTotalBalanceResponse struct { - // pool defines community pool's coins. - Pool github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,1,rep,name=pool,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"pool"` -} - -func (m *QueryTotalBalanceResponse) Reset() { *m = QueryTotalBalanceResponse{} } -func (m *QueryTotalBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalBalanceResponse) ProtoMessage() {} -func (*QueryTotalBalanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_f236f06c43149273, []int{5} -} -func (m *QueryTotalBalanceResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalBalanceResponse.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 *QueryTotalBalanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalBalanceResponse.Merge(m, src) -} -func (m *QueryTotalBalanceResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalBalanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalBalanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalBalanceResponse proto.InternalMessageInfo - -func (m *QueryTotalBalanceResponse) GetPool() github_com_cosmos_cosmos_sdk_types.DecCoins { - if m != nil { - return m.Pool - } - return nil -} - -// QueryAnnualizedRewardsRequest defines the request type for querying the annualized rewards. -type QueryAnnualizedRewardsRequest struct { -} - -func (m *QueryAnnualizedRewardsRequest) Reset() { *m = QueryAnnualizedRewardsRequest{} } -func (m *QueryAnnualizedRewardsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAnnualizedRewardsRequest) ProtoMessage() {} -func (*QueryAnnualizedRewardsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_f236f06c43149273, []int{6} -} -func (m *QueryAnnualizedRewardsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAnnualizedRewardsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAnnualizedRewardsRequest.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 *QueryAnnualizedRewardsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAnnualizedRewardsRequest.Merge(m, src) -} -func (m *QueryAnnualizedRewardsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryAnnualizedRewardsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAnnualizedRewardsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAnnualizedRewardsRequest proto.InternalMessageInfo - -// QueryAnnualizedRewardsResponse defines the response type for querying the annualized rewards. -type QueryAnnualizedRewardsResponse struct { - // staking_rewards is the calculated annualized staking rewards percentage rate - StakingRewards cosmossdk_io_math.LegacyDec `protobuf:"bytes,1,opt,name=staking_rewards,json=stakingRewards,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"staking_rewards"` -} - -func (m *QueryAnnualizedRewardsResponse) Reset() { *m = QueryAnnualizedRewardsResponse{} } -func (m *QueryAnnualizedRewardsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAnnualizedRewardsResponse) ProtoMessage() {} -func (*QueryAnnualizedRewardsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_f236f06c43149273, []int{7} -} -func (m *QueryAnnualizedRewardsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAnnualizedRewardsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAnnualizedRewardsResponse.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 *QueryAnnualizedRewardsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAnnualizedRewardsResponse.Merge(m, src) -} -func (m *QueryAnnualizedRewardsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryAnnualizedRewardsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAnnualizedRewardsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAnnualizedRewardsResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.community.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.community.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryBalanceRequest)(nil), "kava.community.v1beta1.QueryBalanceRequest") - proto.RegisterType((*QueryBalanceResponse)(nil), "kava.community.v1beta1.QueryBalanceResponse") - proto.RegisterType((*QueryTotalBalanceRequest)(nil), "kava.community.v1beta1.QueryTotalBalanceRequest") - proto.RegisterType((*QueryTotalBalanceResponse)(nil), "kava.community.v1beta1.QueryTotalBalanceResponse") - proto.RegisterType((*QueryAnnualizedRewardsRequest)(nil), "kava.community.v1beta1.QueryAnnualizedRewardsRequest") - proto.RegisterType((*QueryAnnualizedRewardsResponse)(nil), "kava.community.v1beta1.QueryAnnualizedRewardsResponse") -} - -func init() { - proto.RegisterFile("kava/community/v1beta1/query.proto", fileDescriptor_f236f06c43149273) -} - -var fileDescriptor_f236f06c43149273 = []byte{ - // 606 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0x31, 0x6f, 0xd3, 0x40, - 0x14, 0xc7, 0x63, 0x68, 0x8b, 0xb8, 0x22, 0x10, 0x47, 0x40, 0x8d, 0x29, 0x4e, 0x31, 0x82, 0x46, - 0x6d, 0x63, 0x37, 0xa9, 0x60, 0x62, 0x21, 0x84, 0x8d, 0x01, 0x0c, 0x53, 0x97, 0xe8, 0xec, 0x9c, - 0x5c, 0x2b, 0x8e, 0xcf, 0xcd, 0x5d, 0x0a, 0x41, 0x2c, 0x74, 0x63, 0x40, 0x42, 0xe2, 0x1b, 0x30, - 0x32, 0x23, 0x3e, 0x43, 0xc7, 0x0a, 0x16, 0xc4, 0x50, 0x50, 0xc2, 0x07, 0x41, 0x77, 0xf7, 0x12, - 0x25, 0x34, 0x8e, 0xd2, 0x29, 0xf1, 0xbb, 0xf7, 0x7f, 0xff, 0xdf, 0xbd, 0xf7, 0x6c, 0x64, 0xb7, - 0xc8, 0x01, 0x71, 0x03, 0xd6, 0x6e, 0x77, 0x93, 0x48, 0xf4, 0xdc, 0x83, 0x8a, 0x4f, 0x05, 0xa9, - 0xb8, 0xfb, 0x5d, 0xda, 0xe9, 0x39, 0x69, 0x87, 0x09, 0x86, 0x6f, 0xc8, 0x1c, 0x67, 0x94, 0xe3, - 0x40, 0x8e, 0x69, 0x05, 0x8c, 0xb7, 0x19, 0x77, 0x7d, 0xc2, 0xe9, 0x48, 0x18, 0xb0, 0x28, 0xd1, - 0x3a, 0xb3, 0xa0, 0xcf, 0x1b, 0xea, 0xc9, 0xd5, 0x0f, 0x70, 0x94, 0x0f, 0x59, 0xc8, 0x74, 0x5c, - 0xfe, 0x83, 0xe8, 0x6a, 0xc8, 0x58, 0x18, 0x53, 0x97, 0xa4, 0x91, 0x4b, 0x92, 0x84, 0x09, 0x22, - 0x22, 0x96, 0x0c, 0x35, 0x77, 0x32, 0x50, 0x53, 0xd2, 0x21, 0x6d, 0x48, 0xb2, 0xf3, 0x08, 0x3f, - 0x97, 0xe8, 0xcf, 0x54, 0xd0, 0xa3, 0xfb, 0x5d, 0xca, 0x85, 0xfd, 0x02, 0x5d, 0x9b, 0x88, 0xf2, - 0x94, 0x25, 0x9c, 0xe2, 0x87, 0x68, 0x49, 0x8b, 0x57, 0x8c, 0x35, 0xa3, 0xb4, 0x5c, 0xb5, 0x9c, - 0xe9, 0x37, 0x75, 0xb4, 0xae, 0xb6, 0x70, 0x74, 0x52, 0xcc, 0x79, 0xa0, 0xb1, 0xaf, 0x43, 0xd1, - 0x1a, 0x89, 0x49, 0x12, 0xd0, 0xa1, 0x57, 0x0f, 0xe5, 0x27, 0xc3, 0x60, 0x46, 0xd0, 0xa2, 0xec, - 0x8d, 0xf4, 0x3a, 0x5f, 0x5a, 0xae, 0x16, 0x1c, 0x68, 0x88, 0xec, 0xde, 0xc8, 0xe8, 0x31, 0x8b, - 0x92, 0xda, 0xb6, 0xb4, 0xf9, 0xf2, 0xbb, 0x58, 0x0a, 0x23, 0xb1, 0xd7, 0xf5, 0x25, 0x0f, 0x74, - 0x0f, 0x7e, 0xca, 0xbc, 0xd9, 0x72, 0x45, 0x2f, 0xa5, 0x5c, 0x09, 0xb8, 0xa7, 0x2b, 0xdb, 0x26, - 0x5a, 0x51, 0xd6, 0x2f, 0x99, 0x20, 0xf1, 0x7f, 0x58, 0x87, 0x06, 0x2a, 0x4c, 0x39, 0x04, 0x38, - 0x8a, 0x16, 0x52, 0xc6, 0x62, 0x60, 0x5b, 0x9d, 0xca, 0x56, 0xa7, 0x81, 0xc2, 0xdb, 0x01, 0xbc, - 0xcd, 0x39, 0xf0, 0x40, 0xc3, 0x3d, 0x55, 0xde, 0x2e, 0xa2, 0x5b, 0x8a, 0xe1, 0x51, 0x92, 0x74, - 0x49, 0x1c, 0xbd, 0xa1, 0x4d, 0x8f, 0xbe, 0x22, 0x9d, 0xe6, 0x68, 0x50, 0x6f, 0x91, 0x95, 0x95, - 0x00, 0xa4, 0xbb, 0xe8, 0x0a, 0x17, 0xa4, 0x15, 0x25, 0x61, 0xa3, 0xa3, 0x8f, 0xd4, 0xf0, 0x2e, - 0xd6, 0x2a, 0x12, 0xeb, 0xd7, 0x49, 0xf1, 0xa6, 0x86, 0xe0, 0xcd, 0x96, 0x13, 0x31, 0xb7, 0x4d, - 0xc4, 0x9e, 0xf3, 0x94, 0x86, 0x24, 0xe8, 0xd5, 0x69, 0xf0, 0xfd, 0x6b, 0x19, 0xc1, 0xd5, 0xea, - 0x34, 0xf0, 0x2e, 0x43, 0x25, 0xf0, 0xa8, 0xbe, 0x5b, 0x44, 0x8b, 0xca, 0x1e, 0xbf, 0x37, 0xd0, - 0x92, 0x1e, 0x3a, 0xde, 0xc8, 0x5a, 0x8a, 0xd3, 0x7b, 0x66, 0x6e, 0xce, 0x95, 0xab, 0x6f, 0x62, - 0xdf, 0x3b, 0xfc, 0xf1, 0xf7, 0xd3, 0xb9, 0x35, 0x6c, 0xb9, 0x33, 0x17, 0x1b, 0x7f, 0x30, 0xd0, - 0x05, 0x98, 0x17, 0x9e, 0x6d, 0x30, 0x39, 0x72, 0x73, 0x6b, 0xbe, 0x64, 0xc0, 0x59, 0x57, 0x38, - 0xb7, 0x71, 0x31, 0x0b, 0xc7, 0x07, 0x86, 0xcf, 0x06, 0xba, 0x34, 0xbe, 0x44, 0x78, 0x7b, 0xa6, - 0xcf, 0x94, 0x65, 0x34, 0x2b, 0x67, 0x50, 0x00, 0x5e, 0x59, 0xe1, 0xad, 0xe3, 0xbb, 0x59, 0x78, - 0x42, 0xaa, 0x1a, 0x43, 0xc8, 0x6f, 0x06, 0xba, 0x7a, 0x6a, 0x89, 0xf0, 0xfd, 0x99, 0xbe, 0x59, - 0x5b, 0x69, 0x3e, 0x38, 0xab, 0x0c, 0x98, 0xab, 0x8a, 0x79, 0x0b, 0x6f, 0x64, 0x31, 0x93, 0x91, - 0x74, 0xb8, 0xcc, 0xb5, 0x27, 0x47, 0x7d, 0xcb, 0x38, 0xee, 0x5b, 0xc6, 0x9f, 0xbe, 0x65, 0x7c, - 0x1c, 0x58, 0xb9, 0xe3, 0x81, 0x95, 0xfb, 0x39, 0xb0, 0x72, 0xbb, 0xe3, 0xef, 0x9b, 0xac, 0x57, - 0x8e, 0x89, 0xcf, 0x75, 0xe5, 0xd7, 0x63, 0xb5, 0xd5, 0x8b, 0xe7, 0x2f, 0xa9, 0xcf, 0xe1, 0xce, - 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x2e, 0xb3, 0x12, 0x9f, 0xe0, 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 { - // Params queires the module params. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Balance queries the balance of all coins of x/community module. - Balance(ctx context.Context, in *QueryBalanceRequest, opts ...grpc.CallOption) (*QueryBalanceResponse, error) - // TotalBalance queries the balance of all coins, including x/distribution, - // x/community, and supplied balances. - TotalBalance(ctx context.Context, in *QueryTotalBalanceRequest, opts ...grpc.CallOption) (*QueryTotalBalanceResponse, error) - // AnnualizedRewards calculates and returns the current annualized reward percentages, - // like staking rewards, for the chain. - AnnualizedRewards(ctx context.Context, in *QueryAnnualizedRewardsRequest, opts ...grpc.CallOption) (*QueryAnnualizedRewardsResponse, 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, "/kava.community.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Balance(ctx context.Context, in *QueryBalanceRequest, opts ...grpc.CallOption) (*QueryBalanceResponse, error) { - out := new(QueryBalanceResponse) - err := c.cc.Invoke(ctx, "/kava.community.v1beta1.Query/Balance", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalBalance(ctx context.Context, in *QueryTotalBalanceRequest, opts ...grpc.CallOption) (*QueryTotalBalanceResponse, error) { - out := new(QueryTotalBalanceResponse) - err := c.cc.Invoke(ctx, "/kava.community.v1beta1.Query/TotalBalance", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) AnnualizedRewards(ctx context.Context, in *QueryAnnualizedRewardsRequest, opts ...grpc.CallOption) (*QueryAnnualizedRewardsResponse, error) { - out := new(QueryAnnualizedRewardsResponse) - err := c.cc.Invoke(ctx, "/kava.community.v1beta1.Query/AnnualizedRewards", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queires the module params. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Balance queries the balance of all coins of x/community module. - Balance(context.Context, *QueryBalanceRequest) (*QueryBalanceResponse, error) - // TotalBalance queries the balance of all coins, including x/distribution, - // x/community, and supplied balances. - TotalBalance(context.Context, *QueryTotalBalanceRequest) (*QueryTotalBalanceResponse, error) - // AnnualizedRewards calculates and returns the current annualized reward percentages, - // like staking rewards, for the chain. - AnnualizedRewards(context.Context, *QueryAnnualizedRewardsRequest) (*QueryAnnualizedRewardsResponse, 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) Balance(ctx context.Context, req *QueryBalanceRequest) (*QueryBalanceResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Balance not implemented") -} -func (*UnimplementedQueryServer) TotalBalance(ctx context.Context, req *QueryTotalBalanceRequest) (*QueryTotalBalanceResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalBalance not implemented") -} -func (*UnimplementedQueryServer) AnnualizedRewards(ctx context.Context, req *QueryAnnualizedRewardsRequest) (*QueryAnnualizedRewardsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method AnnualizedRewards 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: "/kava.community.v1beta1.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_Balance_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryBalanceRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Balance(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.community.v1beta1.Query/Balance", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Balance(ctx, req.(*QueryBalanceRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalBalance_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalBalanceRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalBalance(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.community.v1beta1.Query/TotalBalance", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalBalance(ctx, req.(*QueryTotalBalanceRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_AnnualizedRewards_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAnnualizedRewardsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).AnnualizedRewards(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.community.v1beta1.Query/AnnualizedRewards", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).AnnualizedRewards(ctx, req.(*QueryAnnualizedRewardsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.community.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Balance", - Handler: _Query_Balance_Handler, - }, - { - MethodName: "TotalBalance", - Handler: _Query_TotalBalance_Handler, - }, - { - MethodName: "AnnualizedRewards", - Handler: _Query_AnnualizedRewards_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/community/v1beta1/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 *QueryBalanceRequest) 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 *QueryBalanceRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryBalanceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryBalanceResponse) 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 *QueryBalanceResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryBalanceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Coins) > 0 { - for iNdEx := len(m.Coins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Coins[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 (m *QueryTotalBalanceRequest) 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 *QueryTotalBalanceRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalBalanceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryTotalBalanceResponse) 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 *QueryTotalBalanceResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalBalanceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Pool) > 0 { - for iNdEx := len(m.Pool) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Pool[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 (m *QueryAnnualizedRewardsRequest) 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 *QueryAnnualizedRewardsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAnnualizedRewardsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryAnnualizedRewardsResponse) 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 *QueryAnnualizedRewardsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAnnualizedRewardsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.StakingRewards.Size() - i -= size - if _, err := m.StakingRewards.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - 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 *QueryBalanceRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryBalanceResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Coins) > 0 { - for _, e := range m.Coins { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryTotalBalanceRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryTotalBalanceResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Pool) > 0 { - for _, e := range m.Pool { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryAnnualizedRewardsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryAnnualizedRewardsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.StakingRewards.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 *QueryBalanceRequest) 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: QueryBalanceRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryBalanceRequest: 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 *QueryBalanceResponse) 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: QueryBalanceResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryBalanceResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Coins", 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.Coins = append(m.Coins, types.Coin{}) - if err := m.Coins[len(m.Coins)-1].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 *QueryTotalBalanceRequest) 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: QueryTotalBalanceRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalBalanceRequest: 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 *QueryTotalBalanceResponse) 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: QueryTotalBalanceResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalBalanceResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pool", 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.Pool = append(m.Pool, types.DecCoin{}) - if err := m.Pool[len(m.Pool)-1].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 *QueryAnnualizedRewardsRequest) 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: QueryAnnualizedRewardsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAnnualizedRewardsRequest: 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 *QueryAnnualizedRewardsResponse) 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: QueryAnnualizedRewardsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAnnualizedRewardsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StakingRewards", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.StakingRewards.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/community/types/query.pb.gw.go b/x/community/types/query.pb.gw.go deleted file mode 100644 index 289b1988..00000000 --- a/x/community/types/query.pb.gw.go +++ /dev/null @@ -1,348 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/community/v1beta1/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_Balance_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryBalanceRequest - var metadata runtime.ServerMetadata - - msg, err := client.Balance(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Balance_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryBalanceRequest - var metadata runtime.ServerMetadata - - msg, err := server.Balance(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_TotalBalance_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalBalanceRequest - var metadata runtime.ServerMetadata - - msg, err := client.TotalBalance(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalBalance_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalBalanceRequest - var metadata runtime.ServerMetadata - - msg, err := server.TotalBalance(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_AnnualizedRewards_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAnnualizedRewardsRequest - var metadata runtime.ServerMetadata - - msg, err := client.AnnualizedRewards(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_AnnualizedRewards_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAnnualizedRewardsRequest - var metadata runtime.ServerMetadata - - msg, err := server.AnnualizedRewards(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_Balance_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_Balance_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_Balance_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalBalance_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_TotalBalance_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_TotalBalance_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_AnnualizedRewards_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_AnnualizedRewards_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_AnnualizedRewards_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_Balance_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_Balance_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_Balance_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalBalance_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_TotalBalance_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_TotalBalance_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_AnnualizedRewards_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_AnnualizedRewards_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_AnnualizedRewards_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{"kava", "community", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Balance_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "community", "v1beta1", "balance"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalBalance_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "community", "v1beta1", "total_balance"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_AnnualizedRewards_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "community", "v1beta1", "annualized_rewards"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Balance_0 = runtime.ForwardResponseMessage - - forward_Query_TotalBalance_0 = runtime.ForwardResponseMessage - - forward_Query_AnnualizedRewards_0 = runtime.ForwardResponseMessage -) diff --git a/x/community/types/staking.go b/x/community/types/staking.go deleted file mode 100644 index 4f37222d..00000000 --- a/x/community/types/staking.go +++ /dev/null @@ -1,51 +0,0 @@ -package types - -import ( - "errors" - "time" - - sdkmath "cosmossdk.io/math" -) - -var ( - // DefaultLastAccumulationTime is zero - DefaultLastAccumulationTime = time.Time{} - // DefaultLastTruncationError is zero - DefaultLastTruncationError = sdkmath.LegacyZeroDec() -) - -// NewStakingRewardsState returns a new staking rewards state object -func NewStakingRewardsState( - lastAccumulationTime time.Time, - lastTruncationError sdkmath.LegacyDec, -) StakingRewardsState { - return StakingRewardsState{ - LastAccumulationTime: lastAccumulationTime, - LastTruncationError: lastTruncationError, - } -} - -// DefaultStakingRewardsState returns default params -func DefaultStakingRewardsState() StakingRewardsState { - return NewStakingRewardsState( - DefaultLastAccumulationTime, - DefaultLastTruncationError, - ) -} - -// Validate checks the params are valid -func (p StakingRewardsState) Validate() error { - if err := validateDecNotNilNonNegative(p.LastTruncationError, "LastTruncationError"); err != nil { - return err - } - - if p.LastTruncationError.GTE(sdkmath.LegacyOneDec()) { - return errors.New("LastTruncationError should not be greater or equal to 1") - } - - if p.LastAccumulationTime.IsZero() && !p.LastTruncationError.IsZero() { - return errors.New("LastTruncationError should be zero if last accumulation time is zero") - } - - return nil -} diff --git a/x/community/types/staking.pb.go b/x/community/types/staking.pb.go deleted file mode 100644 index 8b803366..00000000 --- a/x/community/types/staking.pb.go +++ /dev/null @@ -1,386 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/community/v1beta1/staking.proto - -package types - -import ( - cosmossdk_io_math "cosmossdk.io/math" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 - -// StakingRewardsState represents the state of staking reward accumulation between blocks. -type StakingRewardsState struct { - // last_accumulation_time represents the last block time which rewards where calculated and distributed. - // This may be zero to signal accumulation should start on the next interval. - LastAccumulationTime time.Time `protobuf:"bytes,1,opt,name=last_accumulation_time,json=lastAccumulationTime,proto3,stdtime" json:"last_accumulation_time"` - // accumulated_truncation_error represents the sum of previous errors due to truncation on payout - // This value will always be on the interval [0, 1). - LastTruncationError cosmossdk_io_math.LegacyDec `protobuf:"bytes,2,opt,name=last_truncation_error,json=lastTruncationError,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"last_truncation_error"` -} - -func (m *StakingRewardsState) Reset() { *m = StakingRewardsState{} } -func (m *StakingRewardsState) String() string { return proto.CompactTextString(m) } -func (*StakingRewardsState) ProtoMessage() {} -func (*StakingRewardsState) Descriptor() ([]byte, []int) { - return fileDescriptor_fce59dad9b680fa3, []int{0} -} -func (m *StakingRewardsState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *StakingRewardsState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_StakingRewardsState.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 *StakingRewardsState) XXX_Merge(src proto.Message) { - xxx_messageInfo_StakingRewardsState.Merge(m, src) -} -func (m *StakingRewardsState) XXX_Size() int { - return m.Size() -} -func (m *StakingRewardsState) XXX_DiscardUnknown() { - xxx_messageInfo_StakingRewardsState.DiscardUnknown(m) -} - -var xxx_messageInfo_StakingRewardsState proto.InternalMessageInfo - -func (m *StakingRewardsState) GetLastAccumulationTime() time.Time { - if m != nil { - return m.LastAccumulationTime - } - return time.Time{} -} - -func init() { - proto.RegisterType((*StakingRewardsState)(nil), "kava.community.v1beta1.StakingRewardsState") -} - -func init() { - proto.RegisterFile("kava/community/v1beta1/staking.proto", fileDescriptor_fce59dad9b680fa3) -} - -var fileDescriptor_fce59dad9b680fa3 = []byte{ - // 331 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x91, 0x31, 0x6e, 0x2a, 0x31, - 0x10, 0x86, 0xd7, 0xaf, 0x78, 0x7a, 0x6f, 0xd3, 0x01, 0x41, 0x84, 0x48, 0xbb, 0x28, 0x4a, 0x81, - 0x14, 0x61, 0x8b, 0xe4, 0x04, 0x41, 0xd0, 0xa5, 0x02, 0x2a, 0x1a, 0x34, 0x6b, 0x1c, 0xb3, 0x62, - 0xbd, 0x46, 0xeb, 0x59, 0x12, 0x6e, 0xc1, 0x61, 0x72, 0x08, 0x4a, 0x94, 0x0a, 0xa5, 0x20, 0x11, - 0x5c, 0x24, 0xf2, 0x1a, 0x10, 0xdd, 0xcc, 0xe8, 0x9b, 0xcf, 0xfa, 0xc7, 0xfe, 0xfd, 0x0c, 0x16, - 0xc0, 0xb8, 0x56, 0x2a, 0x4f, 0x63, 0x5c, 0xb2, 0x45, 0x3b, 0x12, 0x08, 0x6d, 0x66, 0x10, 0x66, - 0x71, 0x2a, 0xe9, 0x3c, 0xd3, 0xa8, 0x4b, 0x55, 0x4b, 0xd1, 0x33, 0x45, 0x8f, 0x54, 0xfd, 0x86, - 0x6b, 0xa3, 0xb4, 0x19, 0x17, 0x14, 0x73, 0x8d, 0x5b, 0xa9, 0x57, 0xa4, 0x96, 0xda, 0xcd, 0x6d, - 0x75, 0x9c, 0x86, 0x52, 0x6b, 0x99, 0x08, 0x56, 0x74, 0x51, 0xfe, 0xca, 0x30, 0x56, 0xc2, 0x20, - 0xa8, 0xb9, 0x03, 0xee, 0xb6, 0xc4, 0x2f, 0x0f, 0xdc, 0xdb, 0x7d, 0xf1, 0x06, 0xd9, 0xc4, 0x0c, - 0x10, 0x50, 0x94, 0x46, 0x7e, 0x35, 0x01, 0x83, 0x63, 0xe0, 0x3c, 0x57, 0x79, 0x02, 0x18, 0xeb, - 0x74, 0x6c, 0x97, 0x6b, 0xa4, 0x41, 0x9a, 0x57, 0x8f, 0x75, 0xea, 0xcc, 0xf4, 0x64, 0xa6, 0xc3, - 0x93, 0xb9, 0xf3, 0x6f, 0xbd, 0x0b, 0xbd, 0xd5, 0x77, 0x48, 0xfa, 0x15, 0xeb, 0x78, 0xbe, 0x50, - 0x58, 0xa8, 0x24, 0xfc, 0xeb, 0xc2, 0x8d, 0x59, 0x9e, 0x72, 0x67, 0x16, 0x59, 0xa6, 0xb3, 0xda, - 0x9f, 0x06, 0x69, 0xfe, 0xef, 0xb4, 0xed, 0xfa, 0xd7, 0x2e, 0xbc, 0x75, 0xf9, 0xcc, 0x64, 0x46, - 0x63, 0xcd, 0x14, 0xe0, 0x94, 0xbe, 0x08, 0x09, 0x7c, 0xd9, 0x15, 0xfc, 0xf3, 0xa3, 0xe5, 0x1f, - 0xe3, 0x77, 0x05, 0xef, 0x97, 0xad, 0x6f, 0x78, 0xd6, 0xf5, 0xac, 0xad, 0xd3, 0x5b, 0xef, 0x03, - 0xb2, 0xd9, 0x07, 0xe4, 0x67, 0x1f, 0x90, 0xd5, 0x21, 0xf0, 0x36, 0x87, 0xc0, 0xdb, 0x1e, 0x02, - 0x6f, 0xf4, 0x20, 0x63, 0x9c, 0xe6, 0x91, 0x3d, 0x30, 0xb3, 0x97, 0x6e, 0x25, 0x10, 0x99, 0xa2, - 0x62, 0xef, 0x17, 0x7f, 0x83, 0xcb, 0xb9, 0x30, 0xd1, 0xdf, 0x22, 0xe1, 0xd3, 0x6f, 0x00, 0x00, - 0x00, 0xff, 0xff, 0x98, 0xd8, 0x77, 0x55, 0xba, 0x01, 0x00, 0x00, -} - -func (m *StakingRewardsState) 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 *StakingRewardsState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *StakingRewardsState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.LastTruncationError.Size() - i -= size - if _, err := m.LastTruncationError.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintStaking(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.LastAccumulationTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.LastAccumulationTime):]) - if err1 != nil { - return 0, err1 - } - i -= n1 - i = encodeVarintStaking(dAtA, i, uint64(n1)) - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintStaking(dAtA []byte, offset int, v uint64) int { - offset -= sovStaking(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *StakingRewardsState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.LastAccumulationTime) - n += 1 + l + sovStaking(uint64(l)) - l = m.LastTruncationError.Size() - n += 1 + l + sovStaking(uint64(l)) - return n -} - -func sovStaking(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozStaking(x uint64) (n int) { - return sovStaking(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *StakingRewardsState) 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 ErrIntOverflowStaking - } - 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: StakingRewardsState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: StakingRewardsState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LastAccumulationTime", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStaking - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthStaking - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthStaking - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.LastAccumulationTime, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LastTruncationError", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStaking - } - 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 ErrInvalidLengthStaking - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthStaking - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.LastTruncationError.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipStaking(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthStaking - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipStaking(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, ErrIntOverflowStaking - } - 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, ErrIntOverflowStaking - } - 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, ErrIntOverflowStaking - } - 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, ErrInvalidLengthStaking - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupStaking - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthStaking - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthStaking = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowStaking = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupStaking = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/community/types/staking_test.go b/x/community/types/staking_test.go deleted file mode 100644 index 20e83128..00000000 --- a/x/community/types/staking_test.go +++ /dev/null @@ -1,105 +0,0 @@ -package types_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - "github.com/kava-labs/kava/x/community/types" -) - -type stakingRewardsStateTestCase struct { - name string - stakingRewardsState types.StakingRewardsState - expectedErr string -} - -var stakingRewardsStateTestCases = []stakingRewardsStateTestCase{ - { - name: "default stakingRewardsState are valid", - stakingRewardsState: types.DefaultStakingRewardsState(), - expectedErr: "", - }, - { - name: "valid example state", - stakingRewardsState: types.StakingRewardsState{ - LastAccumulationTime: time.Now(), - LastTruncationError: newDecFromString("0.10000000000000000"), - }, - expectedErr: "", - }, - { - name: "last accumulation time can be zero", - stakingRewardsState: types.StakingRewardsState{ - LastAccumulationTime: time.Time{}, - LastTruncationError: sdkmath.LegacyZeroDec(), - }, - expectedErr: "", - }, - { - name: "nil last truncation error is invalid", - stakingRewardsState: types.StakingRewardsState{ - LastAccumulationTime: time.Now(), - LastTruncationError: sdkmath.LegacyDec{}, - }, - expectedErr: "LastTruncationError should not be nil", - }, - { - name: "negative last truncation error is invalid", - stakingRewardsState: types.StakingRewardsState{ - LastAccumulationTime: time.Now(), - LastTruncationError: newDecFromString("-0.10000000000000000"), - }, - expectedErr: "LastTruncationError should not be negative", - }, - { - name: "last truncation error equal to 1 is invalid", - stakingRewardsState: types.StakingRewardsState{ - LastAccumulationTime: time.Now(), - LastTruncationError: newDecFromString("1.00000000000000000"), - }, - expectedErr: "LastTruncationError should not be greater or equal to 1", - }, - { - name: "last truncation error greater than 1 is invalid", - stakingRewardsState: types.StakingRewardsState{ - LastAccumulationTime: time.Now(), - LastTruncationError: newDecFromString("1.00000000000000000"), - }, - expectedErr: "LastTruncationError should not be greater or equal to 1", - }, - { - name: "last truncation error can not be set if last accumulation time is zero", - stakingRewardsState: types.StakingRewardsState{ - LastAccumulationTime: time.Time{}, - LastTruncationError: newDecFromString("0.10000000000000000"), - }, - expectedErr: "LastTruncationError should be zero if last accumulation time is zero", - }, -} - -func TestStakingRewardsStateValidate(t *testing.T) { - for _, tc := range stakingRewardsStateTestCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.stakingRewardsState.Validate() - - if tc.expectedErr == "" { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), tc.expectedErr) - } - }) - } -} - -// newDecFromString returns a new sdkmath.Int from a string -func newDecFromString(str string) sdkmath.LegacyDec { - num, err := sdkmath.LegacyNewDecFromStr(str) - if err != nil { - panic(err) - } - return num -} diff --git a/x/community/types/tx.pb.go b/x/community/types/tx.pb.go deleted file mode 100644 index 96e55333..00000000 --- a/x/community/types/tx.pb.go +++ /dev/null @@ -1,1064 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/community/v1beta1/tx.proto - -package types - -import ( - context "context" - 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" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - 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 - -// MsgFundCommunityPool allows an account to directly fund the community module account. -type MsgFundCommunityPool struct { - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` - Depositor string `protobuf:"bytes,2,opt,name=depositor,proto3" json:"depositor,omitempty"` -} - -func (m *MsgFundCommunityPool) Reset() { *m = MsgFundCommunityPool{} } -func (m *MsgFundCommunityPool) String() string { return proto.CompactTextString(m) } -func (*MsgFundCommunityPool) ProtoMessage() {} -func (*MsgFundCommunityPool) Descriptor() ([]byte, []int) { - return fileDescriptor_e81067e0fbdaca18, []int{0} -} -func (m *MsgFundCommunityPool) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgFundCommunityPool) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgFundCommunityPool.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 *MsgFundCommunityPool) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgFundCommunityPool.Merge(m, src) -} -func (m *MsgFundCommunityPool) XXX_Size() int { - return m.Size() -} -func (m *MsgFundCommunityPool) XXX_DiscardUnknown() { - xxx_messageInfo_MsgFundCommunityPool.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgFundCommunityPool proto.InternalMessageInfo - -// MsgFundCommunityPoolResponse defines the Msg/FundCommunityPool response type. -type MsgFundCommunityPoolResponse struct { -} - -func (m *MsgFundCommunityPoolResponse) Reset() { *m = MsgFundCommunityPoolResponse{} } -func (m *MsgFundCommunityPoolResponse) String() string { return proto.CompactTextString(m) } -func (*MsgFundCommunityPoolResponse) ProtoMessage() {} -func (*MsgFundCommunityPoolResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_e81067e0fbdaca18, []int{1} -} -func (m *MsgFundCommunityPoolResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgFundCommunityPoolResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgFundCommunityPoolResponse.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 *MsgFundCommunityPoolResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgFundCommunityPoolResponse.Merge(m, src) -} -func (m *MsgFundCommunityPoolResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgFundCommunityPoolResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgFundCommunityPoolResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgFundCommunityPoolResponse proto.InternalMessageInfo - -// MsgUpdateParams allows an account to update the community module parameters. -type MsgUpdateParams struct { - // authority is the address that controls the module (defaults to x/gov unless overwritten). - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - // params defines the x/community parameters to update. - Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` -} - -func (m *MsgUpdateParams) Reset() { *m = MsgUpdateParams{} } -func (m *MsgUpdateParams) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateParams) ProtoMessage() {} -func (*MsgUpdateParams) Descriptor() ([]byte, []int) { - return fileDescriptor_e81067e0fbdaca18, []int{2} -} -func (m *MsgUpdateParams) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgUpdateParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateParams.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 *MsgUpdateParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateParams.Merge(m, src) -} -func (m *MsgUpdateParams) XXX_Size() int { - return m.Size() -} -func (m *MsgUpdateParams) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateParams.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateParams proto.InternalMessageInfo - -// MsgUpdateParamsResponse defines the Msg/UpdateParams response type. -type MsgUpdateParamsResponse struct { -} - -func (m *MsgUpdateParamsResponse) Reset() { *m = MsgUpdateParamsResponse{} } -func (m *MsgUpdateParamsResponse) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateParamsResponse) ProtoMessage() {} -func (*MsgUpdateParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_e81067e0fbdaca18, []int{3} -} -func (m *MsgUpdateParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgUpdateParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateParamsResponse.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 *MsgUpdateParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateParamsResponse.Merge(m, src) -} -func (m *MsgUpdateParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgUpdateParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateParamsResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgFundCommunityPool)(nil), "kava.community.v1beta1.MsgFundCommunityPool") - proto.RegisterType((*MsgFundCommunityPoolResponse)(nil), "kava.community.v1beta1.MsgFundCommunityPoolResponse") - proto.RegisterType((*MsgUpdateParams)(nil), "kava.community.v1beta1.MsgUpdateParams") - proto.RegisterType((*MsgUpdateParamsResponse)(nil), "kava.community.v1beta1.MsgUpdateParamsResponse") -} - -func init() { proto.RegisterFile("kava/community/v1beta1/tx.proto", fileDescriptor_e81067e0fbdaca18) } - -var fileDescriptor_e81067e0fbdaca18 = []byte{ - // 446 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x92, 0xcd, 0xaa, 0xd3, 0x40, - 0x14, 0xc7, 0x33, 0xde, 0x4b, 0xe1, 0xce, 0x15, 0xc4, 0x50, 0x34, 0x0d, 0x32, 0xb9, 0xd4, 0x85, - 0x05, 0x6d, 0xc6, 0x5b, 0xc5, 0x85, 0xb8, 0x31, 0x05, 0xc1, 0x45, 0xa1, 0x44, 0xdc, 0xb8, 0x91, - 0x49, 0x32, 0xa4, 0xa1, 0x4d, 0x4e, 0xc8, 0x4c, 0x6a, 0xfb, 0x06, 0x6e, 0x04, 0x1f, 0xc1, 0xa5, - 0xb8, 0x76, 0xe3, 0x1b, 0x74, 0x59, 0x5c, 0xb9, 0x52, 0x49, 0x37, 0x3e, 0x86, 0x24, 0x99, 0xd4, - 0xaa, 0xad, 0x1f, 0xab, 0xf9, 0xfa, 0x9f, 0xf3, 0xff, 0x9d, 0x33, 0x07, 0x5b, 0x53, 0x36, 0x67, - 0xd4, 0x87, 0x38, 0xce, 0x93, 0x48, 0x2e, 0xe9, 0xfc, 0xdc, 0xe3, 0x92, 0x9d, 0x53, 0xb9, 0xb0, - 0xd3, 0x0c, 0x24, 0xe8, 0x57, 0x4a, 0x81, 0xbd, 0x15, 0xd8, 0x4a, 0x60, 0x12, 0x1f, 0x44, 0x0c, - 0x82, 0x7a, 0x4c, 0xf0, 0x6d, 0x94, 0x0f, 0x51, 0x52, 0xc7, 0x99, 0x9d, 0xfa, 0xfd, 0x79, 0x75, - 0xa2, 0xf5, 0x41, 0x3d, 0xb5, 0x43, 0x08, 0xa1, 0xbe, 0x2f, 0x77, 0xea, 0xf6, 0xfa, 0x01, 0x92, - 0x94, 0x65, 0x2c, 0x56, 0xa1, 0xdd, 0x0f, 0x08, 0xb7, 0x47, 0x22, 0x7c, 0x94, 0x27, 0xc1, 0xb0, - 0x51, 0x8e, 0x01, 0x66, 0xba, 0x8f, 0x5b, 0x2c, 0x86, 0x3c, 0x91, 0x06, 0x3a, 0x3b, 0xea, 0x9d, - 0x0e, 0x3a, 0xb6, 0xb2, 0x2c, 0xf9, 0x1a, 0x68, 0x7b, 0x08, 0x51, 0xe2, 0xdc, 0x5e, 0x7d, 0xb6, - 0xb4, 0x77, 0x5f, 0xac, 0x5e, 0x18, 0xc9, 0x49, 0xee, 0x95, 0xb5, 0x29, 0x3e, 0xb5, 0xf4, 0x45, - 0x30, 0xa5, 0x72, 0x99, 0x72, 0x51, 0x05, 0x08, 0x57, 0xa5, 0xd6, 0xef, 0xe1, 0x93, 0x80, 0xa7, - 0x20, 0x22, 0x09, 0x99, 0x71, 0xe1, 0x0c, 0xf5, 0x4e, 0x1c, 0xe3, 0xe3, 0xfb, 0x7e, 0x5b, 0x59, - 0x3d, 0x0c, 0x82, 0x8c, 0x0b, 0xf1, 0x44, 0x66, 0x51, 0x12, 0xba, 0x3f, 0xa4, 0xf7, 0x8f, 0x5f, - 0xbe, 0xb1, 0xb4, 0x2e, 0xc1, 0xd7, 0xf6, 0xa1, 0xbb, 0x5c, 0xa4, 0x90, 0x08, 0xde, 0x7d, 0x85, - 0xf0, 0xa5, 0x91, 0x08, 0x9f, 0xa6, 0x01, 0x93, 0x7c, 0x5c, 0x55, 0x5d, 0x3a, 0xb2, 0x5c, 0x4e, - 0x20, 0x8b, 0xe4, 0xd2, 0x40, 0x7f, 0x73, 0xdc, 0x4a, 0xf5, 0x07, 0xb8, 0x55, 0xf7, 0xad, 0xc2, - 0x3c, 0x1d, 0x10, 0x7b, 0xff, 0x37, 0xda, 0xb5, 0x8f, 0x73, 0x5c, 0xf6, 0xc4, 0x55, 0x31, 0x8a, - 0xb7, 0x83, 0xaf, 0xfe, 0x82, 0xd3, 0xa0, 0x0e, 0xbe, 0x21, 0x7c, 0x34, 0x12, 0xa1, 0xfe, 0x02, - 0x5f, 0xfe, 0xfd, 0x2b, 0x6e, 0x1d, 0xf2, 0xda, 0x57, 0xbd, 0x79, 0xf7, 0x7f, 0xd4, 0x0d, 0x80, - 0x3e, 0xc1, 0x17, 0x7f, 0xea, 0xd3, 0x8d, 0x3f, 0x64, 0xd9, 0x15, 0x9a, 0xf4, 0x1f, 0x85, 0x8d, - 0x93, 0xf3, 0xf8, 0x6d, 0x41, 0xd0, 0xaa, 0x20, 0x68, 0x5d, 0x10, 0xf4, 0xb5, 0x20, 0xe8, 0xf5, - 0x86, 0x68, 0xeb, 0x0d, 0xd1, 0x3e, 0x6d, 0x88, 0xf6, 0xec, 0xe6, 0xce, 0x0c, 0x95, 0x89, 0xfb, - 0x33, 0xe6, 0x89, 0x6a, 0x47, 0x17, 0x3b, 0xb3, 0x5c, 0x0d, 0x93, 0xd7, 0xaa, 0x66, 0xf8, 0xce, - 0xf7, 0x00, 0x00, 0x00, 0xff, 0xff, 0xf0, 0x3a, 0x80, 0xec, 0x74, 0x03, 0x00, 0x00, -} - -func (this *MsgFundCommunityPool) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgFundCommunityPool) - if !ok { - that2, ok := that.(MsgFundCommunityPool) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if len(this.Amount) != len(that1.Amount) { - return false - } - for i := range this.Amount { - if !this.Amount[i].Equal(&that1.Amount[i]) { - return false - } - } - if this.Depositor != that1.Depositor { - return false - } - return true -} -func (this *MsgFundCommunityPoolResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgFundCommunityPoolResponse) - if !ok { - that2, ok := that.(MsgFundCommunityPoolResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - return true -} -func (this *MsgUpdateParams) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgUpdateParams) - if !ok { - that2, ok := that.(MsgUpdateParams) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Authority != that1.Authority { - return false - } - if !this.Params.Equal(&that1.Params) { - return false - } - return true -} -func (this *MsgUpdateParamsResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgUpdateParamsResponse) - if !ok { - that2, ok := that.(MsgUpdateParamsResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - return true -} - -// 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 { - // FundCommunityPool defines a method to allow an account to directly fund the community module account. - FundCommunityPool(ctx context.Context, in *MsgFundCommunityPool, opts ...grpc.CallOption) (*MsgFundCommunityPoolResponse, error) - // UpdateParams defines a method to allow an account to update the community module parameters. - UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) FundCommunityPool(ctx context.Context, in *MsgFundCommunityPool, opts ...grpc.CallOption) (*MsgFundCommunityPoolResponse, error) { - out := new(MsgFundCommunityPoolResponse) - err := c.cc.Invoke(ctx, "/kava.community.v1beta1.Msg/FundCommunityPool", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) { - out := new(MsgUpdateParamsResponse) - err := c.cc.Invoke(ctx, "/kava.community.v1beta1.Msg/UpdateParams", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // FundCommunityPool defines a method to allow an account to directly fund the community module account. - FundCommunityPool(context.Context, *MsgFundCommunityPool) (*MsgFundCommunityPoolResponse, error) - // UpdateParams defines a method to allow an account to update the community module parameters. - UpdateParams(context.Context, *MsgUpdateParams) (*MsgUpdateParamsResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) FundCommunityPool(ctx context.Context, req *MsgFundCommunityPool) (*MsgFundCommunityPoolResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method FundCommunityPool not implemented") -} -func (*UnimplementedMsgServer) UpdateParams(ctx context.Context, req *MsgUpdateParams) (*MsgUpdateParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UpdateParams not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_FundCommunityPool_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgFundCommunityPool) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).FundCommunityPool(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.community.v1beta1.Msg/FundCommunityPool", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).FundCommunityPool(ctx, req.(*MsgFundCommunityPool)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_UpdateParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgUpdateParams) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).UpdateParams(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.community.v1beta1.Msg/UpdateParams", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).UpdateParams(ctx, req.(*MsgUpdateParams)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.community.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "FundCommunityPool", - Handler: _Msg_FundCommunityPool_Handler, - }, - { - MethodName: "UpdateParams", - Handler: _Msg_UpdateParams_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/community/v1beta1/tx.proto", -} - -func (m *MsgFundCommunityPool) 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 *MsgFundCommunityPool) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgFundCommunityPool) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0x12 - } - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *MsgFundCommunityPoolResponse) 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 *MsgFundCommunityPoolResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgFundCommunityPoolResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgUpdateParams) 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 *MsgUpdateParams) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateParams) 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 = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgUpdateParamsResponse) 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 *MsgUpdateParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgFundCommunityPool) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgFundCommunityPoolResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgUpdateParams) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Params.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgUpdateParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgFundCommunityPool) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgFundCommunityPool: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgFundCommunityPool: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-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 Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgFundCommunityPoolResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgFundCommunityPoolResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgFundCommunityPoolResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgUpdateParams) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgUpdateParams: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateParams: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - 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 ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgUpdateParamsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgUpdateParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/das/v1/client/cli/query.go b/x/das/v1/client/cli/query.go new file mode 100644 index 00000000..b7a715e3 --- /dev/null +++ b/x/das/v1/client/cli/query.go @@ -0,0 +1,57 @@ +package cli + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + + "github.com/0glabs/0g-chain/x/das/v1/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" +) + +// GetQueryCmd returns the cli query commands for the inflation module. +func GetQueryCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Querying commands for the das module", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + cmd.AddCommand( + GetNextRequestID(), + ) + + return cmd +} + +func GetNextRequestID() *cobra.Command { + cmd := &cobra.Command{ + Use: "next-request-id", + Short: "Query the next request ID", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + params := &types.QueryNextRequestIDRequest{} + res, err := queryClient.NextRequestID(context.Background(), params) + if err != nil { + return err + } + + return clientCtx.PrintString(fmt.Sprintf("%v\n", res.NextRequestID)) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/x/das/v1/client/cli/tx.go b/x/das/v1/client/cli/tx.go new file mode 100644 index 00000000..1a97c959 --- /dev/null +++ b/x/das/v1/client/cli/tx.go @@ -0,0 +1,103 @@ +package cli + +import ( + "encoding/hex" + "fmt" + "strconv" + + "github.com/0glabs/0g-chain/x/das/v1/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/tx" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/spf13/cobra" +) + +// 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, + } + cmd.AddCommand( + NewRequestDASCmd(), + NewReportDASResultCmd(), + ) + return cmd +} + +func NewRequestDASCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "request-das steram-id batch-header-hash num-blobs", + Short: "Request data-availability-sampling", + Args: cobra.ExactArgs(3), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + numBlobs, err := strconv.Atoi(args[2]) + if err != nil { + return err + } + + msg := types.NewMsgRequestDAS(clientCtx.GetFromAddress(), args[0], args[1], uint32(numBlobs)) + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + return cmd + +} + +func NewReportDASResultCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "report-das-result request-id results", + Short: "Report data-availability-sampling result", + Args: cobra.MinimumNArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + requestID, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return err + } + + n := len(args) - 1 + results := make([]bool, n) + for i := 0; i < n; i++ { + var err error + results[i], err = strconv.ParseBool(args[i+1]) + if err != nil { + return err + } + } + + // get account name by address + accAddr := clientCtx.GetFromAddress() + + samplerAddr, err := sdk.ValAddressFromHex(hex.EncodeToString(accAddr.Bytes())) + if err != nil { + return err + } + + msg := &types.MsgReportDASResult{ + RequestID: requestID, + Sampler: samplerAddr.String(), + Results: results, + } + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + return cmd +} diff --git a/x/das/v1/genesis.go b/x/das/v1/genesis.go new file mode 100644 index 00000000..4780b693 --- /dev/null +++ b/x/das/v1/genesis.go @@ -0,0 +1,39 @@ +package das + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/0glabs/0g-chain/x/das/v1/keeper" + "github.com/0glabs/0g-chain/x/das/v1/types" +) + +// InitGenesis initializes the store state from a genesis state. +func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, gs types.GenesisState) { + if err := gs.Validate(); err != nil { + panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) + } + + keeper.SetNextRequestID(ctx, gs.NextRequestID) + for _, req := range gs.Requests { + keeper.SetDASRequest(ctx, req) + } + for _, resp := range gs.Responses { + keeper.SetDASResponse(ctx, resp) + } +} + +// ExportGenesis returns a GenesisState for a given context and keeper. +func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) *types.GenesisState { + nextRequestID, err := keeper.GetNextRequestID(ctx) + if err != nil { + panic(err) + } + + return types.NewGenesisState( + nextRequestID, + keeper.GetDASRequests(ctx), + keeper.GetDASResponses(ctx), + ) +} diff --git a/x/das/v1/keeper/grpc_query.go b/x/das/v1/keeper/grpc_query.go new file mode 100644 index 00000000..e4fddea2 --- /dev/null +++ b/x/das/v1/keeper/grpc_query.go @@ -0,0 +1,22 @@ +package keeper + +import ( + "context" + + "github.com/0glabs/0g-chain/x/das/v1/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var _ types.QueryServer = Keeper{} + +func (k Keeper) NextRequestID( + c context.Context, + _ *types.QueryNextRequestIDRequest, +) (*types.QueryNextRequestIDResponse, error) { + ctx := sdk.UnwrapSDKContext(c) + nextRequestID, err := k.GetNextRequestID(ctx) + if err != nil { + return nil, err + } + return &types.QueryNextRequestIDResponse{NextRequestID: nextRequestID}, nil +} diff --git a/x/das/v1/keeper/keeper.go b/x/das/v1/keeper/keeper.go new file mode 100644 index 00000000..5dcedad5 --- /dev/null +++ b/x/das/v1/keeper/keeper.go @@ -0,0 +1,198 @@ +package keeper + +import ( + "encoding/hex" + "strconv" + + errorsmod "cosmossdk.io/errors" + "github.com/cometbft/cometbft/libs/log" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store/prefix" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/0glabs/0g-chain/x/das/v1/types" +) + +type Keeper struct { + storeKey storetypes.StoreKey + cdc codec.BinaryCodec + stakingKeeperRef types.StakingKeeperRef +} + +// NewKeeper creates a new das Keeper instance +func NewKeeper( + storeKey storetypes.StoreKey, + cdc codec.BinaryCodec, + stakingKeeper types.StakingKeeperRef, +) Keeper { + return Keeper{ + storeKey: storeKey, + cdc: cdc, + stakingKeeperRef: stakingKeeper, + } +} + +// Logger returns a module-specific logger. +func (k Keeper) Logger(ctx sdk.Context) log.Logger { + return ctx.Logger().With("module", "x/"+types.ModuleName) +} + +func (k Keeper) SetNextRequestID(ctx sdk.Context, id uint64) { + store := ctx.KVStore(k.storeKey) + store.Set(types.NextRequestIDKey, types.GetKeyFromID(id)) +} + +func (k Keeper) GetNextRequestID(ctx sdk.Context) (uint64, error) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.NextRequestIDKey) + if bz == nil { + return 0, errorsmod.Wrap(types.ErrInvalidGenesis, "next request ID not set at genesis") + } + return types.Uint64FromBytes(bz), nil +} + +func (k Keeper) IncrementNextRequestID(ctx sdk.Context) error { + id, err := k.GetNextRequestID(ctx) + if err != nil { + return err + } + k.SetNextRequestID(ctx, id+1) + return nil +} + +func (k Keeper) GetDASRequest(ctx sdk.Context, requestID uint64) (types.DASRequest, bool) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.RequestKeyPrefix) + bz := store.Get(types.GetKeyFromID(requestID)) + if bz == nil { + return types.DASRequest{}, false + } + var req types.DASRequest + k.cdc.MustUnmarshal(bz, &req) + return req, true +} + +func (k Keeper) SetDASRequest(ctx sdk.Context, req types.DASRequest) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.RequestKeyPrefix) + bz := k.cdc.MustMarshal(&req) + store.Set(types.GetKeyFromID(req.ID), bz) +} + +func (k Keeper) IterateDASRequest(ctx sdk.Context, cb func(req types.DASRequest) (stop bool)) { + iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.RequestKeyPrefix) + + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + var req types.DASRequest + k.cdc.MustUnmarshal(iterator.Value(), &req) + if cb(req) { + break + } + } +} + +func (k Keeper) GetDASRequests(ctx sdk.Context) []types.DASRequest { + results := []types.DASRequest{} + k.IterateDASRequest(ctx, func(req types.DASRequest) bool { + results = append(results, req) + return false + }) + return results +} + +func (k Keeper) StoreNewDASRequest( + ctx sdk.Context, + streamIDHexStr string, + batchHeaderHashHexStr string, + numBlobs uint32) (uint64, error) { + requestID, err := k.GetNextRequestID(ctx) + if err != nil { + return 0, err + } + + streamID, err := hex.DecodeString(streamIDHexStr) + if err != nil { + return 0, err + } + + batchHeaderHash, err := hex.DecodeString(batchHeaderHashHexStr) + if err != nil { + return 0, err + } + + req := types.DASRequest{ + ID: requestID, + StreamID: streamID, + BatchHeaderHash: batchHeaderHash, + NumBlobs: numBlobs, + } + k.SetDASRequest(ctx, req) + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeDASRequest, + sdk.NewAttribute(types.AttributeKeyRequestID, strconv.FormatUint(requestID, 10)), + sdk.NewAttribute(types.AttributeKeyStreamID, streamIDHexStr), + sdk.NewAttribute(types.AttributeKeyBatchHeaderHash, batchHeaderHashHexStr), + sdk.NewAttribute(types.AttributeKeyNumBlobs, strconv.FormatUint(uint64(numBlobs), 10)), + ), + ) + + return requestID, nil +} + +func (k Keeper) GetDASResponse( + ctx sdk.Context, requestID uint64, sampler sdk.ValAddress, +) (types.DASResponse, bool) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.ResponseKeyPrefix) + bz := store.Get(types.GetResponseKey(requestID, sampler)) + if bz == nil { + return types.DASResponse{}, false + } + var vote types.DASResponse + k.cdc.MustUnmarshal(bz, &vote) + return vote, true +} + +func (k Keeper) SetDASResponse(ctx sdk.Context, resp types.DASResponse) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.ResponseKeyPrefix) + bz := k.cdc.MustMarshal(&resp) + store.Set(types.GetResponseKey(resp.ID, resp.Sampler), bz) +} + +func (k Keeper) IterateDASResponse(ctx sdk.Context, cb func(resp types.DASResponse) (stop bool)) { + iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.ResponseKeyPrefix) + + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + var resp types.DASResponse + k.cdc.MustUnmarshal(iterator.Value(), &resp) + if cb(resp) { + break + } + } +} + +func (k Keeper) GetDASResponses(ctx sdk.Context) []types.DASResponse { + results := []types.DASResponse{} + k.IterateDASResponse(ctx, func(resp types.DASResponse) bool { + results = append(results, resp) + return false + }) + return results +} + +func (k Keeper) StoreNewDASResponse( + ctx sdk.Context, requestID uint64, sampler sdk.ValAddress, results []bool) error { + if _, found := k.GetDASRequest(ctx, requestID); !found { + return errorsmod.Wrapf(types.ErrUnknownRequest, "%d", requestID) + } + + k.SetDASResponse(ctx, types.DASResponse{ + ID: requestID, + Sampler: sampler, + Results: results, + }) + + return nil +} diff --git a/x/das/v1/keeper/msg_server.go b/x/das/v1/keeper/msg_server.go new file mode 100644 index 00000000..4109f90a --- /dev/null +++ b/x/das/v1/keeper/msg_server.go @@ -0,0 +1,49 @@ +package keeper + +import ( + "context" + + "github.com/0glabs/0g-chain/x/das/v1/types" + sdk "github.com/cosmos/cosmos-sdk/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +var _ types.MsgServer = &Keeper{} + +// RequestDAS handles MsgRequestDAS messages +func (k Keeper) RequestDAS( + goCtx context.Context, msg *types.MsgRequestDAS, +) (*types.MsgRequestDASResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + requestID, err := k.StoreNewDASRequest(ctx, msg.StreamID, msg.BatchHeaderHash, msg.NumBlobs) + if err != nil { + return nil, err + } + k.IncrementNextRequestID(ctx) + return &types.MsgRequestDASResponse{ + RequestID: requestID, + }, nil +} + +// ReportDASResult handles MsgReportDASResult messages +func (k Keeper) ReportDASResult( + goCtx context.Context, msg *types.MsgReportDASResult, +) (*types.MsgReportDASResultResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + sampler, err := sdk.ValAddressFromBech32(msg.Sampler) + if err != nil { + return nil, err + } + + if _, found := k.stakingKeeperRef.GetValidator(ctx, sampler); !found { + return nil, stakingtypes.ErrNoValidatorFound + } + + if err := k.StoreNewDASResponse(ctx, msg.RequestID, sampler, msg.Results); err != nil { + return nil, err + } + + return &types.MsgReportDASResultResponse{}, nil +} diff --git a/x/das/v1/module.go b/x/das/v1/module.go new file mode 100644 index 00000000..288c00bd --- /dev/null +++ b/x/das/v1/module.go @@ -0,0 +1,169 @@ +package das + +import ( + "context" + "encoding/json" + "fmt" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + + "github.com/0glabs/0g-chain/x/das/v1/client/cli" + "github.com/0glabs/0g-chain/x/das/v1/keeper" + "github.com/0glabs/0g-chain/x/das/v1/types" +) + +// consensusVersion defines the current x/committee module consensus version. +const consensusVersion = 1 + +// type check to ensure the interface is properly implemented +var ( + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModule{} + _ module.BeginBlockAppModule = AppModule{} + _ module.EndBlockAppModule = AppModule{} +) + +// app module Basics object +type AppModuleBasic struct{} + +// Name returns the inflation module's name. +func (AppModuleBasic) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec registers the inflation module's types on the given LegacyAmino codec. +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} + +// ConsensusVersion returns the consensus state-breaking version for the module. +func (AppModuleBasic) ConsensusVersion() uint64 { + return consensusVersion +} + +// RegisterInterfaces registers interfaces and implementations of the incentives +// module. +func (AppModuleBasic) RegisterInterfaces(interfaceRegistry codectypes.InterfaceRegistry) { + types.RegisterInterfaces(interfaceRegistry) +} + +// DefaultGenesis returns default genesis state as raw bytes for the incentives +// module. +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { + return cdc.MustMarshalJSON(types.DefaultGenesisState()) +} + +// ValidateGenesis performs genesis state validation for the inflation module. +func (b AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { + var genesisState types.GenesisState + if err := cdc.UnmarshalJSON(bz, &genesisState); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return genesisState.Validate() +} + +// RegisterRESTRoutes performs a no-op as the inflation module doesn't expose REST +// endpoints +func (AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) {} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the inflation module. +func (b AppModuleBasic) RegisterGRPCGatewayRoutes(c client.Context, serveMux *runtime.ServeMux) { + if err := types.RegisterQueryHandlerClient(context.Background(), serveMux, types.NewQueryClient(c)); err != nil { + panic(err) + } +} + +// GetTxCmd returns the root tx command for the inflation module. +func (AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd() +} + +// GetQueryCmd returns no root query command for the inflation module. +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd() +} + +// ___________________________________________________________________________ + +// AppModule implements an application module for the inflation module. +type AppModule struct { + AppModuleBasic + keeper keeper.Keeper +} + +// NewAppModule creates a new AppModule Object +func NewAppModule( + k keeper.Keeper, +) AppModule { + return AppModule{ + AppModuleBasic: AppModuleBasic{}, + keeper: k, + } +} + +// Name returns the inflation module's name. +func (AppModule) Name() string { + return types.ModuleName +} + +// RegisterInvariants registers the inflation module invariants. +func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + +// 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(), am.keeper) + types.RegisterQueryServer(cfg.QueryServer(), am.keeper) +} + +func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { + // am.keeper.BeginBlock(ctx, req) +} + +func (am AppModule) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) []abci.ValidatorUpdate { + // am.keeper.EndBlock(ctx, req) + return []abci.ValidatorUpdate{} +} + +// InitGenesis performs genesis initialization for the inflation module. It returns +// no validator updates. +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { + var genesisState types.GenesisState + + cdc.MustUnmarshalJSON(data, &genesisState) + InitGenesis(ctx, am.keeper, genesisState) + return []abci.ValidatorUpdate{} +} + +// ExportGenesis returns the exported genesis state as raw bytes for the inflation +// module. +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { + gs := ExportGenesis(ctx, am.keeper) + return cdc.MustMarshalJSON(gs) +} + +// ___________________________________________________________________________ + +// AppModuleSimulation functions + +// GenerateGenesisState creates a randomized GenState of the inflation module. +func (am AppModule) GenerateGenesisState(_ *module.SimulationState) { +} + +// RegisterStoreDecoder registers a decoder for inflation module's types. +func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) { +} + +// WeightedOperations doesn't return any inflation module operation. +func (am AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { + return []simtypes.WeightedOperation{} +} diff --git a/x/das/v1/types/codec.go b/x/das/v1/types/codec.go new file mode 100644 index 00000000..883a699e --- /dev/null +++ b/x/das/v1/types/codec.go @@ -0,0 +1,47 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/msgservice" +) + +var ( + amino = codec.NewLegacyAmino() + // ModuleCdc references the global evm module codec. Note, the codec should + // ONLY be used in certain instances of tests and for JSON encoding. + ModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) + + // AminoCdc is a amino codec created to support amino JSON compatible msgs. + AminoCdc = codec.NewAminoCodec(amino) +) + +const ( + // Amino names + requestDASName = "evmos/das/MsgRequestDAS" + reportDASResultName = "evmos/das/MsgReportDASResult" +) + +// NOTE: This is required for the GetSignBytes function +func init() { + RegisterLegacyAminoCodec(amino) + amino.Seal() +} + +// RegisterInterfaces register implementations +func RegisterInterfaces(registry codectypes.InterfaceRegistry) { + registry.RegisterImplementations( + (*sdk.Msg)(nil), + &MsgRequestDAS{}, + &MsgReportDASResult{}, + ) + + msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +} + +// RegisterLegacyAminoCodec required for EIP-712 +func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + cdc.RegisterConcrete(&MsgRequestDAS{}, requestDASName, nil) + cdc.RegisterConcrete(&MsgReportDASResult{}, reportDASResultName, nil) +} diff --git a/x/das/v1/types/errors.go b/x/das/v1/types/errors.go new file mode 100644 index 00000000..77469e4a --- /dev/null +++ b/x/das/v1/types/errors.go @@ -0,0 +1,8 @@ +package types + +import errorsmod "cosmossdk.io/errors" + +var ( + ErrUnknownRequest = errorsmod.Register(ModuleName, 0, "request not found") + ErrInvalidGenesis = errorsmod.Register(ModuleName, 1, "invalid genesis") +) diff --git a/x/das/v1/types/events.go b/x/das/v1/types/events.go new file mode 100644 index 00000000..3a7159a4 --- /dev/null +++ b/x/das/v1/types/events.go @@ -0,0 +1,11 @@ +package types + +// Module event types +const ( + EventTypeDASRequest = "das_request" + + AttributeKeyRequestID = "request_id" + AttributeKeyStreamID = "stream_id" + AttributeKeyBatchHeaderHash = "batch_header_hash" + AttributeKeyNumBlobs = "num_blobs" +) diff --git a/x/das/v1/types/genesis.go b/x/das/v1/types/genesis.go new file mode 100644 index 00000000..fd0c6fde --- /dev/null +++ b/x/das/v1/types/genesis.go @@ -0,0 +1,28 @@ +package types + +const ( + DefaultNextRequestID = 0 +) + +// NewGenesisState returns a new genesis state object for the module. +func NewGenesisState(nextRequestID uint64, requests []DASRequest, responses []DASResponse) *GenesisState { + return &GenesisState{ + NextRequestID: nextRequestID, + Requests: requests, + Responses: responses, + } +} + +// DefaultGenesisState returns the default genesis state for the module. +func DefaultGenesisState() *GenesisState { + return NewGenesisState( + DefaultNextRequestID, + []DASRequest{}, + []DASResponse{}, + ) +} + +// Validate performs basic validation of genesis data. +func (gs GenesisState) Validate() error { + return nil +} diff --git a/x/das/v1/types/genesis.pb.go b/x/das/v1/types/genesis.pb.go new file mode 100644 index 00000000..15cab4cf --- /dev/null +++ b/x/das/v1/types/genesis.pb.go @@ -0,0 +1,1191 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: zgc/das/v1/genesis.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/cosmos-sdk/codec/types" + github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + _ "google.golang.org/protobuf/types/known/timestamppb" + 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 Params struct { +} + +func (m *Params) Reset() { *m = Params{} } +func (m *Params) String() string { return proto.CompactTextString(m) } +func (*Params) ProtoMessage() {} +func (*Params) Descriptor() ([]byte, []int) { + return fileDescriptor_3f8b8b164973ed21, []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 + +// GenesisState defines the das module's genesis state. +type GenesisState struct { + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` + NextRequestID uint64 `protobuf:"varint,2,opt,name=next_request_id,json=nextRequestId,proto3" json:"next_request_id,omitempty"` + Requests []DASRequest `protobuf:"bytes,3,rep,name=requests,proto3" json:"requests"` + Responses []DASResponse `protobuf:"bytes,4,rep,name=responses,proto3" json:"responses"` +} + +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_3f8b8b164973ed21, []int{1} +} +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 + +type DASRequest struct { + ID uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + StreamID []byte `protobuf:"bytes,2,opt,name=stream_id,json=streamId,proto3" json:"stream_id,omitempty"` + BatchHeaderHash []byte `protobuf:"bytes,3,opt,name=batch_header_hash,json=batchHeaderHash,proto3" json:"batch_header_hash,omitempty"` + NumBlobs uint32 `protobuf:"varint,4,opt,name=num_blobs,json=numBlobs,proto3" json:"num_blobs,omitempty"` +} + +func (m *DASRequest) Reset() { *m = DASRequest{} } +func (m *DASRequest) String() string { return proto.CompactTextString(m) } +func (*DASRequest) ProtoMessage() {} +func (*DASRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_3f8b8b164973ed21, []int{2} +} +func (m *DASRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *DASRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_DASRequest.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 *DASRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_DASRequest.Merge(m, src) +} +func (m *DASRequest) XXX_Size() int { + return m.Size() +} +func (m *DASRequest) XXX_DiscardUnknown() { + xxx_messageInfo_DASRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_DASRequest proto.InternalMessageInfo + +func (m *DASRequest) GetID() uint64 { + if m != nil { + return m.ID + } + return 0 +} + +func (m *DASRequest) GetStreamID() []byte { + if m != nil { + return m.StreamID + } + return nil +} + +func (m *DASRequest) GetBatchHeaderHash() []byte { + if m != nil { + return m.BatchHeaderHash + } + return nil +} + +func (m *DASRequest) GetNumBlobs() uint32 { + if m != nil { + return m.NumBlobs + } + return 0 +} + +type DASResponse struct { + ID uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Sampler github_com_cosmos_cosmos_sdk_types.ValAddress `protobuf:"bytes,2,opt,name=sampler,proto3,casttype=github.com/cosmos/cosmos-sdk/types.ValAddress" json:"sampler,omitempty"` + Results []bool `protobuf:"varint,3,rep,packed,name=results,proto3" json:"results,omitempty"` +} + +func (m *DASResponse) Reset() { *m = DASResponse{} } +func (m *DASResponse) String() string { return proto.CompactTextString(m) } +func (*DASResponse) ProtoMessage() {} +func (*DASResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_3f8b8b164973ed21, []int{3} +} +func (m *DASResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *DASResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_DASResponse.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 *DASResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_DASResponse.Merge(m, src) +} +func (m *DASResponse) XXX_Size() int { + return m.Size() +} +func (m *DASResponse) XXX_DiscardUnknown() { + xxx_messageInfo_DASResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_DASResponse proto.InternalMessageInfo + +func (m *DASResponse) GetID() uint64 { + if m != nil { + return m.ID + } + return 0 +} + +func (m *DASResponse) GetSampler() github_com_cosmos_cosmos_sdk_types.ValAddress { + if m != nil { + return m.Sampler + } + return nil +} + +func (m *DASResponse) GetResults() []bool { + if m != nil { + return m.Results + } + return nil +} + +func init() { + proto.RegisterType((*Params)(nil), "zgc.das.v1.Params") + proto.RegisterType((*GenesisState)(nil), "zgc.das.v1.GenesisState") + proto.RegisterType((*DASRequest)(nil), "zgc.das.v1.DASRequest") + proto.RegisterType((*DASResponse)(nil), "zgc.das.v1.DASResponse") +} + +func init() { proto.RegisterFile("zgc/das/v1/genesis.proto", fileDescriptor_3f8b8b164973ed21) } + +var fileDescriptor_3f8b8b164973ed21 = []byte{ + // 521 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x53, 0xbd, 0x6e, 0xd3, 0x50, + 0x14, 0x8e, 0x93, 0x28, 0x75, 0x6e, 0x12, 0x55, 0x35, 0xa8, 0xb8, 0x45, 0xb2, 0xa3, 0x4c, 0x29, + 0x52, 0xec, 0xb4, 0x2c, 0xfc, 0x4c, 0x35, 0x91, 0x48, 0x16, 0x84, 0x1c, 0x89, 0x81, 0xc5, 0xba, + 0xf6, 0xbd, 0xd8, 0x16, 0xb6, 0xaf, 0xf1, 0xb9, 0xae, 0x92, 0x3e, 0x01, 0x23, 0x23, 0x23, 0x12, + 0xaf, 0xc0, 0x43, 0x74, 0xac, 0x98, 0x98, 0x22, 0xe4, 0xbc, 0x04, 0x62, 0x42, 0xb1, 0x6f, 0x48, + 0x04, 0xea, 0x94, 0x7c, 0x7f, 0x3e, 0xdf, 0x91, 0x8f, 0x91, 0x7a, 0xed, 0x7b, 0x26, 0xc1, 0x60, + 0x5e, 0x9d, 0x9b, 0x3e, 0x4d, 0x28, 0x84, 0x60, 0xa4, 0x19, 0xe3, 0x4c, 0x41, 0xd7, 0xbe, 0x67, + 0x10, 0x0c, 0xc6, 0xd5, 0xf9, 0xe9, 0x89, 0xc7, 0x20, 0x66, 0xe0, 0x94, 0x8a, 0x59, 0x81, 0xca, + 0x76, 0x7a, 0xdf, 0x67, 0x3e, 0xab, 0xf8, 0xcd, 0x3f, 0xc1, 0x9e, 0xf8, 0x8c, 0xf9, 0x11, 0x35, + 0x4b, 0xe4, 0xe6, 0xef, 0x4c, 0x9c, 0x2c, 0x85, 0xa4, 0xff, 0x2b, 0xf1, 0x30, 0xa6, 0xc0, 0x71, + 0x9c, 0x56, 0x86, 0x81, 0x8c, 0x5a, 0xaf, 0x71, 0x86, 0x63, 0x18, 0xfc, 0x92, 0x50, 0xf7, 0x65, + 0x55, 0x6a, 0xce, 0x31, 0xa7, 0xca, 0x18, 0xb5, 0xd2, 0x52, 0x52, 0xa5, 0xbe, 0x34, 0xec, 0x5c, + 0x28, 0xc6, 0xae, 0xa4, 0x51, 0x85, 0xac, 0xe6, 0xcd, 0x4a, 0xaf, 0xd9, 0xc2, 0xa7, 0x3c, 0x45, + 0x87, 0x09, 0x5d, 0x70, 0x27, 0xa3, 0x1f, 0x72, 0x0a, 0xdc, 0x09, 0x89, 0x5a, 0xef, 0x4b, 0xc3, + 0xa6, 0x75, 0x54, 0xac, 0xf4, 0xde, 0x2b, 0xba, 0xe0, 0x76, 0xa5, 0xcc, 0x26, 0x76, 0x2f, 0xd9, + 0x83, 0x44, 0x79, 0x82, 0x64, 0x91, 0x02, 0xb5, 0xd1, 0x6f, 0x0c, 0x3b, 0x17, 0xc7, 0xfb, 0xe3, + 0x26, 0x97, 0x73, 0xe1, 0x15, 0x23, 0xff, 0xba, 0x95, 0xe7, 0xa8, 0x9d, 0x51, 0x48, 0x59, 0x02, + 0x14, 0xd4, 0x66, 0x19, 0x7d, 0xf0, 0x5f, 0xb4, 0xd2, 0x45, 0x76, 0xe7, 0x7f, 0xd6, 0xfc, 0xf8, + 0x45, 0xaf, 0x0d, 0x3e, 0x4b, 0x08, 0xed, 0x26, 0x28, 0xc7, 0xa8, 0x1e, 0x92, 0x72, 0xe9, 0xa6, + 0xd5, 0x2a, 0x56, 0x7a, 0x7d, 0x36, 0xb1, 0xeb, 0x21, 0x51, 0xce, 0x50, 0x1b, 0x78, 0x46, 0x71, + 0xbc, 0x5d, 0xac, 0x6b, 0x75, 0x8b, 0x95, 0x2e, 0xcf, 0x4b, 0x72, 0x36, 0xb1, 0xe5, 0x4a, 0x9e, + 0x11, 0xe5, 0x11, 0x3a, 0x72, 0x31, 0xf7, 0x02, 0x27, 0xa0, 0x98, 0xd0, 0xcc, 0x09, 0x30, 0x04, + 0x6a, 0x63, 0x13, 0xb1, 0x0f, 0x4b, 0x61, 0x5a, 0xf2, 0x53, 0x0c, 0x81, 0xf2, 0x10, 0xb5, 0x93, + 0x3c, 0x76, 0xdc, 0x88, 0xb9, 0x9b, 0x05, 0xa4, 0x61, 0xcf, 0x96, 0x93, 0x3c, 0xb6, 0x36, 0x78, + 0xf0, 0x55, 0x42, 0x9d, 0xbd, 0x0d, 0xee, 0xec, 0xe6, 0xa2, 0x03, 0xc0, 0x71, 0x1a, 0xd1, 0x4c, + 0x34, 0x9b, 0xfe, 0x5e, 0xe9, 0x23, 0x3f, 0xe4, 0x41, 0xee, 0x1a, 0x1e, 0x8b, 0xc5, 0x1d, 0x89, + 0x9f, 0x11, 0x90, 0xf7, 0x26, 0x5f, 0xa6, 0x14, 0x8c, 0x37, 0x38, 0xba, 0x24, 0x24, 0xa3, 0x00, + 0xdf, 0xbf, 0x8d, 0xee, 0x89, 0x6b, 0x13, 0x8c, 0xb5, 0xe4, 0x14, 0xec, 0xed, 0x83, 0x15, 0x15, + 0x1d, 0x64, 0x14, 0xf2, 0x48, 0xbc, 0x22, 0xd9, 0xde, 0x42, 0xeb, 0xc5, 0x4d, 0xa1, 0x49, 0xb7, + 0x85, 0x26, 0xfd, 0x2c, 0x34, 0xe9, 0xd3, 0x5a, 0xab, 0xdd, 0xae, 0xb5, 0xda, 0x8f, 0xb5, 0x56, + 0x7b, 0x7b, 0xb6, 0x57, 0x61, 0xec, 0x47, 0xd8, 0x05, 0x73, 0xec, 0x8f, 0xbc, 0x00, 0x87, 0x89, + 0xb9, 0xd8, 0x7e, 0x0b, 0x65, 0x13, 0xb7, 0x55, 0x5e, 0xe4, 0xe3, 0x3f, 0x01, 0x00, 0x00, 0xff, + 0xff, 0x5b, 0x0e, 0xfc, 0x0d, 0x26, 0x03, 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 (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.Responses) > 0 { + for iNdEx := len(m.Responses) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Responses[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + } + if len(m.Requests) > 0 { + for iNdEx := len(m.Requests) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Requests[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if m.NextRequestID != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.NextRequestID)) + i-- + dAtA[i] = 0x10 + } + { + 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 (m *DASRequest) 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 *DASRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *DASRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.NumBlobs != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.NumBlobs)) + i-- + dAtA[i] = 0x20 + } + if len(m.BatchHeaderHash) > 0 { + i -= len(m.BatchHeaderHash) + copy(dAtA[i:], m.BatchHeaderHash) + i = encodeVarintGenesis(dAtA, i, uint64(len(m.BatchHeaderHash))) + i-- + dAtA[i] = 0x1a + } + if len(m.StreamID) > 0 { + i -= len(m.StreamID) + copy(dAtA[i:], m.StreamID) + i = encodeVarintGenesis(dAtA, i, uint64(len(m.StreamID))) + i-- + dAtA[i] = 0x12 + } + if m.ID != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.ID)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *DASResponse) 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 *DASResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *DASResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Results) > 0 { + for iNdEx := len(m.Results) - 1; iNdEx >= 0; iNdEx-- { + i-- + if m.Results[iNdEx] { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + } + i = encodeVarintGenesis(dAtA, i, uint64(len(m.Results))) + i-- + dAtA[i] = 0x1a + } + if len(m.Sampler) > 0 { + i -= len(m.Sampler) + copy(dAtA[i:], m.Sampler) + i = encodeVarintGenesis(dAtA, i, uint64(len(m.Sampler))) + i-- + dAtA[i] = 0x12 + } + if m.ID != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.ID)) + i-- + dAtA[i] = 0x8 + } + 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 *Params) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +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 m.NextRequestID != 0 { + n += 1 + sovGenesis(uint64(m.NextRequestID)) + } + if len(m.Requests) > 0 { + for _, e := range m.Requests { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + if len(m.Responses) > 0 { + for _, e := range m.Responses { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + return n +} + +func (m *DASRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ID != 0 { + n += 1 + sovGenesis(uint64(m.ID)) + } + l = len(m.StreamID) + if l > 0 { + n += 1 + l + sovGenesis(uint64(l)) + } + l = len(m.BatchHeaderHash) + if l > 0 { + n += 1 + l + sovGenesis(uint64(l)) + } + if m.NumBlobs != 0 { + n += 1 + sovGenesis(uint64(m.NumBlobs)) + } + return n +} + +func (m *DASResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ID != 0 { + n += 1 + sovGenesis(uint64(m.ID)) + } + l = len(m.Sampler) + if l > 0 { + n += 1 + l + sovGenesis(uint64(l)) + } + if len(m.Results) > 0 { + n += 1 + sovGenesis(uint64(len(m.Results))) + len(m.Results)*1 + } + 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 *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 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: 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 := 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 (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 != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field NextRequestID", wireType) + } + m.NextRequestID = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.NextRequestID |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Requests", 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.Requests = append(m.Requests, DASRequest{}) + if err := m.Requests[len(m.Requests)-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 Responses", 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.Responses = append(m.Responses, DASResponse{}) + if err := m.Responses[len(m.Responses)-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 (m *DASRequest) 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: DASRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DASRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) + } + m.ID = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ID |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field StreamID", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.StreamID = append(m.StreamID[:0], dAtA[iNdEx:postIndex]...) + if m.StreamID == nil { + m.StreamID = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BatchHeaderHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.BatchHeaderHash = append(m.BatchHeaderHash[:0], dAtA[iNdEx:postIndex]...) + if m.BatchHeaderHash == nil { + m.BatchHeaderHash = []byte{} + } + iNdEx = postIndex + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field NumBlobs", wireType) + } + m.NumBlobs = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.NumBlobs |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + 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 (m *DASResponse) 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: DASResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DASResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) + } + m.ID = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ID |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Sampler", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Sampler = append(m.Sampler[:0], dAtA[iNdEx:postIndex]...) + if m.Sampler == nil { + m.Sampler = []byte{} + } + iNdEx = postIndex + case 3: + if wireType == 0 { + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Results = append(m.Results, bool(v != 0)) + } else if wireType == 2 { + var packedLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + packedLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if packedLen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + packedLen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + var elementCount int + elementCount = packedLen + if elementCount != 0 && len(m.Results) == 0 { + m.Results = make([]bool, 0, elementCount) + } + for iNdEx < postIndex { + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Results = append(m.Results, bool(v != 0)) + } + } else { + return fmt.Errorf("proto: wrong wireType = %d for field Results", wireType) + } + 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/das/v1/types/interfaces.go b/x/das/v1/types/interfaces.go new file mode 100644 index 00000000..ff56b322 --- /dev/null +++ b/x/das/v1/types/interfaces.go @@ -0,0 +1,10 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +type StakingKeeperRef interface { + GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool) +} diff --git a/x/das/v1/types/keys.go b/x/das/v1/types/keys.go new file mode 100644 index 00000000..06846cb9 --- /dev/null +++ b/x/das/v1/types/keys.go @@ -0,0 +1,44 @@ +package types + +import ( + "encoding/binary" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +const ( + // ModuleName The name that will be used throughout the module + ModuleName = "das" + + // StoreKey Top level store key where all module items will be stored + StoreKey = ModuleName +) + +// Key prefixes +var ( + RequestKeyPrefix = []byte{0x00} // prefix for keys that store requests + ResponseKeyPrefix = []byte{0x01} // prefix for keys that store responses + + NextRequestIDKey = []byte{0x02} +) + +// GetKeyFromID returns the bytes to use as a key for a uint64 id +func GetKeyFromID(id uint64) []byte { + return Uint64ToBytes(id) +} + +func GetResponseKey(requestID uint64, sampler sdk.ValAddress) []byte { + return append(GetKeyFromID(requestID), sampler.Bytes()...) +} + +// Uint64ToBytes converts a uint64 into fixed length bytes for use in store keys. +func Uint64ToBytes(id uint64) []byte { + bz := make([]byte, 8) + binary.BigEndian.PutUint64(bz, uint64(id)) + return bz +} + +// Uint64FromBytes converts some fixed length bytes back into a uint64. +func Uint64FromBytes(bz []byte) uint64 { + return binary.BigEndian.Uint64(bz) +} diff --git a/x/das/v1/types/msg.go b/x/das/v1/types/msg.go new file mode 100644 index 00000000..f1c07ce4 --- /dev/null +++ b/x/das/v1/types/msg.go @@ -0,0 +1,57 @@ +package types + +import ( + "encoding/hex" + + errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +var _, _ sdk.Msg = &MsgRequestDAS{}, &MsgReportDASResult{} + +func NewMsgRequestDAS(fromAddr sdk.AccAddress, streamID, hash string, numBlobs uint32) *MsgRequestDAS { + return &MsgRequestDAS{ + Requester: fromAddr.String(), + StreamID: streamID, + BatchHeaderHash: hash, + NumBlobs: numBlobs, + } +} + +func (msg MsgRequestDAS) GetSigners() []sdk.AccAddress { + from, err := sdk.AccAddressFromBech32(msg.Requester) + if err != nil { + panic(err) + } + return []sdk.AccAddress{from} +} + +func (msg MsgRequestDAS) ValidateBasic() error { + _, err := sdk.AccAddressFromBech32(msg.Requester) + if err != nil { + return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid requester account address (%s)", err) + } + + return nil +} + +func (msg *MsgReportDASResult) GetSigners() []sdk.AccAddress { + samplerValAddr, err := sdk.ValAddressFromBech32(msg.Sampler) + if err != nil { + panic(err) + } + accAddr, err := sdk.AccAddressFromHexUnsafe(hex.EncodeToString(samplerValAddr.Bytes())) + if err != nil { + panic(err) + } + return []sdk.AccAddress{accAddr} +} + +func (msg *MsgReportDASResult) ValidateBasic() error { + _, err := sdk.ValAddressFromBech32(msg.Sampler) + if err != nil { + return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sampler validator address (%s)", err) + } + return nil +} diff --git a/x/issuance/types/query.pb.go b/x/das/v1/types/query.pb.go similarity index 50% rename from x/issuance/types/query.pb.go rename to x/das/v1/types/query.pb.go index 3cefbb8b..16015f83 100644 --- a/x/issuance/types/query.pb.go +++ b/x/das/v1/types/query.pb.go @@ -1,11 +1,13 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/issuance/v1beta1/query.proto +// source: zgc/das/v1/query.proto package types import ( context "context" fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/cosmos-sdk/codec/types" _ "github.com/cosmos/gogoproto/gogoproto" grpc1 "github.com/cosmos/gogoproto/grpc" proto "github.com/cosmos/gogoproto/proto" @@ -13,6 +15,7 @@ import ( grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" + _ "google.golang.org/protobuf/types/known/timestamppb" io "io" math "math" math_bits "math/bits" @@ -29,22 +32,21 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package -// QueryParamsRequest defines the request type for querying x/issuance parameters. -type QueryParamsRequest struct { +type QueryNextRequestIDRequest 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_88f8bf3fcbf02033, []int{0} +func (m *QueryNextRequestIDRequest) Reset() { *m = QueryNextRequestIDRequest{} } +func (m *QueryNextRequestIDRequest) String() string { return proto.CompactTextString(m) } +func (*QueryNextRequestIDRequest) ProtoMessage() {} +func (*QueryNextRequestIDRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_d404c1962bca645f, []int{0} } -func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { +func (m *QueryNextRequestIDRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } -func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { +func (m *QueryNextRequestIDRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { - return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) + return xxx_messageInfo_QueryNextRequestIDRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) @@ -54,35 +56,34 @@ func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, return b[:n], nil } } -func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsRequest.Merge(m, src) +func (m *QueryNextRequestIDRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryNextRequestIDRequest.Merge(m, src) } -func (m *QueryParamsRequest) XXX_Size() int { +func (m *QueryNextRequestIDRequest) XXX_Size() int { return m.Size() } -func (m *QueryParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) +func (m *QueryNextRequestIDRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryNextRequestIDRequest.DiscardUnknown(m) } -var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo +var xxx_messageInfo_QueryNextRequestIDRequest proto.InternalMessageInfo -// QueryParamsResponse defines the response type for querying x/issuance parameters. -type QueryParamsResponse struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` +type QueryNextRequestIDResponse struct { + NextRequestID uint64 `protobuf:"varint,1,opt,name=next_request_id,json=nextRequestId,proto3" json:"next_request_id,omitempty"` } -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_88f8bf3fcbf02033, []int{1} +func (m *QueryNextRequestIDResponse) Reset() { *m = QueryNextRequestIDResponse{} } +func (m *QueryNextRequestIDResponse) String() string { return proto.CompactTextString(m) } +func (*QueryNextRequestIDResponse) ProtoMessage() {} +func (*QueryNextRequestIDResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_d404c1962bca645f, []int{1} } -func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { +func (m *QueryNextRequestIDResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } -func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { +func (m *QueryNextRequestIDResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { - return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) + return xxx_messageInfo_QueryNextRequestIDResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) @@ -92,52 +93,48 @@ func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, return b[:n], nil } } -func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsResponse.Merge(m, src) +func (m *QueryNextRequestIDResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryNextRequestIDResponse.Merge(m, src) } -func (m *QueryParamsResponse) XXX_Size() int { +func (m *QueryNextRequestIDResponse) XXX_Size() int { return m.Size() } -func (m *QueryParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) +func (m *QueryNextRequestIDResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryNextRequestIDResponse.DiscardUnknown(m) } -var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo - -func (m *QueryParamsResponse) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} +var xxx_messageInfo_QueryNextRequestIDResponse proto.InternalMessageInfo func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.issuance.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.issuance.v1beta1.QueryParamsResponse") + proto.RegisterType((*QueryNextRequestIDRequest)(nil), "zgc.das.v1.QueryNextRequestIDRequest") + proto.RegisterType((*QueryNextRequestIDResponse)(nil), "zgc.das.v1.QueryNextRequestIDResponse") } -func init() { proto.RegisterFile("kava/issuance/v1beta1/query.proto", fileDescriptor_88f8bf3fcbf02033) } +func init() { proto.RegisterFile("zgc/das/v1/query.proto", fileDescriptor_d404c1962bca645f) } -var fileDescriptor_88f8bf3fcbf02033 = []byte{ - // 288 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xcc, 0x4e, 0x2c, 0x4b, - 0xd4, 0xcf, 0x2c, 0x2e, 0x2e, 0x4d, 0xcc, 0x4b, 0x4e, 0xd5, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, - 0x34, 0xd4, 0x2f, 0x2c, 0x4d, 0x2d, 0xaa, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x05, - 0x29, 0xd1, 0x83, 0x29, 0xd1, 0x83, 0x2a, 0x91, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0xab, 0xd0, - 0x07, 0xb1, 0x20, 0x8a, 0xa5, 0x64, 0xd2, 0xf3, 0xf3, 0xd3, 0x73, 0x52, 0xf5, 0x13, 0x0b, 0x32, - 0xf5, 0x13, 0xf3, 0xf2, 0xf2, 0x4b, 0x12, 0x4b, 0x32, 0xf3, 0xf3, 0x8a, 0xa1, 0xb2, 0xca, 0xd8, - 0x6d, 0x4b, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x84, 0x2a, 0x52, 0x12, 0xe1, 0x12, 0x0a, 0x04, 0x59, - 0x1f, 0x90, 0x58, 0x94, 0x98, 0x5b, 0x1c, 0x94, 0x5a, 0x58, 0x9a, 0x5a, 0x5c, 0xa2, 0x14, 0xc4, - 0x25, 0x8c, 0x22, 0x5a, 0x5c, 0x90, 0x9f, 0x57, 0x9c, 0x2a, 0x64, 0xcd, 0xc5, 0x56, 0x00, 0x16, - 0x91, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x36, 0x92, 0xd5, 0xc3, 0xea, 0x5a, 0x3d, 0x88, 0x36, 0x27, - 0x96, 0x13, 0xf7, 0xe4, 0x19, 0x82, 0xa0, 0x5a, 0x8c, 0x26, 0x30, 0x72, 0xb1, 0x82, 0x0d, 0x15, - 0x6a, 0x63, 0xe4, 0x62, 0x83, 0x28, 0x11, 0xd2, 0xc4, 0x61, 0x02, 0xa6, 0x9b, 0xa4, 0xb4, 0x88, - 0x51, 0x0a, 0x71, 0xa8, 0x92, 0x6a, 0xd3, 0xe5, 0x27, 0x93, 0x99, 0xe4, 0x85, 0x64, 0xf5, 0xb1, - 0x87, 0x01, 0xc4, 0x49, 0x4e, 0x2e, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, - 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x17, 0x1e, 0xcb, 0x31, 0xdc, 0x78, 0x2c, 0xc7, 0x10, - 0xa5, 0x95, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0x0b, 0x36, 0x42, 0x37, 0x27, - 0x31, 0xa9, 0x18, 0x62, 0x58, 0x05, 0xc2, 0xb8, 0x92, 0xca, 0x82, 0xd4, 0xe2, 0x24, 0x36, 0x70, - 0x48, 0x1a, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x44, 0xff, 0xd6, 0x68, 0xde, 0x01, 0x00, 0x00, +var fileDescriptor_d404c1962bca645f = []byte{ + // 334 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x91, 0xbf, 0x4b, 0x03, 0x31, + 0x14, 0xc7, 0x2f, 0xa2, 0x0e, 0x81, 0x22, 0x1e, 0x22, 0xf6, 0x94, 0x54, 0x0b, 0xfe, 0x1a, 0x9a, + 0xb4, 0x3a, 0xb9, 0x16, 0x41, 0x5c, 0x04, 0x5d, 0x04, 0x97, 0x92, 0xbb, 0x8b, 0x69, 0xa0, 0x97, + 0x5c, 0x9b, 0x5c, 0x69, 0x3b, 0xba, 0xb8, 0x2a, 0xfe, 0x53, 0x1d, 0x0b, 0x2e, 0x4e, 0xa2, 0x57, + 0xff, 0x10, 0xe9, 0xe5, 0x0e, 0xad, 0x28, 0x6e, 0xef, 0xbd, 0xef, 0xf7, 0x7d, 0xf3, 0xe1, 0x05, + 0xae, 0x8f, 0x78, 0x40, 0x42, 0xaa, 0x49, 0xbf, 0x41, 0xba, 0x09, 0xeb, 0x0d, 0x71, 0xdc, 0x53, + 0x46, 0xb9, 0x70, 0xc4, 0x03, 0x1c, 0x52, 0x8d, 0xfb, 0x0d, 0xaf, 0x1c, 0x28, 0x1d, 0x29, 0xdd, + 0xca, 0x14, 0x62, 0x1b, 0x6b, 0xf3, 0xd6, 0xb8, 0xe2, 0xca, 0xce, 0x67, 0x55, 0x3e, 0xdd, 0xe2, + 0x4a, 0xf1, 0x0e, 0x23, 0x34, 0x16, 0x84, 0x4a, 0xa9, 0x0c, 0x35, 0x42, 0xc9, 0x62, 0xa7, 0x9c, + 0xab, 0x59, 0xe7, 0x27, 0xb7, 0x84, 0xca, 0xfc, 0x55, 0xaf, 0xf2, 0x53, 0x32, 0x22, 0x62, 0xda, + 0xd0, 0x28, 0xb6, 0x86, 0xea, 0x26, 0x2c, 0x5f, 0xce, 0x28, 0x2f, 0xd8, 0xc0, 0x5c, 0xb1, 0x6e, + 0xc2, 0xb4, 0x39, 0x3f, 0xcd, 0x8b, 0xea, 0x35, 0xf4, 0x7e, 0x13, 0x75, 0xac, 0xa4, 0x66, 0xee, + 0x09, 0x5c, 0x91, 0x6c, 0x60, 0x5a, 0x3d, 0xab, 0xb4, 0x44, 0xb8, 0x01, 0xb6, 0xc1, 0xc1, 0x62, + 0x73, 0x35, 0x7d, 0xad, 0x94, 0xe6, 0x77, 0x4a, 0xf2, 0x5b, 0x1b, 0x1e, 0x3d, 0x02, 0xb8, 0x94, + 0x25, 0xbb, 0xf7, 0x00, 0xce, 0x5b, 0xdd, 0x5d, 0xfc, 0x75, 0x29, 0xfc, 0x27, 0x9b, 0xb7, 0xf7, + 0x9f, 0xcd, 0x52, 0x56, 0xf7, 0xef, 0x9e, 0x3f, 0x9e, 0x16, 0x76, 0xdc, 0x0a, 0xa9, 0xf3, 0xa0, + 0x4d, 0x85, 0x2c, 0x3e, 0x67, 0x46, 0x54, 0xcb, 0xd9, 0x6b, 0x22, 0x6c, 0x9e, 0x8d, 0xdf, 0x91, + 0x33, 0x4e, 0x11, 0x98, 0xa4, 0x08, 0xbc, 0xa5, 0x08, 0x3c, 0x4c, 0x91, 0x33, 0x99, 0x22, 0xe7, + 0x65, 0x8a, 0x9c, 0x9b, 0x43, 0x2e, 0x4c, 0x3b, 0xf1, 0x71, 0xa0, 0x22, 0x52, 0xe7, 0x1d, 0xea, + 0x6b, 0x52, 0xe7, 0x35, 0x1b, 0x38, 0x28, 0x22, 0xcd, 0x30, 0x66, 0xda, 0x5f, 0xce, 0x2e, 0x7b, + 0xfc, 0x19, 0x00, 0x00, 0xff, 0xff, 0xd5, 0x9e, 0xd6, 0x49, 0x0a, 0x02, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -152,8 +149,7 @@ const _ = grpc.SupportPackageIsVersion4 // // 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 { - // Params queries all parameters of the issuance module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) + NextRequestID(ctx context.Context, in *QueryNextRequestIDRequest, opts ...grpc.CallOption) (*QueryNextRequestIDResponse, error) } type queryClient struct { @@ -164,9 +160,9 @@ 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, "/kava.issuance.v1beta1.Query/Params", in, out, opts...) +func (c *queryClient) NextRequestID(ctx context.Context, in *QueryNextRequestIDRequest, opts ...grpc.CallOption) (*QueryNextRequestIDResponse, error) { + out := new(QueryNextRequestIDResponse) + err := c.cc.Invoke(ctx, "/zgc.das.v1.Query/NextRequestID", in, out, opts...) if err != nil { return nil, err } @@ -175,54 +171,53 @@ func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts . // QueryServer is the server API for Query service. type QueryServer interface { - // Params queries all parameters of the issuance module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) + NextRequestID(context.Context, *QueryNextRequestIDRequest) (*QueryNextRequestIDResponse, 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) NextRequestID(ctx context.Context, req *QueryNextRequestIDRequest) (*QueryNextRequestIDResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method NextRequestID 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) +func _Query_NextRequestID_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryNextRequestIDRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) + return srv.(QueryServer).NextRequestID(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/kava.issuance.v1beta1.Query/Params", + FullMethod: "/zgc.das.v1.Query/NextRequestID", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) + return srv.(QueryServer).NextRequestID(ctx, req.(*QueryNextRequestIDRequest)) } return interceptor(ctx, in, info, handler) } var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.issuance.v1beta1.Query", + ServiceName: "zgc.das.v1.Query", HandlerType: (*QueryServer)(nil), Methods: []grpc.MethodDesc{ { - MethodName: "Params", - Handler: _Query_Params_Handler, + MethodName: "NextRequestID", + Handler: _Query_NextRequestID_Handler, }, }, Streams: []grpc.StreamDesc{}, - Metadata: "kava/issuance/v1beta1/query.proto", + Metadata: "zgc/das/v1/query.proto", } -func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { +func (m *QueryNextRequestIDRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -232,12 +227,12 @@ func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { +func (m *QueryNextRequestIDRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QueryNextRequestIDRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int @@ -245,7 +240,7 @@ func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { +func (m *QueryNextRequestIDResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -255,26 +250,21 @@ func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { +func (m *QueryNextRequestIDResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QueryNextRequestIDResponse) 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)) + if m.NextRequestID != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.NextRequestID)) + i-- + dAtA[i] = 0x8 } - i-- - dAtA[i] = 0xa return len(dAtA) - i, nil } @@ -289,7 +279,7 @@ func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } -func (m *QueryParamsRequest) Size() (n int) { +func (m *QueryNextRequestIDRequest) Size() (n int) { if m == nil { return 0 } @@ -298,14 +288,15 @@ func (m *QueryParamsRequest) Size() (n int) { return n } -func (m *QueryParamsResponse) Size() (n int) { +func (m *QueryNextRequestIDResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l - l = m.Params.Size() - n += 1 + l + sovQuery(uint64(l)) + if m.NextRequestID != 0 { + n += 1 + sovQuery(uint64(m.NextRequestID)) + } return n } @@ -315,7 +306,7 @@ func sovQuery(x uint64) (n int) { func sozQuery(x uint64) (n int) { return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } -func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { +func (m *QueryNextRequestIDRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -338,10 +329,10 @@ func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") + return fmt.Errorf("proto: QueryNextRequestIDRequest: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryNextRequestIDRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: @@ -365,7 +356,7 @@ func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { } return nil } -func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { +func (m *QueryNextRequestIDResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -388,17 +379,17 @@ func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") + return fmt.Errorf("proto: QueryNextRequestIDResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryNextRequestIDResponse: 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) + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field NextRequestID", wireType) } - var msglen int + m.NextRequestID = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery @@ -408,25 +399,11 @@ func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + m.NextRequestID |= uint64(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:]) diff --git a/x/issuance/types/query.pb.gw.go b/x/das/v1/types/query.pb.gw.go similarity index 72% rename from x/issuance/types/query.pb.gw.go rename to x/das/v1/types/query.pb.gw.go index 4dc6a1f0..5567645e 100644 --- a/x/issuance/types/query.pb.gw.go +++ b/x/das/v1/types/query.pb.gw.go @@ -1,5 +1,5 @@ // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/issuance/v1beta1/query.proto +// source: zgc/das/v1/query.proto /* Package types is a reverse proxy. @@ -33,20 +33,20 @@ 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 +func request_Query_NextRequestID_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryNextRequestIDRequest var metadata runtime.ServerMetadata - msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + msg, err := client.NextRequestID(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 +func local_request_Query_NextRequestID_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryNextRequestIDRequest var metadata runtime.ServerMetadata - msg, err := server.Params(ctx, &protoReq) + msg, err := server.NextRequestID(ctx, &protoReq) return msg, metadata, err } @@ -57,7 +57,7 @@ func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshal // 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) { + mux.Handle("GET", pattern_Query_NextRequestID_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -68,7 +68,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_NextRequestID_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 { @@ -76,7 +76,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_NextRequestID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) @@ -121,7 +121,7 @@ func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc // "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) { + mux.Handle("GET", pattern_Query_NextRequestID_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) @@ -130,14 +130,14 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_NextRequestID_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()...) + forward_Query_NextRequestID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) @@ -145,9 +145,9 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } var ( - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "issuance", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_NextRequestID_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"0gchain", "das", "v1", "next-request-id"}, "", runtime.AssumeColonVerbOpt(false))) ) var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage + forward_Query_NextRequestID_0 = runtime.ForwardResponseMessage ) diff --git a/x/das/v1/types/tx.pb.go b/x/das/v1/types/tx.pb.go new file mode 100644 index 00000000..f18f23f6 --- /dev/null +++ b/x/das/v1/types/tx.pb.go @@ -0,0 +1,1110 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: zgc/das/v1/tx.proto + +package types + +import ( + context "context" + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/cosmos-sdk/codec/types" + _ "github.com/cosmos/gogoproto/gogoproto" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + 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 + +type MsgRequestDAS struct { + Requester string `protobuf:"bytes,1,opt,name=requester,proto3" json:"requester,omitempty" Requester` + StreamID string `protobuf:"bytes,2,opt,name=stream_id,json=streamId,proto3" json:"stream_id,omitempty"` + BatchHeaderHash string `protobuf:"bytes,3,opt,name=batch_header_hash,json=batchHeaderHash,proto3" json:"batch_header_hash,omitempty"` + NumBlobs uint32 `protobuf:"varint,4,opt,name=num_blobs,json=numBlobs,proto3" json:"num_blobs,omitempty"` +} + +func (m *MsgRequestDAS) Reset() { *m = MsgRequestDAS{} } +func (m *MsgRequestDAS) String() string { return proto.CompactTextString(m) } +func (*MsgRequestDAS) ProtoMessage() {} +func (*MsgRequestDAS) Descriptor() ([]byte, []int) { + return fileDescriptor_030259cfeac21931, []int{0} +} +func (m *MsgRequestDAS) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgRequestDAS) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgRequestDAS.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 *MsgRequestDAS) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgRequestDAS.Merge(m, src) +} +func (m *MsgRequestDAS) XXX_Size() int { + return m.Size() +} +func (m *MsgRequestDAS) XXX_DiscardUnknown() { + xxx_messageInfo_MsgRequestDAS.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgRequestDAS proto.InternalMessageInfo + +type MsgRequestDASResponse struct { + RequestID uint64 `protobuf:"varint,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` +} + +func (m *MsgRequestDASResponse) Reset() { *m = MsgRequestDASResponse{} } +func (m *MsgRequestDASResponse) String() string { return proto.CompactTextString(m) } +func (*MsgRequestDASResponse) ProtoMessage() {} +func (*MsgRequestDASResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_030259cfeac21931, []int{1} +} +func (m *MsgRequestDASResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgRequestDASResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgRequestDASResponse.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 *MsgRequestDASResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgRequestDASResponse.Merge(m, src) +} +func (m *MsgRequestDASResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgRequestDASResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgRequestDASResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgRequestDASResponse proto.InternalMessageInfo + +type MsgReportDASResult struct { + RequestID uint64 `protobuf:"varint,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + Sampler string `protobuf:"bytes,2,opt,name=sampler,proto3" json:"sampler,omitempty"` + Results []bool `protobuf:"varint,3,rep,packed,name=results,proto3" json:"results,omitempty"` +} + +func (m *MsgReportDASResult) Reset() { *m = MsgReportDASResult{} } +func (m *MsgReportDASResult) String() string { return proto.CompactTextString(m) } +func (*MsgReportDASResult) ProtoMessage() {} +func (*MsgReportDASResult) Descriptor() ([]byte, []int) { + return fileDescriptor_030259cfeac21931, []int{2} +} +func (m *MsgReportDASResult) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgReportDASResult) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgReportDASResult.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 *MsgReportDASResult) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgReportDASResult.Merge(m, src) +} +func (m *MsgReportDASResult) XXX_Size() int { + return m.Size() +} +func (m *MsgReportDASResult) XXX_DiscardUnknown() { + xxx_messageInfo_MsgReportDASResult.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgReportDASResult proto.InternalMessageInfo + +type MsgReportDASResultResponse struct { +} + +func (m *MsgReportDASResultResponse) Reset() { *m = MsgReportDASResultResponse{} } +func (m *MsgReportDASResultResponse) String() string { return proto.CompactTextString(m) } +func (*MsgReportDASResultResponse) ProtoMessage() {} +func (*MsgReportDASResultResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_030259cfeac21931, []int{3} +} +func (m *MsgReportDASResultResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgReportDASResultResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgReportDASResultResponse.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 *MsgReportDASResultResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgReportDASResultResponse.Merge(m, src) +} +func (m *MsgReportDASResultResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgReportDASResultResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgReportDASResultResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgReportDASResultResponse proto.InternalMessageInfo + +func init() { + proto.RegisterType((*MsgRequestDAS)(nil), "zgc.das.v1.MsgRequestDAS") + proto.RegisterType((*MsgRequestDASResponse)(nil), "zgc.das.v1.MsgRequestDASResponse") + proto.RegisterType((*MsgReportDASResult)(nil), "zgc.das.v1.MsgReportDASResult") + proto.RegisterType((*MsgReportDASResultResponse)(nil), "zgc.das.v1.MsgReportDASResultResponse") +} + +func init() { proto.RegisterFile("zgc/das/v1/tx.proto", fileDescriptor_030259cfeac21931) } + +var fileDescriptor_030259cfeac21931 = []byte{ + // 452 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x92, 0x4f, 0x6e, 0xd3, 0x40, + 0x14, 0xc6, 0x63, 0x52, 0x41, 0xf2, 0x44, 0x54, 0x31, 0x80, 0xe4, 0x18, 0xe4, 0x86, 0x2c, 0x50, + 0xca, 0x1f, 0x4f, 0x0b, 0x27, 0x20, 0x0a, 0xa2, 0x41, 0xea, 0x66, 0xba, 0x82, 0x8d, 0x35, 0xb6, + 0x87, 0x71, 0x24, 0xdb, 0x63, 0xfc, 0xec, 0xa8, 0xed, 0x29, 0x38, 0x08, 0x0b, 0x8e, 0xd1, 0x65, + 0x97, 0xac, 0x2a, 0x70, 0x6e, 0xc0, 0x09, 0x90, 0xc7, 0x76, 0xd2, 0x50, 0x81, 0xc4, 0x2e, 0xdf, + 0xf7, 0x9b, 0xf9, 0xe6, 0x7b, 0xf1, 0x83, 0xfb, 0xe7, 0xd2, 0xa7, 0x01, 0x47, 0xba, 0x3c, 0xa4, + 0xf9, 0xa9, 0x93, 0x66, 0x2a, 0x57, 0x04, 0xce, 0xa5, 0xef, 0x04, 0x1c, 0x9d, 0xe5, 0xa1, 0x35, + 0xf4, 0x15, 0xc6, 0x0a, 0x5d, 0x4d, 0x68, 0x2d, 0xea, 0x63, 0xd6, 0x03, 0xa9, 0xa4, 0xaa, 0xfd, + 0xea, 0x57, 0xe3, 0x0e, 0xa5, 0x52, 0x32, 0x12, 0x54, 0x2b, 0xaf, 0xf8, 0x44, 0x79, 0x72, 0xd6, + 0x20, 0xf3, 0xda, 0x63, 0x52, 0x24, 0x02, 0x17, 0x4d, 0xd4, 0xf8, 0x9b, 0x01, 0x83, 0x63, 0x94, + 0x4c, 0x7c, 0x2e, 0x04, 0xe6, 0xb3, 0x37, 0x27, 0xe4, 0x39, 0xf4, 0xb3, 0x5a, 0x89, 0xcc, 0x34, + 0x46, 0xc6, 0xa4, 0x3f, 0x1d, 0xfc, 0xba, 0xda, 0xeb, 0xb3, 0xd6, 0x64, 0x1b, 0x4e, 0xf6, 0xa1, + 0x8f, 0x79, 0x26, 0x78, 0xec, 0x2e, 0x02, 0xf3, 0x96, 0x3e, 0x7c, 0xb7, 0xbc, 0xda, 0xeb, 0x9d, + 0x68, 0x73, 0x3e, 0x63, 0xbd, 0x1a, 0xcf, 0x03, 0xf2, 0x0c, 0xee, 0x79, 0x3c, 0xf7, 0x43, 0x37, + 0x14, 0x3c, 0x10, 0x99, 0x1b, 0x72, 0x0c, 0xcd, 0x6e, 0x75, 0x85, 0xed, 0x6a, 0x70, 0xa4, 0xfd, + 0x23, 0x8e, 0x21, 0x79, 0x04, 0xfd, 0xa4, 0x88, 0x5d, 0x2f, 0x52, 0x1e, 0x9a, 0x3b, 0x23, 0x63, + 0x32, 0x60, 0xbd, 0xa4, 0x88, 0xa7, 0x95, 0x1e, 0xbf, 0x85, 0x87, 0x5b, 0x8d, 0x99, 0xc0, 0x54, + 0x25, 0x28, 0xc8, 0x0b, 0x80, 0xa6, 0x59, 0xd5, 0xa6, 0xaa, 0xbe, 0x33, 0x1d, 0x94, 0x9b, 0xea, + 0xf3, 0xd9, 0xba, 0xfa, 0x3c, 0x18, 0x2f, 0x81, 0xe8, 0x98, 0x54, 0x65, 0x4d, 0x4a, 0x11, 0xe5, + 0xff, 0x97, 0x41, 0x4c, 0xb8, 0x83, 0x3c, 0x4e, 0x23, 0x91, 0xd5, 0xc3, 0xb3, 0x56, 0x56, 0x24, + 0xd3, 0x89, 0x68, 0x76, 0x47, 0xdd, 0x49, 0x8f, 0xb5, 0x72, 0xfc, 0x18, 0xac, 0x9b, 0xef, 0xb6, + 0x33, 0xbc, 0xfa, 0x6a, 0x40, 0xf7, 0x18, 0x25, 0x79, 0x0f, 0x70, 0xed, 0x9b, 0x0c, 0x9d, 0xcd, + 0x62, 0x38, 0x5b, 0xc3, 0x5b, 0x4f, 0xfe, 0x8a, 0xd6, 0xff, 0xcb, 0x07, 0xd8, 0xfd, 0x73, 0x4c, + 0xfb, 0xc6, 0xad, 0x2d, 0x6e, 0x3d, 0xfd, 0x37, 0x6f, 0xa3, 0xa7, 0xef, 0x2e, 0x7e, 0xda, 0x9d, + 0x8b, 0xd2, 0x36, 0x2e, 0x4b, 0xdb, 0xf8, 0x51, 0xda, 0xc6, 0x97, 0x95, 0xdd, 0xb9, 0x5c, 0xd9, + 0x9d, 0xef, 0x2b, 0xbb, 0xf3, 0x71, 0x5f, 0x2e, 0xf2, 0xb0, 0xf0, 0x1c, 0x5f, 0xc5, 0xf4, 0x40, + 0x46, 0xdc, 0x43, 0x7a, 0x20, 0x5f, 0xfa, 0x21, 0x5f, 0x24, 0xf4, 0x74, 0xbd, 0xfc, 0x67, 0xa9, + 0x40, 0xef, 0xb6, 0x5e, 0xc7, 0xd7, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0xc2, 0xba, 0x08, 0x98, + 0x17, 0x03, 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 { + RequestDAS(ctx context.Context, in *MsgRequestDAS, opts ...grpc.CallOption) (*MsgRequestDASResponse, error) + ReportDASResult(ctx context.Context, in *MsgReportDASResult, opts ...grpc.CallOption) (*MsgReportDASResultResponse, error) +} + +type msgClient struct { + cc grpc1.ClientConn +} + +func NewMsgClient(cc grpc1.ClientConn) MsgClient { + return &msgClient{cc} +} + +func (c *msgClient) RequestDAS(ctx context.Context, in *MsgRequestDAS, opts ...grpc.CallOption) (*MsgRequestDASResponse, error) { + out := new(MsgRequestDASResponse) + err := c.cc.Invoke(ctx, "/zgc.das.v1.Msg/RequestDAS", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) ReportDASResult(ctx context.Context, in *MsgReportDASResult, opts ...grpc.CallOption) (*MsgReportDASResultResponse, error) { + out := new(MsgReportDASResultResponse) + err := c.cc.Invoke(ctx, "/zgc.das.v1.Msg/ReportDASResult", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// MsgServer is the server API for Msg service. +type MsgServer interface { + RequestDAS(context.Context, *MsgRequestDAS) (*MsgRequestDASResponse, error) + ReportDASResult(context.Context, *MsgReportDASResult) (*MsgReportDASResultResponse, error) +} + +// UnimplementedMsgServer can be embedded to have forward compatible implementations. +type UnimplementedMsgServer struct { +} + +func (*UnimplementedMsgServer) RequestDAS(ctx context.Context, req *MsgRequestDAS) (*MsgRequestDASResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method RequestDAS not implemented") +} +func (*UnimplementedMsgServer) ReportDASResult(ctx context.Context, req *MsgReportDASResult) (*MsgReportDASResultResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ReportDASResult not implemented") +} + +func RegisterMsgServer(s grpc1.Server, srv MsgServer) { + s.RegisterService(&_Msg_serviceDesc, srv) +} + +func _Msg_RequestDAS_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgRequestDAS) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).RequestDAS(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/zgc.das.v1.Msg/RequestDAS", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).RequestDAS(ctx, req.(*MsgRequestDAS)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_ReportDASResult_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgReportDASResult) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).ReportDASResult(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/zgc.das.v1.Msg/ReportDASResult", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).ReportDASResult(ctx, req.(*MsgReportDASResult)) + } + return interceptor(ctx, in, info, handler) +} + +var _Msg_serviceDesc = grpc.ServiceDesc{ + ServiceName: "zgc.das.v1.Msg", + HandlerType: (*MsgServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "RequestDAS", + Handler: _Msg_RequestDAS_Handler, + }, + { + MethodName: "ReportDASResult", + Handler: _Msg_ReportDASResult_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "zgc/das/v1/tx.proto", +} + +func (m *MsgRequestDAS) 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 *MsgRequestDAS) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgRequestDAS) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.NumBlobs != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.NumBlobs)) + i-- + dAtA[i] = 0x20 + } + if len(m.BatchHeaderHash) > 0 { + i -= len(m.BatchHeaderHash) + copy(dAtA[i:], m.BatchHeaderHash) + i = encodeVarintTx(dAtA, i, uint64(len(m.BatchHeaderHash))) + i-- + dAtA[i] = 0x1a + } + if len(m.StreamID) > 0 { + i -= len(m.StreamID) + copy(dAtA[i:], m.StreamID) + i = encodeVarintTx(dAtA, i, uint64(len(m.StreamID))) + i-- + dAtA[i] = 0x12 + } + if len(m.Requester) > 0 { + i -= len(m.Requester) + copy(dAtA[i:], m.Requester) + i = encodeVarintTx(dAtA, i, uint64(len(m.Requester))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgRequestDASResponse) 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 *MsgRequestDASResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgRequestDASResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.RequestID != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.RequestID)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *MsgReportDASResult) 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 *MsgReportDASResult) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgReportDASResult) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Results) > 0 { + for iNdEx := len(m.Results) - 1; iNdEx >= 0; iNdEx-- { + i-- + if m.Results[iNdEx] { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + } + i = encodeVarintTx(dAtA, i, uint64(len(m.Results))) + i-- + dAtA[i] = 0x1a + } + if len(m.Sampler) > 0 { + i -= len(m.Sampler) + copy(dAtA[i:], m.Sampler) + i = encodeVarintTx(dAtA, i, uint64(len(m.Sampler))) + i-- + dAtA[i] = 0x12 + } + if m.RequestID != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.RequestID)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *MsgReportDASResultResponse) 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 *MsgReportDASResultResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgReportDASResultResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func encodeVarintTx(dAtA []byte, offset int, v uint64) int { + offset -= sovTx(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *MsgRequestDAS) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Requester) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.StreamID) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.BatchHeaderHash) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if m.NumBlobs != 0 { + n += 1 + sovTx(uint64(m.NumBlobs)) + } + return n +} + +func (m *MsgRequestDASResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.RequestID != 0 { + n += 1 + sovTx(uint64(m.RequestID)) + } + return n +} + +func (m *MsgReportDASResult) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.RequestID != 0 { + n += 1 + sovTx(uint64(m.RequestID)) + } + l = len(m.Sampler) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if len(m.Results) > 0 { + n += 1 + sovTx(uint64(len(m.Results))) + len(m.Results)*1 + } + return n +} + +func (m *MsgReportDASResultResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func sovTx(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTx(x uint64) (n int) { + return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *MsgRequestDAS) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgRequestDAS: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgRequestDAS: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Requester", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Requester = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field StreamID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.StreamID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BatchHeaderHash", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.BatchHeaderHash = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field NumBlobs", wireType) + } + m.NumBlobs = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.NumBlobs |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgRequestDASResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgRequestDASResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgRequestDASResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field RequestID", wireType) + } + m.RequestID = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.RequestID |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgReportDASResult) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgReportDASResult: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgReportDASResult: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field RequestID", wireType) + } + m.RequestID = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.RequestID |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Sampler", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Sampler = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType == 0 { + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Results = append(m.Results, bool(v != 0)) + } else if wireType == 2 { + var packedLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + packedLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if packedLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + packedLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + var elementCount int + elementCount = packedLen + if elementCount != 0 && len(m.Results) == 0 { + m.Results = make([]bool, 0, elementCount) + } + for iNdEx < postIndex { + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Results = append(m.Results, bool(v != 0)) + } + } else { + return fmt.Errorf("proto: wrong wireType = %d for field Results", wireType) + } + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgReportDASResultResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgReportDASResultResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgReportDASResultResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTx(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, ErrIntOverflowTx + } + 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, ErrIntOverflowTx + } + 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, ErrIntOverflowTx + } + 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, ErrInvalidLengthTx + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTx + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTx + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/earn/client/cli/query.go b/x/earn/client/cli/query.go deleted file mode 100644 index 129eb279..00000000 --- a/x/earn/client/cli/query.go +++ /dev/null @@ -1,208 +0,0 @@ -package cli - -import ( - "context" - "fmt" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/kava-labs/kava/x/earn/types" -) - -// flags for cli queries -const ( - flagDenom = "denom" - flagOwner = "owner" - flagValueInStakedTokens = "value_in_staked_tokens" -) - -// GetQueryCmd returns the cli query commands for the earn module -func GetQueryCmd() *cobra.Command { - earnQueryCommand := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the earn module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - queryParamsCmd(), - queryVaultsCmd(), - queryVaultCmd(), - queryDepositsCmd(), - queryTotalSupplyCmd(), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - earnQueryCommand.AddCommand(cmds...) - - return earnQueryCommand -} - -func queryParamsCmd() *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: "get the earn module parameters", - Long: "Get the current earn module parameters.", - 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) - - req := types.NewQueryParamsRequest() - res, err := queryClient.Params(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } -} - -func queryVaultsCmd() *cobra.Command { - return &cobra.Command{ - Use: "vaults", - Short: "get all earn vaults", - Long: "Get all earn module vaults.", - Args: cobra.NoArgs, - Example: fmt.Sprintf(`%[1]s q %[2]s vaults`, version.AppName, types.ModuleName), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - req := types.NewQueryVaultsRequest() - res, err := queryClient.Vaults(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -func queryVaultCmd() *cobra.Command { - return &cobra.Command{ - Use: "vault", - Short: "get a earn vault", - Long: "Get a specific earn module vault by denom.", - Args: cobra.ExactArgs(1), - Example: fmt.Sprintf(`%[1]s q %[2]s vault usdx`, version.AppName, types.ModuleName), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - req := types.NewQueryVaultRequest(args[0]) - res, err := queryClient.Vault(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -func queryDepositsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "deposits", - Short: "get earn vault deposits", - Long: "Get earn vault deposits for all or specific accounts and vaults.", - Args: cobra.NoArgs, - Example: fmt.Sprintf(`%[1]s q %[2]s deposits -%[1]s q %[2]s deposits --owner kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny --denom usdx -%[1]s q %[2]s deposits --denom usdx`, version.AppName, types.ModuleName), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - ownerBech, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - valueInStakedTokens, err := cmd.Flags().GetBool(flagValueInStakedTokens) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - req := types.NewQueryDepositsRequest( - ownerBech, - denom, - valueInStakedTokens, - pageReq, - ) - res, err := queryClient.Deposits(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, "deposits") - - cmd.Flags().String(flagOwner, "", "(optional) filter for deposits by owner address") - cmd.Flags().String(flagDenom, "", "(optional) filter for deposits by vault denom") - cmd.Flags().Bool(flagValueInStakedTokens, false, "(optional) get underlying staked tokens for staking derivative vaults") - - return cmd -} - -func queryTotalSupplyCmd() *cobra.Command { - return &cobra.Command{ - Use: "total-supply", - Short: "get total supply across all savings strategy vaults", - Long: "Get the sum of all denoms locking into vaults that allow the savings strategy.", - 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.TotalSupply(context.Background(), &types.QueryTotalSupplyRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} diff --git a/x/earn/client/cli/tx.go b/x/earn/client/cli/tx.go deleted file mode 100644 index 2ab9e45d..00000000 --- a/x/earn/client/cli/tx.go +++ /dev/null @@ -1,229 +0,0 @@ -package cli - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - "github.com/kava-labs/kava/x/earn/types" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - earnTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName), - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - getCmdDeposit(), - getCmdWithdraw(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - earnTxCmd.AddCommand(cmds...) - - return earnTxCmd -} - -func getCmdDeposit() *cobra.Command { - return &cobra.Command{ - Use: "deposit [amount] [strategy]", - Short: "deposit coins to an earn vault", - Example: fmt.Sprintf( - `%s tx %s deposit 10000000ukava hard --from `, - version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - amount, err := sdk.ParseCoinNormalized(args[0]) - if err != nil { - return err - } - - strategy := types.NewStrategyTypeFromString(args[1]) - if !strategy.IsValid() { - return fmt.Errorf("invalid strategy type: %s", args[1]) - } - - signer := clientCtx.GetFromAddress() - msg := types.NewMsgDeposit(signer.String(), amount, strategy) - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} - -func getCmdWithdraw() *cobra.Command { - return &cobra.Command{ - Use: "withdraw [amount] [strategy]", - Short: "withdraw coins from an earn vault", - Example: fmt.Sprintf( - `%s tx %s withdraw 10000000ukava hard --from `, - version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - amount, err := sdk.ParseCoinNormalized(args[0]) - if err != nil { - return err - } - - strategy := types.NewStrategyTypeFromString(args[1]) - if !strategy.IsValid() { - return fmt.Errorf("invalid strategy type: %s", args[1]) - } - - fromAddr := clientCtx.GetFromAddress() - msg := types.NewMsgWithdraw(fromAddr.String(), amount, strategy) - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} - -// GetCmdSubmitCommunityPoolDepositProposal implements the command to submit a community-pool deposit proposal -func GetCmdSubmitCommunityPoolDepositProposal() *cobra.Command { - cmd := &cobra.Command{ - Use: "community-pool-deposit [proposal-file]", - Args: cobra.ExactArgs(1), - Short: "Submit a community pool deposit proposal", - Long: strings.TrimSpace( - fmt.Sprintf(`Submit a community pool deposit proposal along with an initial deposit. -The proposal details must be supplied via a JSON file. -Example: -$ %s tx gov submit-proposal community-pool-deposit --from= -Where proposal.json contains: -{ - "title": "Community Pool Deposit", - "description": "Deposit some KAVA from community pool!", - "amount": - { - "denom": "ukava", - "amount": "100000000000" - }, - "deposit": [ - { - "denom": "ukava", - "amount": "1000000000" - } - ] -} -`, - version.AppName, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - proposal, err := ParseCommunityPoolDepositProposalJSON(clientCtx.Codec, args[0]) - if err != nil { - return err - } - - from := clientCtx.GetFromAddress() - content := types.NewCommunityPoolDepositProposal(proposal.Title, proposal.Description, proposal.Amount) - msg, err := govv1beta1.NewMsgSubmitProposal(content, proposal.Deposit, from) - if err != nil { - return err - } - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - return cmd -} - -// GetCmdSubmitCommunityPoolWithdrawProposal implements the command to submit a community-pool withdraw proposal -func GetCmdSubmitCommunityPoolWithdrawProposal() *cobra.Command { - cmd := &cobra.Command{ - Use: "community-pool-withdraw [proposal-file]", - Args: cobra.ExactArgs(1), - Short: "Submit a community pool withdraw proposal", - Long: strings.TrimSpace( - fmt.Sprintf(`Submit a community pool withdraw proposal along with an initial deposit. -The proposal details must be supplied via a JSON file. -Example: -$ %s tx gov submit-proposal community-pool-withdraw --from= -Where proposal.json contains: -{ - "title": "Community Pool Withdraw", - "description": "Withdraw some KAVA from community pool!", - "amount": - { - "denom": "ukava", - "amount": "100000000000" - }, - "deposit": [ - { - "denom": "ukava", - "amount": "1000000000" - } - ] -} -`, - version.AppName, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - proposal, err := ParseCommunityPoolWithdrawProposalJSON(clientCtx.Codec, args[0]) - if err != nil { - return err - } - - from := clientCtx.GetFromAddress() - content := types.NewCommunityPoolWithdrawProposal(proposal.Title, proposal.Description, proposal.Amount) - msg, err := govv1beta1.NewMsgSubmitProposal(content, proposal.Deposit, from) - if err != nil { - return err - } - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - return cmd -} diff --git a/x/earn/client/cli/utils.go b/x/earn/client/cli/utils.go deleted file mode 100644 index c8693ec4..00000000 --- a/x/earn/client/cli/utils.go +++ /dev/null @@ -1,39 +0,0 @@ -package cli - -import ( - "os" - - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/kava-labs/kava/x/earn/types" -) - -// ParseCommunityPoolDepositProposalJSON reads and parses a CommunityPoolDepositProposalJSON from a file. -func ParseCommunityPoolDepositProposalJSON(cdc codec.JSONCodec, proposalFile string) (types.CommunityPoolDepositProposalJSON, error) { - proposal := types.CommunityPoolDepositProposalJSON{} - contents, err := os.ReadFile(proposalFile) - if err != nil { - return proposal, err - } - - if err := cdc.UnmarshalJSON(contents, &proposal); err != nil { - return proposal, err - } - - return proposal, nil -} - -// ParseCommunityPoolWithdrawProposalJSON reads and parses a CommunityPoolWithdrawProposalJSON from a file. -func ParseCommunityPoolWithdrawProposalJSON(cdc codec.JSONCodec, proposalFile string) (types.CommunityPoolWithdrawProposalJSON, error) { - proposal := types.CommunityPoolWithdrawProposalJSON{} - contents, err := os.ReadFile(proposalFile) - if err != nil { - return proposal, err - } - - if err := cdc.UnmarshalJSON(contents, &proposal); err != nil { - return proposal, err - } - - return proposal, nil -} diff --git a/x/earn/client/proposal_handler.go b/x/earn/client/proposal_handler.go deleted file mode 100644 index 22d75829..00000000 --- a/x/earn/client/proposal_handler.go +++ /dev/null @@ -1,13 +0,0 @@ -package client - -import ( - govclient "github.com/cosmos/cosmos-sdk/x/gov/client" - - "github.com/kava-labs/kava/x/earn/client/cli" -) - -// community-pool deposit/withdraw proposal handlers -var ( - DepositProposalHandler = govclient.NewProposalHandler(cli.GetCmdSubmitCommunityPoolDepositProposal) - WithdrawProposalHandler = govclient.NewProposalHandler(cli.GetCmdSubmitCommunityPoolWithdrawProposal) -) diff --git a/x/earn/genesis.go b/x/earn/genesis.go deleted file mode 100644 index 0fd7212a..00000000 --- a/x/earn/genesis.go +++ /dev/null @@ -1,63 +0,0 @@ -package earn - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/earn/keeper" - "github.com/kava-labs/kava/x/earn/types" -) - -// InitGenesis initializes genesis state -func InitGenesis( - ctx sdk.Context, - k keeper.Keeper, - ak types.AccountKeeper, - gs types.GenesisState, -) { - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - // Total of all vault share records, vault record total supply should equal this - vaultTotalShares := types.NewVaultShares() - - for _, vaultShareRecord := range gs.VaultShareRecords { - if err := vaultShareRecord.Validate(); err != nil { - panic(fmt.Sprintf("invalid vault share: %s", err)) - } - - vaultTotalShares = vaultTotalShares.Add(vaultShareRecord.Shares...) - - k.SetVaultShareRecord(ctx, vaultShareRecord) - } - - for _, vaultRecord := range gs.VaultRecords { - if err := vaultRecord.Validate(); err != nil { - panic(fmt.Sprintf("invalid vault record: %s", err)) - } - - if !vaultRecord.TotalShares.Amount.Equal(vaultTotalShares.AmountOf(vaultRecord.TotalShares.Denom)) { - panic(fmt.Sprintf( - "invalid vault record total supply for %s, got %s but sum of vault shares is %s", - vaultRecord.TotalShares.Denom, - vaultRecord.TotalShares.Amount, - vaultTotalShares.AmountOf(vaultRecord.TotalShares.Denom), - )) - } - - k.SetVaultRecord(ctx, vaultRecord) - } - - k.SetParams(ctx, gs.Params) -} - -// ExportGenesis returns a GenesisState for a given context and keeper -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { - params := k.GetParams(ctx) - vaultRecords := k.GetAllVaultRecords(ctx) - vaultShareRecords := k.GetAllVaultShareRecords(ctx) - - return types.NewGenesisState(params, vaultRecords, vaultShareRecords) -} diff --git a/x/earn/genesis_test.go b/x/earn/genesis_test.go deleted file mode 100644 index 2d982a6d..00000000 --- a/x/earn/genesis_test.go +++ /dev/null @@ -1,178 +0,0 @@ -package earn_test - -import ( - "testing" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/earn" - "github.com/kava-labs/kava/x/earn/testutil" - "github.com/kava-labs/kava/x/earn/types" - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type genesisTestSuite struct { - testutil.Suite -} - -func (suite *genesisTestSuite) Test_InitGenesis_ValidationPanic() { - invalidState := types.NewGenesisState( - types.Params{ - AllowedVaults: types.AllowedVaults{ - types.NewAllowedVault( - "usdx", types.StrategyTypes{types.STRATEGY_TYPE_HARD}, - false, - nil, - ), - }, - }, - types.VaultRecords{ - { - TotalShares: types.VaultShare{ - Denom: "", Amount: sdk.NewDec(1), - }, - }, - }, - types.VaultShareRecords{}, - ) - - suite.Panics(func() { - earn.InitGenesis(suite.Ctx, suite.Keeper, suite.AccountKeeper, invalidState) - }, "expected init genesis to panic with invalid state") -} - -func (suite *genesisTestSuite) Test_InitAndExportGenesis() { - depositor_1, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") - suite.Require().NoError(err) - depositor_2, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - suite.Require().NoError(err) - - // slices are sorted by key as stored in the data store, so init and export can be compared with equal - state := types.NewGenesisState( - types.Params{ - AllowedVaults: types.AllowedVaults{ - types.NewAllowedVault( - "usdx", - types.StrategyTypes{types.STRATEGY_TYPE_HARD}, - false, - nil, - ), - types.NewAllowedVault( - "ukava", - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - true, - []sdk.AccAddress{suite.AccountKeeper.GetModuleAddress("distribution")}, - ), - }, - }, - types.VaultRecords{ - types.VaultRecord{ - TotalShares: types.NewVaultShare("ukava", sdk.NewDec(3800000)), - }, - types.VaultRecord{ - TotalShares: types.NewVaultShare("usdx", sdk.NewDec(1000000)), - }, - }, - types.VaultShareRecords{ - types.VaultShareRecord{ - Depositor: depositor_1, - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(500000)), - types.NewVaultShare("ukava", sdk.NewDec(1900000)), - ), - }, - types.VaultShareRecord{ - Depositor: depositor_2, - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(500000)), - types.NewVaultShare("ukava", sdk.NewDec(1900000)), - ), - }, - }, - ) - - earn.InitGenesis(suite.Ctx, suite.Keeper, suite.AccountKeeper, state) - suite.Equal(state.Params, suite.Keeper.GetParams(suite.Ctx)) - - vaultRecord1, _ := suite.Keeper.GetVaultRecord(suite.Ctx, "ukava") - vaultRecord2, _ := suite.Keeper.GetVaultRecord(suite.Ctx, "usdx") - suite.Equal(state.VaultRecords[0], vaultRecord1) - suite.Equal(state.VaultRecords[1], vaultRecord2) - - shareRecord1, _ := suite.Keeper.GetVaultShareRecord(suite.Ctx, depositor_1) - shareRecord2, _ := suite.Keeper.GetVaultShareRecord(suite.Ctx, depositor_2) - - suite.Equal(state.VaultShareRecords[0], shareRecord1) - suite.Equal(state.VaultShareRecords[1], shareRecord2) - - exportedState := earn.ExportGenesis(suite.Ctx, suite.Keeper) - suite.Equal(state, exportedState) -} - -func (suite *genesisTestSuite) Test_Marshall() { - depositor_1, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") - suite.Require().NoError(err) - depositor_2, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - suite.Require().NoError(err) - - // slices are sorted by key as stored in the data store, so init and export can be compared with equal - state := types.NewGenesisState( - types.Params{ - AllowedVaults: types.AllowedVaults{ - types.NewAllowedVault( - "usdx", - types.StrategyTypes{types.STRATEGY_TYPE_HARD}, - false, - nil, - ), - types.NewAllowedVault( - "ukava", - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - true, - []sdk.AccAddress{suite.AccountKeeper.GetModuleAddress("distribution")}, - ), - }, - }, - types.VaultRecords{ - types.VaultRecord{ - TotalShares: types.NewVaultShare("ukava", sdk.NewDec(3800000)), - }, - types.VaultRecord{ - TotalShares: types.NewVaultShare("usdx", sdk.NewDec(1000000)), - }, - }, - types.VaultShareRecords{ - types.VaultShareRecord{ - Depositor: depositor_1, - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(500000)), - types.NewVaultShare("ukava", sdk.NewDec(1900000)), - ), - }, - types.VaultShareRecord{ - Depositor: depositor_2, - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(500000)), - types.NewVaultShare("ukava", sdk.NewDec(1900000)), - ), - }, - }, - ) - - encodingCfg := app.MakeEncodingConfig() - cdc := encodingCfg.Marshaler - - bz, err := cdc.Marshal(&state) - suite.Require().NoError(err, "expected genesis state to marshal without error") - - var decodedState types.GenesisState - err = cdc.Unmarshal(bz, &decodedState) - suite.Require().NoError(err, "expected genesis state to unmarshal without error") - - suite.Equal(state, decodedState) -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(genesisTestSuite)) -} diff --git a/x/earn/handler.go b/x/earn/handler.go deleted file mode 100644 index 08ed4ef4..00000000 --- a/x/earn/handler.go +++ /dev/null @@ -1,25 +0,0 @@ -package earn - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - "github.com/kava-labs/kava/x/earn/keeper" - "github.com/kava-labs/kava/x/earn/types" -) - -// NewCommunityPoolProposalHandler -func NewCommunityPoolProposalHandler(k keeper.Keeper) govv1beta1.Handler { - return func(ctx sdk.Context, content govv1beta1.Content) error { - switch c := content.(type) { - case *types.CommunityPoolDepositProposal: - return keeper.HandleCommunityPoolDepositProposal(ctx, k, c) - case *types.CommunityPoolWithdrawProposal: - return keeper.HandleCommunityPoolWithdrawProposal(ctx, k, c) - default: - return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized earn proposal content type: %T", c) - } - } -} diff --git a/x/earn/keeper/deposit.go b/x/earn/keeper/deposit.go deleted file mode 100644 index 5598e5c1..00000000 --- a/x/earn/keeper/deposit.go +++ /dev/null @@ -1,127 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/earn/types" -) - -// Deposit adds the provided amount from a depositor to a vault. The vault is -// specified by the denom in the amount. -func (k *Keeper) Deposit( - ctx sdk.Context, - depositor sdk.AccAddress, - amount sdk.Coin, - depositStrategy types.StrategyType, -) error { - // Get AllowedVault, if not found (not a valid vault), return error - allowedVault, found := k.GetAllowedVault(ctx, amount.Denom) - if !found { - return types.ErrInvalidVaultDenom - } - - if amount.IsZero() { - return types.ErrInsufficientAmount - } - - // Check if deposit strategy is supported by vault - if !allowedVault.IsStrategyAllowed(depositStrategy) { - return types.ErrInvalidVaultStrategy - } - - // Check if account can deposit -- this checks if the vault is private - // and if so, if the depositor is in the AllowedDepositors list - if !allowedVault.IsAccountAllowed(depositor) { - return types.ErrAccountDepositNotAllowed - } - - // Check if VaultRecord exists, create if not exist - vaultRecord, found := k.GetVaultRecord(ctx, amount.Denom) - if !found { - // Create a new VaultRecord with 0 supply - vaultRecord = types.NewVaultRecord(amount.Denom, sdk.ZeroDec()) - } - - // Get the strategy for the vault - // NOTE: Currently always uses the first one, AllowedVaults are currently - // only valid with 1 and only 1 strategy so this is safe. - // If/When multiple strategies are supported and users can specify specific - // strategies, shares should be issued per-strategy instead of per-vault. - strategy, err := k.GetStrategy(allowedVault.Strategies[0]) - if err != nil { - return err - } - - // Transfer amount to module account - if err := k.bankKeeper.SendCoinsFromAccountToModule( - ctx, - depositor, - types.ModuleName, - sdk.NewCoins(amount), - ); err != nil { - return err - } - - // Get VaultShareRecord for account, create if account has no deposits. - // This can still be found if the account has deposits for other vaults. - vaultShareRecord, found := k.GetVaultShareRecord(ctx, depositor) - if !found { - // Create a new empty VaultShareRecord with 0 supply - vaultShareRecord = types.NewVaultShareRecord(depositor, types.NewVaultShares()) - } - - shares, err := k.ConvertToShares(ctx, amount) - if err != nil { - return fmt.Errorf("failed to convert assets to shares: %w", err) - } - - isNew := vaultShareRecord.Shares.AmountOf(amount.Denom).IsZero() - if !isNew { - // If deposits for this vault already exists, call hook with user's existing shares - k.BeforeVaultDepositModified(ctx, amount.Denom, depositor, vaultShareRecord.Shares.AmountOf(amount.Denom)) - } - - // Increment VaultRecord total shares and account shares - vaultRecord.TotalShares = vaultRecord.TotalShares.Add(shares) - vaultShareRecord.Shares = vaultShareRecord.Shares.Add(shares) - - // Update VaultRecord and VaultShareRecord - k.SetVaultRecord(ctx, vaultRecord) - k.SetVaultShareRecord(ctx, vaultShareRecord) - - if isNew { - // If first deposit in this vault - k.AfterVaultDepositCreated(ctx, amount.Denom, depositor, shares.Amount) - } - - // Deposit to the strategy - if err := strategy.Deposit(ctx, amount); err != nil { - return err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeVaultDeposit, - sdk.NewAttribute(types.AttributeKeyVaultDenom, amount.Denom), - sdk.NewAttribute(types.AttributeKeyDepositor, depositor.String()), - sdk.NewAttribute(types.AttributeKeyShares, shares.Amount.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, amount.Amount.String()), - ), - ) - - return nil -} - -// DepositFromModuleAccount adds the provided amount from a depositor module -// account to a vault. The vault is specified by the denom in the amount. -func (k *Keeper) DepositFromModuleAccount( - ctx sdk.Context, - from string, - wantAmount sdk.Coin, - withdrawStrategy types.StrategyType, -) error { - addr := k.accountKeeper.GetModuleAddress(from) - return k.Deposit(ctx, addr, wantAmount, withdrawStrategy) -} diff --git a/x/earn/keeper/deposit_test.go b/x/earn/keeper/deposit_test.go deleted file mode 100644 index 806d1b17..00000000 --- a/x/earn/keeper/deposit_test.go +++ /dev/null @@ -1,193 +0,0 @@ -package keeper_test - -import ( - "os" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/earn/testutil" - "github.com/kava-labs/kava/x/earn/types" - "github.com/stretchr/testify/suite" -) - -func TestMain(m *testing.M) { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - os.Exit(m.Run()) -} - -type depositTestSuite struct { - testutil.Suite -} - -func (suite *depositTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestDepositTestSuite(t *testing.T) { - suite.Run(t, new(depositTestSuite)) -} - -func (suite *depositTestSuite) TestDeposit_Balances() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance.Sub(depositAmount)), // Account decreases by deposit - ) - - suite.VaultTotalValuesEqual(sdk.NewCoins(depositAmount)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(depositAmount.Denom, sdk.NewDecFromInt(depositAmount.Amount)), - )) -} - -func (suite *depositTestSuite) TestDeposit_Exceed() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 1001) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, sdkerrors.ErrInsufficientFunds) - - // No changes in balances - - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.ModuleAccountBalanceEqual( - sdk.NewCoins(), - ) -} - -func (suite *depositTestSuite) TestDeposit_Zero() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 0) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrInsufficientAmount) - - // No changes in balances - - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.ModuleAccountBalanceEqual( - sdk.NewCoins(), - ) -} - -func (suite *depositTestSuite) TestDeposit_InvalidVault() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 1001) - - // Vault not created -- doesn't exist - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrInvalidVaultDenom) - - // No changes in balances - - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.ModuleAccountBalanceEqual( - sdk.NewCoins(), - ) -} - -func (suite *depositTestSuite) TestDeposit_InvalidStrategy() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 1001) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrInvalidVaultStrategy) -} - -func (suite *depositTestSuite) TestDeposit_PrivateVault() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1) - - suite.CreateVault( - vaultDenom, - types.StrategyTypes{types.STRATEGY_TYPE_HARD}, - true, - []sdk.AccAddress{acc1.GetAddress()}, - ) - - err := suite.Keeper.Deposit(suite.Ctx, acc2.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrAccountDepositNotAllowed, "private vault should not allow deposits from non-allowed addresses") - - err = suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err, "private vault should allow deposits from allowed addresses") -} - -func (suite *depositTestSuite) TestDeposit_bKava() { - vaultDenom := "bkava" - coinDenom := testutil.TestBkavaDenoms[0] - - startBalance := sdk.NewInt64Coin(coinDenom, 1000) - depositAmount := sdk.NewInt64Coin(coinDenom, 100) - - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // vault denom is only "bkava" which has it's own special handler - suite.CreateVault( - vaultDenom, - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - false, - []sdk.AccAddress{}, - ) - - err := suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError( - err, - "should be able to deposit bkava derivative denom in bkava vault", - ) -} diff --git a/x/earn/keeper/grpc_query.go b/x/earn/keeper/grpc_query.go deleted file mode 100644 index b3175c9b..00000000 --- a/x/earn/keeper/grpc_query.go +++ /dev/null @@ -1,569 +0,0 @@ -package keeper - -import ( - "context" - "fmt" - "strings" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/earn/types" -) - -type queryServer struct { - keeper Keeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -var _ types.QueryServer = queryServer{} - -// Params implements the gRPC service handler for querying x/earn parameters. -func (s queryServer) Params( - ctx context.Context, - req *types.QueryParamsRequest, -) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - params := s.keeper.GetParams(sdkCtx) - - return &types.QueryParamsResponse{Params: params}, nil -} - -// Vaults implements the gRPC service handler for querying x/earn vaults. -func (s queryServer) Vaults( - ctx context.Context, - req *types.QueryVaultsRequest, -) (*types.QueryVaultsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - allowedVaults := s.keeper.GetAllowedVaults(sdkCtx) - allowedVaultsMap := make(map[string]types.AllowedVault) - visitedMap := make(map[string]bool) - for _, av := range allowedVaults { - allowedVaultsMap[av.Denom] = av - visitedMap[av.Denom] = false - } - - vaults := []types.VaultResponse{} - - var vaultRecordsErr error - - // Iterate over vault records instead of AllowedVaults to get all bkava-* - // vaults - s.keeper.IterateVaultRecords(sdkCtx, func(record types.VaultRecord) bool { - // Check if bkava, use allowed vault - allowedVaultDenom := record.TotalShares.Denom - if strings.HasPrefix(record.TotalShares.Denom, bkavaPrefix) { - allowedVaultDenom = bkavaDenom - } - - allowedVault, found := allowedVaultsMap[allowedVaultDenom] - if !found { - vaultRecordsErr = fmt.Errorf("vault record not found for vault record denom %s", record.TotalShares.Denom) - return true - } - - totalValue, err := s.keeper.GetVaultTotalValue(sdkCtx, record.TotalShares.Denom) - if err != nil { - vaultRecordsErr = err - // Stop iterating if error - return true - } - - vaults = append(vaults, types.VaultResponse{ - Denom: record.TotalShares.Denom, - Strategies: allowedVault.Strategies, - IsPrivateVault: allowedVault.IsPrivateVault, - AllowedDepositors: addressSliceToStringSlice(allowedVault.AllowedDepositors), - TotalShares: record.TotalShares.Amount.String(), - TotalValue: totalValue.Amount, - }) - - // Mark this allowed vault as visited - visitedMap[allowedVaultDenom] = true - - return false - }) - - if vaultRecordsErr != nil { - return nil, vaultRecordsErr - } - - // Add the allowed vaults that have not been visited yet - // These are always empty vaults, as the vault would have been visited - // earlier if there are any deposits - for denom, visited := range visitedMap { - if visited { - continue - } - - allowedVault, found := allowedVaultsMap[denom] - if !found { - return nil, fmt.Errorf("vault record not found for vault record denom %s", denom) - } - - vaults = append(vaults, types.VaultResponse{ - Denom: denom, - Strategies: allowedVault.Strategies, - IsPrivateVault: allowedVault.IsPrivateVault, - AllowedDepositors: addressSliceToStringSlice(allowedVault.AllowedDepositors), - // No shares, no value - TotalShares: sdk.ZeroDec().String(), - TotalValue: sdk.ZeroInt(), - }) - } - - // Does not include vaults that have no deposits, only iterates over vault - // records which exists only for those with deposits. - return &types.QueryVaultsResponse{ - Vaults: vaults, - }, nil -} - -// Vaults implements the gRPC service handler for querying x/earn vaults. -func (s queryServer) Vault( - ctx context.Context, - req *types.QueryVaultRequest, -) (*types.QueryVaultResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - if req.Denom == "" { - return nil, status.Errorf(codes.InvalidArgument, "empty denom") - } - - // Only 1 vault - allowedVault, found := s.keeper.GetAllowedVault(sdkCtx, req.Denom) - if !found { - return nil, status.Errorf(codes.NotFound, "vault not found with specified denom") - } - - // Handle bkava separately to get total of **all** bkava vaults - if req.Denom == bkavaDenom { - return s.getAggregateBkavaVault(sdkCtx, allowedVault) - } - - // Must be req.Denom and not allowedVault.Denom to get full "bkava" denom - vaultRecord, found := s.keeper.GetVaultRecord(sdkCtx, req.Denom) - if !found { - // No supply yet, no error just set it to zero - vaultRecord.TotalShares = types.NewVaultShare(req.Denom, sdk.ZeroDec()) - } - - totalValue, err := s.keeper.GetVaultTotalValue(sdkCtx, req.Denom) - if err != nil { - return nil, err - } - - vault := types.VaultResponse{ - // VaultRecord denom instead of AllowedVault.Denom for full bkava denom - Denom: vaultRecord.TotalShares.Denom, - Strategies: allowedVault.Strategies, - IsPrivateVault: allowedVault.IsPrivateVault, - AllowedDepositors: addressSliceToStringSlice(allowedVault.AllowedDepositors), - TotalShares: vaultRecord.TotalShares.Amount.String(), - TotalValue: totalValue.Amount, - } - - return &types.QueryVaultResponse{ - Vault: vault, - }, nil -} - -// getAggregateBkavaVault returns a VaultResponse of the total of all bkava -// vaults. -func (s queryServer) getAggregateBkavaVault( - ctx sdk.Context, - allowedVault types.AllowedVault, -) (*types.QueryVaultResponse, error) { - allBkava := sdk.NewCoins() - - var iterErr error - s.keeper.IterateVaultRecords(ctx, func(record types.VaultRecord) (stop bool) { - // Skip non bkava vaults - if !strings.HasPrefix(record.TotalShares.Denom, bkavaPrefix) { - return false - } - - vaultValue, err := s.keeper.GetVaultTotalValue(ctx, record.TotalShares.Denom) - if err != nil { - iterErr = err - return false - } - - allBkava = allBkava.Add(vaultValue) - - return false - }) - - if iterErr != nil { - return nil, iterErr - } - - vaultValue, err := s.keeper.liquidKeeper.GetStakedTokensForDerivatives(ctx, allBkava) - if err != nil { - return nil, err - } - - return &types.QueryVaultResponse{ - Vault: types.VaultResponse{ - Denom: bkavaDenom, - Strategies: allowedVault.Strategies, - IsPrivateVault: allowedVault.IsPrivateVault, - AllowedDepositors: addressSliceToStringSlice(allowedVault.AllowedDepositors), - // Empty for shares, as adding up all shares is not useful information - TotalShares: "0", - TotalValue: vaultValue.Amount, - }, - }, nil -} - -// Deposits implements the gRPC service handler for querying x/earn deposits. -func (s queryServer) Deposits( - ctx context.Context, - req *types.QueryDepositsRequest, -) (*types.QueryDepositsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - if req.Depositor == "" { - return nil, status.Errorf(codes.InvalidArgument, "depositor is required") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - // bkava aggregate total - if req.Denom == bkavaDenom { - return s.getOneAccountBkavaVaultDeposit(sdkCtx, req) - } - - // specific vault - if req.Denom != "" { - return s.getOneAccountOneVaultDeposit(sdkCtx, req) - } - - // all vaults - return s.getOneAccountAllDeposits(sdkCtx, req) -} - -// TotalSupply implements the gRPC service handler for querying x/earn total supply (TVL) -func (s queryServer) TotalSupply( - ctx context.Context, - req *types.QueryTotalSupplyRequest, -) (*types.QueryTotalSupplyResponse, error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) - totalSupply := sdk.NewCoins() - liquidStakedDerivatives := sdk.NewCoins() - - // allowed vaults param contains info on allowed strategies, but bkava is aggregated - allowedVaults := s.keeper.GetAllowedVaults(sdkCtx) - allowedVaultByDenom := make(map[string]types.AllowedVault) - for _, av := range allowedVaults { - allowedVaultByDenom[av.Denom] = av - } - - var vaultRecordErr error - // iterate actual records to properly enumerate all denoms - s.keeper.IterateVaultRecords(sdkCtx, func(vault types.VaultRecord) (stop bool) { - isLiquidStakingDenom := false - // find allowed vault to get parameters. handle translating bkava denoms to allowed vault denom - allowedVaultDenom := vault.TotalShares.Denom - if strings.HasPrefix(vault.TotalShares.Denom, bkavaPrefix) { - isLiquidStakingDenom = true - allowedVaultDenom = bkavaDenom - } - allowedVault, found := allowedVaultByDenom[allowedVaultDenom] - if !found { - vaultRecordErr = fmt.Errorf("vault record not found for vault record denom %s", vault.TotalShares.Denom) - return true - } - - // only consider savings strategy vaults when determining supply - if !allowedVault.IsStrategyAllowed(types.STRATEGY_TYPE_SAVINGS) { - return false - } - - // vault has savings strategy! determine total value of vault and add to sum - vaultSupply, err := s.keeper.GetVaultTotalValue(sdkCtx, vault.TotalShares.Denom) - if err != nil { - vaultRecordErr = err - return true - } - - // liquid staked tokens must be converted to their underlying value - // aggregate them here and then we can convert to underlying values all at once at the end - if isLiquidStakingDenom { - liquidStakedDerivatives = liquidStakedDerivatives.Add(vaultSupply) - } else { - totalSupply = totalSupply.Add(vaultSupply) - } - return false - }) - - // determine underlying value of bkava denoms - if len(liquidStakedDerivatives) > 0 { - underlyingValue, err := s.keeper.liquidKeeper.GetStakedTokensForDerivatives( - sdkCtx, - liquidStakedDerivatives, - ) - if err != nil { - return nil, err - } - totalSupply = totalSupply.Add(sdk.NewCoin(bkavaDenom, underlyingValue.Amount)) - } - - return &types.QueryTotalSupplyResponse{ - Height: sdkCtx.BlockHeight(), - Result: totalSupply, - }, vaultRecordErr -} - -// getOneAccountOneVaultDeposit returns deposits for a specific vault and a specific -// account -func (s queryServer) getOneAccountOneVaultDeposit( - ctx sdk.Context, - req *types.QueryDepositsRequest, -) (*types.QueryDepositsResponse, error) { - depositor, err := sdk.AccAddressFromBech32(req.Depositor) - if err != nil { - return nil, status.Error(codes.InvalidArgument, "Invalid address") - } - - shareRecord, found := s.keeper.GetVaultShareRecord(ctx, depositor) - if !found { - return &types.QueryDepositsResponse{ - Deposits: []types.DepositResponse{ - { - Depositor: depositor.String(), - // Zero shares and zero value for no deposits - Shares: types.NewVaultShares(types.NewVaultShare(req.Denom, sdk.ZeroDec())), - Value: sdk.NewCoins(sdk.NewCoin(req.Denom, sdk.ZeroInt())), - }, - }, - Pagination: nil, - }, nil - } - - // Only requesting the value of the specified denom - value, err := s.keeper.GetVaultAccountValue(ctx, req.Denom, depositor) - if err != nil { - return nil, status.Error(codes.NotFound, err.Error()) - } - - if req.ValueInStakedTokens { - // Get underlying ukava amount if denom is a derivative - if !s.keeper.liquidKeeper.IsDerivativeDenom(ctx, req.Denom) { - return nil, status.Errorf( - codes.InvalidArgument, - "denom %s is not a derivative, ValueInStakedTokens can only be used with liquid derivatives", - req.Denom, - ) - } - - ukavaValue, err := s.keeper.liquidKeeper.GetStakedTokensForDerivatives(ctx, sdk.NewCoins(value)) - if err != nil { - // This should "never" happen if IsDerivativeDenom is true - panic("Error getting ukava value for " + req.Denom) - } - - value = ukavaValue - } - - return &types.QueryDepositsResponse{ - Deposits: []types.DepositResponse{ - { - Depositor: depositor.String(), - // Only respond with requested denom shares - Shares: types.NewVaultShares( - types.NewVaultShare(req.Denom, shareRecord.Shares.AmountOf(req.Denom)), - ), - Value: sdk.NewCoins(value), - }, - }, - Pagination: nil, - }, nil -} - -// getOneAccountBkavaVaultDeposit returns deposits for the aggregated bkava vault -// and a specific account -func (s queryServer) getOneAccountBkavaVaultDeposit( - ctx sdk.Context, - req *types.QueryDepositsRequest, -) (*types.QueryDepositsResponse, error) { - depositor, err := sdk.AccAddressFromBech32(req.Depositor) - if err != nil { - return nil, status.Error(codes.InvalidArgument, "Invalid address") - } - - shareRecord, found := s.keeper.GetVaultShareRecord(ctx, depositor) - if !found { - return &types.QueryDepositsResponse{ - Deposits: []types.DepositResponse{ - { - Depositor: depositor.String(), - // Zero shares and zero value for no deposits - Shares: types.NewVaultShares(types.NewVaultShare(req.Denom, sdk.ZeroDec())), - Value: sdk.NewCoins(sdk.NewCoin(req.Denom, sdk.ZeroInt())), - }, - }, - Pagination: nil, - }, nil - } - - // Get all account deposit values to add up bkava - totalAccountValue, err := getAccountTotalValue(ctx, s.keeper, depositor, shareRecord.Shares) - if err != nil { - return nil, err - } - - // Remove non-bkava coins, GetStakedTokensForDerivatives expects only bkava - totalBkavaValue := sdk.NewCoins() - for _, coin := range totalAccountValue { - if s.keeper.liquidKeeper.IsDerivativeDenom(ctx, coin.Denom) { - totalBkavaValue = totalBkavaValue.Add(coin) - } - } - - // Use account value with only the aggregate bkava converted to underlying staked tokens - stakedValue, err := s.keeper.liquidKeeper.GetStakedTokensForDerivatives(ctx, totalBkavaValue) - if err != nil { - return nil, err - } - - return &types.QueryDepositsResponse{ - Deposits: []types.DepositResponse{ - { - Depositor: depositor.String(), - // Only respond with requested denom shares - Shares: types.NewVaultShares( - types.NewVaultShare(req.Denom, shareRecord.Shares.AmountOf(req.Denom)), - ), - Value: sdk.NewCoins(stakedValue), - }, - }, - Pagination: nil, - }, nil -} - -// getOneAccountAllDeposits returns deposits for all vaults for a specific account -func (s queryServer) getOneAccountAllDeposits( - ctx sdk.Context, - req *types.QueryDepositsRequest, -) (*types.QueryDepositsResponse, error) { - depositor, err := sdk.AccAddressFromBech32(req.Depositor) - if err != nil { - return nil, status.Error(codes.InvalidArgument, "Invalid address") - } - - deposits := []types.DepositResponse{} - - accountShare, found := s.keeper.GetVaultShareRecord(ctx, depositor) - if !found { - return &types.QueryDepositsResponse{ - Deposits: []types.DepositResponse{}, - Pagination: nil, - }, nil - } - - value, err := getAccountTotalValue(ctx, s.keeper, depositor, accountShare.Shares) - if err != nil { - return nil, status.Error(codes.InvalidArgument, err.Error()) - } - - if req.ValueInStakedTokens { - // Plain slice to not sum ukava amounts together. This is not a valid - // sdk.Coin due to multiple coins of the same denom, but we need them to - // be separate in the response to not be an aggregate amount. - var valueInStakedTokens []sdk.Coin - - for _, coin := range value { - // Skip non-bkava coins - if !s.keeper.liquidKeeper.IsDerivativeDenom(ctx, coin.Denom) { - continue - } - - // Derivative coins are converted to underlying staked tokens - ukavaValue, err := s.keeper.liquidKeeper.GetStakedTokensForDerivatives(ctx, sdk.NewCoins(coin)) - if err != nil { - // This should "never" happen if IsDerivativeDenom is true - panic("Error getting ukava value for " + coin.Denom) - } - valueInStakedTokens = append(valueInStakedTokens, ukavaValue) - } - - var filteredShares types.VaultShares - for _, share := range accountShare.Shares { - // Remove non-bkava coins from shares as they are used to - // determine which value is mapped to which denom - // These should be in the same order as valueInStakedTokens - if !s.keeper.liquidKeeper.IsDerivativeDenom(ctx, share.Denom) { - continue - } - - filteredShares = append(filteredShares, share) - } - - value = valueInStakedTokens - accountShare.Shares = filteredShares - } - - deposits = append(deposits, types.DepositResponse{ - Depositor: depositor.String(), - Shares: accountShare.Shares, - Value: value, - }) - - return &types.QueryDepositsResponse{ - Deposits: deposits, - Pagination: nil, - }, nil -} - -// getAccountTotalValue returns the total value for all vaults for a specific -// account based on their shares. -func getAccountTotalValue( - ctx sdk.Context, - keeper Keeper, - account sdk.AccAddress, - shares types.VaultShares, -) (sdk.Coins, error) { - value := sdk.NewCoins() - - for _, share := range shares { - accValue, err := keeper.GetVaultAccountValue(ctx, share.Denom, account) - if err != nil { - return nil, err - } - - value = value.Add(sdk.NewCoin(share.Denom, accValue.Amount)) - } - - return value, nil -} - -func addressSliceToStringSlice(addresses []sdk.AccAddress) []string { - var strings []string - for _, address := range addresses { - strings = append(strings, address.String()) - } - - return strings -} diff --git a/x/earn/keeper/grpc_query_test.go b/x/earn/keeper/grpc_query_test.go deleted file mode 100644 index 2ba413c3..00000000 --- a/x/earn/keeper/grpc_query_test.go +++ /dev/null @@ -1,905 +0,0 @@ -package keeper_test - -import ( - "context" - "fmt" - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/earn/keeper" - "github.com/kava-labs/kava/x/earn/testutil" - "github.com/kava-labs/kava/x/earn/types" - liquidtypes "github.com/kava-labs/kava/x/liquid/types" -) - -type grpcQueryTestSuite struct { - testutil.Suite - - queryClient types.QueryClient -} - -func (suite *grpcQueryTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) - - queryHelper := baseapp.NewQueryServerTestHelper(suite.Ctx, suite.App.InterfaceRegistry()) - types.RegisterQueryServer(queryHelper, keeper.NewQueryServerImpl(suite.Keeper)) - - suite.queryClient = types.NewQueryClient(queryHelper) -} - -func TestGrpcQueryTestSuite(t *testing.T) { - suite.Run(t, new(grpcQueryTestSuite)) -} - -func (suite *grpcQueryTestSuite) TestQueryParams() { - vaultDenom := "usdx" - - res, err := suite.queryClient.Params(context.Background(), types.NewQueryParamsRequest()) - suite.Require().NoError(err) - // ElementsMatch instead of Equal because AllowedVaults{} != AllowedVaults(nil) - suite.Require().ElementsMatch(types.DefaultParams().AllowedVaults, res.Params.AllowedVaults) - - // Add vault to params - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Query again for added vault - res, err = suite.queryClient.Params(context.Background(), types.NewQueryParamsRequest()) - suite.Require().NoError(err) - suite.Require().Equal( - types.AllowedVaults{ - types.NewAllowedVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil), - }, - res.Params.AllowedVaults, - ) -} - -func (suite *grpcQueryTestSuite) TestVaults_ZeroSupply() { - // Add vaults - suite.CreateVault("usdx", types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault("busd", types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - suite.Run("single", func() { - res, err := suite.queryClient.Vault(context.Background(), types.NewQueryVaultRequest("usdx")) - suite.Require().NoError(err) - suite.Require().Equal( - types.VaultResponse{ - Denom: "usdx", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: nil, - TotalShares: sdk.NewDec(0).String(), - TotalValue: sdkmath.NewInt(0), - }, - res.Vault, - ) - }) - - suite.Run("all", func() { - res, err := suite.queryClient.Vaults(context.Background(), types.NewQueryVaultsRequest()) - suite.Require().NoError(err) - suite.Require().ElementsMatch([]types.VaultResponse{ - { - Denom: "usdx", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: nil, - TotalShares: sdk.ZeroDec().String(), - TotalValue: sdk.ZeroInt(), - }, - { - Denom: "busd", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: nil, - TotalShares: sdk.ZeroDec().String(), - TotalValue: sdk.ZeroInt(), - }, - }, - res.Vaults, - ) - }) -} - -func (suite *grpcQueryTestSuite) TestVaults_WithSupply() { - vaultDenom := "usdx" - vault2Denom := testutil.TestBkavaDenoms[0] - - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - deposit2Amount := sdk.NewInt64Coin(vault2Denom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault("bkava", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins( - sdk.NewInt64Coin(vaultDenom, 1000), - sdk.NewInt64Coin(vault2Denom, 1000), - ), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - err = suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), deposit2Amount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - res, err := suite.queryClient.Vaults(context.Background(), types.NewQueryVaultsRequest()) - suite.Require().NoError(err) - suite.Require().Len(res.Vaults, 2) - suite.Require().ElementsMatch( - []types.VaultResponse{ - { - Denom: vaultDenom, - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: nil, - TotalShares: sdk.NewDecFromInt(depositAmount.Amount).String(), - TotalValue: depositAmount.Amount, - }, - { - Denom: vault2Denom, - Strategies: []types.StrategyType{types.STRATEGY_TYPE_SAVINGS}, - IsPrivateVault: false, - AllowedDepositors: nil, - TotalShares: sdk.NewDecFromInt(deposit2Amount.Amount).String(), - TotalValue: deposit2Amount.Amount, - }, - }, - res.Vaults, - ) -} - -func (suite *grpcQueryTestSuite) TestVaults_MixedSupply() { - vaultDenom := "usdx" - vault2Denom := "busd" - vault3Denom := testutil.TestBkavaDenoms[0] - - depositAmount := sdk.NewInt64Coin(vault3Denom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault(vault2Denom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault("bkava", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins( - sdk.NewInt64Coin(vaultDenom, 1000), - sdk.NewInt64Coin(vault2Denom, 1000), - sdk.NewInt64Coin(vault3Denom, 1000), - ), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - res, err := suite.queryClient.Vaults(context.Background(), types.NewQueryVaultsRequest()) - suite.Require().NoError(err) - suite.Require().Len(res.Vaults, 3) - suite.Require().ElementsMatch( - []types.VaultResponse{ - { - Denom: vaultDenom, - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: nil, - TotalShares: sdk.ZeroDec().String(), - TotalValue: sdk.ZeroInt(), - }, - { - Denom: vault2Denom, - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: nil, - TotalShares: sdk.ZeroDec().String(), - TotalValue: sdk.ZeroInt(), - }, - { - Denom: vault3Denom, - Strategies: []types.StrategyType{types.STRATEGY_TYPE_SAVINGS}, - IsPrivateVault: false, - AllowedDepositors: nil, - TotalShares: sdk.NewDecFromInt(depositAmount.Amount).String(), - TotalValue: depositAmount.Amount, - }, - }, - res.Vaults, - ) -} - -func (suite *grpcQueryTestSuite) TestVault_NotFound() { - _, err := suite.queryClient.Vault(context.Background(), types.NewQueryVaultRequest("usdx")) - suite.Require().Error(err) - suite.Require().ErrorIs(err, status.Errorf(codes.NotFound, "vault not found with specified denom")) -} - -func (suite *grpcQueryTestSuite) TestDeposits() { - // Validator setup for bkava - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr1, valAccAddr2, delegator := addrs[0], addrs[1], addrs[2] - valAddr1 := sdk.ValAddress(valAccAddr1) - valAddr2 := sdk.ValAddress(valAccAddr2) - - vault1Denom := "usdx" - vault2Denom := "busd" - vault3Denom := fmt.Sprintf("bkava-%s", valAddr1.String()) - vault4Denom := fmt.Sprintf("bkava-%s", valAddr2.String()) - - initialUkavaBalance := sdkmath.NewInt(1e9) - startBalance := sdk.NewCoins( - sdk.NewCoin("ukava", initialUkavaBalance), - sdk.NewInt64Coin(vault1Denom, 1000), - sdk.NewInt64Coin(vault2Denom, 1000), - // Bkava isn't actually minted via x/liquid - sdk.NewInt64Coin(vault3Denom, 1000), - sdk.NewInt64Coin(vault4Denom, 1000), - ) - - delegateAmount := sdkmath.NewInt(100e6) - - suite.App.FundAccount(suite.Ctx, valAccAddr1, startBalance) - suite.App.FundAccount(suite.Ctx, valAccAddr2, startBalance) - suite.App.FundAccount(suite.Ctx, delegator, startBalance) - - suite.CreateNewUnbondedValidator(valAddr1, initialUkavaBalance) - suite.CreateNewUnbondedValidator(valAddr2, initialUkavaBalance) - suite.CreateDelegation(valAddr1, delegator, delegateAmount) - suite.CreateDelegation(valAddr2, delegator, delegateAmount) - - staking.EndBlocker(suite.Ctx, suite.App.GetStakingKeeper()) - - savingsParams := suite.SavingsKeeper.GetParams(suite.Ctx) - savingsParams.SupportedDenoms = append(savingsParams.SupportedDenoms, "bkava") - suite.SavingsKeeper.SetParams(suite.Ctx, savingsParams) - - // Add vaults - suite.CreateVault(vault1Denom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault(vault2Denom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault("bkava", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - deposit1Amount := sdk.NewInt64Coin(vault1Denom, 100) - deposit2Amount := sdk.NewInt64Coin(vault2Denom, 200) - deposit3Amount := sdk.NewInt64Coin(vault3Denom, 200) - deposit4Amount := sdk.NewInt64Coin(vault4Denom, 300) - - // Accounts - acc1 := suite.CreateAccount(startBalance, 0).GetAddress() - acc2 := delegator - - // Deposit into each vault from each account - 4 total deposits - // Acc 1: usdx + busd - // Acc 2: usdx + bkava-1 + bkava-2 - err := suite.Keeper.Deposit(suite.Ctx, acc1, deposit1Amount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - err = suite.Keeper.Deposit(suite.Ctx, acc1, deposit2Amount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - err = suite.Keeper.Deposit(suite.Ctx, acc2, deposit1Amount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - err = suite.Keeper.Deposit(suite.Ctx, acc2, deposit3Amount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - err = suite.Keeper.Deposit(suite.Ctx, acc2, deposit4Amount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - suite.Run("specific vault", func() { - // Query all deposits for account 1 - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(acc1.String(), vault1Denom, false, nil), - ) - suite.Require().NoError(err) - suite.Require().Len(res.Deposits, 1) - suite.Require().ElementsMatchf( - []types.DepositResponse{ - { - Depositor: acc1.String(), - // Only includes specified deposit shares - Shares: types.NewVaultShares( - types.NewVaultShare(deposit1Amount.Denom, sdk.NewDecFromInt(deposit1Amount.Amount)), - ), - // Only the specified vault denom value - Value: sdk.NewCoins(deposit1Amount), - }, - }, - res.Deposits, - "deposits should match, got %v", - res.Deposits, - ) - }) - - suite.Run("specific bkava vault", func() { - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(acc2.String(), vault3Denom, false, nil), - ) - suite.Require().NoError(err) - suite.Require().Len(res.Deposits, 1) - suite.Require().ElementsMatchf( - []types.DepositResponse{ - { - Depositor: acc2.String(), - // Only includes specified deposit shares - Shares: types.NewVaultShares( - types.NewVaultShare(deposit3Amount.Denom, sdk.NewDecFromInt(deposit3Amount.Amount)), - ), - // Only the specified vault denom value - Value: sdk.NewCoins(deposit3Amount), - }, - }, - res.Deposits, - "deposits should match, got %v", - res.Deposits, - ) - }) - - suite.Run("specific bkava vault in staked tokens", func() { - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(acc2.String(), vault3Denom, true, nil), - ) - suite.Require().NoError(err) - suite.Require().Len(res.Deposits, 1) - suite.Require().Equal( - types.DepositResponse{ - Depositor: acc2.String(), - // Only includes specified deposit shares - Shares: types.NewVaultShares( - types.NewVaultShare(deposit3Amount.Denom, sdk.NewDecFromInt(deposit3Amount.Amount)), - ), - // Only the specified vault denom value - Value: sdk.NewCoins( - sdk.NewCoin("ukava", deposit3Amount.Amount), - ), - }, - res.Deposits[0], - ) - }) - - suite.Run("invalid vault", func() { - _, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(acc1.String(), "notavaliddenom", false, nil), - ) - suite.Require().Error(err) - suite.Require().ErrorIs(err, status.Errorf(codes.NotFound, "vault for notavaliddenom not found")) - }) - - suite.Run("all vaults", func() { - // Query all deposits for account 1 - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(acc1.String(), "", false, nil), - ) - suite.Require().NoError(err) - suite.Require().Len(res.Deposits, 1) - suite.Require().ElementsMatch( - []types.DepositResponse{ - { - Depositor: acc1.String(), - Shares: types.NewVaultShares( - types.NewVaultShare(deposit1Amount.Denom, sdk.NewDecFromInt(deposit1Amount.Amount)), - types.NewVaultShare(deposit2Amount.Denom, sdk.NewDecFromInt(deposit2Amount.Amount)), - ), - Value: sdk.NewCoins(deposit1Amount, deposit2Amount), - }, - }, - res.Deposits, - ) - }) - - suite.Run("all vaults value in staked tokens", func() { - // Query all deposits for account 1 with value in staked tokens - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(acc2.String(), "", true, nil), - ) - suite.Require().NoError(err) - suite.Require().Len(res.Deposits, 1) - suite.Require().Equal( - types.DepositResponse{ - Depositor: acc2.String(), - Shares: types.VaultShares{ - // Does not include non-bkava vaults - types.NewVaultShare(deposit4Amount.Denom, sdk.NewDecFromInt(deposit4Amount.Amount)), - types.NewVaultShare(deposit3Amount.Denom, sdk.NewDecFromInt(deposit3Amount.Amount)), - }, - Value: sdk.Coins{ - // Does not include non-bkava vaults - sdk.NewCoin("ukava", deposit4Amount.Amount), - sdk.NewCoin("ukava", deposit3Amount.Amount), - }, - }, - res.Deposits[0], - ) - for i := range res.Deposits[0].Shares { - suite.Equal( - res.Deposits[0].Shares[i].Amount, - sdk.NewDecFromInt(res.Deposits[0].Value[i].Amount), - "order of deposit value should match shares", - ) - } - }) -} - -func (suite *grpcQueryTestSuite) TestDeposits_NoDeposits() { - vault1Denom := "usdx" - vault2Denom := "busd" - - // Add vaults - suite.CreateVault(vault1Denom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault(vault2Denom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault("bkava", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - // Accounts - acc1 := suite.CreateAccount(sdk.NewCoins(), 0).GetAddress() - - suite.Run("specific vault", func() { - // Query all deposits for account 1 - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(acc1.String(), vault1Denom, false, nil), - ) - suite.Require().NoError(err) - suite.Require().Len(res.Deposits, 1) - suite.Require().ElementsMatchf( - []types.DepositResponse{ - { - Depositor: acc1.String(), - // Zero shares and zero value - Shares: nil, - Value: nil, - }, - }, - res.Deposits, - "deposits should match, got %v", - res.Deposits, - ) - }) - - suite.Run("all vaults", func() { - // Query all deposits for account 1 - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(acc1.String(), "", false, nil), - ) - suite.Require().NoError(err) - suite.Require().Empty(res.Deposits) - }) -} - -func (suite *grpcQueryTestSuite) TestDeposits_NoDepositor() { - _, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest("", "usdx", false, nil), - ) - suite.Require().Error(err) - suite.Require().ErrorIs(err, status.Error(codes.InvalidArgument, "depositor is required")) -} - -func (suite *grpcQueryTestSuite) TestDeposits_InvalidAddress() { - _, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest("asdf", "usdx", false, nil), - ) - suite.Require().Error(err) - suite.Require().ErrorIs(err, status.Error(codes.InvalidArgument, "Invalid address")) - - _, err = suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest("asdf", "", false, nil), - ) - suite.Require().Error(err) - suite.Require().ErrorIs(err, status.Error(codes.InvalidArgument, "Invalid address")) -} - -func (suite *grpcQueryTestSuite) TestDeposits_bKava() { - // vault denom is only "bkava" which has it's own special handler - suite.CreateVault( - "bkava", - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - false, - []sdk.AccAddress{}, - ) - - suite.CreateVault( - "ukava", - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - false, - []sdk.AccAddress{}, - ) - - address1, derivatives1, _ := suite.createAccountWithDerivatives(testutil.TestBkavaDenoms[0], sdkmath.NewInt(1e9)) - address2, derivatives2, _ := suite.createAccountWithDerivatives(testutil.TestBkavaDenoms[1], sdkmath.NewInt(1e9)) - - err := suite.App.FundAccount(suite.Ctx, address1, sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e9)))) - suite.Require().NoError(err) - - // Slash the last validator to reduce the value of it's derivatives to test bkava to underlying token conversion. - // First call end block to bond validator to enable slashing. - staking.EndBlocker(suite.Ctx, suite.App.GetStakingKeeper()) - err = suite.slashValidator(sdk.ValAddress(address2), sdk.MustNewDecFromStr("0.5")) - suite.Require().NoError(err) - - suite.Run("no deposits", func() { - // Query all deposits for account 1 - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(address1.String(), "bkava", false, nil), - ) - suite.Require().NoError(err) - suite.Require().Len(res.Deposits, 1) - suite.Require().ElementsMatchf( - []types.DepositResponse{ - { - Depositor: address1.String(), - // Zero shares for "bkava" aggregate - Shares: nil, - // Only the specified vault denom value - Value: nil, - }, - }, - res.Deposits, - "deposits should match, got %v", - res.Deposits, - ) - }) - - err = suite.Keeper.Deposit(suite.Ctx, address1, derivatives1, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - err = suite.BankKeeper.SendCoins(suite.Ctx, address2, address1, sdk.NewCoins(derivatives2)) - suite.Require().NoError(err) - err = suite.Keeper.Deposit(suite.Ctx, address1, derivatives2, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - err = suite.Keeper.Deposit(suite.Ctx, address1, sdk.NewInt64Coin("ukava", 1e6), types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - suite.Run("multiple deposits", func() { - // Query all deposits for account 1 - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(address1.String(), "bkava", false, nil), - ) - suite.Require().NoError(err) - suite.Require().Len(res.Deposits, 1) - // first validator isn't slashed, so bkava units equal to underlying staked tokens - // last validator slashed 50% so derivatives are worth half - // Excludes non-bkava deposits - expectedValue := derivatives1.Amount.Add(derivatives2.Amount.QuoRaw(2)) - suite.Require().ElementsMatchf( - []types.DepositResponse{ - { - Depositor: address1.String(), - // Zero shares for "bkava" aggregate - Shares: nil, - // Value returned in units of staked token - Value: sdk.NewCoins( - sdk.NewCoin(suite.bondDenom(), expectedValue), - ), - }, - }, - res.Deposits, - "deposits should match, got %v", - res.Deposits, - ) - }) -} - -func (suite *grpcQueryTestSuite) TestVault_bKava_Single() { - vaultDenom := "bkava" - coinDenom := testutil.TestBkavaDenoms[0] - - startBalance := sdk.NewInt64Coin(coinDenom, 1000) - depositAmount := sdk.NewInt64Coin(coinDenom, 100) - - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // vault denom is only "bkava" which has it's own special handler - suite.CreateVault( - vaultDenom, - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - false, - []sdk.AccAddress{}, - ) - - err := suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError( - err, - "should be able to deposit bkava derivative denom in bkava vault", - ) - - res, err := suite.queryClient.Vault( - context.Background(), - types.NewQueryVaultRequest(coinDenom), - ) - suite.Require().NoError(err) - suite.Require().Equal( - types.VaultResponse{ - Denom: coinDenom, - Strategies: types.StrategyTypes{ - types.STRATEGY_TYPE_SAVINGS, - }, - IsPrivateVault: false, - AllowedDepositors: []string(nil), - TotalShares: "100.000000000000000000", - TotalValue: sdkmath.NewInt(100), - }, - res.Vault, - ) -} - -func (suite *grpcQueryTestSuite) TestVault_bKava_Aggregate() { - vaultDenom := "bkava" - - address1, derivatives1, _ := suite.createAccountWithDerivatives(testutil.TestBkavaDenoms[0], sdkmath.NewInt(1e9)) - address2, derivatives2, _ := suite.createAccountWithDerivatives(testutil.TestBkavaDenoms[1], sdkmath.NewInt(1e9)) - address3, derivatives3, _ := suite.createAccountWithDerivatives(testutil.TestBkavaDenoms[2], sdkmath.NewInt(1e9)) - // Slash the last validator to reduce the value of it's derivatives to test bkava to underlying token conversion. - // First call end block to bond validator to enable slashing. - staking.EndBlocker(suite.Ctx, suite.App.GetStakingKeeper()) - err := suite.slashValidator(sdk.ValAddress(address3), sdk.MustNewDecFromStr("0.5")) - suite.Require().NoError(err) - - // vault denom is only "bkava" which has it's own special handler - suite.CreateVault( - vaultDenom, - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - false, - []sdk.AccAddress{}, - ) - - err = suite.Keeper.Deposit(suite.Ctx, address1, derivatives1, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - err = suite.Keeper.Deposit(suite.Ctx, address2, derivatives2, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - err = suite.Keeper.Deposit(suite.Ctx, address3, derivatives3, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Query "bkava" to get aggregate amount - res, err := suite.queryClient.Vault( - context.Background(), - types.NewQueryVaultRequest(vaultDenom), - ) - suite.Require().NoError(err) - // first two validators are not slashed, so bkava units equal to underlying staked tokens - expectedValue := derivatives1.Amount.Add(derivatives2.Amount) - // last validator slashed 50% so derivatives are worth half - expectedValue = expectedValue.Add(derivatives2.Amount.QuoRaw(2)) - suite.Require().Equal( - types.VaultResponse{ - Denom: vaultDenom, - Strategies: types.StrategyTypes{ - types.STRATEGY_TYPE_SAVINGS, - }, - IsPrivateVault: false, - AllowedDepositors: []string(nil), - // No shares for aggregate - TotalShares: "0", - TotalValue: expectedValue, - }, - res.Vault, - ) -} - -func (suite *grpcQueryTestSuite) TestTotalSupply() { - deposit := func(addr sdk.AccAddress, denom string, amount int64) { - err := suite.Keeper.Deposit( - suite.Ctx, - addr, - sdk.NewInt64Coin(denom, amount), - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - } - testCases := []struct { - name string - setup func() - expectedSupply sdk.Coins - }{ - { - name: "no vaults mean no supply", - setup: func() {}, - expectedSupply: nil, - }, - { - name: "no savings vaults mean no supply", - setup: func() { - suite.CreateVault("usdx", types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault("busd", types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - }, - expectedSupply: nil, - }, - { - name: "empty savings vaults mean no supply", - setup: func() { - suite.CreateVault("usdx", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - suite.CreateVault("busd", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - }, - expectedSupply: nil, - }, - { - name: "calculates supply of savings vaults", - setup: func() { - vault1Denom := "usdx" - vault2Denom := "busd" - suite.CreateVault(vault1Denom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - suite.CreateVault(vault2Denom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - acc1 := suite.CreateAccount(sdk.NewCoins( - sdk.NewInt64Coin(vault1Denom, 1e6), - sdk.NewInt64Coin(vault2Denom, 1e6), - ), 0) - deposit(acc1.GetAddress(), vault1Denom, 1e5) - deposit(acc1.GetAddress(), vault2Denom, 1e5) - acc2 := suite.CreateAccount(sdk.NewCoins( - sdk.NewInt64Coin(vault1Denom, 1e6), - sdk.NewInt64Coin(vault2Denom, 1e6), - ), 0) - deposit(acc2.GetAddress(), vault1Denom, 2e5) - deposit(acc2.GetAddress(), vault2Denom, 2e5) - }, - expectedSupply: sdk.NewCoins( - sdk.NewInt64Coin("usdx", 3e5), - sdk.NewInt64Coin("busd", 3e5), - ), - }, - { - name: "calculates supply of savings vaults, even when private", - setup: func() { - vault1Denom := "ukava" - vault2Denom := "busd" - - acc1 := suite.CreateAccount(sdk.NewCoins( - sdk.NewInt64Coin(vault1Denom, 1e6), - sdk.NewInt64Coin(vault2Denom, 1e6), - ), 0) - acc2 := suite.CreateAccount(sdk.NewCoins( - sdk.NewInt64Coin(vault1Denom, 1e6), - sdk.NewInt64Coin(vault2Denom, 1e6), - ), 0) - - suite.CreateVault( - vault1Denom, - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - true, // private! - []sdk.AccAddress{acc1.GetAddress()}, // only acc1 can deposit. - ) - suite.CreateVault("busd", - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - false, - nil, - ) - - deposit(acc1.GetAddress(), vault1Denom, 1e5) - deposit(acc1.GetAddress(), vault2Denom, 1e5) - deposit(acc2.GetAddress(), vault2Denom, 2e5) - }, - expectedSupply: sdk.NewCoins( - sdk.NewInt64Coin("ukava", 1e5), - sdk.NewInt64Coin("busd", 3e5), - ), - }, - { - name: "aggregates supply of bkava vaults accounting for slashing", - setup: func() { - address1, derivatives1, _ := suite.createAccountWithDerivatives(testutil.TestBkavaDenoms[0], sdkmath.NewInt(1e9)) - address2, derivatives2, _ := suite.createAccountWithDerivatives(testutil.TestBkavaDenoms[1], sdkmath.NewInt(1e9)) - - // bond validators - staking.EndBlocker(suite.Ctx, suite.App.GetStakingKeeper()) - // slash val2 - its shares are now 80% as valuable! - err := suite.slashValidator(sdk.ValAddress(address2), sdk.MustNewDecFromStr("0.2")) - suite.Require().NoError(err) - - // create "bkava" vault. it holds all bkava denoms - suite.CreateVault("bkava", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, []sdk.AccAddress{}) - - // deposit bkava - deposit(address1, testutil.TestBkavaDenoms[0], derivatives1.Amount.Int64()) - deposit(address2, testutil.TestBkavaDenoms[1], derivatives2.Amount.Int64()) - }, - expectedSupply: sdk.NewCoins( - sdk.NewCoin( - "bkava", - sdkmath.NewIntFromUint64(1e9). // derivative 1 - Add(sdkmath.NewInt(1e9).MulRaw(80).QuoRaw(100))), // derivative 2: original value * 80% - ), - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - tc.setup() - res, err := suite.queryClient.TotalSupply( - sdk.WrapSDKContext(suite.Ctx), - &types.QueryTotalSupplyRequest{}, - ) - suite.Require().NoError(err) - suite.Require().Equal(tc.expectedSupply, res.Result) - }) - } -} - -// createUnbondedValidator creates an unbonded validator with the given amount of self-delegation. -func (suite *grpcQueryTestSuite) createUnbondedValidator(address sdk.ValAddress, selfDelegation sdk.Coin, minSelfDelegation sdkmath.Int) error { - msg, err := stakingtypes.NewMsgCreateValidator( - address, - ed25519.GenPrivKey().PubKey(), - selfDelegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - minSelfDelegation, - ) - if err != nil { - return err - } - - msgServer := stakingkeeper.NewMsgServerImpl(suite.App.GetStakingKeeper()) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.Ctx), msg) - return err -} - -// createAccountWithDerivatives creates an account with the given amount and denom of derivative token. -// Internally, it creates a validator account and mints derivatives from the validator's self delegation. -func (suite *grpcQueryTestSuite) createAccountWithDerivatives(denom string, amount sdkmath.Int) (sdk.AccAddress, sdk.Coin, sdk.Coins) { - valAddress, err := liquidtypes.ParseLiquidStakingTokenDenom(denom) - suite.Require().NoError(err) - address := sdk.AccAddress(valAddress) - - remainingSelfDelegation := sdkmath.NewInt(1e6) - selfDelegation := sdk.NewCoin( - suite.bondDenom(), - amount.Add(remainingSelfDelegation), - ) - - suite.NewAccountFromAddr(address, sdk.NewCoins(selfDelegation)) - - err = suite.createUnbondedValidator(valAddress, selfDelegation, remainingSelfDelegation) - suite.Require().NoError(err) - - toConvert := sdk.NewCoin(suite.bondDenom(), amount) - derivatives, err := suite.App.GetLiquidKeeper().MintDerivative(suite.Ctx, - address, - valAddress, - toConvert, - ) - suite.Require().NoError(err) - - fullBalance := suite.BankKeeper.GetAllBalances(suite.Ctx, address) - - return address, derivatives, fullBalance -} - -// slashValidator slashes the validator with the given address by the given percentage. -func (suite *grpcQueryTestSuite) slashValidator(address sdk.ValAddress, slashFraction sdk.Dec) error { - stakingKeeper := suite.App.GetStakingKeeper() - - validator, found := stakingKeeper.GetValidator(suite.Ctx, address) - suite.Require().True(found) - consAddr, err := validator.GetConsAddr() - suite.Require().NoError(err) - - // Assume infraction was at current height. Note unbonding delegations and redelegations are only slashed if created after - // the infraction height so none will be slashed. - infractionHeight := suite.Ctx.BlockHeight() - - power := stakingKeeper.TokensToConsensusPower(suite.Ctx, validator.GetTokens()) - - stakingKeeper.Slash(suite.Ctx, consAddr, infractionHeight, power, slashFraction) - return nil -} - -// bondDenom fetches the staking denom from the staking module. -func (suite *grpcQueryTestSuite) bondDenom() string { - return suite.App.GetStakingKeeper().BondDenom(suite.Ctx) -} diff --git a/x/earn/keeper/hooks.go b/x/earn/keeper/hooks.go deleted file mode 100644 index 36a33ce3..00000000 --- a/x/earn/keeper/hooks.go +++ /dev/null @@ -1,34 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/earn/types" -) - -// Implements EarnHooks interface -var _ types.EarnHooks = Keeper{} - -// AfterVaultDepositCreated - call hook if registered -func (k Keeper) AfterVaultDepositCreated( - ctx sdk.Context, - vaultDenom string, - depositor sdk.AccAddress, - sharesOwned sdk.Dec, -) { - if k.hooks != nil { - k.hooks.AfterVaultDepositCreated(ctx, vaultDenom, depositor, sharesOwned) - } -} - -// BeforeVaultDepositModified - call hook if registered -func (k Keeper) BeforeVaultDepositModified( - ctx sdk.Context, - vaultDenom string, - depositor sdk.AccAddress, - sharesOwned sdk.Dec, -) { - if k.hooks != nil { - k.hooks.BeforeVaultDepositModified(ctx, vaultDenom, depositor, sharesOwned) - } -} diff --git a/x/earn/keeper/hooks_test.go b/x/earn/keeper/hooks_test.go deleted file mode 100644 index 55d8b673..00000000 --- a/x/earn/keeper/hooks_test.go +++ /dev/null @@ -1,539 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/kava-labs/kava/x/earn/testutil" - "github.com/kava-labs/kava/x/earn/types" - "github.com/kava-labs/kava/x/earn/types/mocks" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/suite" -) - -type hookTestSuite struct { - testutil.Suite -} - -func (suite *hookTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestHookTestSuite(t *testing.T) { - suite.Run(t, new(hookTestSuite)) -} - -func (suite *hookTestSuite) TestHooks_DepositAndWithdraw() { - suite.Keeper.ClearHooks() - earnHooks := mocks.NewEarnHooks(suite.T()) - suite.Keeper.SetHooks(earnHooks) - - vault1Denom := "usdx" - vault2Denom := "ukava" - acc1deposit1Amount := sdk.NewInt64Coin(vault1Denom, 100) - acc1deposit2Amount := sdk.NewInt64Coin(vault2Denom, 200) - - acc2deposit1Amount := sdk.NewInt64Coin(vault1Denom, 200) - acc2deposit2Amount := sdk.NewInt64Coin(vault2Denom, 300) - - suite.CreateVault(vault1Denom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault(vault2Denom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins( - sdk.NewInt64Coin(vault1Denom, 1000), - sdk.NewInt64Coin(vault2Denom, 1000), - ), 0) - - acc2 := suite.CreateAccount(sdk.NewCoins( - sdk.NewInt64Coin(vault1Denom, 1000), - sdk.NewInt64Coin(vault2Denom, 1000), - ), 1) - - // first deposit creates vault - calls AfterVaultDepositCreated with initial shares - // shares are 1:1 - earnHooks.On( - "AfterVaultDepositCreated", - suite.Ctx, - acc1deposit1Amount.Denom, - acc.GetAddress(), - sdk.NewDecFromInt(acc1deposit1Amount.Amount), - ).Once() - err := suite.Keeper.Deposit( - suite.Ctx, - acc.GetAddress(), - acc1deposit1Amount, - types.STRATEGY_TYPE_HARD, - ) - suite.Require().NoError(err) - - // second deposit adds to vault - calls BeforeVaultDepositModified - // shares given are the initial shares, not new the shares added to the vault - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc1deposit1Amount.Denom, - acc.GetAddress(), - sdk.NewDecFromInt(acc1deposit1Amount.Amount), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc.GetAddress(), - acc1deposit1Amount, - types.STRATEGY_TYPE_HARD, - ) - suite.Require().NoError(err) - - // get the shares from the store from the last deposit - shareRecord, found := suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc.GetAddress(), - ) - suite.Require().True(found) - - // third deposit adds to vault - calls BeforeVaultDepositModified - // shares given are the shares added in previous deposit, not the shares added to the vault now - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc1deposit1Amount.Denom, - acc.GetAddress(), - shareRecord.AmountOf(acc1deposit1Amount.Denom), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc.GetAddress(), - acc1deposit1Amount, - types.STRATEGY_TYPE_HARD, - ) - suite.Require().NoError(err) - - // new deposit denom into vault creates the deposit and calls AfterVaultDepositCreated - earnHooks.On( - "AfterVaultDepositCreated", - suite.Ctx, - acc1deposit2Amount.Denom, - acc.GetAddress(), - sdk.NewDecFromInt(acc1deposit2Amount.Amount), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc.GetAddress(), - acc1deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // second deposit into vault calls BeforeVaultDepositModified with initial shares given - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc1deposit2Amount.Denom, - acc.GetAddress(), - sdk.NewDecFromInt(acc1deposit2Amount.Amount), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc.GetAddress(), - acc1deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // get the shares from the store from the last deposit - shareRecord, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc.GetAddress(), - ) - suite.Require().True(found) - - // third deposit into vault calls BeforeVaultDepositModified with shares from last deposit - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc1deposit2Amount.Denom, - acc.GetAddress(), - shareRecord.AmountOf(acc1deposit2Amount.Denom), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc.GetAddress(), - acc1deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // ------------------------------------------------------------ - // Second account deposits - - // first deposit by user - calls AfterVaultDepositCreated with user's shares - // not total shares - earnHooks.On( - "AfterVaultDepositCreated", - suite.Ctx, - acc2deposit1Amount.Denom, - acc2.GetAddress(), - sdk.NewDecFromInt(acc2deposit1Amount.Amount), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc2.GetAddress(), - acc2deposit1Amount, - types.STRATEGY_TYPE_HARD, - ) - suite.Require().NoError(err) - - // second deposit adds to vault - calls BeforeVaultDepositModified - // shares given are the initial shares, not new the shares added to the vault - // and not the total vault shares - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc2deposit1Amount.Denom, - acc2.GetAddress(), - sdk.NewDecFromInt(acc2deposit1Amount.Amount), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc2.GetAddress(), - acc2deposit1Amount, - types.STRATEGY_TYPE_HARD, - ) - suite.Require().NoError(err) - - // get the shares from the store from the last deposit - shareRecord2, found := suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc2.GetAddress(), - ) - suite.Require().True(found) - - // third deposit adds to vault - calls BeforeVaultDepositModified - // shares given are the shares added in previous deposit, not the shares added to the vault now - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc2deposit1Amount.Denom, - acc2.GetAddress(), - shareRecord2.AmountOf(acc2deposit1Amount.Denom), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc2.GetAddress(), - acc2deposit1Amount, - types.STRATEGY_TYPE_HARD, - ) - suite.Require().NoError(err) - - // new deposit denom into vault creates the deposit and calls AfterVaultDepositCreated - earnHooks.On( - "AfterVaultDepositCreated", - suite.Ctx, - acc2deposit2Amount.Denom, - acc2.GetAddress(), - sdk.NewDecFromInt(acc2deposit2Amount.Amount), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc2.GetAddress(), - acc2deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // second deposit into vault calls BeforeVaultDepositModified with initial shares given - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc2deposit2Amount.Denom, - acc2.GetAddress(), - sdk.NewDecFromInt(acc2deposit2Amount.Amount), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc2.GetAddress(), - acc2deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // get the shares from the store from the last deposit - shareRecord2, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc2.GetAddress(), - ) - suite.Require().True(found) - - // third deposit into vault calls BeforeVaultDepositModified with shares from last deposit - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc2deposit2Amount.Denom, - acc2.GetAddress(), - shareRecord2.AmountOf(acc2deposit2Amount.Denom), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc2.GetAddress(), - acc2deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // ------------------------------------------------------------ - // test hooks with a full withdraw of all shares deposit 1 denom - shareRecord, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc.GetAddress(), - ) - suite.Require().True(found) - - // all shares given to BeforeVaultDepositModified - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc1deposit1Amount.Denom, - acc.GetAddress(), - shareRecord.AmountOf(acc1deposit1Amount.Denom), - ).Once() - _, err = suite.Keeper.Withdraw( - suite.Ctx, - acc.GetAddress(), - // 3 deposits, multiply original deposit amount by 3 - sdk.NewCoin(acc1deposit1Amount.Denom, acc1deposit1Amount.Amount.MulRaw(3)), - types.STRATEGY_TYPE_HARD, - ) - suite.Require().NoError(err) - - // test hooks on partial withdraw - shareRecord, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc.GetAddress(), - ) - suite.Require().True(found) - - // all shares given to before deposit modified even with partial withdraw - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc1deposit2Amount.Denom, - acc.GetAddress(), - shareRecord.AmountOf(acc1deposit2Amount.Denom), - ).Once() - _, err = suite.Keeper.Withdraw( - suite.Ctx, - acc.GetAddress(), - acc1deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // test hooks on second partial withdraw - shareRecord, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc.GetAddress(), - ) - suite.Require().True(found) - - // all shares given to before deposit modified even with partial withdraw - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc1deposit2Amount.Denom, - acc.GetAddress(), - shareRecord.AmountOf(acc1deposit2Amount.Denom), - ).Once() - _, err = suite.Keeper.Withdraw( - suite.Ctx, - acc.GetAddress(), - acc1deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // test hooks withdraw all remaining shares - shareRecord, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc.GetAddress(), - ) - suite.Require().True(found) - - // all shares given to before deposit modified even with partial withdraw - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc1deposit2Amount.Denom, - acc.GetAddress(), - shareRecord.AmountOf(acc1deposit2Amount.Denom), - ).Once() - _, err = suite.Keeper.Withdraw( - suite.Ctx, - acc.GetAddress(), - acc1deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // ------------------------------------------------------------ - // withdraw from acc2 - shareRecord, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc2.GetAddress(), - ) - suite.Require().True(found) - - // all shares given to BeforeVaultDepositModified - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc2deposit1Amount.Denom, - acc2.GetAddress(), - shareRecord.AmountOf(acc2deposit1Amount.Denom), - ).Once() - _, err = suite.Keeper.Withdraw( - suite.Ctx, - acc2.GetAddress(), - // 3 deposits, multiply original deposit amount by 3 - sdk.NewCoin(acc2deposit1Amount.Denom, acc2deposit1Amount.Amount.MulRaw(3)), - types.STRATEGY_TYPE_HARD, - ) - suite.Require().NoError(err) - - // test hooks on partial withdraw - shareRecord2, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc2.GetAddress(), - ) - suite.Require().True(found) - - // all shares given to before deposit modified even with partial withdraw - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc2deposit2Amount.Denom, - acc2.GetAddress(), - shareRecord2.AmountOf(acc2deposit2Amount.Denom), - ).Once() - _, err = suite.Keeper.Withdraw( - suite.Ctx, - acc2.GetAddress(), - acc2deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // test hooks on second partial withdraw - shareRecord2, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc2.GetAddress(), - ) - suite.Require().True(found) - - // all shares given to before deposit modified even with partial withdraw - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc2deposit2Amount.Denom, - acc2.GetAddress(), - shareRecord2.AmountOf(acc2deposit2Amount.Denom), - ).Once() - _, err = suite.Keeper.Withdraw( - suite.Ctx, - acc2.GetAddress(), - acc2deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // test hooks withdraw all remaining shares - shareRecord2, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc2.GetAddress(), - ) - suite.Require().True(found) - - // all shares given to before deposit modified even with partial withdraw - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc2deposit2Amount.Denom, - acc2.GetAddress(), - shareRecord2.AmountOf(acc2deposit2Amount.Denom), - ).Once() - _, err = suite.Keeper.Withdraw( - suite.Ctx, - acc2.GetAddress(), - acc2deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) -} - -func (suite *hookTestSuite) TestHooks_NoPanicsOnNilHooks() { - suite.Keeper.ClearHooks() - - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - withdrawAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // AfterVaultDepositModified should not panic if no hooks are registered - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // BeforeVaultDepositModified should not panic if no hooks are registered - err = suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // BeforeVaultDepositModified should not panic if no hooks are registered - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), withdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) -} - -func (suite *hookTestSuite) TestHooks_HookOrdering() { - suite.Keeper.ClearHooks() - earnHooks := &mocks.EarnHooks{} - suite.Keeper.SetHooks(earnHooks) - - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - earnHooks.On("AfterVaultDepositCreated", suite.Ctx, depositAmount.Denom, acc.GetAddress(), sdk.NewDecFromInt(depositAmount.Amount)). - Run(func(args mock.Arguments) { - shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc.GetAddress()) - suite.Require().True(found, "expected after hook to be called after shares are updated") - suite.Require().Equal(sdk.NewDecFromInt(depositAmount.Amount), shares.AmountOf(depositAmount.Denom)) - }) - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - earnHooks.On("BeforeVaultDepositModified", suite.Ctx, depositAmount.Denom, acc.GetAddress(), sdk.NewDecFromInt(depositAmount.Amount)). - Run(func(args mock.Arguments) { - shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc.GetAddress()) - suite.Require().True(found, "expected after hook to be called after shares are updated") - suite.Require().Equal(sdk.NewDecFromInt(depositAmount.Amount), shares.AmountOf(depositAmount.Denom)) - }) - err = suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - existingShares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc.GetAddress()) - suite.Require().True(found) - earnHooks.On("BeforeVaultDepositModified", suite.Ctx, depositAmount.Denom, acc.GetAddress(), existingShares.AmountOf(depositAmount.Denom)). - Run(func(args mock.Arguments) { - shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc.GetAddress()) - suite.Require().True(found, "expected after hook to be called after shares are updated") - suite.Require().Equal(sdk.NewDecFromInt(depositAmount.Amount.MulRaw(2)), shares.AmountOf(depositAmount.Denom)) - }) - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) -} diff --git a/x/earn/keeper/invariants.go b/x/earn/keeper/invariants.go deleted file mode 100644 index 880921e8..00000000 --- a/x/earn/keeper/invariants.go +++ /dev/null @@ -1,115 +0,0 @@ -package keeper - -import ( - "github.com/kava-labs/kava/x/earn/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// RegisterInvariants registers the swap module invariants -func RegisterInvariants(ir sdk.InvariantRegistry, k Keeper) { - ir.RegisterRoute(types.ModuleName, "vault-records", VaultRecordsInvariant(k)) - ir.RegisterRoute(types.ModuleName, "share-records", ShareRecordsInvariant(k)) - ir.RegisterRoute(types.ModuleName, "vault-shares", VaultSharesInvariant(k)) -} - -// AllInvariants runs all invariants of the swap module -func AllInvariants(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - if res, stop := VaultRecordsInvariant(k)(ctx); stop { - return res, stop - } - - if res, stop := ShareRecordsInvariant(k)(ctx); stop { - return res, stop - } - - res, stop := VaultSharesInvariant(k)(ctx) - return res, stop - } -} - -// VaultRecordsInvariant iterates all vault records and asserts that they are valid -func VaultRecordsInvariant(k Keeper) sdk.Invariant { - broken := false - message := sdk.FormatInvariant(types.ModuleName, "validate vault records broken", "vault record invalid") - - return func(ctx sdk.Context) (string, bool) { - k.IterateVaultRecords(ctx, func(record types.VaultRecord) bool { - if err := record.Validate(); err != nil { - broken = true - return true - } - return false - }) - - return message, broken - } -} - -// ShareRecordsInvariant iterates all share records and asserts that they are valid -func ShareRecordsInvariant(k Keeper) sdk.Invariant { - broken := false - message := sdk.FormatInvariant(types.ModuleName, "validate share records broken", "share record invalid") - - return func(ctx sdk.Context) (string, bool) { - k.IterateVaultShareRecords(ctx, func(record types.VaultShareRecord) bool { - if err := record.Validate(); err != nil { - broken = true - return true - } - return false - }) - - return message, broken - } -} - -type vaultShares struct { - totalShares types.VaultShare - totalSharesOwned types.VaultShare -} - -// VaultSharesInvariant iterates all vaults and shares and ensures the total vault shares match the sum of depositor shares -func VaultSharesInvariant(k Keeper) sdk.Invariant { - broken := false - message := sdk.FormatInvariant(types.ModuleName, "vault shares broken", "vault shares do not match depositor shares") - - return func(ctx sdk.Context) (string, bool) { - totalShares := make(map[string]vaultShares) - - k.IterateVaultRecords(ctx, func(record types.VaultRecord) bool { - totalShares[record.TotalShares.Denom] = vaultShares{ - totalShares: record.TotalShares, - totalSharesOwned: types.NewVaultShare(record.TotalShares.Denom, sdk.ZeroDec()), - } - - return false - }) - - k.IterateVaultShareRecords(ctx, func(sr types.VaultShareRecord) bool { - for _, share := range sr.Shares { - if shares, found := totalShares[share.Denom]; found { - shares.totalSharesOwned = shares.totalSharesOwned.Add(share) - totalShares[share.Denom] = shares - } else { - totalShares[share.Denom] = vaultShares{ - totalShares: types.NewVaultShare(share.Denom, sdk.ZeroDec()), - totalSharesOwned: share, - } - } - } - - return false - }) - - for _, share := range totalShares { - if !share.totalShares.Amount.Equal(share.totalSharesOwned.Amount) { - broken = true - break - } - } - - return message, broken - } -} diff --git a/x/earn/keeper/invariants_test.go b/x/earn/keeper/invariants_test.go deleted file mode 100644 index cd0ebd4a..00000000 --- a/x/earn/keeper/invariants_test.go +++ /dev/null @@ -1,182 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/earn/keeper" - "github.com/kava-labs/kava/x/earn/testutil" - "github.com/kava-labs/kava/x/earn/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" -) - -type invariantTestSuite struct { - testutil.Suite - - invariants map[string]map[string]sdk.Invariant - addrs []sdk.AccAddress -} - -func TestInvariantTestSuite(t *testing.T) { - suite.Run(t, new(invariantTestSuite)) -} - -func (suite *invariantTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.invariants = make(map[string]map[string]sdk.Invariant) - keeper.RegisterInvariants(suite, suite.Keeper) - - _, addrs := app.GeneratePrivKeyAddressPairs(4) - suite.addrs = addrs -} - -func (suite *invariantTestSuite) SetupValidState() { - suite.Keeper.SetVaultRecord(suite.Ctx, types.NewVaultRecord( - "usdx", - sdk.MustNewDecFromStr("100"), - )) - suite.Keeper.SetVaultRecord(suite.Ctx, types.NewVaultRecord( - "ukava", - sdk.MustNewDecFromStr("250.123456"), - )) - - vaultShare1 := types.NewVaultShareRecord( - suite.addrs[0], - types.NewVaultShares( - types.NewVaultShare("usdx", sdk.MustNewDecFromStr("50")), - types.NewVaultShare("ukava", sdk.MustNewDecFromStr("105.123")), - ), - ) - vaultShare2 := types.NewVaultShareRecord( - suite.addrs[1], - types.NewVaultShares( - types.NewVaultShare("usdx", sdk.MustNewDecFromStr("50")), - types.NewVaultShare("ukava", sdk.MustNewDecFromStr("145.000456")), - ), - ) - - suite.Require().NoError(vaultShare1.Validate()) - suite.Require().NoError(vaultShare2.Validate()) - - suite.Keeper.SetVaultShareRecord(suite.Ctx, vaultShare1) - suite.Keeper.SetVaultShareRecord(suite.Ctx, vaultShare2) -} - -func (suite *invariantTestSuite) RegisterRoute(moduleName string, route string, invariant sdk.Invariant) { - _, exists := suite.invariants[moduleName] - - if !exists { - suite.invariants[moduleName] = make(map[string]sdk.Invariant) - } - - suite.invariants[moduleName][route] = invariant -} - -func (suite *invariantTestSuite) runInvariant(route string, invariant func(k keeper.Keeper) sdk.Invariant) (string, bool) { - ctx := suite.Ctx - registeredInvariant := suite.invariants[types.ModuleName][route] - suite.Require().NotNil(registeredInvariant) - - // direct call - dMessage, dBroken := invariant(suite.Keeper)(ctx) - // registered call - rMessage, rBroken := registeredInvariant(ctx) - // all call - aMessage, aBroken := keeper.AllInvariants(suite.Keeper)(ctx) - - // require matching values for direct call and registered call - suite.Require().Equal(dMessage, rMessage, "expected registered invariant message to match") - suite.Require().Equal(dBroken, rBroken, "expected registered invariant broken to match") - // require matching values for direct call and all invariants call if broken - suite.Require().Equalf(dBroken, aBroken, "expected all invariant broken to match, direct %v != all %v", dBroken, aBroken) - if dBroken { - suite.Require().Equal(dMessage, aMessage, "expected all invariant message to match") - } - - // return message, broken - return dMessage, dBroken -} - -func (suite *invariantTestSuite) TestVaultRecordsInvariant() { - // default state is valid - message, broken := suite.runInvariant("vault-records", keeper.VaultRecordsInvariant) - suite.Equal("earn: validate vault records broken invariant\nvault record invalid\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("vault-records", keeper.VaultRecordsInvariant) - suite.Equal("earn: validate vault records broken invariant\nvault record invalid\n", message) - suite.Equal(false, broken) - - // broken with invalid vault record - suite.Keeper.SetVaultRecord(suite.Ctx, types.VaultRecord{ - TotalShares: types.VaultShare{ - Denom: "invalid denom", - Amount: sdk.MustNewDecFromStr("101"), - }, - }) - message, broken = suite.runInvariant("vault-records", keeper.VaultRecordsInvariant) - suite.Equal("earn: validate vault records broken invariant\nvault record invalid\n", message) - suite.Equal(true, broken) -} - -func (suite *invariantTestSuite) TestShareRecordsInvariant() { - message, broken := suite.runInvariant("share-records", keeper.ShareRecordsInvariant) - suite.Equal("earn: validate share records broken invariant\nshare record invalid\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("share-records", keeper.ShareRecordsInvariant) - suite.Equal("earn: validate share records broken invariant\nshare record invalid\n", message) - suite.Equal(false, broken) - - // broken with invalid share record - suite.Keeper.SetVaultShareRecord(suite.Ctx, types.NewVaultShareRecord( - suite.addrs[0], - // Directly create vaultshares instead of NewVaultShares() to avoid sanitization - types.VaultShares{ - types.NewVaultShare("ukava", sdk.MustNewDecFromStr("50")), - types.NewVaultShare("ukava", sdk.MustNewDecFromStr("105.123")), - }, - )) - message, broken = suite.runInvariant("share-records", keeper.ShareRecordsInvariant) - suite.Equal("earn: validate share records broken invariant\nshare record invalid\n", message) - suite.Equal(true, broken) -} - -func (suite *invariantTestSuite) TestVaultSharesInvariant() { - message, broken := suite.runInvariant("vault-shares", keeper.VaultSharesInvariant) - suite.Equal("earn: vault shares broken invariant\nvault shares do not match depositor shares\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("vault-shares", keeper.VaultSharesInvariant) - suite.Equal("earn: vault shares broken invariant\nvault shares do not match depositor shares\n", message) - suite.Equal(false, broken) - - // broken when total shares are greater than depositor shares - suite.Keeper.SetVaultRecord(suite.Ctx, types.NewVaultRecord( - "usdx", - sdk.MustNewDecFromStr("101"), - )) - message, broken = suite.runInvariant("vault-shares", keeper.VaultSharesInvariant) - suite.Equal("earn: vault shares broken invariant\nvault shares do not match depositor shares\n", message) - suite.Equal(true, broken) - - // broken when total shares are less than the depositor shares - suite.Keeper.SetVaultRecord(suite.Ctx, types.NewVaultRecord( - "usdx", - sdk.MustNewDecFromStr("99.999"), - )) - message, broken = suite.runInvariant("vault-shares", keeper.VaultSharesInvariant) - suite.Equal("earn: vault shares broken invariant\nvault shares do not match depositor shares\n", message) - suite.Equal(true, broken) - - // broken when vault record is missing - suite.Keeper.DeleteVaultRecord(suite.Ctx, "usdx") - message, broken = suite.runInvariant("vault-shares", keeper.VaultSharesInvariant) - suite.Equal("earn: vault shares broken invariant\nvault shares do not match depositor shares\n", message) - suite.Equal(true, broken) -} diff --git a/x/earn/keeper/keeper.go b/x/earn/keeper/keeper.go deleted file mode 100644 index c7a691d7..00000000 --- a/x/earn/keeper/keeper.go +++ /dev/null @@ -1,70 +0,0 @@ -package keeper - -import ( - "github.com/cosmos/cosmos-sdk/codec" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - "github.com/kava-labs/kava/x/earn/types" - - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// Keeper keeper for the earn module -type Keeper struct { - key storetypes.StoreKey - cdc codec.Codec - paramSubspace paramtypes.Subspace - hooks types.EarnHooks - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - liquidKeeper types.LiquidKeeper - - // Keepers used for strategies - hardKeeper types.HardKeeper - savingsKeeper types.SavingsKeeper - - // Keeper for community pool transfers - distKeeper types.DistributionKeeper -} - -// NewKeeper creates a new keeper -func NewKeeper( - cdc codec.Codec, - key storetypes.StoreKey, - paramstore paramtypes.Subspace, - accountKeeper types.AccountKeeper, - bankKeeper types.BankKeeper, - liquidKeeper types.LiquidKeeper, - hardKeeper types.HardKeeper, - savingsKeeper types.SavingsKeeper, - distKeeper types.DistributionKeeper, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - key: key, - cdc: cdc, - paramSubspace: paramstore, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - liquidKeeper: liquidKeeper, - hardKeeper: hardKeeper, - savingsKeeper: savingsKeeper, - distKeeper: distKeeper, - } -} - -// SetHooks adds hooks to the keeper. -func (k *Keeper) SetHooks(sh types.EarnHooks) *Keeper { - if k.hooks != nil { - panic("cannot set earn hooks twice") - } - k.hooks = sh - return k -} - -// ClearHooks clears the hooks on the keeper -func (k *Keeper) ClearHooks() { - k.hooks = nil -} diff --git a/x/earn/keeper/msg_server.go b/x/earn/keeper/msg_server.go deleted file mode 100644 index 1e719b99..00000000 --- a/x/earn/keeper/msg_server.go +++ /dev/null @@ -1,70 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/earn/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the earn MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -// Deposit handles MsgDeposit messages -func (m msgServer) Deposit(goCtx context.Context, msg *types.MsgDeposit) (*types.MsgDepositResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - - if err := m.keeper.Deposit(ctx, depositor, msg.Amount, msg.Strategy); err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.String()), - ), - ) - - return &types.MsgDepositResponse{}, nil -} - -// Withdraw handles MsgWithdraw messages -func (m msgServer) Withdraw(goCtx context.Context, msg *types.MsgWithdraw) (*types.MsgWithdrawResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - from, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - return nil, err - } - - _, err = m.keeper.Withdraw(ctx, from, msg.Amount, msg.Strategy) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, from.String()), - ), - ) - - return &types.MsgWithdrawResponse{}, nil -} diff --git a/x/earn/keeper/msg_server_test.go b/x/earn/keeper/msg_server_test.go deleted file mode 100644 index 04efa27d..00000000 --- a/x/earn/keeper/msg_server_test.go +++ /dev/null @@ -1,139 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - - "github.com/cometbft/cometbft/crypto" - "github.com/kava-labs/kava/x/earn/keeper" - "github.com/kava-labs/kava/x/earn/testutil" - "github.com/kava-labs/kava/x/earn/types" - "github.com/stretchr/testify/suite" -) - -var moduleAccAddress = sdk.AccAddress(crypto.AddressHash([]byte(types.ModuleAccountName))) - -type msgServerTestSuite struct { - testutil.Suite - - msgServer types.MsgServer -} - -func (suite *msgServerTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) - - suite.msgServer = keeper.NewMsgServerImpl(suite.Keeper) -} - -func TestMsgServerTestSuite(t *testing.T) { - suite.Run(t, new(msgServerTestSuite)) -} - -func (suite *msgServerTestSuite) TestDeposit() { - vaultDenom := "usdx" - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - msg := types.NewMsgDeposit(acc.GetAddress().String(), depositAmount, types.STRATEGY_TYPE_HARD) - _, err := suite.msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance.Sub(depositAmount)), - ) - - // Bank: Send deposit Account -> Module account - suite.EventsContains( - suite.GetEvents(), - sdk.NewEvent( - banktypes.EventTypeTransfer, - sdk.NewAttribute(banktypes.AttributeKeyRecipient, moduleAccAddress.String()), - sdk.NewAttribute(banktypes.AttributeKeySender, acc.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, depositAmount.String()), - ), - ) - - // Keeper Deposit() - suite.EventsContains( - suite.GetEvents(), - sdk.NewEvent( - types.EventTypeVaultDeposit, - sdk.NewAttribute(types.AttributeKeyVaultDenom, depositAmount.Denom), - sdk.NewAttribute(types.AttributeKeyDepositor, acc.GetAddress().String()), - // Shares 1:1 to amount - sdk.NewAttribute(types.AttributeKeyShares, sdk.NewDecFromInt(depositAmount.Amount).String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, depositAmount.Amount.String()), - ), - ) - - // Msg server module - suite.EventsContains( - suite.GetEvents(), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, acc.GetAddress().String()), - ), - ) -} - -func (suite *msgServerTestSuite) TestWithdraw() { - vaultDenom := "usdx" - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - msgDeposit := types.NewMsgDeposit(acc.GetAddress().String(), depositAmount, types.STRATEGY_TYPE_HARD) - _, err := suite.msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), msgDeposit) - suite.Require().NoError(err) - - // Withdraw all - msgWithdraw := types.NewMsgWithdraw(acc.GetAddress().String(), depositAmount, types.STRATEGY_TYPE_HARD) - _, err = suite.msgServer.Withdraw(sdk.WrapSDKContext(suite.Ctx), msgWithdraw) - suite.Require().NoError(err) - - // Bank: Send deposit Account -> Module account - suite.EventsContains( - suite.GetEvents(), - sdk.NewEvent( - banktypes.EventTypeTransfer, - // Direction opposite from Deposit() - sdk.NewAttribute(banktypes.AttributeKeyRecipient, acc.GetAddress().String()), - sdk.NewAttribute(banktypes.AttributeKeySender, moduleAccAddress.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, depositAmount.String()), - ), - ) - - // Keeper Withdraw() - suite.EventsContains( - suite.GetEvents(), - sdk.NewEvent( - types.EventTypeVaultWithdraw, - sdk.NewAttribute(types.AttributeKeyVaultDenom, depositAmount.Denom), - sdk.NewAttribute(types.AttributeKeyOwner, acc.GetAddress().String()), - sdk.NewAttribute(types.AttributeKeyShares, sdk.NewDecFromInt(depositAmount.Amount).String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, depositAmount.Amount.String()), - ), - ) - - // Msg server module - suite.EventsContains( - suite.GetEvents(), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, acc.GetAddress().String()), - ), - ) -} diff --git a/x/earn/keeper/params.go b/x/earn/keeper/params.go deleted file mode 100644 index 217b514e..00000000 --- a/x/earn/keeper/params.go +++ /dev/null @@ -1,62 +0,0 @@ -package keeper - -import ( - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/earn/types" -) - -const ( - bkavaDenom = "bkava" - bkavaPrefix = bkavaDenom + "-" -) - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - var p types.Params - k.paramSubspace.GetParamSet(ctx, &p) - - return p -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} - -// GetAllowedVaults returns the list of allowed vaults from the module params. -func (k Keeper) GetAllowedVaults(ctx sdk.Context) types.AllowedVaults { - return k.GetParams(ctx).AllowedVaults -} - -// getAllowedVaultRaw returns a single vault from the module params specified -// by the denom. -func (k Keeper) getAllowedVaultRaw( - ctx sdk.Context, - vaultDenom string, -) (types.AllowedVault, bool) { - for _, allowedVault := range k.GetAllowedVaults(ctx) { - if allowedVault.Denom == vaultDenom { - return allowedVault, true - } - } - - return types.AllowedVault{}, false -} - -// GetAllowedVault returns the AllowedVault that corresponds to the -// given denom. If the denom starts with "bkava-" where it will return the -// "bkava" AllowedVault. Otherwise, it will return the exact match for the -// corresponding AllowedVault denom. -func (k *Keeper) GetAllowedVault( - ctx sdk.Context, - vaultDenom string, -) (types.AllowedVault, bool) { - if strings.HasPrefix(vaultDenom, bkavaPrefix) { - return k.getAllowedVaultRaw(ctx, bkavaDenom) - } - - return k.getAllowedVaultRaw(ctx, vaultDenom) -} diff --git a/x/earn/keeper/proposal_handler.go b/x/earn/keeper/proposal_handler.go deleted file mode 100644 index 03b08c7c..00000000 --- a/x/earn/keeper/proposal_handler.go +++ /dev/null @@ -1,49 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/earn/types" - kavadisttypes "github.com/kava-labs/kava/x/kavadist/types" -) - -// HandleCommunityPoolDepositProposal is a handler for executing a passed community pool deposit proposal -func HandleCommunityPoolDepositProposal(ctx sdk.Context, k Keeper, p *types.CommunityPoolDepositProposal) error { - fundAcc := k.accountKeeper.GetModuleAccount(ctx, kavadisttypes.FundModuleAccount) - if err := k.distKeeper.DistributeFromFeePool(ctx, sdk.NewCoins(p.Amount), fundAcc.GetAddress()); err != nil { - return err - } - - err := k.DepositFromModuleAccount(ctx, kavadisttypes.FundModuleAccount, p.Amount, types.STRATEGY_TYPE_SAVINGS) - if err != nil { - return err - } - - return nil - -} - -// HandleCommunityPoolWithdrawProposal is a handler for executing a passed community pool withdraw proposal. -func HandleCommunityPoolWithdrawProposal(ctx sdk.Context, k Keeper, p *types.CommunityPoolWithdrawProposal) error { - // Withdraw to fund module account - withdrawAmount, err := k.WithdrawFromModuleAccount(ctx, kavadisttypes.FundModuleAccount, p.Amount, types.STRATEGY_TYPE_SAVINGS) - if err != nil { - return err - } - - // Move funds to the community pool manually - err = k.bankKeeper.SendCoinsFromModuleToModule( - ctx, - kavadisttypes.FundModuleAccount, - k.distKeeper.GetDistributionAccount(ctx).GetName(), - sdk.NewCoins(withdrawAmount), - ) - if err != nil { - return err - } - feePool := k.distKeeper.GetFeePool(ctx) - newCommunityPool := feePool.CommunityPool.Add(sdk.NewDecCoinFromCoin(withdrawAmount)) - feePool.CommunityPool = newCommunityPool - k.distKeeper.SetFeePool(ctx, feePool) - return nil -} diff --git a/x/earn/keeper/proposal_handler_test.go b/x/earn/keeper/proposal_handler_test.go deleted file mode 100644 index 1d030abc..00000000 --- a/x/earn/keeper/proposal_handler_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/earn/keeper" - "github.com/kava-labs/kava/x/earn/testutil" - "github.com/kava-labs/kava/x/earn/types" - "github.com/stretchr/testify/suite" -) - -type proposalTestSuite struct { - testutil.Suite -} - -func (suite *proposalTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestProposalTestSuite(t *testing.T) { - suite.Run(t, new(proposalTestSuite)) -} - -func (suite *proposalTestSuite) TestCommunityDepositProposal() { - distKeeper := suite.App.GetDistrKeeper() - ctx := suite.Ctx - macc := distKeeper.GetDistributionAccount(ctx) - fundAmount := sdk.NewCoins(sdk.NewInt64Coin("ukava", 100000000)) - depositAmount := sdk.NewCoin("ukava", sdkmath.NewInt(10000000)) - suite.Require().NoError(suite.App.FundModuleAccount(ctx, macc.GetName(), fundAmount)) - feePool := distKeeper.GetFeePool(ctx) - feePool.CommunityPool = sdk.NewDecCoinsFromCoins(fundAmount...) - distKeeper.SetFeePool(ctx, feePool) - suite.CreateVault("ukava", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - prop := types.NewCommunityPoolDepositProposal("test title", - "desc", depositAmount) - err := keeper.HandleCommunityPoolDepositProposal(ctx, suite.Keeper, prop) - suite.Require().NoError(err) - - balance := suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) - suite.Require().Equal(fundAmount.Sub(depositAmount), balance) - feePool = distKeeper.GetFeePool(ctx) - communityPoolBalance, change := feePool.CommunityPool.TruncateDecimal() - suite.Require().Equal(fundAmount.Sub(depositAmount), communityPoolBalance) - suite.Require().True(change.Empty()) -} - -func (suite *proposalTestSuite) TestCommunityWithdrawProposal() { - distKeeper := suite.App.GetDistrKeeper() - ctx := suite.Ctx - macc := distKeeper.GetDistributionAccount(ctx) - fundAmount := sdk.NewCoins(sdk.NewInt64Coin("ukava", 100000000)) - depositAmount := sdk.NewCoin("ukava", sdkmath.NewInt(10000000)) - suite.Require().NoError(suite.App.FundModuleAccount(ctx, macc.GetName(), fundAmount)) - feePool := distKeeper.GetFeePool(ctx) - feePool.CommunityPool = sdk.NewDecCoinsFromCoins(fundAmount...) - distKeeper.SetFeePool(ctx, feePool) - // TODO update to STRATEGY_TYPE_SAVINGS once implemented - suite.CreateVault("ukava", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - deposit := types.NewCommunityPoolDepositProposal("test title", - "desc", depositAmount) - err := keeper.HandleCommunityPoolDepositProposal(ctx, suite.Keeper, deposit) - suite.Require().NoError(err) - - balance := suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) - suite.Require().Equal(fundAmount.Sub(depositAmount), balance) - - withdraw := types.NewCommunityPoolWithdrawProposal("test title", - "desc", depositAmount) - err = keeper.HandleCommunityPoolWithdrawProposal(ctx, suite.Keeper, withdraw) - suite.Require().NoError(err) - balance = suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) - suite.Require().Equal(fundAmount, balance) - feePool = distKeeper.GetFeePool(ctx) - communityPoolBalance, change := feePool.CommunityPool.TruncateDecimal() - suite.Require().Equal(fundAmount, communityPoolBalance) - suite.Require().True(change.Empty()) -} diff --git a/x/earn/keeper/strategy.go b/x/earn/keeper/strategy.go deleted file mode 100644 index 7aa9a001..00000000 --- a/x/earn/keeper/strategy.go +++ /dev/null @@ -1,40 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/earn/types" -) - -// Strategy is the interface that must be implemented by a strategy. -type Strategy interface { - // GetStrategyType returns the strategy type - GetStrategyType() types.StrategyType - - // GetEstimatedTotalAssets returns the estimated total assets of the - // strategy with the specified denom. This is the value if the strategy were - // to liquidate all assets. - // - // **Note:** This may not reflect the true value as it may become outdated - // from market changes. - GetEstimatedTotalAssets(ctx sdk.Context, denom string) (sdk.Coin, error) - - // Deposit the specified amount of coins into this strategy. - Deposit(ctx sdk.Context, amount sdk.Coin) error - - // Withdraw the specified amount of coins from this strategy. - Withdraw(ctx sdk.Context, amount sdk.Coin) error -} - -// GetStrategy returns the strategy for the given strategy type. -func (k *Keeper) GetStrategy(strategyType types.StrategyType) (Strategy, error) { - switch strategyType { - case types.STRATEGY_TYPE_HARD: - return (*HardStrategy)(k), nil - case types.STRATEGY_TYPE_SAVINGS: - return (*SavingsStrategy)(k), nil - default: - return nil, fmt.Errorf("unknown strategy type: %s", strategyType) - } -} diff --git a/x/earn/keeper/strategy_hard.go b/x/earn/keeper/strategy_hard.go deleted file mode 100644 index b703435e..00000000 --- a/x/earn/keeper/strategy_hard.go +++ /dev/null @@ -1,49 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/earn/types" -) - -// HardStrategy defines the strategy that deposits assets to Hard -type HardStrategy Keeper - -var _ Strategy = (*HardStrategy)(nil) - -// GetStrategyType returns the strategy type -func (s *HardStrategy) GetStrategyType() types.StrategyType { - return types.STRATEGY_TYPE_HARD -} - -// GetEstimatedTotalAssets returns the current value of all assets deposited -// in hard. -func (s *HardStrategy) GetEstimatedTotalAssets(ctx sdk.Context, denom string) (sdk.Coin, error) { - macc := s.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - deposit, found := s.hardKeeper.GetSyncedDeposit(ctx, macc.GetAddress()) - if !found { - // Return 0 if no deposit exists for module account - return sdk.NewCoin(denom, sdk.ZeroInt()), nil - } - - // Only return the deposit for the vault denom. - for _, coin := range deposit.Amount { - if coin.Denom == denom { - return coin, nil - } - } - - // Return 0 if no deposit exists for the vault denom - return sdk.NewCoin(denom, sdk.ZeroInt()), nil -} - -// Deposit deposits the specified amount of coins into hard. -func (s *HardStrategy) Deposit(ctx sdk.Context, amount sdk.Coin) error { - macc := s.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - return s.hardKeeper.Deposit(ctx, macc.GetAddress(), sdk.NewCoins(amount)) -} - -// Withdraw withdraws the specified amount of coins from hard. -func (s *HardStrategy) Withdraw(ctx sdk.Context, amount sdk.Coin) error { - macc := s.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - return s.hardKeeper.Withdraw(ctx, macc.GetAddress(), sdk.NewCoins(amount)) -} diff --git a/x/earn/keeper/strategy_hard_test.go b/x/earn/keeper/strategy_hard_test.go deleted file mode 100644 index a283763e..00000000 --- a/x/earn/keeper/strategy_hard_test.go +++ /dev/null @@ -1,497 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/earn/testutil" - "github.com/kava-labs/kava/x/earn/types" - - "github.com/stretchr/testify/suite" -) - -type strategyHardTestSuite struct { - testutil.Suite -} - -func (suite *strategyHardTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestStrategyLendTestSuite(t *testing.T) { - suite.Run(t, new(strategyHardTestSuite)) -} - -func (suite *strategyHardTestSuite) TestGetStrategyType() { - strategy, err := suite.Keeper.GetStrategy(types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - suite.Equal(types.STRATEGY_TYPE_HARD, strategy.GetStrategyType()) -} - -func (suite *strategyHardTestSuite) TestDeposit_SingleAcc() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - suite.HardDepositAmountEqual(sdk.NewCoins(depositAmount)) - suite.VaultTotalValuesEqual(sdk.NewCoins(depositAmount)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(depositAmount.Denom, sdk.NewDecFromInt(depositAmount.Amount)), - )) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenom) - suite.Require().NoError(err) - - suite.Equal(depositAmount, totalValue) -} - -func (suite *strategyHardTestSuite) TestDeposit_SingleAcc_MultipleDeposits() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Second deposit - err = suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - expectedVaultBalance := depositAmount.Add(depositAmount) - suite.HardDepositAmountEqual(sdk.NewCoins(expectedVaultBalance)) - suite.VaultTotalValuesEqual(sdk.NewCoins(expectedVaultBalance)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(expectedVaultBalance.Denom, sdk.NewDecFromInt(expectedVaultBalance.Amount)), - )) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenom) - suite.Require().NoError(err) - - suite.Equal(depositAmount.Add(depositAmount), totalValue) -} - -func (suite *strategyHardTestSuite) TestDeposit_MultipleAcc_MultipleDeposits() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - expectedTotalValue := sdk.NewCoin(vaultDenom, depositAmount.Amount.MulRaw(4)) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // 2 deposits each account - for i := 0; i < 2; i++ { - // Deposit from acc1 - err := suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Deposit from acc2 - err = suite.Keeper.Deposit(suite.Ctx, acc2.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - } - - suite.HardDepositAmountEqual(sdk.NewCoins(expectedTotalValue)) - suite.VaultTotalValuesEqual(sdk.NewCoins(expectedTotalValue)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(expectedTotalValue.Denom, sdk.NewDecFromInt(expectedTotalValue.Amount)), - )) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenom) - suite.Require().NoError(err) - - suite.Equal(expectedTotalValue, totalValue) -} - -func (suite *strategyHardTestSuite) TestGetVaultTotalValue_Empty() { - vaultDenom := "usdx" - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenom) - suite.Require().NoError(err) - - suite.Equal(sdk.NewCoin(vaultDenom, sdk.ZeroInt()), totalValue) -} - -func (suite *strategyHardTestSuite) TestGetVaultTotalValue_NoDenomDeposit() { - // 2 Vaults usdx, busd - // 1st vault has deposits - // 2nd vault has no deposits - vaultDenom := "usdx" - vaultDenomBusd := "busd" - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault(vaultDenomBusd, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // Deposit vault1 - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Query vault total, hard deposit exists for account, but amount in busd does not - // Vault2 does not have any value, only returns amount for the correct denom - // if a hard deposit already exists - totalValueBusd, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenomBusd) - suite.Require().NoError(err) - - suite.Equal(sdk.NewCoin(vaultDenomBusd, sdk.ZeroInt()), totalValueBusd) -} - -// ---------------------------------------------------------------------------- -// Withdraw - -func (suite *strategyHardTestSuite) TestWithdraw() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - suite.HardDepositAmountEqual(sdk.NewCoins(depositAmount)) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenom) - suite.Require().NoError(err) - suite.Equal(depositAmount, totalValue) - - // Withdraw - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - suite.HardDepositAmountEqual(sdk.NewCoins()) - suite.VaultTotalValuesEqual(sdk.NewCoins()) - suite.VaultTotalSharesEqual(types.NewVaultShares()) - - totalValue, err = suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenom) - suite.Require().NoError(err) - suite.Equal(sdk.NewInt64Coin(vaultDenom, 0), totalValue) - - // Withdraw again - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrVaultRecordNotFound, "vault should be deleted when no more supply") -} - -func (suite *strategyHardTestSuite) TestWithdraw_OnlyWithdrawOwnSupply() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Deposits from 2 accounts - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - err := suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Withdraw - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Withdraw again - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs( - err, - types.ErrVaultShareRecordNotFound, - "should only be able to withdraw the account's own supply", - ) -} - -func (suite *strategyHardTestSuite) TestWithdraw_WithAccumulatedHard() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Deposits accounts - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - - err := suite.Keeper.Deposit(suite.Ctx, acc, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Deposit from acc2 so the vault doesn't get deleted when withdrawing - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Direct hard deposit from module account to increase vault value - err = suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 20))) - suite.Require().NoError(err) - - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.HardKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 20))) - suite.Require().NoError(err) - - // Query account value - accValue, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc) - suite.Require().NoError(err) - suite.Equal(depositAmount.AddAmount(sdkmath.NewInt(10)), accValue) - - // Withdraw 100, 10 remaining - _, err = suite.Keeper.Withdraw(suite.Ctx, acc, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Withdraw 100 again -- too much - _, err = suite.Keeper.Withdraw(suite.Ctx, acc, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs( - err, - types.ErrInsufficientValue, - "cannot withdraw more than account value", - ) - - // Half of remaining 10, 5 remaining - _, err = suite.Keeper.Withdraw(suite.Ctx, acc, sdk.NewCoin(vaultDenom, sdkmath.NewInt(5)), types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Withdraw all - _, err = suite.Keeper.Withdraw(suite.Ctx, acc, sdk.NewCoin(vaultDenom, sdkmath.NewInt(5)), types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - accValue, err = suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc) - suite.Require().Errorf( - err, - "account should be deleted when all shares withdrawn but has %s value still", - accValue, - ) - suite.Require().Equal("account vault share record for usdx not found", err.Error()) -} - -func (suite *strategyHardTestSuite) TestAccountShares() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 1000))) - suite.Require().NoError(err) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Deposit from account1 - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - - // 1. acc1 deposit 100 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - acc1Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100), acc1Shares.AmountOf(vaultDenom), "initial deposit 1:1 shares") - - // 2. Direct hard deposit from module account to increase vault value - // Total value: 100 -> 110 - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.HardKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 10))) - suite.Require().NoError(err) - - // 2. acc2 deposit 100 - // share price is 10% more expensive now - // hard 110 -> 210 - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // 100 * 100 / 210 = 47.619047619 shares - // 2.1 price * 47.619047619 = 99.9999999999 - acc2Value, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc2) - suite.Require().NoError(err) - suite.Equal( - sdkmath.NewInt(99), - acc2Value.Amount, - "value 1 less than deposit amount with different share price, decimals truncated", - ) - - acc2Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc2) - suite.Require().True(found) - // 100 * 100 / 110 = 190.909090909090909091 - // QuoInt64() truncates - expectedAcc2Shares := sdk.NewDec(100).MulInt64(100).QuoInt64(110) - suite.Equal(expectedAcc2Shares, acc2Shares.AmountOf(vaultDenom)) - - vaultTotalShares, found := suite.Keeper.GetVaultTotalShares(suite.Ctx, vaultDenom) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100).Add(expectedAcc2Shares), vaultTotalShares.Amount) - - // Hard deposit again from module account to triple original value - // 210 -> 300 - err = suite.HardKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 90))) - suite.Require().NoError(err) - - // Deposit again from acc1 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - acc1Shares, found = suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - // totalShares = 100 + 90 = 190 - // totalValue = 100 + 10 + 100 + 90 = 300 - // sharesIssued = assetAmount * (shareCount / totalTokens) - // sharedIssued = 100 * 190 / 300 = 63.3 = 63 - // total shares = 100 + 63 = 163 - suite.Equal( - sdk.NewDec(100).Add(sdk.NewDec(100).Mul(vaultTotalShares.Amount).Quo(sdk.NewDec(300))), - acc1Shares.AmountOf(vaultDenom), - "shares should consist of 100 of 1x share price and 63 of 3x share price", - ) -} - -func (suite *strategyHardTestSuite) TestWithdraw_AccumulatedAmount() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 1000))) - suite.Require().NoError(err) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Deposit from account1 - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - - // 1. acc1 deposit 100 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // acc2 deposit 100, just to make sure other deposits do not affect acc1 - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - acc1Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100), acc1Shares.AmountOf(vaultDenom), "initial deposit 1:1 shares") - - // 2. Direct hard deposit from module account to increase vault value - // Total value: 200 -> 220, 110 each account - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.HardKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 20))) - suite.Require().NoError(err) - - // 3. Withdraw all from acc1 - including accumulated amount - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, depositAmount.AddAmount(sdkmath.NewInt(10)), types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - _, found = suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().False(found, "should have withdrawn entire shares") -} - -func (suite *strategyHardTestSuite) TestWithdraw_AccumulatedTruncated() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 1000))) - suite.Require().NoError(err) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Deposit from account1 - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - - // 1. acc1 deposit 100 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // acc2 deposit 100, just to make sure other deposits do not affect acc1 - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - acc1Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100), acc1Shares.AmountOf(vaultDenom), "initial deposit 1:1 shares") - - // 2. Direct hard deposit from module account to increase vault value - // Total value: 200 -> 211, 105.5 each account - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.HardKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 11))) - suite.Require().NoError(err) - - accBal, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc1) - suite.Require().NoError(err) - suite.Equal(depositAmount.AddAmount(sdkmath.NewInt(5)), accBal, "acc1 should have 105 usdx") - - // 3. Withdraw all from acc1 - including accumulated amount - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, depositAmount.AddAmount(sdkmath.NewInt(5)), types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - acc1Shares, found = suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().Falsef(found, "should have withdrawn entire shares but has %s", acc1Shares) - - _, err = suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc1) - suite.Require().Error(err) -} - -func (suite *strategyHardTestSuite) TestWithdraw_ExpensiveShares() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 2000))) - suite.Require().NoError(err) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Deposit from account1 - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - - // 1. acc1 deposit 100 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - acc1Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100), acc1Shares.AmountOf(vaultDenom), "initial deposit 1:1 shares") - - // 2. Direct hard deposit from module account to increase vault value - // Total value: 100 -> 2000, shares now 10usdx each - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.HardKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 1900))) - suite.Require().NoError(err) - - accBal, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc1) - suite.Require().NoError(err) - suite.Equal(sdkmath.NewInt(2000), accBal.Amount, "acc1 should have 2000 usdx") - - // 3. Withdraw all from acc1 - including accumulated amount - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, sdk.NewInt64Coin(vaultDenom, 2000), types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - acc1Shares, found = suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().Falsef(found, "should have withdrawn entire shares but has %s", acc1Shares) - - _, err = suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc1) - suite.Require().Error(err) -} diff --git a/x/earn/keeper/strategy_savings.go b/x/earn/keeper/strategy_savings.go deleted file mode 100644 index c5955e67..00000000 --- a/x/earn/keeper/strategy_savings.go +++ /dev/null @@ -1,49 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/earn/types" -) - -// SavingsStrategy defines the strategy that deposits assets to x/savings -type SavingsStrategy Keeper - -var _ Strategy = (*SavingsStrategy)(nil) - -// GetStrategyType returns the strategy type -func (s *SavingsStrategy) GetStrategyType() types.StrategyType { - return types.STRATEGY_TYPE_SAVINGS -} - -// GetEstimatedTotalAssets returns the current value of all assets deposited -// in savings. -func (s *SavingsStrategy) GetEstimatedTotalAssets(ctx sdk.Context, denom string) (sdk.Coin, error) { - macc := s.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - deposit, found := s.savingsKeeper.GetDeposit(ctx, macc.GetAddress()) - if !found { - // Return 0 if no deposit exists for module account - return sdk.NewCoin(denom, sdk.ZeroInt()), nil - } - - // Only return the deposit for the vault denom. - for _, coin := range deposit.Amount { - if coin.Denom == denom { - return coin, nil - } - } - - // Return 0 if no deposit exists for the vault denom - return sdk.NewCoin(denom, sdk.ZeroInt()), nil -} - -// Deposit deposits the specified amount of coins into savings. -func (s *SavingsStrategy) Deposit(ctx sdk.Context, amount sdk.Coin) error { - macc := s.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - return s.savingsKeeper.Deposit(ctx, macc.GetAddress(), sdk.NewCoins(amount)) -} - -// Withdraw withdraws the specified amount of coins from savings. -func (s *SavingsStrategy) Withdraw(ctx sdk.Context, amount sdk.Coin) error { - macc := s.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - return s.savingsKeeper.Withdraw(ctx, macc.GetAddress(), sdk.NewCoins(amount)) -} diff --git a/x/earn/keeper/strategy_savings_test.go b/x/earn/keeper/strategy_savings_test.go deleted file mode 100644 index 72ad8d24..00000000 --- a/x/earn/keeper/strategy_savings_test.go +++ /dev/null @@ -1,487 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/earn/testutil" - "github.com/kava-labs/kava/x/earn/types" - - "github.com/stretchr/testify/suite" -) - -const savingsVaultDenom = "ukava" - -type strategySavingsTestSuite struct { - testutil.Suite -} - -func (suite *strategySavingsTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestStrategySavingsTestSuite(t *testing.T) { - suite.Run(t, new(strategySavingsTestSuite)) -} - -func (suite *strategySavingsTestSuite) TestGetStrategyType() { - strategy, err := suite.Keeper.GetStrategy(types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - suite.Equal(types.STRATEGY_TYPE_SAVINGS, strategy.GetStrategyType()) -} - -func (suite *strategySavingsTestSuite) TestDeposit_SingleAcc() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - suite.SavingsDepositAmountEqual(sdk.NewCoins(depositAmount)) - suite.VaultTotalValuesEqual(sdk.NewCoins(depositAmount)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(depositAmount.Denom, sdk.NewDecFromInt(depositAmount.Amount)), - )) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, savingsVaultDenom) - suite.Require().NoError(err) - - suite.Equal(depositAmount, totalValue) -} - -func (suite *strategySavingsTestSuite) TestDeposit_SingleAcc_MultipleDeposits() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Second deposit - err = suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - expectedVaultBalance := depositAmount.Add(depositAmount) - suite.SavingsDepositAmountEqual(sdk.NewCoins(expectedVaultBalance)) - suite.VaultTotalValuesEqual(sdk.NewCoins(expectedVaultBalance)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(expectedVaultBalance.Denom, sdk.NewDecFromInt(expectedVaultBalance.Amount)), - )) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, savingsVaultDenom) - suite.Require().NoError(err) - - suite.Equal(depositAmount.Add(depositAmount), totalValue) -} - -func (suite *strategySavingsTestSuite) TestDeposit_MultipleAcc_MultipleDeposits() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - - expectedTotalValue := sdk.NewCoin(savingsVaultDenom, depositAmount.Amount.MulRaw(4)) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // 2 deposits each account - for i := 0; i < 2; i++ { - // Deposit from acc1 - err := suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Deposit from acc2 - err = suite.Keeper.Deposit(suite.Ctx, acc2.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - } - - suite.SavingsDepositAmountEqual(sdk.NewCoins(expectedTotalValue)) - suite.VaultTotalValuesEqual(sdk.NewCoins(expectedTotalValue)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(expectedTotalValue.Denom, sdk.NewDecFromInt(expectedTotalValue.Amount)), - )) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, savingsVaultDenom) - suite.Require().NoError(err) - - suite.Equal(expectedTotalValue, totalValue) -} - -func (suite *strategySavingsTestSuite) TestGetVaultTotalValue_Empty() { - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, savingsVaultDenom) - suite.Require().NoError(err) - - suite.Equal(sdk.NewCoin(savingsVaultDenom, sdk.ZeroInt()), totalValue) -} - -func (suite *strategySavingsTestSuite) TestGetVaultTotalValue_NoDenomDeposit() { - // 2 Vaults usdx, busd - // 1st vault has deposits - // 2nd vault has no deposits - - vaultDenomBusd := "busd" - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - suite.CreateVault(vaultDenomBusd, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // Deposit vault1 - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Query vault total, savings deposit exists for account, but amount in busd does not - // Vault2 does not have any value, only returns amount for the correct denom - // if a savings deposit already exists - totalValueBusd, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenomBusd) - suite.Require().NoError(err) - - suite.Equal(sdk.NewCoin(vaultDenomBusd, sdk.ZeroInt()), totalValueBusd) -} - -// ---------------------------------------------------------------------------- -// Withdraw - -func (suite *strategySavingsTestSuite) TestWithdraw() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - suite.SavingsDepositAmountEqual(sdk.NewCoins(depositAmount)) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, savingsVaultDenom) - suite.Require().NoError(err) - suite.Equal(depositAmount, totalValue) - - // Withdraw - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - suite.SavingsDepositAmountEqual(sdk.NewCoins()) - suite.VaultTotalValuesEqual(sdk.NewCoins()) - suite.VaultTotalSharesEqual(types.NewVaultShares()) - - totalValue, err = suite.Keeper.GetVaultTotalValue(suite.Ctx, savingsVaultDenom) - suite.Require().NoError(err) - suite.Equal(sdk.NewInt64Coin(savingsVaultDenom, 0), totalValue) - - // Withdraw again - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrVaultRecordNotFound, "vault should be deleted when no more supply") -} - -func (suite *strategySavingsTestSuite) TestWithdraw_OnlyWithdrawOwnSupply() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - // Deposits from 2 accounts - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - err := suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Withdraw - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Withdraw again - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().Error(err) - suite.Require().ErrorIs( - err, - types.ErrVaultShareRecordNotFound, - "should only be able to withdraw the account's own supply", - ) -} - -func (suite *strategySavingsTestSuite) TestWithdraw_WithAccumulatedSavings() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - // Deposits accounts - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - - err := suite.Keeper.Deposit(suite.Ctx, acc, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Deposit from acc2 so the vault doesn't get deleted when withdrawing - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Direct savings deposit from module account to increase vault value - err = suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 20))) - suite.Require().NoError(err) - - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.SavingsKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 20))) - suite.Require().NoError(err) - - // Query account value - accValue, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, savingsVaultDenom, acc) - suite.Require().NoError(err) - suite.Equal(depositAmount.AddAmount(sdkmath.NewInt(10)), accValue) - - // Withdraw 100, 10 remaining - _, err = suite.Keeper.Withdraw(suite.Ctx, acc, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Withdraw 100 again -- too much - _, err = suite.Keeper.Withdraw(suite.Ctx, acc, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().Error(err) - suite.Require().ErrorIs( - err, - types.ErrInsufficientValue, - "cannot withdraw more than account value", - ) - - // Half of remaining 10, 5 remaining - _, err = suite.Keeper.Withdraw(suite.Ctx, acc, sdk.NewCoin(savingsVaultDenom, sdkmath.NewInt(5)), types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Withdraw all - _, err = suite.Keeper.Withdraw(suite.Ctx, acc, sdk.NewCoin(savingsVaultDenom, sdkmath.NewInt(5)), types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - accValue, err = suite.Keeper.GetVaultAccountValue(suite.Ctx, savingsVaultDenom, acc) - suite.Require().Errorf( - err, - "account should be deleted when all shares withdrawn but has %s value still", - accValue, - ) - suite.Require().Equal("account vault share record for ukava not found", err.Error()) -} - -func (suite *strategySavingsTestSuite) TestAccountShares() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 1000))) - suite.Require().NoError(err) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - // Deposit from account1 - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - - // 1. acc1 deposit 100 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - acc1Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100), acc1Shares.AmountOf(savingsVaultDenom), "initial deposit 1:1 shares") - - // 2. Direct savings deposit from module account to increase vault value - // Total value: 100 -> 110 - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.SavingsKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 10))) - suite.Require().NoError(err) - - // 2. acc2 deposit 100 - // share price is 10% more expensive now - // savings 110 -> 210 - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // 100 * 100 / 210 = 47.619047619 shares - // 2.1 price * 47.619047619 = 99.9999999999 - acc2Value, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, savingsVaultDenom, acc2) - suite.Require().NoError(err) - suite.Equal( - sdkmath.NewInt(99), - acc2Value.Amount, - "value 1 less than deposit amount with different share price, decimals truncated", - ) - - acc2Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc2) - suite.Require().True(found) - // 100 * 100 / 110 = 90.909090909090909091 - // QuoInt64() truncates - expectedAcc2Shares := sdk.NewDec(100).MulInt64(100).QuoInt64(110) - suite.Equal(expectedAcc2Shares, acc2Shares.AmountOf(savingsVaultDenom)) - - vaultTotalShares, found := suite.Keeper.GetVaultTotalShares(suite.Ctx, savingsVaultDenom) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100).Add(expectedAcc2Shares), vaultTotalShares.Amount) - - // Savings deposit again from module account to triple original value - // 210 -> 300 - err = suite.SavingsKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 90))) - suite.Require().NoError(err) - - // Deposit again from acc1 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - acc1Shares, found = suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - // totalShares = 100 + 90 = 190 - // totalValue = 100 + 10 + 100 + 90 = 300 - // sharesIssued = assetAmount * (shareCount / totalTokens) - // sharedIssued = 100 * 190 / 300 = 63.3 = 63 - // total shares = 100 + 63 = 163 - suite.Equal( - sdk.NewDec(100).Add(sdk.NewDec(100).Mul(vaultTotalShares.Amount).Quo(sdk.NewDec(300))), - acc1Shares.AmountOf(savingsVaultDenom), - "shares should consist of 100 of 1x share price and 63 of 3x share price", - ) -} - -func (suite *strategySavingsTestSuite) TestWithdraw_AccumulatedAmount() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 1000))) - suite.Require().NoError(err) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - // Deposit from account1 - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - - // 1. acc1 deposit 100 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // acc2 deposit 100, just to make sure other deposits do not affect acc1 - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - acc1Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100), acc1Shares.AmountOf(savingsVaultDenom), "initial deposit 1:1 shares") - - // 2. Direct savings deposit from module account to increase vault value - // Total value: 200 -> 220, 110 each account - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.SavingsKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 20))) - suite.Require().NoError(err) - - // 3. Withdraw all from acc1 - including accumulated amount - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, depositAmount.AddAmount(sdkmath.NewInt(10)), types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - _, found = suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().False(found, "should have withdrawn entire shares") -} - -func (suite *strategySavingsTestSuite) TestWithdraw_AccumulatedTruncated() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 1000))) - suite.Require().NoError(err) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - // Deposit from account1 - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - - // 1. acc1 deposit 100 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // acc2 deposit 100, just to make sure other deposits do not affect acc1 - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - acc1Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100), acc1Shares.AmountOf(savingsVaultDenom), "initial deposit 1:1 shares") - - // 2. Direct savings deposit from module account to increase vault value - // Total value: 200 -> 211, 105.5 each account - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.SavingsKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 11))) - suite.Require().NoError(err) - - accBal, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, savingsVaultDenom, acc1) - suite.Require().NoError(err) - suite.Equal(depositAmount.AddAmount(sdkmath.NewInt(5)), accBal, "acc1 should have 105 usdx") - - // 3. Withdraw all from acc1 - including accumulated amount - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, depositAmount.AddAmount(sdkmath.NewInt(5)), types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - acc1Shares, found = suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().Falsef(found, "should have withdrawn entire shares but has %s", acc1Shares) - - _, err = suite.Keeper.GetVaultAccountValue(suite.Ctx, savingsVaultDenom, acc1) - suite.Require().Error(err) -} - -func (suite *strategySavingsTestSuite) TestWithdraw_ExpensiveShares() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 2000))) - suite.Require().NoError(err) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - // Deposit from account1 - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - - // 1. acc1 deposit 100 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - acc1Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100), acc1Shares.AmountOf(savingsVaultDenom), "initial deposit 1:1 shares") - - // 2. Direct savings deposit from module account to increase vault value - // Total value: 100 -> 2000, shares now 10usdx each - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.SavingsKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 1900))) - suite.Require().NoError(err) - - accBal, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, savingsVaultDenom, acc1) - suite.Require().NoError(err) - suite.Equal(sdkmath.NewInt(2000), accBal.Amount, "acc1 should have 2000 usdx") - - // 3. Withdraw all from acc1 - including accumulated amount - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, sdk.NewInt64Coin(savingsVaultDenom, 2000), types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - acc1Shares, found = suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().Falsef(found, "should have withdrawn entire shares but has %s", acc1Shares) - - _, err = suite.Keeper.GetVaultAccountValue(suite.Ctx, savingsVaultDenom, acc1) - suite.Require().Error(err) -} diff --git a/x/earn/keeper/vault.go b/x/earn/keeper/vault.go deleted file mode 100644 index edb689e1..00000000 --- a/x/earn/keeper/vault.go +++ /dev/null @@ -1,73 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/earn/types" -) - -// GetVaultTotalShares returns the total shares of a vault. -func (k *Keeper) GetVaultTotalShares( - ctx sdk.Context, - denom string, -) (types.VaultShare, bool) { - vault, found := k.GetVaultRecord(ctx, denom) - if !found { - return types.VaultShare{}, false - } - - return vault.TotalShares, true -} - -// GetVaultTotalValue returns the total value of a vault, i.e. the realizable -// total value if the vault were to liquidate its entire strategies. -// -// **Note:** This does not include the tokens held in bank by the module -// account. If it were to be included, also note that the module account is -// unblocked and can receive funds from bank sends. -func (k *Keeper) GetVaultTotalValue( - ctx sdk.Context, - denom string, -) (sdk.Coin, error) { - allowedVault, found := k.GetAllowedVault(ctx, denom) - if !found { - return sdk.Coin{}, types.ErrVaultRecordNotFound - } - - strategy, err := k.GetStrategy(allowedVault.Strategies[0]) - if err != nil { - return sdk.Coin{}, types.ErrInvalidVaultStrategy - } - - // Denom can be different from allowedVault.Denom for bkava - return strategy.GetEstimatedTotalAssets(ctx, denom) -} - -// GetVaultAccountShares returns the shares for a single address for all vaults. -func (k *Keeper) GetVaultAccountShares( - ctx sdk.Context, - acc sdk.AccAddress, -) (types.VaultShares, bool) { - vaultShareRecord, found := k.GetVaultShareRecord(ctx, acc) - if !found { - return nil, false - } - - return vaultShareRecord.Shares, true -} - -// GetVaultAccountValue returns the value of a single address within a vault -// if the account were to withdraw their entire balance. -func (k *Keeper) GetVaultAccountValue( - ctx sdk.Context, - denom string, - acc sdk.AccAddress, -) (sdk.Coin, error) { - accShares, found := k.GetVaultAccountShares(ctx, acc) - if !found { - return sdk.Coin{}, fmt.Errorf("account vault share record for %s not found", denom) - } - - return k.ConvertToAssets(ctx, accShares.GetShare(denom)) -} diff --git a/x/earn/keeper/vault_record.go b/x/earn/keeper/vault_record.go deleted file mode 100644 index 9a7eb29d..00000000 --- a/x/earn/keeper/vault_record.go +++ /dev/null @@ -1,85 +0,0 @@ -package keeper - -import ( - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/earn/types" -) - -// ---------------------------------------------------------------------------- -// VaultRecord -- vault total shares - -// GetVaultRecord returns the vault record for a given denom. -func (k *Keeper) GetVaultRecord( - ctx sdk.Context, - vaultDenom string, -) (types.VaultRecord, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.VaultRecordKeyPrefix) - - bz := store.Get(types.VaultKey(vaultDenom)) - if bz == nil { - return types.VaultRecord{}, false - } - - var record types.VaultRecord - k.cdc.MustUnmarshal(bz, &record) - - return record, true -} - -// UpdateVaultRecord updates the vault record in state for a given denom. This -// deletes it if the supply is zero and updates the state if supply is non-zero. -func (k *Keeper) UpdateVaultRecord( - ctx sdk.Context, - vaultRecord types.VaultRecord, -) { - if vaultRecord.TotalShares.Amount.IsZero() { - k.DeleteVaultRecord(ctx, vaultRecord.TotalShares.Denom) - } else { - k.SetVaultRecord(ctx, vaultRecord) - } -} - -// DeleteVaultRecord deletes the vault record for a given denom. -func (k *Keeper) DeleteVaultRecord(ctx sdk.Context, vaultDenom string) { - store := prefix.NewStore(ctx.KVStore(k.key), types.VaultRecordKeyPrefix) - store.Delete(types.VaultKey(vaultDenom)) -} - -// SetVaultRecord sets the vault record for a given denom. -func (k *Keeper) SetVaultRecord(ctx sdk.Context, record types.VaultRecord) { - store := prefix.NewStore(ctx.KVStore(k.key), types.VaultRecordKeyPrefix) - bz := k.cdc.MustMarshal(&record) - store.Set(types.VaultKey(record.TotalShares.Denom), bz) -} - -// IterateVaultRecords iterates over all vault objects in the store and performs -// a callback function. -func (k Keeper) IterateVaultRecords( - ctx sdk.Context, - cb func(record types.VaultRecord) (stop bool), -) { - store := prefix.NewStore(ctx.KVStore(k.key), types.VaultRecordKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - var record types.VaultRecord - k.cdc.MustUnmarshal(iterator.Value(), &record) - if cb(record) { - break - } - } -} - -// GetAllVaultRecords returns all vault records from the store. -func (k Keeper) GetAllVaultRecords(ctx sdk.Context) types.VaultRecords { - var records types.VaultRecords - - k.IterateVaultRecords(ctx, func(record types.VaultRecord) bool { - records = append(records, record) - return false - }) - - return records -} diff --git a/x/earn/keeper/vault_share.go b/x/earn/keeper/vault_share.go deleted file mode 100644 index 36f3c608..00000000 --- a/x/earn/keeper/vault_share.go +++ /dev/null @@ -1,82 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/earn/types" -) - -// ConvertToShares converts a given amount of tokens to shares. -func (k *Keeper) ConvertToShares(ctx sdk.Context, assets sdk.Coin) (types.VaultShare, error) { - totalShares, found := k.GetVaultTotalShares(ctx, assets.Denom) - if !found { - // No shares issued yet, so shares are issued 1:1 - return types.NewVaultShare(assets.Denom, sdk.NewDecFromInt(assets.Amount)), nil - } - - totalValue, err := k.GetVaultTotalValue(ctx, assets.Denom) - if err != nil { - return types.VaultShare{}, err - } - - if totalValue.Amount.IsZero() { - return types.VaultShare{}, fmt.Errorf("total value of vault is zero") - } - - // sharePrice = totalValue / totalShares - // issuedShares = assets / sharePrice - // issuedShares = assets / (totalValue / totalShares) - // = assets * (totalShares / totalValue) - // = (assets * totalShares) / totalValue - // - // Multiply by reciprocal of sharePrice to avoid two divisions and limit - // rounding to one time. Per-share price is also not used as there is a loss - // of precision. - - // Division is done at the last step as there is a slight amount that is - // rounded down. - // For example: - // 100 * 100 / 105 == 10000 / 105 == 95.238095238095238095 - // 100 * (100 / 105) == 100 * 0.952380952380952380 == 95.238095238095238000 - // rounded down and truncated ^ loss of precision ^ - issuedShares := sdk.NewDecFromInt(assets.Amount).Mul(totalShares.Amount).QuoTruncate(sdk.NewDecFromInt(totalValue.Amount)) - - if issuedShares.IsZero() { - return types.VaultShare{}, fmt.Errorf("share count is zero") - } - - return types.NewVaultShare(assets.Denom, issuedShares), nil -} - -// ConvertToAssets converts a given amount of shares to tokens. -func (k *Keeper) ConvertToAssets(ctx sdk.Context, share types.VaultShare) (sdk.Coin, error) { - totalVaultShares, found := k.GetVaultTotalShares(ctx, share.Denom) - if !found { - return sdk.Coin{}, fmt.Errorf("vault for %s not found", share.Denom) - } - - totalValue, err := k.GetVaultTotalValue(ctx, share.Denom) - if err != nil { - return sdk.Coin{}, err - } - - // percentOwnership := accShares / totalVaultShares - // accValue := totalValue * percentOwnership - // accValue := totalValue * accShares / totalVaultShares - // Division must be last to avoid rounding errors and properly truncate. - value := sdk.NewDecFromInt(totalValue.Amount).Mul(share.Amount).QuoTruncate(totalVaultShares.Amount) - - return sdk.NewCoin(share.Denom, value.TruncateInt()), nil -} - -// ShareIsDust returns true if the share value is less than 1 coin -func (k *Keeper) ShareIsDust(ctx sdk.Context, share types.VaultShare) (bool, error) { - coin, err := k.ConvertToAssets(ctx, share) - if err != nil { - return false, err - } - - // Truncated int, becomes zero if < 1 - return coin.IsZero(), nil -} diff --git a/x/earn/keeper/vault_share_record.go b/x/earn/keeper/vault_share_record.go deleted file mode 100644 index 03585397..00000000 --- a/x/earn/keeper/vault_share_record.go +++ /dev/null @@ -1,93 +0,0 @@ -package keeper - -import ( - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/earn/types" -) - -// ---------------------------------------------------------------------------- -// VaultShareRecords -- user shares per vault - -// GetVaultShareRecord returns the vault share record for a given denom and -// account. -func (k *Keeper) GetVaultShareRecord( - ctx sdk.Context, - acc sdk.AccAddress, -) (types.VaultShareRecord, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.VaultShareRecordKeyPrefix) - - bz := store.Get(types.DepositorVaultSharesKey(acc)) - if bz == nil { - return types.VaultShareRecord{}, false - } - - var record types.VaultShareRecord - k.cdc.MustUnmarshal(bz, &record) - - return record, true -} - -// UpdateVaultShareRecord updates the vault share record in state for a given -// denom and account. This deletes it if the supply is zero and updates the -// state if supply is non-zero. -func (k *Keeper) UpdateVaultShareRecord( - ctx sdk.Context, - record types.VaultShareRecord, -) { - if record.Shares.IsZero() { - k.DeleteVaultShareRecord(ctx, record.Depositor) - } else { - k.SetVaultShareRecord(ctx, record) - } -} - -// DeleteVaultShareRecord deletes the vault share record for a given account. -func (k *Keeper) DeleteVaultShareRecord( - ctx sdk.Context, - acc sdk.AccAddress, -) { - store := prefix.NewStore(ctx.KVStore(k.key), types.VaultShareRecordKeyPrefix) - store.Delete(types.DepositorVaultSharesKey(acc)) -} - -// SetVaultShareRecord sets the vault share record for a given account. -func (k *Keeper) SetVaultShareRecord( - ctx sdk.Context, - record types.VaultShareRecord, -) { - store := prefix.NewStore(ctx.KVStore(k.key), types.VaultShareRecordKeyPrefix) - bz := k.cdc.MustMarshal(&record) - store.Set(types.DepositorVaultSharesKey(record.Depositor), bz) -} - -// IterateVaultShareRecords iterates over all vault share objects in the store -// and performs a callback function. -func (k Keeper) IterateVaultShareRecords( - ctx sdk.Context, - cb func(record types.VaultShareRecord) (stop bool), -) { - store := prefix.NewStore(ctx.KVStore(k.key), types.VaultShareRecordKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - var record types.VaultShareRecord - k.cdc.MustUnmarshal(iterator.Value(), &record) - if cb(record) { - break - } - } -} - -// GetAllVaultShareRecords returns all vault share records from the store. -func (k Keeper) GetAllVaultShareRecords(ctx sdk.Context) types.VaultShareRecords { - var records types.VaultShareRecords - - k.IterateVaultShareRecords(ctx, func(record types.VaultShareRecord) bool { - records = append(records, record) - return false - }) - - return records -} diff --git a/x/earn/keeper/vault_share_record_test.go b/x/earn/keeper/vault_share_record_test.go deleted file mode 100644 index 89eb4806..00000000 --- a/x/earn/keeper/vault_share_record_test.go +++ /dev/null @@ -1,90 +0,0 @@ -package keeper_test - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/earn/types" -) - -// ---------------------------------------------------------------------------- -// State methods - -func (suite *vaultTestSuite) TestGetVaultRecord() { - record := types.NewVaultRecord("usdx", sdk.ZeroDec()) - - _, found := suite.Keeper.GetVaultRecord(suite.Ctx, record.TotalShares.Denom) - suite.Require().False(found) - - suite.Keeper.SetVaultRecord(suite.Ctx, record) - - stateRecord, found := suite.Keeper.GetVaultRecord(suite.Ctx, record.TotalShares.Denom) - suite.Require().True(found) - suite.Require().Equal(record, stateRecord) -} - -func (suite *vaultTestSuite) TestUpdateVaultRecord() { - record := types.NewVaultRecord("usdx", sdk.ZeroDec()) - - record.TotalShares = types.NewVaultShare("usdx", sdk.NewDec(100)) - - // Update vault - suite.Keeper.UpdateVaultRecord(suite.Ctx, record) - - stateRecord, found := suite.Keeper.GetVaultRecord(suite.Ctx, record.TotalShares.Denom) - suite.Require().True(found, "vault record with supply should exist") - suite.Require().Equal(record, stateRecord) - - // Remove supply - record.TotalShares = types.NewVaultShare("usdx", sdk.NewDec(0)) - suite.Keeper.UpdateVaultRecord(suite.Ctx, record) - - _, found = suite.Keeper.GetVaultRecord(suite.Ctx, record.TotalShares.Denom) - suite.Require().False(found, "vault record with 0 supply should be deleted") -} - -func (suite *vaultTestSuite) TestGetVaultShareRecord() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - record := types.NewVaultShareRecord(acc.GetAddress(), types.NewVaultShares()) - - // Check share doesn't exist before deposit - - _, found := suite.Keeper.GetVaultShareRecord(suite.Ctx, acc.GetAddress()) - suite.Require().False(found, "vault share record should not exist before deposit") - - // Update share record - record.Shares = types.NewVaultShares( - types.NewVaultShare(vaultDenom, sdk.NewDec(100)), - ) - suite.Keeper.SetVaultShareRecord(suite.Ctx, record) - - // Check share exists and matches set value - stateRecord, found := suite.Keeper.GetVaultShareRecord(suite.Ctx, acc.GetAddress()) - suite.Require().True(found) - suite.Require().Equal(record, stateRecord) -} - -func (suite *vaultTestSuite) TestUpdateVaultShareRecord() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - record := types.NewVaultShareRecord(acc.GetAddress(), types.NewVaultShares( - types.NewVaultShare(vaultDenom, sdk.NewDec(100)), - )) - - // Update vault - suite.Keeper.UpdateVaultShareRecord(suite.Ctx, record) - - stateRecord, found := suite.Keeper.GetVaultShareRecord(suite.Ctx, acc.GetAddress()) - suite.Require().True(found, "vault share record with supply should exist") - suite.Require().Equal(record, stateRecord) - - // Remove supply - record.Shares = types.NewVaultShares() - suite.Keeper.UpdateVaultShareRecord(suite.Ctx, record) - - _, found = suite.Keeper.GetVaultShareRecord(suite.Ctx, acc.GetAddress()) - suite.Require().False(found, "vault share record with 0 supply should be deleted") -} diff --git a/x/earn/keeper/vault_share_test.go b/x/earn/keeper/vault_share_test.go deleted file mode 100644 index 8cefd82a..00000000 --- a/x/earn/keeper/vault_share_test.go +++ /dev/null @@ -1,133 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/earn/testutil" - "github.com/kava-labs/kava/x/earn/types" -) - -type vaultShareTestSuite struct { - testutil.Suite -} - -func (suite *vaultShareTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestVaultShareTestSuite(t *testing.T) { - suite.Run(t, new(vaultShareTestSuite)) -} - -func (suite *vaultShareTestSuite) TestConvertToShares() { - vaultDenom := "usdx" - - tests := []struct { - name string - beforeConvert func() - giveAmount sdk.Coin - wantShares types.VaultShare - }{ - { - name: "initial 1:1", - beforeConvert: func() {}, - giveAmount: sdk.NewCoin(vaultDenom, sdkmath.NewInt(100)), - wantShares: types.NewVaultShare(vaultDenom, sdk.NewDec(100)), - }, - { - name: "value doubled", - - beforeConvert: func() { - // set total shares set total value for hard - // value is double than shares - // shares is 2x price now - suite.addTotalShareAndValue(vaultDenom, sdk.NewDec(100), sdkmath.NewInt(200)) - }, - giveAmount: sdk.NewCoin(vaultDenom, sdkmath.NewInt(100)), - wantShares: types.NewVaultShare(vaultDenom, sdk.NewDec(50)), - }, - { - name: "truncate", - - beforeConvert: func() { - suite.addTotalShareAndValue(vaultDenom, sdk.NewDec(1000), sdkmath.NewInt(1001)) - }, - giveAmount: sdk.NewCoin(vaultDenom, sdkmath.NewInt(100)), - // 100 * 100 / 101 = 99.0099something - wantShares: types.NewVaultShare(vaultDenom, sdk.NewDec(100).MulInt64(1000).QuoInt64(1001)), - }, - } - - for _, tt := range tests { - suite.Run(tt.name, func() { - // Reset state - suite.Suite.SetupTest() - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - err := suite.App.FundModuleAccount( - suite.Ctx, - types.ModuleName, - sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 10000)), - ) - suite.Require().NoError(err) - - // Run any deposits or any other setup - tt.beforeConvert() - - issuedShares, err := suite.Keeper.ConvertToShares(suite.Ctx, tt.giveAmount) - suite.Require().NoError(err) - - suite.Equal(tt.wantShares, issuedShares) - }) - } -} - -func (suite *vaultShareTestSuite) addTotalShareAndValue( - vaultDenom string, - vaultShares sdk.Dec, - hardDeposit sdkmath.Int, -) { - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - - vaultRecord, found := suite.Keeper.GetVaultRecord(suite.Ctx, vaultDenom) - if !found { - vaultRecord = types.NewVaultRecord(vaultDenom, sdk.ZeroDec()) - } - - // Add to vault record - vaultRecord.TotalShares.Amount = vaultRecord.TotalShares.Amount.Add(vaultShares) - - // set total shares - suite.Keeper.UpdateVaultRecord( - suite.Ctx, - vaultRecord, - ) - // add value for hard -- this does not set - err := suite.HardKeeper.Deposit( - suite.Ctx, - macc.GetAddress(), - sdk.NewCoins(sdk.NewCoin(vaultDenom, hardDeposit)), - ) - suite.Require().NoError(err) -} - -func TestPrecisionMulQuoOrder(t *testing.T) { - assetAmount := sdk.NewDec(100) - totalShares := sdk.NewDec(100) - totalValue := sdk.NewDec(105) - - // issuedShares = assetAmount * (totalValue / totalShares) - // = (assetAmount * totalShares) / totalValue - mulFirst := assetAmount.Mul(totalShares).QuoTruncate(totalValue) - quoFirst := assetAmount.Mul(totalShares.QuoTruncate(totalValue)) - - assert.Equal(t, sdk.MustNewDecFromStr("95.238095238095238095"), mulFirst) - assert.Equal(t, sdk.MustNewDecFromStr("95.238095238095238000"), quoFirst) - - assert.NotEqual(t, mulFirst, quoFirst) -} diff --git a/x/earn/keeper/vault_test.go b/x/earn/keeper/vault_test.go deleted file mode 100644 index d1568880..00000000 --- a/x/earn/keeper/vault_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/earn/testutil" - "github.com/kava-labs/kava/x/earn/types" - "github.com/stretchr/testify/suite" -) - -type vaultTestSuite struct { - testutil.Suite -} - -func (suite *vaultTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestVaultTestSuite(t *testing.T) { - suite.Run(t, new(vaultTestSuite)) -} - -func (suite *vaultTestSuite) TestGetVaultTotalShares() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - vaultTotalShares, found := suite.Keeper.GetVaultTotalShares(suite.Ctx, vaultDenom) - suite.Require().True(found) - - suite.Equal(sdk.NewDecFromInt(depositAmount.Amount), vaultTotalShares.Amount) -} - -func (suite *vaultTestSuite) TestGetVaultTotalShares_NotFound() { - vaultDenom := "usdx" - - _, found := suite.Keeper.GetVaultTotalShares(suite.Ctx, vaultDenom) - suite.Require().False(found) -} - -func (suite *vaultTestSuite) TestGetVaultTotalValue() { - vaultDenom := "usdx" - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenom) - suite.Require().NoError(err) - suite.Equal(sdkmath.NewInt(0), totalValue.Amount) -} - -func (suite *vaultTestSuite) TestGetVaultTotalValue_NotFound() { - vaultDenom := "usdx" - - _, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenom) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrVaultRecordNotFound) -} - -func (suite *vaultTestSuite) TestInvalidVaultStrategy() { - vaultDenom := "usdx" - - suite.PanicsWithValue("value from ParamSetPair is invalid: invalid strategy 99999", func() { - suite.CreateVault(vaultDenom, types.StrategyTypes{99999}, false, nil) // not valid strategy type - }) -} - -func (suite *vaultTestSuite) TestGetVaultAccountSupplied() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - deposit1Amount := sdk.NewInt64Coin(vaultDenom, 100) - deposit2Amount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1) - - // Before deposit, account supplied is 0 - - _, found := suite.Keeper.GetVaultShareRecord(suite.Ctx, acc1.GetAddress()) - suite.Require().False(found) - - _, found = suite.Keeper.GetVaultShareRecord(suite.Ctx, acc2.GetAddress()) - suite.Require().False(found) - - // Deposits from both accounts - err := suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), deposit1Amount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - err = suite.Keeper.Deposit(suite.Ctx, acc2.GetAddress(), deposit2Amount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Check balances - - vaultAcc1Supplied, found := suite.Keeper.GetVaultShareRecord(suite.Ctx, acc1.GetAddress()) - suite.Require().True(found) - - vaultAcc2Supplied, found := suite.Keeper.GetVaultShareRecord(suite.Ctx, acc2.GetAddress()) - suite.Require().True(found) - - // Account supply only includes the deposit from respective accounts - suite.Equal(sdk.NewDecFromInt(deposit1Amount.Amount), vaultAcc1Supplied.Shares.AmountOf(vaultDenom)) - suite.Equal(sdk.NewDecFromInt(deposit1Amount.Amount), vaultAcc2Supplied.Shares.AmountOf(vaultDenom)) -} - -func (suite *vaultTestSuite) TestGetVaultAccountValue() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - accValue, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc.GetAddress()) - suite.Require().NoError(err) - suite.Equal(depositAmount, accValue, "value should be same as deposit amount") -} - -func (suite *vaultTestSuite) TestGetVaultAccountValue_VaultNotFound() { - vaultDenom := "usdx" - acc := suite.CreateAccount(sdk.NewCoins(), 0) - - _, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc.GetAddress()) - suite.Require().Error(err) - suite.Require().Equal("account vault share record for usdx not found", err.Error()) -} - -func (suite *vaultTestSuite) TestGetVaultAccountValue_ShareNotFound() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Deposit from acc1 so that vault record exists - err := suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Query from acc2 with no share record - _, err = suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc2.GetAddress()) - suite.Require().Error(err) - suite.Require().Equal("account vault share record for usdx not found", err.Error()) -} diff --git a/x/earn/keeper/withdraw.go b/x/earn/keeper/withdraw.go deleted file mode 100644 index f11a21bf..00000000 --- a/x/earn/keeper/withdraw.go +++ /dev/null @@ -1,168 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/earn/types" -) - -// Withdraw removes the amount of supplied tokens from a vault and transfers it -// back to the account. -func (k *Keeper) Withdraw( - ctx sdk.Context, - from sdk.AccAddress, - wantAmount sdk.Coin, - withdrawStrategy types.StrategyType, -) (sdk.Coin, error) { - // Get AllowedVault, if not found (not a valid vault), return error - allowedVault, found := k.GetAllowedVault(ctx, wantAmount.Denom) - if !found { - return sdk.Coin{}, types.ErrInvalidVaultDenom - } - - if wantAmount.IsZero() { - return sdk.Coin{}, types.ErrInsufficientAmount - } - - // Check if withdraw strategy is supported by vault - if !allowedVault.IsStrategyAllowed(withdrawStrategy) { - return sdk.Coin{}, types.ErrInvalidVaultStrategy - } - - // Check if VaultRecord exists - vaultRecord, found := k.GetVaultRecord(ctx, wantAmount.Denom) - if !found { - return sdk.Coin{}, types.ErrVaultRecordNotFound - } - - // Get account share record for the vault - vaultShareRecord, found := k.GetVaultShareRecord(ctx, from) - if !found { - return sdk.Coin{}, types.ErrVaultShareRecordNotFound - } - - withdrawShares, err := k.ConvertToShares(ctx, wantAmount) - if err != nil { - return sdk.Coin{}, fmt.Errorf("failed to convert assets to shares: %w", err) - } - - accCurrentShares := vaultShareRecord.Shares.AmountOf(wantAmount.Denom) - // Check if account is not withdrawing more shares than they have - if accCurrentShares.LT(withdrawShares.Amount) { - return sdk.Coin{}, errorsmod.Wrapf( - types.ErrInsufficientValue, - "account has less %s vault shares than withdraw shares, %s < %s", - wantAmount.Denom, - accCurrentShares, - withdrawShares.Amount, - ) - } - - // Convert shares to amount to get truncated true share value - withdrawAmount, err := k.ConvertToAssets(ctx, withdrawShares) - if err != nil { - return sdk.Coin{}, fmt.Errorf("failed to convert shares to assets: %w", err) - } - - accountValue, err := k.GetVaultAccountValue(ctx, wantAmount.Denom, from) - if err != nil { - return sdk.Coin{}, fmt.Errorf("failed to get account value: %w", err) - } - - // Check if withdrawAmount > account value - if withdrawAmount.Amount.GT(accountValue.Amount) { - return sdk.Coin{}, errorsmod.Wrapf( - types.ErrInsufficientValue, - "account has less %s vault value than withdraw amount, %s < %s", - withdrawAmount.Denom, - accountValue.Amount, - withdrawAmount.Amount, - ) - } - - // Get the strategy for the vault - strategy, err := k.GetStrategy(allowedVault.Strategies[0]) - if err != nil { - return sdk.Coin{}, err - } - - // Not necessary to check if amount denom is allowed for the strategy, as - // there would be no vault record if it weren't allowed. - - // Withdraw the withdrawAmount from the strategy - if err := strategy.Withdraw(ctx, withdrawAmount); err != nil { - return sdk.Coin{}, fmt.Errorf("failed to withdraw from strategy: %w", err) - } - - // Send coins back to account, must withdraw from strategy first or the - // module account may not have any funds to send. - if err := k.bankKeeper.SendCoinsFromModuleToAccount( - ctx, - types.ModuleName, - from, - sdk.NewCoins(withdrawAmount), - ); err != nil { - return sdk.Coin{}, err - } - - // Check if new account balance of shares results in account share value - // of < 1 of a sdk.Coin. This share value is not able to be withdrawn and - // should just be removed. - isDust, err := k.ShareIsDust( - ctx, - vaultShareRecord.Shares.GetShare(withdrawAmount.Denom).Sub(withdrawShares), - ) - if err != nil { - return sdk.Coin{}, err - } - - if isDust { - // Modify withdrawShares to subtract entire share balance for denom - // This does not modify the actual withdraw coin amount as the - // difference is < 1coin. - withdrawShares = vaultShareRecord.Shares.GetShare(withdrawAmount.Denom) - } - - // Call hook before record is modified with the user's current shares - k.BeforeVaultDepositModified(ctx, wantAmount.Denom, from, accCurrentShares) - - // Decrement VaultRecord and VaultShareRecord supplies - must delete same - // amounts - vaultShareRecord.Shares = vaultShareRecord.Shares.Sub(withdrawShares) - vaultRecord.TotalShares = vaultRecord.TotalShares.Sub(withdrawShares) - - // Update VaultRecord and VaultShareRecord, deletes if zero supply - k.UpdateVaultRecord(ctx, vaultRecord) - k.UpdateVaultShareRecord(ctx, vaultShareRecord) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeVaultWithdraw, - sdk.NewAttribute(types.AttributeKeyVaultDenom, withdrawAmount.Denom), - sdk.NewAttribute(types.AttributeKeyOwner, from.String()), - sdk.NewAttribute(types.AttributeKeyShares, withdrawShares.Amount.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, withdrawAmount.Amount.String()), - ), - ) - - return withdrawAmount, nil -} - -// WithdrawFromModuleAccount removes the amount of supplied tokens from a vault and transfers it -// back to the module account. The module account must be unblocked from receiving transfers. -func (k *Keeper) WithdrawFromModuleAccount( - ctx sdk.Context, - from string, - wantAmount sdk.Coin, - withdrawStrategy types.StrategyType, -) (sdk.Coin, error) { - // Ensure the module account exists to prevent SendCoins from creating a new non-module account. - acc := k.accountKeeper.GetModuleAccount(ctx, from) - if acc == nil { - return sdk.Coin{}, fmt.Errorf("module account not found: %s", from) - } - return k.Withdraw(ctx, acc.GetAddress(), wantAmount, withdrawStrategy) -} diff --git a/x/earn/keeper/withdraw_test.go b/x/earn/keeper/withdraw_test.go deleted file mode 100644 index 4b8d0b4d..00000000 --- a/x/earn/keeper/withdraw_test.go +++ /dev/null @@ -1,274 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/earn/testutil" - "github.com/kava-labs/kava/x/earn/types" - "github.com/stretchr/testify/suite" -) - -type withdrawTestSuite struct { - testutil.Suite -} - -func (suite *withdrawTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestWithdrawTestSuite(t *testing.T) { - suite.Run(t, new(withdrawTestSuite)) -} - -func (suite *withdrawTestSuite) TestWithdraw_NoVaultRecord() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - withdrawAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // Withdraw without having any prior deposits - _, err := suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), withdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrVaultRecordNotFound) - - // No balance changes - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.ModuleAccountBalanceEqual( - sdk.NewCoins(), - ) -} - -func (suite *withdrawTestSuite) TestWithdraw_NoVaultShareRecord() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - - acc1DepositAmount := sdk.NewCoin(vaultDenom, sdkmath.NewInt(100)) - acc2WithdrawAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Create deposit from acc1 so the VaultRecord exists in state - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - err := suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), acc1DepositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1) - - // Withdraw from acc2 without having any prior deposits - _, err = suite.Keeper.Withdraw(suite.Ctx, acc2.GetAddress(), acc2WithdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrVaultShareRecordNotFound) - - // No balance changes in acc2 - suite.AccountBalanceEqual( - acc2.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.VaultTotalValuesEqual(sdk.NewCoins(acc1DepositAmount)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(acc1DepositAmount.Denom, sdk.NewDecFromInt(acc1DepositAmount.Amount)), - )) -} - -func (suite *withdrawTestSuite) TestWithdraw_ExceedBalance() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - withdrawAmount := sdk.NewInt64Coin(vaultDenom, 200) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), withdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrInsufficientValue) - - // Balances still the same after deposit - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance.Sub(depositAmount)), - ) - - suite.VaultTotalValuesEqual(sdk.NewCoins(depositAmount)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(depositAmount.Denom, sdk.NewDecFromInt(depositAmount.Amount)), - )) -} - -func (suite *withdrawTestSuite) TestWithdraw_Zero() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - withdrawAmount := sdk.NewInt64Coin(vaultDenom, 0) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - _, err := suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), withdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrInsufficientAmount) - - // No changes in balances - - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.ModuleAccountBalanceEqual( - sdk.NewCoins(), - ) -} - -func (suite *withdrawTestSuite) TestWithdraw_InvalidVault() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - withdrawAmount := sdk.NewInt64Coin(vaultDenom, 1001) - - // Vault not created -- doesn't exist - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - _, err := suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), withdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrInvalidVaultDenom) - - // No changes in balances - - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.ModuleAccountBalanceEqual( - sdk.NewCoins(), - ) -} - -func (suite *withdrawTestSuite) TestWithdraw_InvalidStrategy() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - withdrawAmount := sdk.NewInt64Coin(vaultDenom, 1001) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - _, err := suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), withdrawAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrInvalidVaultStrategy) -} - -func (suite *withdrawTestSuite) TestWithdraw_FullBalance() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - withdrawAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), withdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // No net changes in balances - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.ModuleAccountBalanceEqual( - sdk.NewCoins(), - ) -} - -func (suite *withdrawTestSuite) TestWithdraw_Partial() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - partialWithdrawAmount := sdk.NewInt64Coin(vaultDenom, 50) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), partialWithdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance.Sub(depositAmount).Add(partialWithdrawAmount)), - ) - - // Second withdraw for remaining 50 - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), partialWithdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // No more balance to withdraw - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), partialWithdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrVaultRecordNotFound, "vault record should be deleted after no more supplied") - - // No net changes in balances - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.ModuleAccountBalanceEqual( - sdk.NewCoins(), - ) -} - -func (suite *withdrawTestSuite) TestWithdraw_bKava() { - vaultDenom := "bkava" - coinDenom := testutil.TestBkavaDenoms[0] - - startBalance := sdk.NewInt64Coin(coinDenom, 1000) - depositAmount := sdk.NewInt64Coin(coinDenom, 100) - - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // vault denom is only "bkava" which has it's own special handler - suite.CreateVault( - vaultDenom, - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - false, - []sdk.AccAddress{}, - ) - - err := suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError( - err, - "should be able to deposit bkava derivative denom in bkava vault", - ) - - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError( - err, - "should be able to withdraw bkava derivative denom from bkava vault", - ) -} diff --git a/x/earn/module.go b/x/earn/module.go deleted file mode 100644 index 03374364..00000000 --- a/x/earn/module.go +++ /dev/null @@ -1,146 +0,0 @@ -package earn - -import ( - "context" - "encoding/json" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/kava-labs/kava/x/earn/client/cli" - "github.com/kava-labs/kava/x/earn/keeper" - "github.com/kava-labs/kava/x/earn/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - gs := types.DefaultGenesisState() - return cdc.MustMarshalJSON(&gs) -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) - if err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the gov module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// GetTxCmd returns the root tx command for the module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper authkeeper.AccountKeeper - bankKeeper types.BankKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper authkeeper.AccountKeeper, bankKeeper types.BankKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - } -} - -// Name module name -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// RegisterInvariants register module invariants -func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { - keeper.RegisterInvariants(ir, am.keeper) -} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) -} - -// InitGenesis module init-genesis -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, am.accountKeeper, genState) - - return []abci.ValidatorUpdate{} -} - -// ExportGenesis module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(&gs) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) { -} - -// EndBlock module end-block -func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/earn/testutil/suite.go b/x/earn/testutil/suite.go deleted file mode 100644 index 063dca41..00000000 --- a/x/earn/testutil/suite.go +++ /dev/null @@ -1,459 +0,0 @@ -package testutil - -import ( - "fmt" - "reflect" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/earn/keeper" - "github.com/kava-labs/kava/x/earn/types" - "github.com/kava-labs/kava/x/hard" - - hardkeeper "github.com/kava-labs/kava/x/hard/keeper" - hardtypes "github.com/kava-labs/kava/x/hard/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" - savingskeeper "github.com/kava-labs/kava/x/savings/keeper" - savingstypes "github.com/kava-labs/kava/x/savings/types" - - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" -) - -var TestBkavaDenoms = []string{ - "bkava-kavavaloper15gqc744d05xacn4n6w2furuads9fu4pqn6zxlu", - "bkava-kavavaloper15qdefkmwswysgg4qxgqpqr35k3m49pkx8yhpte", - "bkava-kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42", -} - -// Suite implements a test suite for the earn module integration tests -type Suite struct { - suite.Suite - Keeper keeper.Keeper - App app.TestApp - Ctx sdk.Context - BankKeeper bankkeeper.Keeper - AccountKeeper authkeeper.AccountKeeper - - // Strategy Keepers - HardKeeper hardkeeper.Keeper - SavingsKeeper savingskeeper.Keeper -} - -// SetupTest instantiates a new app, keepers, and sets suite state -func (suite *Suite) SetupTest() { - // Pricefeed required for withdrawing from hard - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("10.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - }, - } - - hardGS := hardtypes.NewGenesisState(hardtypes.NewParams( - hardtypes.MoneyMarkets{ - hardtypes.NewMoneyMarket( - "usdx", - hardtypes.NewBorrowLimit( - true, - sdk.MustNewDecFromStr("20000000"), - sdk.MustNewDecFromStr("1"), - ), - "usdx:usd", - sdkmath.NewInt(1000000), - hardtypes.NewInterestRateModel( - sdk.MustNewDecFromStr("0.05"), - sdk.MustNewDecFromStr("2"), - sdk.MustNewDecFromStr("0.8"), - sdk.MustNewDecFromStr("10"), - ), - sdk.MustNewDecFromStr("0.05"), - sdk.ZeroDec(), - ), - hardtypes.NewMoneyMarket( - "busd", - hardtypes.NewBorrowLimit( - true, - sdk.MustNewDecFromStr("20000000"), - sdk.MustNewDecFromStr("1"), - ), - "busd:usd", - sdkmath.NewInt(1000000), - hardtypes.NewInterestRateModel( - sdk.MustNewDecFromStr("0.05"), - sdk.MustNewDecFromStr("2"), - sdk.MustNewDecFromStr("0.8"), - sdk.MustNewDecFromStr("10"), - ), - sdk.MustNewDecFromStr("0.05"), - sdk.ZeroDec(), - ), - hardtypes.NewMoneyMarket( - "kava", - hardtypes.NewBorrowLimit( - true, - sdk.MustNewDecFromStr("20000000"), - sdk.MustNewDecFromStr("1"), - ), - "kava:usd", - sdkmath.NewInt(1000000), - hardtypes.NewInterestRateModel( - sdk.MustNewDecFromStr("0.05"), - sdk.MustNewDecFromStr("2"), - sdk.MustNewDecFromStr("0.8"), - sdk.MustNewDecFromStr("10"), - ), - sdk.MustNewDecFromStr("0.05"), - sdk.ZeroDec(), - ), - }, - sdk.NewDec(10), - ), - hardtypes.DefaultAccumulationTimes, - hardtypes.DefaultDeposits, - hardtypes.DefaultBorrows, - hardtypes.DefaultTotalSupplied, - hardtypes.DefaultTotalBorrowed, - hardtypes.DefaultTotalReserves, - ) - - savingsGS := savingstypes.NewGenesisState( - savingstypes.NewParams( - []string{ - "ukava", - "busd", - "usdx", - TestBkavaDenoms[0], - TestBkavaDenoms[1], - TestBkavaDenoms[2], - }, - ), - nil, - ) - - stakingParams := stakingtypes.DefaultParams() - stakingParams.BondDenom = "ukava" - - stakingGs := stakingtypes.GenesisState{ - Params: stakingParams, - } - - tApp := app.NewTestApp() - - tApp.InitializeFromGenesisStates( - app.GenesisState{ - pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS), - hardtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS), - savingstypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&savingsGS), - stakingtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&stakingGs), - }, - ) - - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - suite.Ctx = ctx - suite.App = tApp - suite.Keeper = tApp.GetEarnKeeper() - suite.BankKeeper = tApp.GetBankKeeper() - suite.AccountKeeper = tApp.GetAccountKeeper() - - suite.HardKeeper = tApp.GetHardKeeper() - suite.SavingsKeeper = tApp.GetSavingsKeeper() - - hard.BeginBlocker(suite.Ctx, suite.HardKeeper) -} - -// GetEvents returns emitted events on the sdk context -func (suite *Suite) GetEvents() sdk.Events { - return suite.Ctx.EventManager().Events() -} - -// AddCoinsToModule adds coins to the earn module account -func (suite *Suite) AddCoinsToModule(amount sdk.Coins) { - // Does not use suite.BankKeeper.MintCoins as module account would not have permission to mint - err := banktestutil.FundModuleAccount(suite.BankKeeper, suite.Ctx, types.ModuleName, amount) - suite.Require().NoError(err) -} - -// RemoveCoinsFromModule removes coins to the earn module account -func (suite *Suite) RemoveCoinsFromModule(amount sdk.Coins) { - // Earn module does not have BurnCoins permission so we need to transfer to gov first to burn - err := suite.BankKeeper.SendCoinsFromModuleToModule(suite.Ctx, types.ModuleAccountName, govtypes.ModuleName, amount) - suite.Require().NoError(err) - err = suite.BankKeeper.BurnCoins(suite.Ctx, govtypes.ModuleName, amount) - suite.Require().NoError(err) -} - -// CreateAccount creates a new account from the provided balance, using index -// to create different new addresses. -func (suite *Suite) CreateAccount(initialBalance sdk.Coins, index int) authtypes.AccountI { - _, addrs := app.GeneratePrivKeyAddressPairs(index + 1) - ak := suite.App.GetAccountKeeper() - - acc := ak.NewAccountWithAddress(suite.Ctx, addrs[index]) - ak.SetAccount(suite.Ctx, acc) - - err := banktestutil.FundAccount(suite.BankKeeper, suite.Ctx, acc.GetAddress(), initialBalance) - suite.Require().NoError(err) - - return acc -} - -// NewAccountFromAddr creates a new account from the provided address with the provided balance -func (suite *Suite) NewAccountFromAddr(addr sdk.AccAddress, balance sdk.Coins) authtypes.AccountI { - ak := suite.App.GetAccountKeeper() - - acc := ak.NewAccountWithAddress(suite.Ctx, addr) - ak.SetAccount(suite.Ctx, acc) - - err := banktestutil.FundAccount(suite.BankKeeper, suite.Ctx, acc.GetAddress(), balance) - suite.Require().NoError(err) - - return acc -} - -// CreateVault adds a new vault to the keeper parameters -func (suite *Suite) CreateVault( - vaultDenom string, - vaultStrategies types.StrategyTypes, - isPrivateVault bool, - allowedDepositors []sdk.AccAddress, -) { - vault := types.NewAllowedVault(vaultDenom, vaultStrategies, isPrivateVault, allowedDepositors) - - allowedVaults := suite.Keeper.GetAllowedVaults(suite.Ctx) - allowedVaults = append(allowedVaults, vault) - - params := types.NewParams(allowedVaults) - - suite.Keeper.SetParams( - suite.Ctx, - params, - ) -} - -// AccountBalanceEqual asserts that the coins match the account balance -func (suite *Suite) AccountBalanceEqual(addr sdk.AccAddress, coins sdk.Coins) { - balance := suite.BankKeeper.GetAllBalances(suite.Ctx, addr) - suite.Equal(coins, balance, fmt.Sprintf("expected account balance to equal coins %s, but got %s", coins, balance)) -} - -// ModuleAccountBalanceEqual asserts that the earn module account balance matches the provided coins -func (suite *Suite) ModuleAccountBalanceEqual(coins sdk.Coins) { - balance := suite.BankKeeper.GetAllBalances( - suite.Ctx, - suite.AccountKeeper.GetModuleAddress(types.ModuleAccountName), - ) - suite.Equal(coins, balance, fmt.Sprintf("expected module account balance to equal coins %s, but got %s", coins, balance)) -} - -// ---------------------------------------------------------------------------- -// Earn - -// VaultTotalValuesEqual asserts that the vault total values match the provided -// values. -func (suite *Suite) VaultTotalValuesEqual(expected sdk.Coins) { - for _, coin := range expected { - vaultBal, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, coin.Denom) - suite.Require().NoError(err, "failed to get vault balance") - suite.Require().Equal(coin, vaultBal) - } -} - -// VaultTotalSharesEqual asserts that the vault total shares match the provided -// values. -func (suite *Suite) VaultTotalSharesEqual(expected types.VaultShares) { - for _, share := range expected { - vaultBal, found := suite.Keeper.GetVaultTotalShares(suite.Ctx, share.Denom) - suite.Require().Truef(found, "%s vault does not exist", share.Denom) - suite.Require().Equal(share.Amount, vaultBal.Amount) - } -} - -// VaultAccountSharesEqual asserts that the vault account shares match the provided -// values. -func (suite *Suite) VaultAccountSharesEqual(accs []sdk.AccAddress, supplies []sdk.Coins) { - for i, acc := range accs { - coins := supplies[i] - - accVaultBal, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc) - suite.Require().True(found) - - for _, coin := range coins { - suite.Require().Equal( - coin.Amount, - accVaultBal.AmountOf(coin.Denom), - "expected account vault balance to equal coins %s, but got %s", - coins, accVaultBal, - ) - } - } -} - -// ---------------------------------------------------------------------------- -// Hard - -// HardDepositAmountEqual asserts that the hard deposit amount matches the provided -// values. -func (suite *Suite) HardDepositAmountEqual(expected sdk.Coins) { - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - - hardDeposit, found := suite.HardKeeper.GetSyncedDeposit(suite.Ctx, macc.GetAddress()) - if expected.IsZero() { - suite.Require().False(found) - return - } - - suite.Require().True(found, "hard should have a deposit") - suite.Require().Equalf( - expected, - hardDeposit.Amount, - "hard should have a deposit with the amount %v", - expected, - ) -} - -// ---------------------------------------------------------------------------- -// Savings - -// SavingsDepositAmountEqual asserts that the savings deposit amount matches the -// provided values. -func (suite *Suite) SavingsDepositAmountEqual(expected sdk.Coins) { - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - - savingsDeposit, found := suite.SavingsKeeper.GetDeposit(suite.Ctx, macc.GetAddress()) - if expected.IsZero() { - suite.Require().False(found) - return - } - - suite.Require().True(found, "savings should have a deposit") - suite.Require().Equalf( - expected, - savingsDeposit.Amount, - "savings should have a deposit with the amount %v", - expected, - ) -} - -// ---------------------------------------------------------------------------- -// Staking - -// CreateNewUnbondedValidator creates a new validator in the staking module. -// New validators are unbonded until the end blocker is run. -func (suite *Suite) CreateNewUnbondedValidator(addr sdk.ValAddress, selfDelegation sdkmath.Int) stakingtypes.Validator { - // Create a validator - err := suite.deliverMsgCreateValidator(suite.Ctx, addr, suite.NewBondCoin(selfDelegation)) - suite.Require().NoError(err) - - // New validators are created in an unbonded state. Note if the end blocker is run later this validator could become bonded. - - validator, found := suite.App.GetStakingKeeper().GetValidator(suite.Ctx, addr) - suite.Require().True(found) - return validator -} - -// NewBondCoin creates a Coin with the current staking denom. -func (suite *Suite) NewBondCoin(amount sdkmath.Int) sdk.Coin { - stakingDenom := suite.App.GetStakingKeeper().BondDenom(suite.Ctx) - return sdk.NewCoin(stakingDenom, amount) -} - -// CreateDelegation delegates tokens to a validator. -func (suite *Suite) CreateDelegation(valAddr sdk.ValAddress, delegator sdk.AccAddress, amount sdkmath.Int) sdk.Dec { - sk := suite.App.GetStakingKeeper() - - stakingDenom := sk.BondDenom(suite.Ctx) - msg := stakingtypes.NewMsgDelegate( - delegator, - valAddr, - sdk.NewCoin(stakingDenom, amount), - ) - - msgServer := stakingkeeper.NewMsgServerImpl(sk) - _, err := msgServer.Delegate(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - del, found := sk.GetDelegation(suite.Ctx, delegator, valAddr) - suite.Require().True(found) - return del.Shares -} - -func (suite *Suite) deliverMsgCreateValidator(ctx sdk.Context, address sdk.ValAddress, selfDelegation sdk.Coin) error { - msg, err := stakingtypes.NewMsgCreateValidator( - address, - ed25519.GenPrivKey().PubKey(), - selfDelegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - sdkmath.NewInt(1e6), - ) - if err != nil { - return err - } - - msgServer := stakingkeeper.NewMsgServerImpl(suite.App.GetStakingKeeper()) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.Ctx), msg) - return err -} - -// ---------------------------------------------------------------------------- - -// EventsContains asserts that the expected event is in the provided events -func (suite *Suite) EventsContains(events sdk.Events, expectedEvent sdk.Event) { - foundMatch := false - for _, event := range events { - if event.Type == expectedEvent.Type { - if reflect.DeepEqual(attrsToMap(expectedEvent.Attributes), attrsToMap(event.Attributes)) { - foundMatch = true - } - } - } - - suite.True(foundMatch, fmt.Sprintf("event of type %s not found or did not match", expectedEvent.Type)) -} - -func attrsToMap(attrs []abci.EventAttribute) []sdk.Attribute { // new cosmos changed the event attribute type - out := []sdk.Attribute{} - - for _, attr := range attrs { - out = append(out, sdk.NewAttribute(string(attr.Key), string(attr.Value))) - } - - return out -} diff --git a/x/earn/types/codec.go b/x/earn/types/codec.go deleted file mode 100644 index 8b773ff8..00000000 --- a/x/earn/types/codec.go +++ /dev/null @@ -1,50 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the -// earn module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgDeposit{}, "earn/MsgDeposit", nil) - cdc.RegisterConcrete(&MsgWithdraw{}, "earn/MsgWithdraw", nil) - cdc.RegisterConcrete(&CommunityPoolDepositProposal{}, "kava/CommunityPoolDepositProposal", nil) - cdc.RegisterConcrete(&CommunityPoolWithdrawProposal{}, "kava/CommunityPoolWithdrawProposal", nil) -} - -// RegisterInterfaces registers proto messages under their interfaces for unmarshalling, -// in addition to registerting the msg service for handling tx msgs -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgDeposit{}, - &MsgWithdraw{}, - ) - registry.RegisterImplementations((*govv1beta1.Content)(nil), - &CommunityPoolDepositProposal{}, - &CommunityPoolWithdrawProposal{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - // ModuleCdc represents the legacy amino codec for the module - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/earn/types/errors.go b/x/earn/types/errors.go deleted file mode 100644 index f733e8de..00000000 --- a/x/earn/types/errors.go +++ /dev/null @@ -1,14 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// earn module errors -var ( - ErrInvalidVaultDenom = errorsmod.Register(ModuleName, 2, "invalid vault denom") - ErrInvalidVaultStrategy = errorsmod.Register(ModuleName, 3, "vault does not support this strategy") - ErrInsufficientAmount = errorsmod.Register(ModuleName, 4, "insufficient amount") - ErrInsufficientValue = errorsmod.Register(ModuleName, 5, "insufficient vault account value") - ErrVaultRecordNotFound = errorsmod.Register(ModuleName, 6, "vault record not found") - ErrVaultShareRecordNotFound = errorsmod.Register(ModuleName, 7, "vault share record not found") - ErrAccountDepositNotAllowed = errorsmod.Register(ModuleName, 8, "account is not allowed to deposit to this vault") -) diff --git a/x/earn/types/events.go b/x/earn/types/events.go deleted file mode 100644 index bcb38000..00000000 --- a/x/earn/types/events.go +++ /dev/null @@ -1,12 +0,0 @@ -package types - -// Event types for earn module -const ( - AttributeValueCategory = ModuleName - EventTypeVaultDeposit = "vault_deposit" - EventTypeVaultWithdraw = "vault_withdraw" - AttributeKeyVaultDenom = "vault_denom" - AttributeKeyDepositor = "depositor" - AttributeKeyShares = "shares" - AttributeKeyOwner = "owner" -) diff --git a/x/earn/types/expected_keepers.go b/x/earn/types/expected_keepers.go deleted file mode 100644 index e2533c88..00000000 --- a/x/earn/types/expected_keepers.go +++ /dev/null @@ -1,63 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" - disttypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - - hardtypes "github.com/kava-labs/kava/x/hard/types" - savingstypes "github.com/kava-labs/kava/x/savings/types" -) - -// AccountKeeper defines the expected account keeper -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI - SetModuleAccount(sdk.Context, types.ModuleAccountI) - GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, name string) types.ModuleAccountI -} - -// BankKeeper defines the expected interface needed to retrieve account balances. -type BankKeeper interface { - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, 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 -} - -// DistributionKeeper defines the expected interface needed for community-pool deposits to earn vaults -type DistributionKeeper interface { - GetFeePool(ctx sdk.Context) (feePool disttypes.FeePool) - SetFeePool(ctx sdk.Context, feePool disttypes.FeePool) - GetDistributionAccount(ctx sdk.Context) types.ModuleAccountI - DistributeFromFeePool(ctx sdk.Context, amount sdk.Coins, receiveAddr sdk.AccAddress) error -} - -// LiquidKeeper defines the expected interface needed for derivative to staked token conversions. -type LiquidKeeper interface { - GetStakedTokensForDerivatives(ctx sdk.Context, derivatives sdk.Coins) (sdk.Coin, error) - IsDerivativeDenom(ctx sdk.Context, denom string) bool -} - -// HardKeeper defines the expected interface needed for the hard strategy. -type HardKeeper interface { - Deposit(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error - Withdraw(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error - - GetSyncedDeposit(ctx sdk.Context, depositor sdk.AccAddress) (hardtypes.Deposit, bool) -} - -// SavingsKeeper defines the expected interface needed for the savings strategy. -type SavingsKeeper interface { - Deposit(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error - Withdraw(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error - - GetDeposit(ctx sdk.Context, depositor sdk.AccAddress) (savingstypes.Deposit, bool) -} - -// EarnHooks are event hooks called when a user's deposit to a earn vault changes. -type EarnHooks interface { - AfterVaultDepositCreated(ctx sdk.Context, vaultDenom string, depositor sdk.AccAddress, sharesOwned sdk.Dec) - BeforeVaultDepositModified(ctx sdk.Context, vaultDenom string, depositor sdk.AccAddress, sharesOwned sdk.Dec) -} diff --git a/x/earn/types/genesis.go b/x/earn/types/genesis.go deleted file mode 100644 index 05eebfb1..00000000 --- a/x/earn/types/genesis.go +++ /dev/null @@ -1,40 +0,0 @@ -package types - -// NewGenesisState creates a new genesis state. -func NewGenesisState( - params Params, - vaultRecords VaultRecords, - vaultShareRecords VaultShareRecords, -) GenesisState { - return GenesisState{ - Params: params, - VaultRecords: vaultRecords, - VaultShareRecords: vaultShareRecords, - } -} - -// Validate validates the module's genesis state -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - - if err := gs.VaultRecords.Validate(); err != nil { - return err - } - - if err := gs.VaultShareRecords.Validate(); err != nil { - return err - } - - return nil -} - -// DefaultGenesisState returns a default genesis state -func DefaultGenesisState() GenesisState { - return NewGenesisState( - DefaultParams(), - VaultRecords{}, - VaultShareRecords{}, - ) -} diff --git a/x/earn/types/genesis.pb.go b/x/earn/types/genesis.pb.go deleted file mode 100644 index ff3b0779..00000000 --- a/x/earn/types/genesis.pb.go +++ /dev/null @@ -1,454 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/earn/v1beta1/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 earn module's genesis state. -type GenesisState struct { - // params defines all the parameters related to earn - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - // vault_records defines the available vaults - VaultRecords VaultRecords `protobuf:"bytes,2,rep,name=vault_records,json=vaultRecords,proto3,castrepeated=VaultRecords" json:"vault_records"` - // share_records defines the owned shares of each vault - VaultShareRecords VaultShareRecords `protobuf:"bytes,3,rep,name=vault_share_records,json=vaultShareRecords,proto3,castrepeated=VaultShareRecords" json:"vault_share_records"` -} - -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_514fe130cb964f8c, []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) GetVaultRecords() VaultRecords { - if m != nil { - return m.VaultRecords - } - return nil -} - -func (m *GenesisState) GetVaultShareRecords() VaultShareRecords { - if m != nil { - return m.VaultShareRecords - } - return nil -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.earn.v1beta1.GenesisState") -} - -func init() { proto.RegisterFile("kava/earn/v1beta1/genesis.proto", fileDescriptor_514fe130cb964f8c) } - -var fileDescriptor_514fe130cb964f8c = []byte{ - // 294 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcf, 0x4e, 0x2c, 0x4b, - 0xd4, 0x4f, 0x4d, 0x2c, 0xca, 0xd3, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x4f, - 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x04, 0x29, 0xd0, - 0x03, 0x29, 0xd0, 0x83, 0x2a, 0x90, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0xcb, 0xea, 0x83, 0x58, - 0x10, 0x85, 0x52, 0x72, 0x98, 0x26, 0x15, 0x24, 0x16, 0x25, 0xe6, 0x42, 0x0d, 0x92, 0x92, 0xc5, - 0x94, 0x2f, 0x4b, 0x2c, 0xcd, 0x29, 0x81, 0x48, 0x2b, 0x4d, 0x62, 0xe2, 0xe2, 0x71, 0x87, 0xd8, - 0x1c, 0x5c, 0x92, 0x58, 0x92, 0x2a, 0x64, 0xce, 0xc5, 0x06, 0xd1, 0x2f, 0xc1, 0xa8, 0xc0, 0xa8, - 0xc1, 0x6d, 0x24, 0xa9, 0x87, 0xe1, 0x12, 0xbd, 0x00, 0xb0, 0x02, 0x27, 0x96, 0x13, 0xf7, 0xe4, - 0x19, 0x82, 0xa0, 0xca, 0x85, 0x22, 0xb9, 0x78, 0xc1, 0x06, 0xc7, 0x17, 0xa5, 0x26, 0xe7, 0x17, - 0xa5, 0x14, 0x4b, 0x30, 0x29, 0x30, 0x6b, 0x70, 0x1b, 0xc9, 0x61, 0xd1, 0x1f, 0x06, 0x52, 0x17, - 0x04, 0x56, 0xe6, 0x24, 0x02, 0x32, 0x64, 0xd5, 0x7d, 0x79, 0x1e, 0x24, 0xc1, 0xe2, 0x20, 0x9e, - 0x32, 0x24, 0x9e, 0x50, 0x1e, 0x97, 0x30, 0xc4, 0xe8, 0xe2, 0x8c, 0xc4, 0xa2, 0x54, 0xb8, 0x05, - 0xcc, 0x60, 0x0b, 0x94, 0x71, 0x59, 0x10, 0x0c, 0x52, 0x0c, 0xb5, 0x45, 0x12, 0x6a, 0x8b, 0x20, - 0xba, 0x4c, 0x71, 0x90, 0x60, 0x19, 0xba, 0x90, 0x93, 0xc3, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, - 0xc9, 0x31, 0x3e, 0x78, 0x24, 0xc7, 0x38, 0xe1, 0xb1, 0x1c, 0xc3, 0x85, 0xc7, 0x72, 0x0c, 0x37, - 0x1e, 0xcb, 0x31, 0x44, 0xa9, 0xa5, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, - 0x83, 0xac, 0xd5, 0xcd, 0x49, 0x4c, 0x2a, 0x06, 0xb3, 0xf4, 0x2b, 0x20, 0x81, 0x5c, 0x52, 0x59, - 0x90, 0x5a, 0x9c, 0xc4, 0x06, 0x0e, 0x5d, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x8d, 0x54, - 0x3b, 0x56, 0xe8, 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.VaultShareRecords) > 0 { - for iNdEx := len(m.VaultShareRecords) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.VaultShareRecords[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.VaultRecords) > 0 { - for iNdEx := len(m.VaultRecords) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.VaultRecords[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.VaultRecords) > 0 { - for _, e := range m.VaultRecords { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.VaultShareRecords) > 0 { - for _, e := range m.VaultShareRecords { - 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 VaultRecords", 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.VaultRecords = append(m.VaultRecords, VaultRecord{}) - if err := m.VaultRecords[len(m.VaultRecords)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field VaultShareRecords", 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.VaultShareRecords = append(m.VaultShareRecords, VaultShareRecord{}) - if err := m.VaultShareRecords[len(m.VaultShareRecords)-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/earn/types/keys.go b/x/earn/types/keys.go deleted file mode 100644 index ede49dfd..00000000 --- a/x/earn/types/keys.go +++ /dev/null @@ -1,36 +0,0 @@ -package types - -import sdk "github.com/cosmos/cosmos-sdk/types" - -const ( - // ModuleName name that will be used throughout the module - ModuleName = "earn" - - // ModuleAccountName name of module account used to hold liquidity - ModuleAccountName = "earn" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default name for parameter store - DefaultParamspace = ModuleName -) - -// key prefixes for store -var ( - VaultRecordKeyPrefix = []byte{0x01} // denom -> vault - VaultShareRecordKeyPrefix = []byte{0x02} // depositor address -> vault shares -) - -// VaultKey returns a key generated from a vault denom -func VaultKey(denom string) []byte { - return []byte(denom) -} - -// DepositorVaultSharesKey returns a key from a depositor address -func DepositorVaultSharesKey(depositor sdk.AccAddress) []byte { - return depositor.Bytes() -} diff --git a/x/earn/types/mocks/EarnHooks.go b/x/earn/types/mocks/EarnHooks.go deleted file mode 100644 index 97df2f16..00000000 --- a/x/earn/types/mocks/EarnHooks.go +++ /dev/null @@ -1,38 +0,0 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. - -package mocks - -import ( - types "github.com/cosmos/cosmos-sdk/types" - mock "github.com/stretchr/testify/mock" -) - -// EarnHooks is an autogenerated mock type for the EarnHooks type -type EarnHooks struct { - mock.Mock -} - -// AfterVaultDepositCreated provides a mock function with given fields: ctx, vaultDenom, depositor, sharesOwned -func (_m *EarnHooks) AfterVaultDepositCreated(ctx types.Context, vaultDenom string, depositor types.AccAddress, sharesOwned types.Dec) { - _m.Called(ctx, vaultDenom, depositor, sharesOwned) -} - -// BeforeVaultDepositModified provides a mock function with given fields: ctx, vaultDenom, depositor, sharesOwned -func (_m *EarnHooks) BeforeVaultDepositModified(ctx types.Context, vaultDenom string, depositor types.AccAddress, sharesOwned types.Dec) { - _m.Called(ctx, vaultDenom, depositor, sharesOwned) -} - -type mockConstructorTestingTNewEarnHooks interface { - mock.TestingT - Cleanup(func()) -} - -// NewEarnHooks creates a new instance of EarnHooks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewEarnHooks(t mockConstructorTestingTNewEarnHooks) *EarnHooks { - mock := &EarnHooks{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/x/earn/types/msg.go b/x/earn/types/msg.go deleted file mode 100644 index 4adbeeab..00000000 --- a/x/earn/types/msg.go +++ /dev/null @@ -1,125 +0,0 @@ -package types - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" -) - -var ( - _ sdk.Msg = &MsgDeposit{} - _ sdk.Msg = &MsgWithdraw{} - _ legacytx.LegacyMsg = &MsgDeposit{} - _ legacytx.LegacyMsg = &MsgWithdraw{} -) - -// legacy message types -const ( - TypeMsgDeposit = "earn_msg_deposit" - TypeMsgWithdraw = "earn_msg_withdraw" -) - -// NewMsgDeposit returns a new MsgDeposit. -func NewMsgDeposit(depositor string, amount sdk.Coin, strategy StrategyType) *MsgDeposit { - return &MsgDeposit{ - Depositor: depositor, - Amount: amount, - Strategy: strategy, - } -} - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgDeposit) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Depositor); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if err := msg.Amount.Validate(); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, err.Error()) - } - - if err := msg.Strategy.Validate(); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, err.Error()) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgDeposit) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgDeposit) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - panic(err) - } - - return []sdk.AccAddress{depositor} -} - -// Route implements the LegacyMsg.Route method. -func (msg MsgDeposit) Route() string { - return RouterKey -} - -// Type implements the LegacyMsg.Type method. -func (msg MsgDeposit) Type() string { - return TypeMsgDeposit -} - -// NewMsgWithdraw returns a new MsgWithdraw. -func NewMsgWithdraw(from string, amount sdk.Coin, strategy StrategyType) *MsgWithdraw { - return &MsgWithdraw{ - From: from, - Amount: amount, - Strategy: strategy, - } -} - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgWithdraw) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.From); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if err := msg.Amount.Validate(); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, err.Error()) - } - - if err := msg.Strategy.Validate(); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, err.Error()) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgWithdraw) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgWithdraw) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - panic(err) - } - - return []sdk.AccAddress{depositor} -} - -// Route implements the LegacyMsg.Route method. -func (msg MsgWithdraw) Route() string { - return RouterKey -} - -// Type implements the LegacyMsg.Type method. -func (msg MsgWithdraw) Type() string { - return TypeMsgWithdraw -} diff --git a/x/earn/types/params.go b/x/earn/types/params.go deleted file mode 100644 index 5a5b18e2..00000000 --- a/x/earn/types/params.go +++ /dev/null @@ -1,51 +0,0 @@ -package types - -import ( - fmt "fmt" - - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// Parameter keys and default values -var ( - KeyAllowedVaults = []byte("AllowedVaults") - DefaultAllowedVaults = AllowedVaults{} -) - -// NewParams returns a new params object -func NewParams(allowedVaults AllowedVaults) Params { - return Params{ - AllowedVaults: allowedVaults, - } -} - -// DefaultParams returns default params for earn module -func DefaultParams() Params { - return NewParams(DefaultAllowedVaults) -} - -// ParamKeyTable for earn module. -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements params.ParamSet -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyAllowedVaults, &p.AllowedVaults, validateAllowedVaultsParams), - } -} - -// Validate checks that the parameters have valid values. -func (p Params) Validate() error { - return p.AllowedVaults.Validate() -} - -func validateAllowedVaultsParams(i interface{}) error { - p, ok := i.(AllowedVaults) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return p.Validate() -} diff --git a/x/earn/types/params.pb.go b/x/earn/types/params.pb.go deleted file mode 100644 index da8b8274..00000000 --- a/x/earn/types/params.pb.go +++ /dev/null @@ -1,331 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/earn/v1beta1/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 of the earn module. -type Params struct { - AllowedVaults AllowedVaults `protobuf:"bytes,1,rep,name=allowed_vaults,json=allowedVaults,proto3,castrepeated=AllowedVaults" json:"allowed_vaults"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_b9b515f90f68dc5a, []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 (m *Params) GetAllowedVaults() AllowedVaults { - if m != nil { - return m.AllowedVaults - } - return nil -} - -func init() { - proto.RegisterType((*Params)(nil), "kava.earn.v1beta1.Params") -} - -func init() { proto.RegisterFile("kava/earn/v1beta1/params.proto", fileDescriptor_b9b515f90f68dc5a) } - -var fileDescriptor_b9b515f90f68dc5a = []byte{ - // 212 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcb, 0x4e, 0x2c, 0x4b, - 0xd4, 0x4f, 0x4d, 0x2c, 0xca, 0xd3, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x2f, 0x48, - 0x2c, 0x4a, 0xcc, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x04, 0xc9, 0xeb, 0x81, - 0xe4, 0xf5, 0xa0, 0xf2, 0x52, 0x22, 0xe9, 0xf9, 0xe9, 0xf9, 0x60, 0x59, 0x7d, 0x10, 0x0b, 0xa2, - 0x50, 0x4a, 0x16, 0xd3, 0xa0, 0xb2, 0xc4, 0xd2, 0x9c, 0x12, 0x88, 0xb4, 0x52, 0x3a, 0x17, 0x5b, - 0x00, 0xd8, 0x5c, 0xa1, 0x58, 0x2e, 0xbe, 0xc4, 0x9c, 0x9c, 0xfc, 0xf2, 0xd4, 0x94, 0x78, 0xb0, - 0x82, 0x62, 0x09, 0x46, 0x05, 0x66, 0x0d, 0x6e, 0x23, 0x79, 0x3d, 0x0c, 0xab, 0xf4, 0x1c, 0x21, - 0x0a, 0xc3, 0x40, 0xea, 0x9c, 0x44, 0x4f, 0xdc, 0x93, 0x67, 0x58, 0x75, 0x5f, 0x9e, 0x17, 0x59, - 0xb4, 0x38, 0x88, 0x37, 0x11, 0x99, 0xeb, 0xe4, 0x70, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, - 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, - 0x72, 0x0c, 0x51, 0x6a, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x20, - 0xab, 0x74, 0x73, 0x12, 0x93, 0x8a, 0xc1, 0x2c, 0xfd, 0x0a, 0x88, 0xc3, 0x4b, 0x2a, 0x0b, 0x52, - 0x8b, 0x93, 0xd8, 0xc0, 0x2e, 0x36, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x93, 0xe4, 0x56, 0x4c, - 0x1b, 0x01, 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 - if len(m.AllowedVaults) > 0 { - for iNdEx := len(m.AllowedVaults) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.AllowedVaults[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - 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 - if len(m.AllowedVaults) > 0 { - for _, e := range m.AllowedVaults { - l = e.Size() - n += 1 + l + sovParams(uint64(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 { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AllowedVaults", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AllowedVaults = append(m.AllowedVaults, AllowedVault{}) - if err := m.AllowedVaults[len(m.AllowedVaults)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - 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/earn/types/proposal.go b/x/earn/types/proposal.go deleted file mode 100644 index ee4433b8..00000000 --- a/x/earn/types/proposal.go +++ /dev/null @@ -1,118 +0,0 @@ -package types - -import ( - fmt "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - govcodec "github.com/cosmos/cosmos-sdk/x/gov/codec" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -const ( - // ProposalTypeCommunityPoolDeposit defines the type for a CommunityPoolDepositProposal - ProposalTypeCommunityPoolDeposit = "CommunityPoolDeposit" - // ProposalTypeCommunityPoolWithdraw defines the type for a CommunityPoolDepositProposal - ProposalTypeCommunityPoolWithdraw = "CommunityPoolWithdraw" -) - -// Assert CommunityPoolDepositProposal implements govtypes.Content at compile-time -var ( - _ govv1beta1.Content = &CommunityPoolDepositProposal{} - _ govv1beta1.Content = &CommunityPoolWithdrawProposal{} -) - -func init() { - govv1beta1.RegisterProposalType(ProposalTypeCommunityPoolDeposit) - govcodec.ModuleCdc.Amino.RegisterConcrete(&CommunityPoolDepositProposal{}, "kava/CommunityPoolDepositProposal", nil) - govv1beta1.RegisterProposalType(ProposalTypeCommunityPoolWithdraw) - govcodec.ModuleCdc.Amino.RegisterConcrete(&CommunityPoolWithdrawProposal{}, "kava/CommunityPoolWithdrawProposal", nil) -} - -// NewCommunityPoolDepositProposal creates a new community pool deposit proposal. -func NewCommunityPoolDepositProposal(title, description string, amount sdk.Coin) *CommunityPoolDepositProposal { - return &CommunityPoolDepositProposal{ - Title: title, - Description: description, - Amount: amount, - } -} - -// GetTitle returns the title of a community pool deposit proposal. -func (cdp *CommunityPoolDepositProposal) GetTitle() string { return cdp.Title } - -// GetDescription returns the description of a community pool deposit proposal. -func (cdp *CommunityPoolDepositProposal) GetDescription() string { return cdp.Description } - -// GetDescription returns the routing key of a community pool deposit proposal. -func (cdp *CommunityPoolDepositProposal) ProposalRoute() string { return RouterKey } - -// ProposalType returns the type of a community pool deposit proposal. -func (cdp *CommunityPoolDepositProposal) ProposalType() string { - return ProposalTypeCommunityPoolDeposit -} - -// String implements fmt.Stringer -func (cdp *CommunityPoolDepositProposal) String() string { - - var b strings.Builder - b.WriteString(fmt.Sprintf(`Community Pool Deposit Proposal: - Title: %s - Description: %s - Amount: %s -`, cdp.Title, cdp.Description, cdp.Amount)) - return b.String() -} - -// ValidateBasic stateless validation of a community pool multi-spend proposal. -func (cdp *CommunityPoolDepositProposal) ValidateBasic() error { - err := govv1beta1.ValidateAbstract(cdp) - if err != nil { - return err - } - return cdp.Amount.Validate() -} - -// NewCommunityPoolWithdrawProposal creates a new community pool deposit proposal. -func NewCommunityPoolWithdrawProposal(title, description string, amount sdk.Coin) *CommunityPoolWithdrawProposal { - return &CommunityPoolWithdrawProposal{ - Title: title, - Description: description, - Amount: amount, - } -} - -// GetTitle returns the title of a community pool withdraw proposal. -func (cdp *CommunityPoolWithdrawProposal) GetTitle() string { return cdp.Title } - -// GetDescription returns the description of a community pool withdraw proposal. -func (cdp *CommunityPoolWithdrawProposal) GetDescription() string { return cdp.Description } - -// GetDescription returns the routing key of a community pool withdraw proposal. -func (cdp *CommunityPoolWithdrawProposal) ProposalRoute() string { return RouterKey } - -// ProposalType returns the type of a community pool withdraw proposal. -func (cdp *CommunityPoolWithdrawProposal) ProposalType() string { - return ProposalTypeCommunityPoolWithdraw -} - -// String implements fmt.Stringer -func (cdp *CommunityPoolWithdrawProposal) String() string { - - var b strings.Builder - b.WriteString(fmt.Sprintf(`Community Pool Withdraw Proposal: - Title: %s - Description: %s - Amount: %s -`, cdp.Title, cdp.Description, cdp.Amount)) - return b.String() -} - -// ValidateBasic stateless validation of a community pool multi-spend proposal. -func (cdp *CommunityPoolWithdrawProposal) ValidateBasic() error { - err := govv1beta1.ValidateAbstract(cdp) - if err != nil { - return err - } - return cdp.Amount.Validate() -} diff --git a/x/earn/types/proposal.pb.go b/x/earn/types/proposal.pb.go deleted file mode 100644 index 8a4408c5..00000000 --- a/x/earn/types/proposal.pb.go +++ /dev/null @@ -1,1285 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/earn/v1beta1/proposal.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 - -// CommunityPoolDepositProposal deposits from the community pool into an earn vault -type CommunityPoolDepositProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *CommunityPoolDepositProposal) Reset() { *m = CommunityPoolDepositProposal{} } -func (*CommunityPoolDepositProposal) ProtoMessage() {} -func (*CommunityPoolDepositProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_c374f1a8c57e13e2, []int{0} -} -func (m *CommunityPoolDepositProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolDepositProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolDepositProposal.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 *CommunityPoolDepositProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolDepositProposal.Merge(m, src) -} -func (m *CommunityPoolDepositProposal) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolDepositProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolDepositProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolDepositProposal proto.InternalMessageInfo - -// CommunityPoolDepositProposalJSON defines a CommunityPoolDepositProposal with a deposit -type CommunityPoolDepositProposalJSON struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` - Deposit github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,4,rep,name=deposit,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"deposit"` -} - -func (m *CommunityPoolDepositProposalJSON) Reset() { *m = CommunityPoolDepositProposalJSON{} } -func (m *CommunityPoolDepositProposalJSON) String() string { return proto.CompactTextString(m) } -func (*CommunityPoolDepositProposalJSON) ProtoMessage() {} -func (*CommunityPoolDepositProposalJSON) Descriptor() ([]byte, []int) { - return fileDescriptor_c374f1a8c57e13e2, []int{1} -} -func (m *CommunityPoolDepositProposalJSON) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolDepositProposalJSON) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolDepositProposalJSON.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 *CommunityPoolDepositProposalJSON) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolDepositProposalJSON.Merge(m, src) -} -func (m *CommunityPoolDepositProposalJSON) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolDepositProposalJSON) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolDepositProposalJSON.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolDepositProposalJSON proto.InternalMessageInfo - -// CommunityPoolWithdrawProposal withdraws from an earn vault back to community pool -type CommunityPoolWithdrawProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *CommunityPoolWithdrawProposal) Reset() { *m = CommunityPoolWithdrawProposal{} } -func (*CommunityPoolWithdrawProposal) ProtoMessage() {} -func (*CommunityPoolWithdrawProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_c374f1a8c57e13e2, []int{2} -} -func (m *CommunityPoolWithdrawProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolWithdrawProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolWithdrawProposal.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 *CommunityPoolWithdrawProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolWithdrawProposal.Merge(m, src) -} -func (m *CommunityPoolWithdrawProposal) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolWithdrawProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolWithdrawProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolWithdrawProposal proto.InternalMessageInfo - -// CommunityPoolWithdrawProposalJSON defines a CommunityPoolWithdrawProposal with a deposit -type CommunityPoolWithdrawProposalJSON struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` - Deposit github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,4,rep,name=deposit,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"deposit"` -} - -func (m *CommunityPoolWithdrawProposalJSON) Reset() { *m = CommunityPoolWithdrawProposalJSON{} } -func (m *CommunityPoolWithdrawProposalJSON) String() string { return proto.CompactTextString(m) } -func (*CommunityPoolWithdrawProposalJSON) ProtoMessage() {} -func (*CommunityPoolWithdrawProposalJSON) Descriptor() ([]byte, []int) { - return fileDescriptor_c374f1a8c57e13e2, []int{3} -} -func (m *CommunityPoolWithdrawProposalJSON) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolWithdrawProposalJSON) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolWithdrawProposalJSON.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 *CommunityPoolWithdrawProposalJSON) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolWithdrawProposalJSON.Merge(m, src) -} -func (m *CommunityPoolWithdrawProposalJSON) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolWithdrawProposalJSON) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolWithdrawProposalJSON.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolWithdrawProposalJSON proto.InternalMessageInfo - -func init() { - proto.RegisterType((*CommunityPoolDepositProposal)(nil), "kava.earn.v1beta1.CommunityPoolDepositProposal") - proto.RegisterType((*CommunityPoolDepositProposalJSON)(nil), "kava.earn.v1beta1.CommunityPoolDepositProposalJSON") - proto.RegisterType((*CommunityPoolWithdrawProposal)(nil), "kava.earn.v1beta1.CommunityPoolWithdrawProposal") - proto.RegisterType((*CommunityPoolWithdrawProposalJSON)(nil), "kava.earn.v1beta1.CommunityPoolWithdrawProposalJSON") -} - -func init() { proto.RegisterFile("kava/earn/v1beta1/proposal.proto", fileDescriptor_c374f1a8c57e13e2) } - -var fileDescriptor_c374f1a8c57e13e2 = []byte{ - // 371 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xc8, 0x4e, 0x2c, 0x4b, - 0xd4, 0x4f, 0x4d, 0x2c, 0xca, 0xd3, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x2f, 0x28, - 0xca, 0x2f, 0xc8, 0x2f, 0x4e, 0xcc, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x04, 0xa9, - 0xd0, 0x03, 0xa9, 0xd0, 0x83, 0xaa, 0x90, 0x92, 0x4b, 0xce, 0x2f, 0xce, 0xcd, 0x2f, 0xd6, 0x4f, - 0x4a, 0x2c, 0x4e, 0x85, 0x6b, 0x4b, 0xce, 0xcf, 0xcc, 0x83, 0x68, 0x91, 0x12, 0x49, 0xcf, 0x4f, - 0xcf, 0x07, 0x33, 0xf5, 0x41, 0x2c, 0x88, 0xa8, 0xd2, 0x4c, 0x46, 0x2e, 0x19, 0xe7, 0xfc, 0xdc, - 0xdc, 0xd2, 0xbc, 0xcc, 0x92, 0xca, 0x80, 0xfc, 0xfc, 0x1c, 0x97, 0xd4, 0x82, 0xfc, 0xe2, 0xcc, - 0x92, 0x00, 0xa8, 0x7d, 0x42, 0x22, 0x5c, 0xac, 0x25, 0x99, 0x25, 0x39, 0xa9, 0x12, 0x8c, 0x0a, - 0x8c, 0x1a, 0x9c, 0x41, 0x10, 0x8e, 0x90, 0x02, 0x17, 0x77, 0x4a, 0x6a, 0x71, 0x72, 0x51, 0x66, - 0x41, 0x49, 0x66, 0x7e, 0x9e, 0x04, 0x13, 0x58, 0x0e, 0x59, 0x48, 0xc8, 0x9c, 0x8b, 0x2d, 0x31, - 0x37, 0xbf, 0x34, 0xaf, 0x44, 0x82, 0x59, 0x81, 0x51, 0x83, 0xdb, 0x48, 0x52, 0x0f, 0xe2, 0x3e, - 0x3d, 0x90, 0xfb, 0x60, 0x8e, 0xd6, 0x73, 0xce, 0xcf, 0xcc, 0x73, 0x62, 0x39, 0x71, 0x4f, 0x9e, - 0x21, 0x08, 0xaa, 0xdc, 0x8a, 0xa3, 0x63, 0x81, 0x3c, 0xc3, 0x8c, 0x05, 0xf2, 0x0c, 0x4a, 0x2d, - 0x4c, 0x5c, 0x0a, 0xf8, 0xdc, 0xe6, 0x15, 0xec, 0xef, 0x47, 0x77, 0xf7, 0x09, 0xa5, 0x72, 0xb1, - 0xa7, 0x40, 0xdc, 0x21, 0xc1, 0xa2, 0xc0, 0x8c, 0x5f, 0xa7, 0x01, 0x48, 0xe7, 0xaa, 0xfb, 0xf2, - 0x1a, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0xd0, 0x68, 0x82, 0x50, - 0xba, 0xc5, 0x29, 0xd9, 0xfa, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x60, 0x0d, 0xc5, 0x41, 0x30, 0xb3, - 0xe1, 0xc1, 0xc0, 0xa8, 0x34, 0x8b, 0x91, 0x4b, 0x16, 0x25, 0x18, 0xc2, 0x33, 0x4b, 0x32, 0x52, - 0x8a, 0x12, 0xcb, 0x07, 0x43, 0x1c, 0xb5, 0x32, 0x71, 0x29, 0xe2, 0x75, 0xdc, 0xc8, 0x88, 0x24, - 0x27, 0x87, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, - 0x63, 0x39, 0x86, 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, 0x88, 0x52, 0x43, 0x32, 0x16, - 0x94, 0x6b, 0x75, 0x73, 0x12, 0x93, 0x8a, 0xc1, 0x2c, 0xfd, 0x0a, 0x48, 0x1e, 0x07, 0x1b, 0x9d, - 0xc4, 0x06, 0xce, 0x90, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x21, 0xfc, 0xed, 0xa9, 0xfd, - 0x03, 0x00, 0x00, -} - -func (m *CommunityPoolDepositProposal) 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 *CommunityPoolDepositProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolDepositProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CommunityPoolDepositProposalJSON) 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 *CommunityPoolDepositProposalJSON) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolDepositProposalJSON) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Deposit) > 0 { - for iNdEx := len(m.Deposit) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposit[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CommunityPoolWithdrawProposal) 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 *CommunityPoolWithdrawProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolWithdrawProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CommunityPoolWithdrawProposalJSON) 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 *CommunityPoolWithdrawProposalJSON) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolWithdrawProposalJSON) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Deposit) > 0 { - for iNdEx := len(m.Deposit) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposit[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintProposal(dAtA []byte, offset int, v uint64) int { - offset -= sovProposal(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *CommunityPoolDepositProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovProposal(uint64(l)) - return n -} - -func (m *CommunityPoolDepositProposalJSON) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovProposal(uint64(l)) - if len(m.Deposit) > 0 { - for _, e := range m.Deposit { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func (m *CommunityPoolWithdrawProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovProposal(uint64(l)) - return n -} - -func (m *CommunityPoolWithdrawProposalJSON) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovProposal(uint64(l)) - if len(m.Deposit) > 0 { - for _, e := range m.Deposit { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func sovProposal(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozProposal(x uint64) (n int) { - return sovProposal(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *CommunityPoolDepositProposal) 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 ErrIntOverflowProposal - } - 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: CommunityPoolDepositProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolDepositProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityPoolDepositProposalJSON) 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 ErrIntOverflowProposal - } - 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: CommunityPoolDepositProposalJSON: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolDepositProposalJSON: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposit", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Deposit = append(m.Deposit, types.Coin{}) - if err := m.Deposit[len(m.Deposit)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityPoolWithdrawProposal) 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 ErrIntOverflowProposal - } - 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: CommunityPoolWithdrawProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolWithdrawProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityPoolWithdrawProposalJSON) 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 ErrIntOverflowProposal - } - 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: CommunityPoolWithdrawProposalJSON: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolWithdrawProposalJSON: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposit", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Deposit = append(m.Deposit, types.Coin{}) - if err := m.Deposit[len(m.Deposit)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipProposal(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, ErrIntOverflowProposal - } - 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, ErrIntOverflowProposal - } - 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, ErrIntOverflowProposal - } - 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, ErrInvalidLengthProposal - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupProposal - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthProposal - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthProposal = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowProposal = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupProposal = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/earn/types/query.go b/x/earn/types/query.go deleted file mode 100644 index 5bc93996..00000000 --- a/x/earn/types/query.go +++ /dev/null @@ -1,35 +0,0 @@ -package types - -import "github.com/cosmos/cosmos-sdk/types/query" - -// NewQueryParamsRequest returns a new QueryParamsRequest -func NewQueryParamsRequest() *QueryParamsRequest { - return &QueryParamsRequest{} -} - -// NewQueryVaultsRequest returns a new QueryVaultsRequest -func NewQueryVaultsRequest() *QueryVaultsRequest { - return &QueryVaultsRequest{} -} - -// NewQueryVaultRequest returns a new QueryVaultRequest -func NewQueryVaultRequest(denom string) *QueryVaultRequest { - return &QueryVaultRequest{ - Denom: denom, - } -} - -// NewQueryDepositsRequest returns a new QueryDepositsRequest -func NewQueryDepositsRequest( - depositor string, - denom string, - ValueInStakedTokens bool, - pagination *query.PageRequest, -) *QueryDepositsRequest { - return &QueryDepositsRequest{ - Depositor: depositor, - Denom: denom, - ValueInStakedTokens: ValueInStakedTokens, - Pagination: pagination, - } -} diff --git a/x/earn/types/query.pb.go b/x/earn/types/query.pb.go deleted file mode 100644 index a470d300..00000000 --- a/x/earn/types/query.pb.go +++ /dev/null @@ -1,2931 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/earn/v1beta1/query.proto - -package types - -import ( - context "context" - 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" - 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 defines the request type for querying x/earn parameters. -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_63f8dee2f3192a6b, []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 defines the response type for querying x/earn parameters. -type QueryParamsResponse struct { - // params represents the earn module parameters - 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_63f8dee2f3192a6b, []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 - -// QueryVaultsRequest is the request type for the Query/Vaults RPC method. -type QueryVaultsRequest struct { -} - -func (m *QueryVaultsRequest) Reset() { *m = QueryVaultsRequest{} } -func (m *QueryVaultsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryVaultsRequest) ProtoMessage() {} -func (*QueryVaultsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{2} -} -func (m *QueryVaultsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryVaultsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryVaultsRequest.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 *QueryVaultsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryVaultsRequest.Merge(m, src) -} -func (m *QueryVaultsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryVaultsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryVaultsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryVaultsRequest proto.InternalMessageInfo - -// QueryVaultsResponse is the response type for the Query/Vaults RPC method. -type QueryVaultsResponse struct { - // vaults represents the earn module vaults - Vaults []VaultResponse `protobuf:"bytes,1,rep,name=vaults,proto3" json:"vaults"` -} - -func (m *QueryVaultsResponse) Reset() { *m = QueryVaultsResponse{} } -func (m *QueryVaultsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryVaultsResponse) ProtoMessage() {} -func (*QueryVaultsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{3} -} -func (m *QueryVaultsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryVaultsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryVaultsResponse.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 *QueryVaultsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryVaultsResponse.Merge(m, src) -} -func (m *QueryVaultsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryVaultsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryVaultsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryVaultsResponse proto.InternalMessageInfo - -// QueryVaultRequest is the request type for the Query/Vault RPC method. -type QueryVaultRequest struct { - // vault filters vault by denom - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` -} - -func (m *QueryVaultRequest) Reset() { *m = QueryVaultRequest{} } -func (m *QueryVaultRequest) String() string { return proto.CompactTextString(m) } -func (*QueryVaultRequest) ProtoMessage() {} -func (*QueryVaultRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{4} -} -func (m *QueryVaultRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryVaultRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryVaultRequest.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 *QueryVaultRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryVaultRequest.Merge(m, src) -} -func (m *QueryVaultRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryVaultRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryVaultRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryVaultRequest proto.InternalMessageInfo - -// QueryVaultResponse is the response type for the Query/Vault RPC method. -type QueryVaultResponse struct { - // vault represents the queried earn module vault - Vault VaultResponse `protobuf:"bytes,1,opt,name=vault,proto3" json:"vault"` -} - -func (m *QueryVaultResponse) Reset() { *m = QueryVaultResponse{} } -func (m *QueryVaultResponse) String() string { return proto.CompactTextString(m) } -func (*QueryVaultResponse) ProtoMessage() {} -func (*QueryVaultResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{5} -} -func (m *QueryVaultResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryVaultResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryVaultResponse.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 *QueryVaultResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryVaultResponse.Merge(m, src) -} -func (m *QueryVaultResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryVaultResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryVaultResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryVaultResponse proto.InternalMessageInfo - -// VaultResponse is the response type for a vault. -type VaultResponse struct { - // denom represents the denom of the vault - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - // VaultStrategy is the strategy used for this vault. - Strategies StrategyTypes `protobuf:"varint,2,rep,packed,name=strategies,proto3,enum=kava.earn.v1beta1.StrategyType,castrepeated=StrategyTypes" json:"strategies,omitempty"` - // IsPrivateVault is true if the vault only allows depositors contained in - // AllowedDepositors. - IsPrivateVault bool `protobuf:"varint,3,opt,name=is_private_vault,json=isPrivateVault,proto3" json:"is_private_vault,omitempty"` - // AllowedDepositors is a list of addresses that are allowed to deposit to - // this vault if IsPrivateVault is true. Addresses not contained in this list - // are not allowed to deposit into this vault. If IsPrivateVault is false, - // this should be empty and ignored. - AllowedDepositors []string `protobuf:"bytes,4,rep,name=allowed_depositors,json=allowedDepositors,proto3" json:"allowed_depositors,omitempty"` - // TotalShares is the total amount of shares issued to depositors. - TotalShares string `protobuf:"bytes,5,opt,name=total_shares,json=totalShares,proto3" json:"total_shares,omitempty"` - // TotalValue is the total value of denom coins supplied to the vault if the - // vault were to be liquidated. - TotalValue github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,6,opt,name=total_value,json=totalValue,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"total_value"` -} - -func (m *VaultResponse) Reset() { *m = VaultResponse{} } -func (m *VaultResponse) String() string { return proto.CompactTextString(m) } -func (*VaultResponse) ProtoMessage() {} -func (*VaultResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{6} -} -func (m *VaultResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *VaultResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_VaultResponse.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 *VaultResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_VaultResponse.Merge(m, src) -} -func (m *VaultResponse) XXX_Size() int { - return m.Size() -} -func (m *VaultResponse) XXX_DiscardUnknown() { - xxx_messageInfo_VaultResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_VaultResponse proto.InternalMessageInfo - -// QueryDepositsRequest is the request type for the Query/Deposits RPC method. -type QueryDepositsRequest struct { - // depositor optionally filters deposits by depositor - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - // denom optionally filters deposits by vault denom - Denom string `protobuf:"bytes,2,opt,name=denom,proto3" json:"denom,omitempty"` - // respond with vault value in ukava for bkava vaults - ValueInStakedTokens bool `protobuf:"varint,3,opt,name=value_in_staked_tokens,json=valueInStakedTokens,proto3" json:"value_in_staked_tokens,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,4,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDepositsRequest) Reset() { *m = QueryDepositsRequest{} } -func (m *QueryDepositsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsRequest) ProtoMessage() {} -func (*QueryDepositsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{7} -} -func (m *QueryDepositsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsRequest.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 *QueryDepositsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsRequest.Merge(m, src) -} -func (m *QueryDepositsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsRequest proto.InternalMessageInfo - -// QueryDepositsResponse is the response type for the Query/Deposits RPC method. -type QueryDepositsResponse struct { - // deposits returns the deposits matching the requested parameters - Deposits []DepositResponse `protobuf:"bytes,1,rep,name=deposits,proto3" json:"deposits"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDepositsResponse) Reset() { *m = QueryDepositsResponse{} } -func (m *QueryDepositsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsResponse) ProtoMessage() {} -func (*QueryDepositsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{8} -} -func (m *QueryDepositsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsResponse.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 *QueryDepositsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsResponse.Merge(m, src) -} -func (m *QueryDepositsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsResponse proto.InternalMessageInfo - -// DepositResponse defines a deposit query response type. -type DepositResponse struct { - // depositor represents the owner of the deposit. - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - // Shares represent the issued shares from their corresponding vaults. - Shares VaultShares `protobuf:"bytes,2,rep,name=shares,proto3,castrepeated=VaultShares" json:"shares"` - // Value represents the total accumulated value of denom coins supplied to - // vaults. This may be greater than or equal to amount_supplied depending on - // the strategy. - Value github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=value,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"value"` -} - -func (m *DepositResponse) Reset() { *m = DepositResponse{} } -func (m *DepositResponse) String() string { return proto.CompactTextString(m) } -func (*DepositResponse) ProtoMessage() {} -func (*DepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{9} -} -func (m *DepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DepositResponse.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 *DepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_DepositResponse.Merge(m, src) -} -func (m *DepositResponse) XXX_Size() int { - return m.Size() -} -func (m *DepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_DepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_DepositResponse proto.InternalMessageInfo - -// QueryTotalSupplyRequest defines the request type for Query/TotalSupply method. -type QueryTotalSupplyRequest struct { -} - -func (m *QueryTotalSupplyRequest) Reset() { *m = QueryTotalSupplyRequest{} } -func (m *QueryTotalSupplyRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalSupplyRequest) ProtoMessage() {} -func (*QueryTotalSupplyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{10} -} -func (m *QueryTotalSupplyRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalSupplyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalSupplyRequest.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 *QueryTotalSupplyRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalSupplyRequest.Merge(m, src) -} -func (m *QueryTotalSupplyRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalSupplyRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalSupplyRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalSupplyRequest proto.InternalMessageInfo - -// TotalSupplyResponse defines the response type for the Query/TotalSupply method. -type QueryTotalSupplyResponse struct { - // Height is the block height at which these totals apply - Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` - // Result is a list of coins supplied to earn - Result github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=result,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"result"` -} - -func (m *QueryTotalSupplyResponse) Reset() { *m = QueryTotalSupplyResponse{} } -func (m *QueryTotalSupplyResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalSupplyResponse) ProtoMessage() {} -func (*QueryTotalSupplyResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{11} -} -func (m *QueryTotalSupplyResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalSupplyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalSupplyResponse.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 *QueryTotalSupplyResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalSupplyResponse.Merge(m, src) -} -func (m *QueryTotalSupplyResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalSupplyResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalSupplyResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalSupplyResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.earn.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.earn.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryVaultsRequest)(nil), "kava.earn.v1beta1.QueryVaultsRequest") - proto.RegisterType((*QueryVaultsResponse)(nil), "kava.earn.v1beta1.QueryVaultsResponse") - proto.RegisterType((*QueryVaultRequest)(nil), "kava.earn.v1beta1.QueryVaultRequest") - proto.RegisterType((*QueryVaultResponse)(nil), "kava.earn.v1beta1.QueryVaultResponse") - proto.RegisterType((*VaultResponse)(nil), "kava.earn.v1beta1.VaultResponse") - proto.RegisterType((*QueryDepositsRequest)(nil), "kava.earn.v1beta1.QueryDepositsRequest") - proto.RegisterType((*QueryDepositsResponse)(nil), "kava.earn.v1beta1.QueryDepositsResponse") - proto.RegisterType((*DepositResponse)(nil), "kava.earn.v1beta1.DepositResponse") - proto.RegisterType((*QueryTotalSupplyRequest)(nil), "kava.earn.v1beta1.QueryTotalSupplyRequest") - proto.RegisterType((*QueryTotalSupplyResponse)(nil), "kava.earn.v1beta1.QueryTotalSupplyResponse") -} - -func init() { proto.RegisterFile("kava/earn/v1beta1/query.proto", fileDescriptor_63f8dee2f3192a6b) } - -var fileDescriptor_63f8dee2f3192a6b = []byte{ - // 971 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x56, 0xcf, 0x6f, 0x1b, 0x45, - 0x14, 0xf6, 0xda, 0xb1, 0x95, 0x3c, 0xd3, 0x42, 0x26, 0xa6, 0xd8, 0x2e, 0x59, 0x3b, 0x4b, 0x9b, - 0x98, 0x40, 0x76, 0x69, 0x2a, 0xc1, 0xa5, 0x20, 0x61, 0x22, 0xaa, 0x70, 0x40, 0x65, 0x13, 0x7a, - 0x40, 0x42, 0xd6, 0x38, 0x1e, 0x6d, 0x56, 0x71, 0x76, 0xb6, 0x3b, 0x63, 0x43, 0x40, 0x5c, 0xfa, - 0x0f, 0x80, 0xc4, 0x81, 0x03, 0x77, 0x0e, 0x3d, 0xf7, 0x8f, 0xc8, 0xb1, 0x2a, 0x17, 0xc4, 0xa1, - 0xa5, 0x09, 0x67, 0xce, 0x1c, 0xd1, 0xcc, 0xbc, 0xf5, 0x8f, 0xd8, 0x4e, 0x22, 0xd4, 0x53, 0xb2, - 0xef, 0xc7, 0xf7, 0x7d, 0x6f, 0xe6, 0xcd, 0x7b, 0x86, 0xe5, 0x03, 0xda, 0xa7, 0x1e, 0xa3, 0x49, - 0xe4, 0xf5, 0x6f, 0xb5, 0x99, 0xa4, 0xb7, 0xbc, 0x07, 0x3d, 0x96, 0x1c, 0xb9, 0x71, 0xc2, 0x25, - 0x27, 0x8b, 0xca, 0xed, 0x2a, 0xb7, 0x8b, 0xee, 0xea, 0xfa, 0x1e, 0x17, 0x87, 0x5c, 0x78, 0x6d, - 0x2a, 0x98, 0x89, 0x1d, 0x64, 0xc6, 0x34, 0x08, 0x23, 0x2a, 0x43, 0x1e, 0x99, 0xf4, 0xaa, 0x3d, - 0x1a, 0x9b, 0x46, 0xed, 0xf1, 0x30, 0xf5, 0x57, 0x8c, 0xbf, 0xa5, 0xbf, 0x3c, 0xf3, 0x81, 0xae, - 0x52, 0xc0, 0x03, 0x6e, 0xec, 0xea, 0x3f, 0xb4, 0xbe, 0x19, 0x70, 0x1e, 0x74, 0x99, 0x47, 0xe3, - 0xd0, 0xa3, 0x51, 0xc4, 0xa5, 0x66, 0x4b, 0x73, 0xec, 0xc9, 0x62, 0x62, 0x9a, 0xd0, 0xc3, 0xd4, - 0x5f, 0x9f, 0xf4, 0x0b, 0x99, 0x50, 0xc9, 0x02, 0xac, 0xb7, 0x3a, 0xe5, 0x38, 0xfa, 0xb4, 0xd7, - 0x95, 0xc6, 0xed, 0x94, 0x80, 0x7c, 0xa1, 0x2a, 0xbe, 0xa7, 0x51, 0x7d, 0xf6, 0xa0, 0xc7, 0x84, - 0x74, 0x3e, 0x87, 0xa5, 0x31, 0xab, 0x88, 0x79, 0x24, 0x18, 0xf9, 0x00, 0x0a, 0x86, 0xbd, 0x6c, - 0xd5, 0xad, 0x46, 0x71, 0xb3, 0xe2, 0x4e, 0x1c, 0xa6, 0x6b, 0x52, 0x9a, 0x73, 0xc7, 0xcf, 0x6a, - 0x19, 0x1f, 0xc3, 0x07, 0x2c, 0xf7, 0x15, 0xf3, 0x80, 0xe5, 0x4b, 0x64, 0x49, 0xad, 0xc8, 0xf2, - 0x11, 0x14, 0xb4, 0x42, 0xc5, 0x92, 0x6b, 0x14, 0x37, 0xeb, 0x53, 0x58, 0x74, 0x4a, 0x9a, 0x91, - 0x92, 0x99, 0x2c, 0xe7, 0x6d, 0x58, 0x1c, 0xc2, 0x22, 0x17, 0x29, 0x41, 0xbe, 0xc3, 0x22, 0x7e, - 0xa8, 0x95, 0x2f, 0xf8, 0xe6, 0xc3, 0xf1, 0x47, 0x75, 0x0d, 0x04, 0xdc, 0x81, 0xbc, 0x86, 0xc2, - 0x2a, 0x2f, 0xcb, 0x6f, 0x92, 0x9c, 0x7f, 0xb2, 0x70, 0x65, 0x1c, 0x6f, 0x2a, 0x37, 0xf1, 0x01, - 0xf0, 0xaa, 0x42, 0x26, 0xca, 0xd9, 0x7a, 0xae, 0x71, 0x75, 0xb3, 0x36, 0x85, 0x6a, 0x07, 0xef, - 0x73, 0xf7, 0x28, 0x66, 0xcd, 0xc5, 0x47, 0xcf, 0x6b, 0x57, 0x46, 0x2d, 0xc2, 0x1f, 0x41, 0x21, - 0x0d, 0x78, 0x2d, 0x54, 0xbd, 0x17, 0xf6, 0xa9, 0x64, 0x2d, 0x53, 0x44, 0xae, 0x6e, 0x35, 0xe6, - 0xfd, 0xab, 0xa1, 0xb8, 0x67, 0xcc, 0x5a, 0x1b, 0xb9, 0x0b, 0x84, 0x76, 0xbb, 0xfc, 0x1b, 0xd6, - 0x69, 0x75, 0x58, 0xcc, 0x45, 0x28, 0x79, 0x22, 0xca, 0x73, 0xf5, 0x5c, 0x63, 0xa1, 0x59, 0x7e, - 0xfa, 0x78, 0xa3, 0x84, 0xad, 0xfb, 0x71, 0xa7, 0x93, 0x30, 0x21, 0x76, 0x64, 0x12, 0x46, 0x81, - 0xbf, 0x88, 0x39, 0x5b, 0x83, 0x14, 0xb2, 0x02, 0xaf, 0x48, 0x2e, 0x69, 0xb7, 0x25, 0xf6, 0x69, - 0xc2, 0x44, 0x39, 0xaf, 0x6b, 0x2c, 0x6a, 0xdb, 0x8e, 0x36, 0x91, 0xaf, 0xc1, 0x7c, 0xb6, 0xfa, - 0xb4, 0xdb, 0x63, 0xe5, 0x82, 0x8a, 0x68, 0xde, 0x51, 0x67, 0xf6, 0xe7, 0xb3, 0xda, 0x6a, 0x10, - 0xca, 0xfd, 0x5e, 0xdb, 0xdd, 0xe3, 0x87, 0xf8, 0x5c, 0xf0, 0xcf, 0x86, 0xe8, 0x1c, 0x78, 0x52, - 0x95, 0xe8, 0x6e, 0x47, 0xf2, 0xe9, 0xe3, 0x0d, 0x40, 0x49, 0xdb, 0x91, 0xf4, 0x41, 0x03, 0xde, - 0x57, 0x78, 0xce, 0x0b, 0x0b, 0x4a, 0xfa, 0x16, 0x51, 0x55, 0xda, 0x5f, 0xe4, 0x7d, 0x58, 0x18, - 0xd4, 0x66, 0xce, 0xfe, 0x9c, 0xd2, 0x86, 0xa1, 0xc3, 0xfb, 0xca, 0x8e, 0xde, 0xd7, 0x6d, 0xb8, - 0xa6, 0xf5, 0xb7, 0xc2, 0xa8, 0x25, 0x24, 0x3d, 0x60, 0x9d, 0x96, 0xe4, 0x07, 0x2c, 0x12, 0x78, - 0xc2, 0x4b, 0xda, 0xbb, 0x1d, 0xed, 0x68, 0xdf, 0xae, 0x76, 0x91, 0x4f, 0x01, 0x86, 0x23, 0xa4, - 0x3c, 0xa7, 0xfb, 0x69, 0xd5, 0x45, 0x01, 0x6a, 0x86, 0xb8, 0x66, 0x36, 0x0d, 0x5f, 0x4f, 0xc0, - 0x50, 0xbe, 0x3f, 0x92, 0xe9, 0xfc, 0x66, 0xc1, 0xeb, 0x67, 0x6a, 0xc4, 0xe6, 0xda, 0x82, 0x79, - 0x54, 0x9e, 0xbe, 0x17, 0x67, 0x4a, 0x13, 0x61, 0xda, 0x99, 0x8e, 0x1d, 0x64, 0x92, 0xbb, 0x63, - 0x3a, 0xb3, 0x5a, 0xe7, 0xda, 0x85, 0x3a, 0x0d, 0xd8, 0x98, 0xd0, 0x7f, 0x2d, 0x78, 0xf5, 0x0c, - 0xd9, 0xff, 0xbe, 0x87, 0xcf, 0xa0, 0x80, 0x4d, 0x95, 0xd5, 0x85, 0x2d, 0xcf, 0x7a, 0x88, 0xba, - 0xcf, 0x9a, 0x4b, 0xaa, 0xa6, 0x47, 0xcf, 0x6b, 0xc5, 0xa1, 0x4d, 0xf8, 0x88, 0x40, 0xa8, 0x7a, - 0xd3, 0xaa, 0xfb, 0x72, 0x1a, 0xaa, 0x32, 0x56, 0x5b, 0x0a, 0xf6, 0x09, 0x0f, 0xa3, 0xe6, 0x7b, - 0x08, 0xd3, 0xb8, 0x44, 0x63, 0xaa, 0x04, 0xe1, 0x1b, 0x64, 0xa7, 0x02, 0x6f, 0xe8, 0x2b, 0xda, - 0xd5, 0xad, 0xdf, 0x8b, 0xe3, 0xee, 0x51, 0x3a, 0xe9, 0x7e, 0xb1, 0xa0, 0x3c, 0xe9, 0xc3, 0xe3, - 0xb9, 0x06, 0x85, 0x7d, 0x16, 0x06, 0xfb, 0x66, 0xde, 0xe4, 0x7c, 0xfc, 0x22, 0x7b, 0x50, 0x48, - 0x98, 0x50, 0x4f, 0x38, 0xfb, 0xf2, 0x35, 0x23, 0xf4, 0xe6, 0xaf, 0x79, 0xc8, 0x6b, 0x65, 0xe4, - 0x3b, 0x28, 0x98, 0xd9, 0x4d, 0x6e, 0x4e, 0x39, 0xe7, 0xc9, 0x25, 0x51, 0x5d, 0xbd, 0x28, 0xcc, - 0xd4, 0xe7, 0xac, 0x3c, 0xfc, 0xfd, 0xef, 0x9f, 0xb3, 0xd7, 0x49, 0xc5, 0x9b, 0xb5, 0xcc, 0x14, - 0xb7, 0x59, 0x02, 0xb3, 0xb9, 0xc7, 0x56, 0xc7, 0x6c, 0xee, 0xf1, 0x5d, 0x72, 0x2e, 0xb7, 0x59, - 0x17, 0xe4, 0xa1, 0x05, 0x79, 0x33, 0x13, 0x6f, 0x9c, 0x0b, 0x9a, 0x52, 0xdf, 0xbc, 0x20, 0x0a, - 0x99, 0xdf, 0xd5, 0xcc, 0xab, 0xe4, 0xc6, 0x4c, 0x66, 0xef, 0x7b, 0x3d, 0x58, 0x3e, 0x5c, 0x5f, - 0xff, 0x41, 0x89, 0x98, 0x4f, 0x9f, 0x36, 0x59, 0x9b, 0xc5, 0x70, 0x66, 0xc0, 0x55, 0x1b, 0x17, - 0x07, 0xa2, 0x9a, 0xb7, 0xb4, 0x9a, 0x65, 0x72, 0x7d, 0x8a, 0x9a, 0xc1, 0x10, 0xf8, 0xd1, 0x82, - 0xe2, 0x48, 0x83, 0x92, 0xf5, 0x59, 0xf0, 0x93, 0x1d, 0x5e, 0x7d, 0xe7, 0x52, 0xb1, 0xa8, 0x66, - 0x4d, 0xab, 0x59, 0x21, 0xb5, 0x29, 0x6a, 0x70, 0x99, 0xe8, 0x84, 0xe6, 0xd6, 0xf1, 0x0b, 0x3b, - 0x73, 0x7c, 0x62, 0x5b, 0x4f, 0x4e, 0x6c, 0xeb, 0xaf, 0x13, 0xdb, 0xfa, 0xe9, 0xd4, 0xce, 0x3c, - 0x39, 0xb5, 0x33, 0x7f, 0x9c, 0xda, 0x99, 0xaf, 0x46, 0x57, 0x87, 0x02, 0xda, 0xe8, 0xd2, 0xb6, - 0x30, 0x90, 0xdf, 0x1a, 0x50, 0xdd, 0xf1, 0xed, 0x82, 0xfe, 0xa9, 0x73, 0xfb, 0xbf, 0x00, 0x00, - 0x00, 0xff, 0xff, 0xb7, 0x20, 0xeb, 0xea, 0x1a, 0x0a, 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 { - // Params queries all parameters of the earn module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Vaults queries all vaults - Vaults(ctx context.Context, in *QueryVaultsRequest, opts ...grpc.CallOption) (*QueryVaultsResponse, error) - // Vault queries a single vault based on the vault denom - Vault(ctx context.Context, in *QueryVaultRequest, opts ...grpc.CallOption) (*QueryVaultResponse, error) - // Deposits queries deposit details based on depositor address and vault - Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) - // TotalSupply returns the total sum of all coins currently locked into the earn module. - TotalSupply(ctx context.Context, in *QueryTotalSupplyRequest, opts ...grpc.CallOption) (*QueryTotalSupplyResponse, 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, "/kava.earn.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Vaults(ctx context.Context, in *QueryVaultsRequest, opts ...grpc.CallOption) (*QueryVaultsResponse, error) { - out := new(QueryVaultsResponse) - err := c.cc.Invoke(ctx, "/kava.earn.v1beta1.Query/Vaults", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Vault(ctx context.Context, in *QueryVaultRequest, opts ...grpc.CallOption) (*QueryVaultResponse, error) { - out := new(QueryVaultResponse) - err := c.cc.Invoke(ctx, "/kava.earn.v1beta1.Query/Vault", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) { - out := new(QueryDepositsResponse) - err := c.cc.Invoke(ctx, "/kava.earn.v1beta1.Query/Deposits", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalSupply(ctx context.Context, in *QueryTotalSupplyRequest, opts ...grpc.CallOption) (*QueryTotalSupplyResponse, error) { - out := new(QueryTotalSupplyResponse) - err := c.cc.Invoke(ctx, "/kava.earn.v1beta1.Query/TotalSupply", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries all parameters of the earn module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Vaults queries all vaults - Vaults(context.Context, *QueryVaultsRequest) (*QueryVaultsResponse, error) - // Vault queries a single vault based on the vault denom - Vault(context.Context, *QueryVaultRequest) (*QueryVaultResponse, error) - // Deposits queries deposit details based on depositor address and vault - Deposits(context.Context, *QueryDepositsRequest) (*QueryDepositsResponse, error) - // TotalSupply returns the total sum of all coins currently locked into the earn module. - TotalSupply(context.Context, *QueryTotalSupplyRequest) (*QueryTotalSupplyResponse, 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) Vaults(ctx context.Context, req *QueryVaultsRequest) (*QueryVaultsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Vaults not implemented") -} -func (*UnimplementedQueryServer) Vault(ctx context.Context, req *QueryVaultRequest) (*QueryVaultResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Vault not implemented") -} -func (*UnimplementedQueryServer) Deposits(ctx context.Context, req *QueryDepositsRequest) (*QueryDepositsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposits not implemented") -} -func (*UnimplementedQueryServer) TotalSupply(ctx context.Context, req *QueryTotalSupplyRequest) (*QueryTotalSupplyResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalSupply 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: "/kava.earn.v1beta1.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_Vaults_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryVaultsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Vaults(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.earn.v1beta1.Query/Vaults", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Vaults(ctx, req.(*QueryVaultsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Vault_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryVaultRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Vault(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.earn.v1beta1.Query/Vault", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Vault(ctx, req.(*QueryVaultRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Deposits_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDepositsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Deposits(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.earn.v1beta1.Query/Deposits", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Deposits(ctx, req.(*QueryDepositsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalSupply_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalSupplyRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalSupply(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.earn.v1beta1.Query/TotalSupply", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalSupply(ctx, req.(*QueryTotalSupplyRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.earn.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Vaults", - Handler: _Query_Vaults_Handler, - }, - { - MethodName: "Vault", - Handler: _Query_Vault_Handler, - }, - { - MethodName: "Deposits", - Handler: _Query_Deposits_Handler, - }, - { - MethodName: "TotalSupply", - Handler: _Query_TotalSupply_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/earn/v1beta1/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 *QueryVaultsRequest) 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 *QueryVaultsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryVaultsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryVaultsResponse) 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 *QueryVaultsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryVaultsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Vaults) > 0 { - for iNdEx := len(m.Vaults) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Vaults[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 (m *QueryVaultRequest) 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 *QueryVaultRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryVaultRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryVaultResponse) 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 *QueryVaultResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryVaultResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Vault.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 *VaultResponse) 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 *VaultResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *VaultResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.TotalValue.Size() - i -= size - if _, err := m.TotalValue.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - if len(m.TotalShares) > 0 { - i -= len(m.TotalShares) - copy(dAtA[i:], m.TotalShares) - i = encodeVarintQuery(dAtA, i, uint64(len(m.TotalShares))) - i-- - dAtA[i] = 0x2a - } - if len(m.AllowedDepositors) > 0 { - for iNdEx := len(m.AllowedDepositors) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.AllowedDepositors[iNdEx]) - copy(dAtA[i:], m.AllowedDepositors[iNdEx]) - i = encodeVarintQuery(dAtA, i, uint64(len(m.AllowedDepositors[iNdEx]))) - i-- - dAtA[i] = 0x22 - } - } - if m.IsPrivateVault { - i-- - if m.IsPrivateVault { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x18 - } - if len(m.Strategies) > 0 { - dAtA4 := make([]byte, len(m.Strategies)*10) - var j3 int - for _, num := range m.Strategies { - for num >= 1<<7 { - dAtA4[j3] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j3++ - } - dAtA4[j3] = uint8(num) - j3++ - } - i -= j3 - copy(dAtA[i:], dAtA4[:j3]) - i = encodeVarintQuery(dAtA, i, uint64(j3)) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDepositsRequest) 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 *QueryDepositsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsRequest) 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] = 0x22 - } - if m.ValueInStakedTokens { - i-- - if m.ValueInStakedTokens { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x18 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0x12 - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDepositsResponse) 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 *QueryDepositsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsResponse) 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.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[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 (m *DepositResponse) 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 *DepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Value) > 0 { - for iNdEx := len(m.Value) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Value[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Shares) > 0 { - for iNdEx := len(m.Shares) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Shares[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalSupplyRequest) 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 *QueryTotalSupplyRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalSupplyRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryTotalSupplyResponse) 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 *QueryTotalSupplyResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalSupplyResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Result) > 0 { - for iNdEx := len(m.Result) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Result[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if m.Height != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.Height)) - i-- - dAtA[i] = 0x8 - } - 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 *QueryVaultsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryVaultsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Vaults) > 0 { - for _, e := range m.Vaults { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryVaultRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryVaultResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Vault.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *VaultResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.Strategies) > 0 { - l = 0 - for _, e := range m.Strategies { - l += sovQuery(uint64(e)) - } - n += 1 + sovQuery(uint64(l)) + l - } - if m.IsPrivateVault { - n += 2 - } - if len(m.AllowedDepositors) > 0 { - for _, s := range m.AllowedDepositors { - l = len(s) - n += 1 + l + sovQuery(uint64(l)) - } - } - l = len(m.TotalShares) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = m.TotalValue.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryDepositsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.ValueInStakedTokens { - n += 2 - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDepositsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Deposits) > 0 { - for _, e := range m.Deposits { - 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 (m *DepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.Shares) > 0 { - for _, e := range m.Shares { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.Value) > 0 { - for _, e := range m.Value { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryTotalSupplyRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryTotalSupplyResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Height != 0 { - n += 1 + sovQuery(uint64(m.Height)) - } - if len(m.Result) > 0 { - for _, e := range m.Result { - l = e.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 *QueryVaultsRequest) 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: QueryVaultsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryVaultsRequest: 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 *QueryVaultsResponse) 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: QueryVaultsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryVaultsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Vaults", 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.Vaults = append(m.Vaults, VaultResponse{}) - if err := m.Vaults[len(m.Vaults)-1].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 *QueryVaultRequest) 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: QueryVaultRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryVaultRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - 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 *QueryVaultResponse) 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: QueryVaultResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryVaultResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Vault", 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.Vault.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 *VaultResponse) 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: VaultResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: VaultResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType == 0 { - var v StrategyType - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= StrategyType(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Strategies = append(m.Strategies, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - if elementCount != 0 && len(m.Strategies) == 0 { - m.Strategies = make([]StrategyType, 0, elementCount) - } - for iNdEx < postIndex { - var v StrategyType - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= StrategyType(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Strategies = append(m.Strategies, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field Strategies", wireType) - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field IsPrivateVault", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.IsPrivateVault = bool(v != 0) - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AllowedDepositors", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AllowedDepositors = append(m.AllowedDepositors, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalShares", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TotalShares = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalValue", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TotalValue.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 *QueryDepositsRequest) 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: QueryDepositsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ValueInStakedTokens", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.ValueInStakedTokens = bool(v != 0) - case 4: - 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 *QueryDepositsResponse) 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: QueryDepositsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposits", 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.Deposits = append(m.Deposits, DepositResponse{}) - if err := m.Deposits[len(m.Deposits)-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 (m *DepositResponse) 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: DepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Shares", 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.Shares = append(m.Shares, VaultShare{}) - if err := m.Shares[len(m.Shares)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", 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.Value = append(m.Value, types.Coin{}) - if err := m.Value[len(m.Value)-1].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 *QueryTotalSupplyRequest) 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: QueryTotalSupplyRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalSupplyRequest: 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 *QueryTotalSupplyResponse) 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: QueryTotalSupplyResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalSupplyResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) - } - m.Height = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Height |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Result", 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.Result = append(m.Result, types.Coin{}) - if err := m.Result[len(m.Result)-1].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/earn/types/query.pb.gw.go b/x/earn/types/query.pb.gw.go deleted file mode 100644 index 408bd2a3..00000000 --- a/x/earn/types/query.pb.gw.go +++ /dev/null @@ -1,467 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/earn/v1beta1/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_Vaults_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryVaultsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Vaults(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Vaults_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryVaultsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Vaults(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Vault_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryVaultRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["denom"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "denom") - } - - protoReq.Denom, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "denom", err) - } - - msg, err := client.Vault(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Vault_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryVaultRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["denom"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "denom") - } - - protoReq.Denom, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "denom", err) - } - - msg, err := server.Vault(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Deposits_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - 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_Deposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Deposits(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - 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_Deposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Deposits(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_TotalSupply_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalSupplyRequest - var metadata runtime.ServerMetadata - - msg, err := client.TotalSupply(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalSupply_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalSupplyRequest - var metadata runtime.ServerMetadata - - msg, err := server.TotalSupply(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_Vaults_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_Vaults_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_Vaults_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Vault_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_Vault_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_Vault_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_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_Deposits_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_Deposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalSupply_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_TotalSupply_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_TotalSupply_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_Vaults_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_Vaults_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_Vaults_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Vault_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_Vault_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_Vault_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_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_Deposits_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_Deposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalSupply_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_TotalSupply_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_TotalSupply_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{"kava", "earn", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Vaults_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "earn", "v1beta1", "vaults"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Vault_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 3, 0, 4, 1, 5, 4}, []string{"kava", "earn", "v1beta1", "vaults", "denom"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Deposits_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "earn", "v1beta1", "deposits"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalSupply_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "earn", "v1beta1", "total_supply"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Vaults_0 = runtime.ForwardResponseMessage - - forward_Query_Vault_0 = runtime.ForwardResponseMessage - - forward_Query_Deposits_0 = runtime.ForwardResponseMessage - - forward_Query_TotalSupply_0 = runtime.ForwardResponseMessage -) diff --git a/x/earn/types/share.go b/x/earn/types/share.go deleted file mode 100644 index 1e6d1531..00000000 --- a/x/earn/types/share.go +++ /dev/null @@ -1,383 +0,0 @@ -package types - -import ( - fmt "fmt" - "sort" - "strings" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewVaultShare returns a new VaultShare -func NewVaultShare(denom string, amount sdk.Dec) VaultShare { - share := VaultShare{ - Denom: denom, - Amount: amount, - } - - if err := share.Validate(); err != nil { - panic(err) - } - - return share -} - -// Validate returns an error if a VaultShare is invalid. -func (share VaultShare) Validate() error { - if err := sdk.ValidateDenom(share.Denom); err != nil { - return errorsmod.Wrap(ErrInvalidVaultDenom, err.Error()) - } - - if share.Amount.IsNil() { - return fmt.Errorf("nil share amount: %s", share.Amount) - } - - if share.Amount.IsNegative() { - return fmt.Errorf("vault share amount %v is negative", share.Amount) - } - - return nil -} - -// IsValid returns true if the VaultShare is valid -func (share VaultShare) IsValid() bool { - return share.Validate() == nil -} - -func (share VaultShare) IsPositive() bool { - return share.Amount.IsPositive() -} - -// Add adds amounts of two vault shares with same denom. If the shares differ in -// denom then it panics. -func (share VaultShare) Add(vsB VaultShare) VaultShare { - if share.Denom != vsB.Denom { - panic(fmt.Sprintf("invalid share denominations; %s, %s", share.Denom, vsB.Denom)) - } - - return NewVaultShare(share.Denom, share.Amount.Add(vsB.Amount)) -} - -// IsZero returns if this represents no shares -func (share VaultShare) IsZero() bool { - return share.Amount.IsZero() -} - -// IsNegative returns true if the share amount is negative and false otherwise. -func (share VaultShare) IsNegative() bool { - return share.Amount.IsNegative() -} - -// Sub subtracts amounts of two vault shares with same denom. If the shares -// differ in denom then it panics. -func (share VaultShare) Sub(vsB VaultShare) VaultShare { - if share.Denom != vsB.Denom { - panic(fmt.Sprintf("invalid share denominations; %s, %s", share.Denom, vsB.Denom)) - } - - res := NewVaultShare(share.Denom, share.Amount.Sub(vsB.Amount)) - if res.Amount.IsNegative() { - panic("negative share amount") - } - - return res -} - -func (share VaultShare) String() string { - return fmt.Sprintf("%v%v", share.Amount, share.Denom) -} - -// VaultShares is a slice of VaultShare. -type VaultShares []VaultShare - -// NewVaultShares returns new VaultShares -func NewVaultShares(shares ...VaultShare) VaultShares { - newVaultShares := sanitizeVaultShares(shares) - if err := newVaultShares.Validate(); err != nil { - panic(fmt.Errorf("invalid share set %s: %w", newVaultShares, err)) - } - - return newVaultShares -} - -func sanitizeVaultShares(shares VaultShares) VaultShares { - newVaultShares := removeZeroShares(shares) - if len(newVaultShares) == 0 { - return VaultShares{} - } - - return newVaultShares.Sort() -} - -// Validate returns an error if a slice of VaultShares is invalid. -func (shares VaultShares) Validate() error { - switch len(shares) { - case 0: - return nil - - case 1: - if err := sdk.ValidateDenom(shares[0].Denom); err != nil { - return err - } - if !shares[0].IsPositive() { - return fmt.Errorf("share %s amount is not positive", shares[0]) - } - return nil - default: - // check single share case - if err := (VaultShares{shares[0]}).Validate(); err != nil { - return err - } - - lowDenom := shares[0].Denom - seenDenoms := make(map[string]bool) - seenDenoms[lowDenom] = true - - for _, share := range shares[1:] { - if seenDenoms[share.Denom] { - return fmt.Errorf("duplicate denomination %s", share.Denom) - } - if err := sdk.ValidateDenom(share.Denom); err != nil { - return err - } - if share.Denom <= lowDenom { - return fmt.Errorf("denomination %s is not sorted", share.Denom) - } - if !share.IsPositive() { - return fmt.Errorf("share %s amount is not positive", share.Denom) - } - - // we compare each share against the last denom - lowDenom = share.Denom - seenDenoms[share.Denom] = true - } - - return nil - } -} - -// IsValid returns true if the VaultShares are valid -func (shares VaultShares) IsValid() bool { - return shares.Validate() == nil -} - -// Add adds two sets of VaultShares. -func (shares VaultShares) Add(sharesB ...VaultShare) VaultShares { - return shares.safeAdd(sharesB) -} - -// safeAdd will perform addition of two shares sets. If both share sets are -// empty, then an empty set is returned. If only a single set is empty, the -// other set is returned. Otherwise, the shares are compared in order of their -// denomination and addition only occurs when the denominations match, otherwise -// the share is simply added to the sum assuming it's not zero. -// The function panics if `shares` or `sharesB` are not sorted (ascending). -func (shares VaultShares) safeAdd(sharesB VaultShares) VaultShares { - // probably the best way will be to make Shares and interface and hide the structure - // definition (type alias) - if !shares.isSorted() { - panic("Shares (self) must be sorted") - } - if !sharesB.isSorted() { - panic("Wrong argument: shares must be sorted") - } - - sum := (VaultShares)(nil) - indexA, indexB := 0, 0 - lenA, lenB := len(shares), len(sharesB) - - for { - if indexA == lenA { - if indexB == lenB { - // return nil shares if both sets are empty - return sum - } - - // return set B (excluding zero shares) if set A is empty - return append(sum, removeZeroShares(sharesB[indexB:])...) - } else if indexB == lenB { - // return set A (excluding zero shares) if set B is empty - return append(sum, removeZeroShares(shares[indexA:])...) - } - - shareA, shareB := shares[indexA], sharesB[indexB] - - switch strings.Compare(shareA.Denom, shareB.Denom) { - case -1: // share A denom < share B denom - if !shareA.IsZero() { - sum = append(sum, shareA) - } - - indexA++ - - case 0: // share A denom == share B denom - res := shareA.Add(shareB) - if !res.IsZero() { - sum = append(sum, res) - } - - indexA++ - indexB++ - - case 1: // share A denom > share B denom - if !shareB.IsZero() { - sum = append(sum, shareB) - } - - indexB++ - } - } -} - -// Sub subtracts a set of shares from another. -// -// e.g. -// {2A, 3B} - {A} = {A, 3B} -// {2A} - {0B} = {2A} -// {A, B} - {A} = {B} -// -// CONTRACT: Sub will never return Shares where one Share has a non-positive -// amount. In otherwords, IsValid will always return true. -func (shares VaultShares) Sub(sharesB ...VaultShare) VaultShares { - diff, hasNeg := shares.SafeSub(sharesB) - if hasNeg { - panic("negative share amount") - } - - return diff -} - -// SafeSub performs the same arithmetic as Sub but returns a boolean if any -// negative share amount was returned. -// The function panics if `shares` or `sharesB` are not sorted (ascending). -func (shares VaultShares) SafeSub(sharesB VaultShares) (VaultShares, bool) { - diff := shares.safeAdd(sharesB.negative()) - return diff, diff.IsAnyNegative() -} - -// IsAnyNegative returns true if there is at least one share whose amount -// is negative; returns false otherwise. It returns false if the share set -// is empty too. -func (shares VaultShares) IsAnyNegative() bool { - for _, share := range shares { - if share.IsNegative() { - return true - } - } - - return false -} - -// negative returns a set of shares with all amount negative. -func (shares VaultShares) negative() VaultShares { - res := make(VaultShares, 0, len(shares)) - - for _, share := range shares { - res = append(res, VaultShare{ - Denom: share.Denom, - Amount: share.Amount.Neg(), - }) - } - - return res -} - -// AmountOf returns the amount of shares of the given denom. -func (shares VaultShares) AmountOf(denom string) sdk.Dec { - for _, s := range shares { - if s.Denom == denom { - return s.Amount - } - } - - return sdk.ZeroDec() -} - -// GetShare the single share of the given denom. -func (shares VaultShares) GetShare(denom string) VaultShare { - for _, s := range shares { - if s.Denom == denom { - return s - } - } - - return NewVaultShare(denom, sdk.ZeroDec()) -} - -// IsZero returns true if the VaultShares is empty. -func (shares VaultShares) IsZero() bool { - for _, s := range shares { - // If any amount is non-zero, false - if !s.Amount.IsZero() { - return false - } - } - - return true -} - -func (shares VaultShares) isSorted() bool { - for i := 1; i < len(shares); i++ { - if shares[i-1].Denom > shares[i].Denom { - return false - } - } - return true -} - -func (shares VaultShares) String() string { - if len(shares) == 0 { - return "" - } - - out := "" - for _, share := range shares { - out += fmt.Sprintf("%v,", share.String()) - } - - return out[:len(out)-1] -} - -// removeZeroShares removes all zero shares from the given share set in-place. -func removeZeroShares(shares VaultShares) VaultShares { - for i := 0; i < len(shares); i++ { - if shares[i].IsZero() { - break - } else if i == len(shares)-1 { - return shares - } - } - - var result VaultShares - if len(shares) > 0 { - result = make(VaultShares, 0, len(shares)-1) - } - - for _, share := range shares { - if !share.IsZero() { - result = append(result, share) - } - } - - return result -} - -// ---------------------------------------------------------------------------- -// VaultShares sort interface - -func (shares VaultShares) Len() int { return len(shares) } - -// Less implements sort.Interface for VaultShares -func (shares VaultShares) Less(i, j int) bool { return shares[i].Denom < shares[j].Denom } - -// Swap implements sort.Interface for VaultShares -func (shares VaultShares) Swap(i, j int) { shares[i], shares[j] = shares[j], shares[i] } - -var _ sort.Interface = VaultShares{} - -// Sort is a helper function to sort the set of vault shares in-place -func (shares VaultShares) Sort() VaultShares { - sort.Sort(shares) - return shares -} diff --git a/x/earn/types/share_test.go b/x/earn/types/share_test.go deleted file mode 100644 index 08341736..00000000 --- a/x/earn/types/share_test.go +++ /dev/null @@ -1,446 +0,0 @@ -package types_test - -import ( - "strings" - "testing" - - "github.com/kava-labs/kava/x/earn/types" - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var ( - testDenom1 = "ukava" - testDenom2 = "usdx" -) - -func d(i int64) sdk.Dec { - return sdk.NewDec(i) -} - -type vaultShareTestSuite struct { - suite.Suite -} - -func TestVaultShareTestSuite(t *testing.T) { - suite.Run(t, new(vaultShareTestSuite)) -} - -func (s *vaultShareTestSuite) TestNewVaultShareFromDec() { - s.Require().NotPanics(func() { - types.NewVaultShare(testDenom1, sdk.NewDec(5)) - }) - s.Require().NotPanics(func() { - types.NewVaultShare(testDenom1, sdk.ZeroDec()) - }) - s.Require().NotPanics(func() { - types.NewVaultShare(strings.ToUpper(testDenom1), sdk.NewDec(5)) - }) - s.Require().Panics(func() { - types.NewVaultShare(testDenom1, sdk.NewDec(-5)) - }) -} - -func (s *vaultShareTestSuite) TestAddVaultShare() { - vaultShareA1 := types.NewVaultShare(testDenom1, sdk.NewDecWithPrec(11, 1)) - vaultShareA2 := types.NewVaultShare(testDenom1, sdk.NewDecWithPrec(22, 1)) - vaultShareB1 := types.NewVaultShare(testDenom2, sdk.NewDecWithPrec(11, 1)) - - // regular add - res := vaultShareA1.Add(vaultShareA1) - s.Require().Equal(vaultShareA2, res, "sum of shares is incorrect") - - // bad denom add - s.Require().Panics(func() { - vaultShareA1.Add(vaultShareB1) - }, "expected panic on sum of different denoms") -} - -func (s *vaultShareTestSuite) TestAddVaultShares() { - one := sdk.NewDec(1) - zero := sdk.NewDec(0) - two := sdk.NewDec(2) - - cases := []struct { - inputOne types.VaultShares - inputTwo types.VaultShares - expected types.VaultShares - }{ - { - types.VaultShares{ - {testDenom1, one}, - {testDenom2, one}, - }, - types.VaultShares{ - {testDenom1, one}, - {testDenom2, one}, - }, - types.VaultShares{ - {testDenom1, two}, - {testDenom2, two}, - }, - }, - { - types.VaultShares{ - {testDenom1, zero}, - {testDenom2, one}, - }, - types.VaultShares{ - {testDenom1, zero}, - {testDenom2, zero}, - }, - types.VaultShares{ - {testDenom2, one}, - }, - }, - { - types.VaultShares{ - {testDenom1, zero}, - {testDenom2, zero}, - }, - types.VaultShares{ - {testDenom1, zero}, - {testDenom2, zero}, - }, - types.VaultShares(nil), - }, - } - - for tcIndex, tc := range cases { - res := tc.inputOne.Add(tc.inputTwo...) - s.Require().Equal(tc.expected, res, "sum of shares is incorrect, tc #%d", tcIndex) - } -} - -func (s *vaultShareTestSuite) TestFilteredZeroVaultShares() { - cases := []struct { - name string - input types.VaultShares - original string - expected string - }{ - { - name: "all greater than zero", - input: types.VaultShares{ - {"testa", sdk.NewDec(1)}, - {"testb", sdk.NewDec(2)}, - {"testc", sdk.NewDec(3)}, - {"testd", sdk.NewDec(4)}, - {"teste", sdk.NewDec(5)}, - }, - original: "1.000000000000000000testa,2.000000000000000000testb,3.000000000000000000testc,4.000000000000000000testd,5.000000000000000000teste", - expected: "1.000000000000000000testa,2.000000000000000000testb,3.000000000000000000testc,4.000000000000000000testd,5.000000000000000000teste", - }, - { - name: "zero share in middle", - input: types.VaultShares{ - {"testa", sdk.NewDec(1)}, - {"testb", sdk.NewDec(2)}, - {"testc", sdk.NewDec(0)}, - {"testd", sdk.NewDec(4)}, - {"teste", sdk.NewDec(5)}, - }, - original: "1.000000000000000000testa,2.000000000000000000testb,0.000000000000000000testc,4.000000000000000000testd,5.000000000000000000teste", - expected: "1.000000000000000000testa,2.000000000000000000testb,4.000000000000000000testd,5.000000000000000000teste", - }, - { - name: "zero share end (unordered)", - input: types.VaultShares{ - {"teste", sdk.NewDec(5)}, - {"testc", sdk.NewDec(3)}, - {"testa", sdk.NewDec(1)}, - {"testd", sdk.NewDec(4)}, - {"testb", sdk.NewDec(0)}, - }, - original: "5.000000000000000000teste,3.000000000000000000testc,1.000000000000000000testa,4.000000000000000000testd,0.000000000000000000testb", - expected: "1.000000000000000000testa,3.000000000000000000testc,4.000000000000000000testd,5.000000000000000000teste", - }, - } - - for _, tt := range cases { - undertest := types.NewVaultShares(tt.input...) - s.Require().Equal(tt.expected, undertest.String(), "NewVaultShares must return expected results") - s.Require().Equal(tt.original, tt.input.String(), "input must be unmodified and match original") - } -} - -func (s *vaultShareTestSuite) TestIsValid() { - tests := []struct { - share types.VaultShare - expectPass bool - msg string - }{ - { - types.NewVaultShare("mytoken", sdk.NewDec(10)), - true, - "valid shares should have passed", - }, - { - types.VaultShare{Denom: "BTC", Amount: sdk.NewDec(10)}, - true, - "valid uppercase denom", - }, - { - types.VaultShare{Denom: "Bitshare", Amount: sdk.NewDec(10)}, - true, - "valid mixed case denom", - }, - { - types.VaultShare{Denom: "btc", Amount: sdk.NewDec(-10)}, - false, - "negative amount", - }, - } - - for _, tc := range tests { - tc := tc - if tc.expectPass { - s.Require().True(tc.share.IsValid(), tc.msg) - } else { - s.Require().False(tc.share.IsValid(), tc.msg) - } - } -} - -func (s *vaultShareTestSuite) TestSubVaultShare() { - tests := []struct { - share types.VaultShare - expectPass bool - msg string - }{ - { - types.NewVaultShare("mytoken", sdk.NewDec(20)), - true, - "valid shares should have passed", - }, - { - types.NewVaultShare("othertoken", sdk.NewDec(20)), - false, - "denom mismatch", - }, - { - types.NewVaultShare("mytoken", sdk.NewDec(9)), - false, - "negative amount", - }, - } - - vaultShare := types.NewVaultShare("mytoken", sdk.NewDec(10)) - - for _, tc := range tests { - tc := tc - if tc.expectPass { - equal := tc.share.Sub(vaultShare) - s.Require().Equal(equal, vaultShare, tc.msg) - } else { - s.Require().Panics(func() { tc.share.Sub(vaultShare) }, tc.msg) - } - } -} - -func (s *vaultShareTestSuite) TestSubVaultShares() { - tests := []struct { - shares types.VaultShares - expectPass bool - msg string - }{ - { - types.NewVaultShares(types.NewVaultShare("mytoken", d(10)), types.NewVaultShare("btc", d(20)), types.NewVaultShare("eth", d(30))), - true, - "sorted shares should have passed", - }, - { - types.VaultShares{types.NewVaultShare("mytoken", d(10)), types.NewVaultShare("btc", d(20)), types.NewVaultShare("eth", d(30))}, - false, - "unorted shares should panic", - }, - { - types.VaultShares{types.VaultShare{Denom: "BTC", Amount: sdk.NewDec(10)}, types.NewVaultShare("eth", d(15)), types.NewVaultShare("mytoken", d(5))}, - false, - "invalid denoms", - }, - } - - vaultShares := types.NewVaultShares(types.NewVaultShare("btc", d(10)), types.NewVaultShare("eth", d(15)), types.NewVaultShare("mytoken", d(5))) - - for _, tc := range tests { - tc := tc - if tc.expectPass { - equal := tc.shares.Sub(vaultShares...) - s.Require().Equal(equal, vaultShares, tc.msg) - } else { - s.Require().Panics(func() { tc.shares.Sub(vaultShares...) }, tc.msg) - } - } -} - -func (s *vaultShareTestSuite) TestSortVaultShares() { - good := types.VaultShares{ - types.NewVaultShare("gas", d(1)), - types.NewVaultShare("mineral", d(1)), - types.NewVaultShare("tree", d(1)), - } - empty := types.VaultShares{ - types.NewVaultShare("gold", d(0)), - } - badSort1 := types.VaultShares{ - types.NewVaultShare("tree", d(1)), - types.NewVaultShare("gas", d(1)), - types.NewVaultShare("mineral", d(1)), - } - badSort2 := types.VaultShares{ // both are after the first one, but the second and third are in the wrong order - types.NewVaultShare("gas", d(1)), - types.NewVaultShare("tree", d(1)), - types.NewVaultShare("mineral", d(1)), - } - badAmt := types.VaultShares{ - types.NewVaultShare("gas", d(1)), - types.NewVaultShare("tree", d(0)), - types.NewVaultShare("mineral", d(1)), - } - dup := types.VaultShares{ - types.NewVaultShare("gas", d(1)), - types.NewVaultShare("gas", d(1)), - types.NewVaultShare("mineral", d(1)), - } - cases := []struct { - name string - shares types.VaultShares - before, after bool // valid before/after sort - }{ - {"valid shares", good, true, true}, - {"empty shares", empty, false, false}, - {"unsorted shares (1)", badSort1, false, true}, - {"unsorted shares (2)", badSort2, false, true}, - {"zero amount shares", badAmt, false, false}, - {"duplicate shares", dup, false, false}, - } - - for _, tc := range cases { - s.Require().Equal(tc.before, tc.shares.IsValid(), "share validity is incorrect before sorting; %s", tc.name) - tc.shares.Sort() - s.Require().Equal(tc.after, tc.shares.IsValid(), "share validity is incorrect after sorting; %s", tc.name) - } -} - -func (s *vaultShareTestSuite) TestVaultSharesValidate() { - testCases := []struct { - input types.VaultShares - expectedPass bool - }{ - {types.VaultShares{}, true}, - {types.VaultShares{types.VaultShare{testDenom1, sdk.NewDec(5)}}, true}, - {types.VaultShares{types.VaultShare{testDenom1, sdk.NewDec(5)}, types.VaultShare{testDenom2, sdk.NewDec(100000)}}, true}, - {types.VaultShares{types.VaultShare{testDenom1, sdk.NewDec(-5)}}, false}, - {types.VaultShares{types.VaultShare{"BTC", sdk.NewDec(5)}}, true}, - {types.VaultShares{types.VaultShare{"0BTC", sdk.NewDec(5)}}, false}, - {types.VaultShares{types.VaultShare{testDenom1, sdk.NewDec(5)}, types.VaultShare{"B", sdk.NewDec(100000)}}, false}, - {types.VaultShares{types.VaultShare{testDenom1, sdk.NewDec(5)}, types.VaultShare{testDenom2, sdk.NewDec(-100000)}}, false}, - {types.VaultShares{types.VaultShare{testDenom1, sdk.NewDec(-5)}, types.VaultShare{testDenom2, sdk.NewDec(100000)}}, false}, - {types.VaultShares{types.VaultShare{"BTC", sdk.NewDec(5)}, types.VaultShare{testDenom2, sdk.NewDec(100000)}}, true}, - {types.VaultShares{types.VaultShare{"0BTC", sdk.NewDec(5)}, types.VaultShare{testDenom2, sdk.NewDec(100000)}}, false}, - } - - for i, tc := range testCases { - err := tc.input.Validate() - if tc.expectedPass { - s.Require().NoError(err, "unexpected result for test case #%d, input: %v", i, tc.input) - } else { - s.Require().Error(err, "unexpected result for test case #%d, input: %v", i, tc.input) - } - } -} - -func (s *vaultShareTestSuite) TestVaultSharesString() { - testCases := []struct { - input types.VaultShares - expected string - }{ - {types.VaultShares{}, ""}, - { - types.VaultShares{ - types.NewVaultShare("atom", sdk.NewDecWithPrec(5040000000000000000, sdk.Precision)), - types.NewVaultShare("stake", sdk.NewDecWithPrec(4000000000000000, sdk.Precision)), - }, - "5.040000000000000000atom,0.004000000000000000stake", - }, - } - - for i, tc := range testCases { - out := tc.input.String() - s.Require().Equal(tc.expected, out, "unexpected result for test case #%d, input: %v", i, tc.input) - } -} - -func (s *vaultShareTestSuite) TestNewVaultSharesWithIsValid() { - fake1 := append(types.NewVaultShares(types.NewVaultShare("mytoken", d(10))), types.VaultShare{Denom: "10BTC", Amount: sdk.NewDec(10)}) - fake2 := append(types.NewVaultShares(types.NewVaultShare("mytoken", d(10))), types.VaultShare{Denom: "BTC", Amount: sdk.NewDec(-10)}) - - tests := []struct { - share types.VaultShares - expectPass bool - msg string - }{ - { - types.NewVaultShares(types.NewVaultShare("mytoken", d(10))), - true, - "valid shares should have passed", - }, - { - fake1, - false, - "invalid denoms", - }, - { - fake2, - false, - "negative amount", - }, - } - - for _, tc := range tests { - tc := tc - if tc.expectPass { - s.Require().True(tc.share.IsValid(), tc.msg) - } else { - s.Require().False(tc.share.IsValid(), tc.msg) - } - } -} - -func (s *vaultShareTestSuite) TestVaultShares_AddVaultShareWithIsValid() { - lengthTestVaultShares := types.NewVaultShares().Add(types.NewVaultShare("mytoken", d(10))).Add(types.VaultShare{Denom: "BTC", Amount: sdk.NewDec(10)}) - s.Require().Equal(2, len(lengthTestVaultShares), "should be 2") - - tests := []struct { - share types.VaultShares - expectPass bool - msg string - }{ - { - types.NewVaultShares().Add(types.NewVaultShare("mytoken", d(10))), - true, - "valid shares should have passed", - }, - { - types.NewVaultShares().Add(types.NewVaultShare("mytoken", d(10))).Add(types.VaultShare{Denom: "0BTC", Amount: sdk.NewDec(10)}), - false, - "invalid denoms", - }, - { - types.NewVaultShares().Add(types.NewVaultShare("mytoken", d(10))).Add(types.VaultShare{Denom: "BTC", Amount: sdk.NewDec(-10)}), - false, - "negative amount", - }, - } - - for _, tc := range tests { - tc := tc - if tc.expectPass { - s.Require().True(tc.share.IsValid(), tc.msg) - } else { - s.Require().False(tc.share.IsValid(), tc.msg) - } - } -} diff --git a/x/earn/types/strategy.go b/x/earn/types/strategy.go deleted file mode 100644 index 5afe5d9d..00000000 --- a/x/earn/types/strategy.go +++ /dev/null @@ -1,62 +0,0 @@ -package types - -import ( - "fmt" - "strings" -) - -// IsValid returns true if the StrategyType status is valid and false otherwise. -func (s StrategyType) IsValid() bool { - return s == STRATEGY_TYPE_HARD || s == STRATEGY_TYPE_SAVINGS -} - -// Validate returns an error if the StrategyType is invalid. -func (s StrategyType) Validate() error { - if !s.IsValid() { - return fmt.Errorf("invalid strategy %s", s) - } - - return nil -} - -// NewStrategyTypeFromString converts string to StrategyType type -func NewStrategyTypeFromString(str string) StrategyType { - switch strings.ToLower(str) { - case "hard": - return STRATEGY_TYPE_HARD - case "savings": - return STRATEGY_TYPE_SAVINGS - default: - return STRATEGY_TYPE_UNSPECIFIED - } -} - -// StrategyTypes defines a slice of StrategyType -type StrategyTypes []StrategyType - -// Validate returns an error if StrategyTypes are invalid. -func (strategies StrategyTypes) Validate() error { - if len(strategies) == 0 { - return fmt.Errorf("empty StrategyTypes") - } - - if len(strategies) != 1 { - return fmt.Errorf("must have exactly one strategy type, multiple strategies are not supported") - } - - uniqueStrategies := make(map[StrategyType]bool) - - for _, strategy := range strategies { - if err := strategy.Validate(); err != nil { - return err - } - - if _, found := uniqueStrategies[strategy]; found { - return fmt.Errorf("duplicate strategy %s", strategy) - } - - uniqueStrategies[strategy] = true - } - - return nil -} diff --git a/x/earn/types/strategy.pb.go b/x/earn/types/strategy.pb.go deleted file mode 100644 index a20f602c..00000000 --- a/x/earn/types/strategy.pb.go +++ /dev/null @@ -1,80 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/earn/v1beta1/strategy.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - 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 - -// StrategyType is the type of strategy that a vault uses to optimize yields. -type StrategyType int32 - -const ( - // STRATEGY_TYPE_UNSPECIFIED represents an unspecified or invalid strategy type. - STRATEGY_TYPE_UNSPECIFIED StrategyType = 0 - // STRATEGY_TYPE_HARD represents the strategy that deposits assets in the Hard - // module. - STRATEGY_TYPE_HARD StrategyType = 1 - // STRATEGY_TYPE_SAVINGS represents the strategy that deposits assets in the - // Savings module. - STRATEGY_TYPE_SAVINGS StrategyType = 2 -) - -var StrategyType_name = map[int32]string{ - 0: "STRATEGY_TYPE_UNSPECIFIED", - 1: "STRATEGY_TYPE_HARD", - 2: "STRATEGY_TYPE_SAVINGS", -} - -var StrategyType_value = map[string]int32{ - "STRATEGY_TYPE_UNSPECIFIED": 0, - "STRATEGY_TYPE_HARD": 1, - "STRATEGY_TYPE_SAVINGS": 2, -} - -func (x StrategyType) String() string { - return proto.EnumName(StrategyType_name, int32(x)) -} - -func (StrategyType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_257c4968dd48fa09, []int{0} -} - -func init() { - proto.RegisterEnum("kava.earn.v1beta1.StrategyType", StrategyType_name, StrategyType_value) -} - -func init() { proto.RegisterFile("kava/earn/v1beta1/strategy.proto", fileDescriptor_257c4968dd48fa09) } - -var fileDescriptor_257c4968dd48fa09 = []byte{ - // 220 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xc8, 0x4e, 0x2c, 0x4b, - 0xd4, 0x4f, 0x4d, 0x2c, 0xca, 0xd3, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x2f, 0x2e, - 0x29, 0x4a, 0x2c, 0x49, 0x4d, 0xaf, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x04, 0xa9, - 0xd0, 0x03, 0xa9, 0xd0, 0x83, 0xaa, 0x90, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0xcb, 0xea, 0x83, - 0x58, 0x10, 0x85, 0x5a, 0x69, 0x5c, 0x3c, 0xc1, 0x50, 0xad, 0x21, 0x95, 0x05, 0xa9, 0x42, 0xb2, - 0x5c, 0x92, 0xc1, 0x21, 0x41, 0x8e, 0x21, 0xae, 0xee, 0x91, 0xf1, 0x21, 0x91, 0x01, 0xae, 0xf1, - 0xa1, 0x7e, 0xc1, 0x01, 0xae, 0xce, 0x9e, 0x6e, 0x9e, 0xae, 0x2e, 0x02, 0x0c, 0x42, 0x62, 0x5c, - 0x42, 0xa8, 0xd2, 0x1e, 0x8e, 0x41, 0x2e, 0x02, 0x8c, 0x42, 0x92, 0x5c, 0xa2, 0xa8, 0xe2, 0xc1, - 0x8e, 0x61, 0x9e, 0x7e, 0xee, 0xc1, 0x02, 0x4c, 0x52, 0x2c, 0x1d, 0x8b, 0xe5, 0x18, 0x9c, 0x1c, - 0x4e, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, - 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0x4a, 0x2d, 0x3d, 0xb3, 0x24, 0xa3, - 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0x1f, 0xe4, 0x6a, 0xdd, 0x9c, 0xc4, 0xa4, 0x62, 0x30, 0x4b, - 0xbf, 0x02, 0xe2, 0xc7, 0x92, 0xca, 0x82, 0xd4, 0xe2, 0x24, 0x36, 0xb0, 0x83, 0x8d, 0x01, 0x01, - 0x00, 0x00, 0xff, 0xff, 0x81, 0x9e, 0x23, 0x1c, 0xfd, 0x00, 0x00, 0x00, -} diff --git a/x/earn/types/strategy_test.go b/x/earn/types/strategy_test.go deleted file mode 100644 index ed8fd1c5..00000000 --- a/x/earn/types/strategy_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/kava-labs/kava/x/earn/types" - "github.com/stretchr/testify/require" -) - -func TestNewStrategyTypeFromString(t *testing.T) { - tests := []struct { - name string - strategy string - expected types.StrategyType - }{ - { - name: "hard", - strategy: "hard", - expected: types.STRATEGY_TYPE_HARD, - }, - { - name: "savings", - strategy: "savings", - expected: types.STRATEGY_TYPE_SAVINGS, - }, - { - name: "unspecified", - strategy: "not a valid strategy name", - expected: types.STRATEGY_TYPE_UNSPECIFIED, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - actual := types.NewStrategyTypeFromString(tc.strategy) - if actual != tc.expected { - t.Errorf("expected %s, got %s", tc.expected, actual) - } - }) - } -} - -func TestValidateStrategyTypes(t *testing.T) { - type errArgs struct { - expectPass bool - contains string - } - - tests := []struct { - name string - strategies types.StrategyTypes - errArgs errArgs - }{ - { - name: "valid - hard", - strategies: types.StrategyTypes{types.STRATEGY_TYPE_HARD}, - errArgs: errArgs{ - expectPass: true, - }, - }, - { - name: "valid - savings", - strategies: types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - errArgs: errArgs{ - expectPass: true, - }, - }, - { - name: "invalid - duplicate", - strategies: types.StrategyTypes{ - types.STRATEGY_TYPE_SAVINGS, - types.STRATEGY_TYPE_SAVINGS, - }, - errArgs: errArgs{ - expectPass: false, - // This will change to duplicate error if multiple strategies are supported - contains: "must have exactly one strategy type, multiple strategies are not supported", - }, - }, - { - name: "invalid - unspecified", - strategies: types.StrategyTypes{types.STRATEGY_TYPE_UNSPECIFIED}, - errArgs: errArgs{ - expectPass: false, - contains: "invalid strategy", - }, - }, - { - name: "invalid - zero", - strategies: types.StrategyTypes{}, - errArgs: errArgs{ - expectPass: false, - contains: "empty StrategyTypes", - }, - }, - { - name: "invalid - more than 1", - strategies: types.StrategyTypes{ - types.STRATEGY_TYPE_HARD, - types.STRATEGY_TYPE_SAVINGS, - }, - errArgs: errArgs{ - expectPass: false, - contains: "must have exactly one strategy type, multiple strategies are not supported", - }, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - err := tc.strategies.Validate() - if tc.errArgs.expectPass { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errArgs.contains) - } - }) - } -} diff --git a/x/earn/types/tx.pb.go b/x/earn/types/tx.pb.go deleted file mode 100644 index 44555c8d..00000000 --- a/x/earn/types/tx.pb.go +++ /dev/null @@ -1,1120 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/earn/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - 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 - -// MsgDeposit represents a message for depositing assedts into a vault -type MsgDeposit struct { - // depositor represents the address to deposit funds from - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - // Amount represents the token to deposit. The vault corresponds to the denom - // of the amount coin. - Amount types.Coin `protobuf:"bytes,2,opt,name=amount,proto3" json:"amount"` - // Strategy is the vault strategy to use. - Strategy StrategyType `protobuf:"varint,3,opt,name=strategy,proto3,enum=kava.earn.v1beta1.StrategyType" json:"strategy,omitempty"` -} - -func (m *MsgDeposit) Reset() { *m = MsgDeposit{} } -func (m *MsgDeposit) String() string { return proto.CompactTextString(m) } -func (*MsgDeposit) ProtoMessage() {} -func (*MsgDeposit) Descriptor() ([]byte, []int) { - return fileDescriptor_2e9dcf48a3fa0009, []int{0} -} -func (m *MsgDeposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDeposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDeposit.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 *MsgDeposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDeposit.Merge(m, src) -} -func (m *MsgDeposit) XXX_Size() int { - return m.Size() -} -func (m *MsgDeposit) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDeposit.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDeposit proto.InternalMessageInfo - -// MsgDepositResponse defines the Msg/Deposit response type. -type MsgDepositResponse struct { - Shares VaultShare `protobuf:"bytes,1,opt,name=shares,proto3" json:"shares"` -} - -func (m *MsgDepositResponse) Reset() { *m = MsgDepositResponse{} } -func (m *MsgDepositResponse) String() string { return proto.CompactTextString(m) } -func (*MsgDepositResponse) ProtoMessage() {} -func (*MsgDepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2e9dcf48a3fa0009, []int{1} -} -func (m *MsgDepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDepositResponse.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 *MsgDepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDepositResponse.Merge(m, src) -} -func (m *MsgDepositResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgDepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDepositResponse proto.InternalMessageInfo - -func (m *MsgDepositResponse) GetShares() VaultShare { - if m != nil { - return m.Shares - } - return VaultShare{} -} - -// MsgWithdraw represents a message for withdrawing liquidity from a vault -type MsgWithdraw struct { - // from represents the address we are withdrawing for - From string `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` - // Amount represents the token to withdraw. The vault corresponds to the denom - // of the amount coin. - Amount types.Coin `protobuf:"bytes,2,opt,name=amount,proto3" json:"amount"` - // Strategy is the vault strategy to use. - Strategy StrategyType `protobuf:"varint,3,opt,name=strategy,proto3,enum=kava.earn.v1beta1.StrategyType" json:"strategy,omitempty"` -} - -func (m *MsgWithdraw) Reset() { *m = MsgWithdraw{} } -func (m *MsgWithdraw) String() string { return proto.CompactTextString(m) } -func (*MsgWithdraw) ProtoMessage() {} -func (*MsgWithdraw) Descriptor() ([]byte, []int) { - return fileDescriptor_2e9dcf48a3fa0009, []int{2} -} -func (m *MsgWithdraw) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdraw) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdraw.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 *MsgWithdraw) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdraw.Merge(m, src) -} -func (m *MsgWithdraw) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdraw) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdraw.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdraw proto.InternalMessageInfo - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -type MsgWithdrawResponse struct { - Shares VaultShare `protobuf:"bytes,1,opt,name=shares,proto3" json:"shares"` -} - -func (m *MsgWithdrawResponse) Reset() { *m = MsgWithdrawResponse{} } -func (m *MsgWithdrawResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawResponse) ProtoMessage() {} -func (*MsgWithdrawResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2e9dcf48a3fa0009, []int{3} -} -func (m *MsgWithdrawResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawResponse.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 *MsgWithdrawResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawResponse.Merge(m, src) -} -func (m *MsgWithdrawResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawResponse proto.InternalMessageInfo - -func (m *MsgWithdrawResponse) GetShares() VaultShare { - if m != nil { - return m.Shares - } - return VaultShare{} -} - -func init() { - proto.RegisterType((*MsgDeposit)(nil), "kava.earn.v1beta1.MsgDeposit") - proto.RegisterType((*MsgDepositResponse)(nil), "kava.earn.v1beta1.MsgDepositResponse") - proto.RegisterType((*MsgWithdraw)(nil), "kava.earn.v1beta1.MsgWithdraw") - proto.RegisterType((*MsgWithdrawResponse)(nil), "kava.earn.v1beta1.MsgWithdrawResponse") -} - -func init() { proto.RegisterFile("kava/earn/v1beta1/tx.proto", fileDescriptor_2e9dcf48a3fa0009) } - -var fileDescriptor_2e9dcf48a3fa0009 = []byte{ - // 442 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x53, 0x41, 0x6b, 0x13, 0x41, - 0x14, 0xde, 0xb1, 0x21, 0xb6, 0x13, 0x10, 0x1c, 0x7b, 0x48, 0x17, 0x3a, 0x09, 0x01, 0x4b, 0x0e, - 0x76, 0x96, 0x46, 0x50, 0xb0, 0x17, 0x8d, 0x5e, 0x83, 0xb8, 0x11, 0x05, 0x2f, 0x32, 0x9b, 0x1d, - 0x27, 0x8b, 0xdd, 0x9d, 0x65, 0xde, 0x24, 0x36, 0xff, 0xc0, 0xa3, 0x3f, 0xc1, 0xb3, 0x67, 0xc1, - 0xab, 0xc7, 0x1e, 0x8b, 0x27, 0x4f, 0x22, 0xc9, 0x1f, 0x91, 0xdd, 0x99, 0xdd, 0x08, 0x09, 0xf5, - 0x22, 0xf4, 0xf6, 0x66, 0xbe, 0xef, 0x7b, 0xfb, 0xbd, 0x6f, 0xe7, 0x61, 0xff, 0x3d, 0x9f, 0xf3, - 0x40, 0x70, 0x9d, 0x05, 0xf3, 0x93, 0x48, 0x18, 0x7e, 0x12, 0x98, 0x73, 0x96, 0x6b, 0x65, 0x14, - 0xb9, 0x5d, 0x60, 0xac, 0xc0, 0x98, 0xc3, 0x7c, 0x3a, 0x51, 0x90, 0x2a, 0x08, 0x22, 0x0e, 0xa2, - 0x16, 0x4c, 0x54, 0x92, 0x59, 0x89, 0x7f, 0x60, 0xf1, 0xb7, 0xe5, 0x29, 0xb0, 0x07, 0x07, 0xed, - 0x4b, 0x25, 0x95, 0xbd, 0x2f, 0x2a, 0x77, 0xdb, 0xdd, 0xfc, 0x3e, 0x18, 0xcd, 0x8d, 0x90, 0x0b, - 0xc7, 0x38, 0xdc, 0x64, 0xcc, 0xf9, 0xec, 0xcc, 0x58, 0xb8, 0xf7, 0x1d, 0x61, 0x3c, 0x02, 0xf9, - 0x4c, 0xe4, 0x0a, 0x12, 0x43, 0x1e, 0xe0, 0xbd, 0xd8, 0x96, 0x4a, 0xb7, 0x51, 0x17, 0xf5, 0xf7, - 0x86, 0xed, 0x1f, 0x5f, 0x8f, 0xf7, 0x9d, 0x95, 0x27, 0x71, 0xac, 0x05, 0xc0, 0xd8, 0xe8, 0x24, - 0x93, 0xe1, 0x9a, 0x4a, 0x1e, 0xe2, 0x26, 0x4f, 0xd5, 0x2c, 0x33, 0xed, 0x1b, 0x5d, 0xd4, 0x6f, - 0x0d, 0x0e, 0x98, 0x53, 0x14, 0x93, 0x56, 0xe3, 0xb3, 0xa7, 0x2a, 0xc9, 0x86, 0x8d, 0x8b, 0x5f, - 0x1d, 0x2f, 0x74, 0x74, 0x72, 0x8a, 0x77, 0x2b, 0xc3, 0xed, 0x9d, 0x2e, 0xea, 0xdf, 0x1a, 0x74, - 0xd8, 0x46, 0x6e, 0x6c, 0xec, 0x28, 0x2f, 0x17, 0xb9, 0x08, 0x6b, 0xc1, 0xa3, 0xc6, 0xc7, 0xcf, - 0x1d, 0xaf, 0xf7, 0x02, 0x93, 0xf5, 0x04, 0xa1, 0x80, 0x5c, 0x65, 0x20, 0xc8, 0x29, 0x6e, 0xc2, - 0x94, 0x6b, 0x01, 0xe5, 0x18, 0xad, 0xc1, 0xe1, 0x96, 0xb6, 0xaf, 0x8a, 0x20, 0xc6, 0x05, 0xab, - 0x72, 0x65, 0x25, 0xbd, 0x6f, 0x08, 0xb7, 0x46, 0x20, 0x5f, 0x27, 0x66, 0x1a, 0x6b, 0xfe, 0x81, - 0xdc, 0xc3, 0x8d, 0x77, 0x5a, 0xa5, 0xff, 0x4c, 0xa4, 0x64, 0x5d, 0x6b, 0x18, 0x21, 0xbe, 0xf3, - 0x97, 0xf1, 0xff, 0x92, 0xc6, 0xe0, 0x0b, 0xc2, 0x3b, 0x23, 0x90, 0xe4, 0x39, 0xbe, 0x59, 0xbd, - 0x93, 0x6d, 0xfa, 0xf5, 0x4f, 0xf0, 0xef, 0x5e, 0x09, 0xd7, 0xae, 0x42, 0xbc, 0x5b, 0x47, 0x4c, - 0xb7, 0x4b, 0x2a, 0xdc, 0x3f, 0xba, 0x1a, 0xaf, 0x7a, 0x0e, 0x1f, 0x5f, 0x2c, 0x29, 0xba, 0x5c, - 0x52, 0xf4, 0x7b, 0x49, 0xd1, 0xa7, 0x15, 0xf5, 0x2e, 0x57, 0xd4, 0xfb, 0xb9, 0xa2, 0xde, 0x9b, - 0x23, 0x99, 0x98, 0xe9, 0x2c, 0x62, 0x13, 0x95, 0x06, 0x45, 0xaf, 0xe3, 0x33, 0x1e, 0x41, 0x59, - 0x05, 0xe7, 0x76, 0x41, 0xcc, 0x22, 0x17, 0x10, 0x35, 0xcb, 0xcd, 0xb8, 0xff, 0x27, 0x00, 0x00, - 0xff, 0xff, 0x9c, 0x47, 0x8e, 0xc7, 0xdc, 0x03, 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 { - // Deposit defines a method for depositing assets into a vault - Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) - // Withdraw defines a method for withdrawing assets into a vault - Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) { - out := new(MsgDepositResponse) - err := c.cc.Invoke(ctx, "/kava.earn.v1beta1.Msg/Deposit", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) { - out := new(MsgWithdrawResponse) - err := c.cc.Invoke(ctx, "/kava.earn.v1beta1.Msg/Withdraw", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // Deposit defines a method for depositing assets into a vault - Deposit(context.Context, *MsgDeposit) (*MsgDepositResponse, error) - // Withdraw defines a method for withdrawing assets into a vault - Withdraw(context.Context, *MsgWithdraw) (*MsgWithdrawResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Deposit(ctx context.Context, req *MsgDeposit) (*MsgDepositResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposit not implemented") -} -func (*UnimplementedMsgServer) Withdraw(ctx context.Context, req *MsgWithdraw) (*MsgWithdrawResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Withdraw not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Deposit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgDeposit) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Deposit(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.earn.v1beta1.Msg/Deposit", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Deposit(ctx, req.(*MsgDeposit)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Withdraw_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdraw) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Withdraw(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.earn.v1beta1.Msg/Withdraw", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Withdraw(ctx, req.(*MsgWithdraw)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.earn.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Deposit", - Handler: _Msg_Deposit_Handler, - }, - { - MethodName: "Withdraw", - Handler: _Msg_Withdraw_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/earn/v1beta1/tx.proto", -} - -func (m *MsgDeposit) 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 *MsgDeposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDeposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Strategy != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Strategy)) - i-- - dAtA[i] = 0x18 - } - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgDepositResponse) 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 *MsgDepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Shares.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *MsgWithdraw) 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 *MsgWithdraw) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdraw) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Strategy != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Strategy)) - i-- - dAtA[i] = 0x18 - } - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.From) > 0 { - i -= len(m.From) - copy(dAtA[i:], m.From) - i = encodeVarintTx(dAtA, i, uint64(len(m.From))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawResponse) 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 *MsgWithdrawResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Shares.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgDeposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - if m.Strategy != 0 { - n += 1 + sovTx(uint64(m.Strategy)) - } - return n -} - -func (m *MsgDepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Shares.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgWithdraw) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.From) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - if m.Strategy != 0 { - n += 1 + sovTx(uint64(m.Strategy)) - } - return n -} - -func (m *MsgWithdrawResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Shares.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgDeposit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDeposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDeposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Strategy", wireType) - } - m.Strategy = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Strategy |= StrategyType(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDepositResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Shares", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Shares.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdraw) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdraw: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdraw: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.From = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Strategy", wireType) - } - m.Strategy = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Strategy |= StrategyType(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Shares", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Shares.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/earn/types/vault.go b/x/earn/types/vault.go deleted file mode 100644 index 907c25e1..00000000 --- a/x/earn/types/vault.go +++ /dev/null @@ -1,171 +0,0 @@ -package types - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewVaultRecord returns a new VaultRecord with 0 supply. -func NewVaultRecord(vaultDenom string, amount sdk.Dec) VaultRecord { - return VaultRecord{ - TotalShares: NewVaultShare(vaultDenom, amount), - } -} - -// Validate returns an error if a VaultRecord is invalid. -func (vr *VaultRecord) Validate() error { - return vr.TotalShares.Validate() -} - -// VaultRecords is a slice of VaultRecord. -type VaultRecords []VaultRecord - -// Validate returns an error if a slice of VaultRecords is invalid. -func (vrs VaultRecords) Validate() error { - denoms := make(map[string]bool) - - for _, vr := range vrs { - if err := vr.Validate(); err != nil { - return err - } - - if denoms[vr.TotalShares.Denom] { - return fmt.Errorf("duplicate vault denom %s", vr.TotalShares.Denom) - } - - denoms[vr.TotalShares.Denom] = true - } - - return nil -} - -// NewVaultShareRecord returns a new VaultShareRecord with the provided supplied -// coins. -func NewVaultShareRecord(depositor sdk.AccAddress, shares VaultShares) VaultShareRecord { - return VaultShareRecord{ - Depositor: depositor, - Shares: shares, - } -} - -// Validate returns an error if an VaultShareRecord is invalid. -func (vsr VaultShareRecord) Validate() error { - if vsr.Depositor.Empty() { - return fmt.Errorf("depositor is empty") - } - - if err := vsr.Shares.Validate(); err != nil { - return fmt.Errorf("invalid vault share record shares: %w", err) - } - - return nil -} - -// VaultShareRecords is a slice of VaultShareRecord. -type VaultShareRecords []VaultShareRecord - -// Validate returns an error if a slice of VaultRecords is invalid. -func (vsrs VaultShareRecords) Validate() error { - addrs := make(map[string]bool) - - for _, vr := range vsrs { - if err := vr.Validate(); err != nil { - return err - } - - if _, found := addrs[vr.Depositor.String()]; found { - return fmt.Errorf("duplicate address %s", vr.Depositor.String()) - } - - addrs[vr.Depositor.String()] = true - } - - return nil -} - -// NewAllowedVault returns a new AllowedVault with the given values. -func NewAllowedVault( - denom string, - strategyTypes StrategyTypes, - isPrivateVault bool, - allowedDepositors []sdk.AccAddress, -) AllowedVault { - return AllowedVault{ - Denom: denom, - Strategies: strategyTypes, - IsPrivateVault: isPrivateVault, - AllowedDepositors: allowedDepositors, - } -} - -// Validate returns an error if the AllowedVault is invalid -func (a *AllowedVault) Validate() error { - if err := sdk.ValidateDenom(a.Denom); err != nil { - return errorsmod.Wrap(ErrInvalidVaultDenom, err.Error()) - } - - // Private -> 1+ allowed depositors - // Non-private -> 0 allowed depositors - if a.IsPrivateVault && len(a.AllowedDepositors) == 0 { - return fmt.Errorf("private vaults require non-empty AllowedDepositors") - } - - if !a.IsPrivateVault && len(a.AllowedDepositors) > 0 { - return fmt.Errorf("non-private vaults cannot have any AllowedDepositors") - } - - return a.Strategies.Validate() -} - -// IsStrategyAllowed returns true if the given strategy type is allowed for the -// vault. -func (a *AllowedVault) IsStrategyAllowed(strategy StrategyType) bool { - for _, s := range a.Strategies { - if s == strategy { - return true - } - } - - return false -} - -// IsAccountAllowed returns true if the given account is allowed to deposit into -// the vault. -func (a *AllowedVault) IsAccountAllowed(account sdk.AccAddress) bool { - // Anyone can deposit to non-private vaults - if !a.IsPrivateVault { - return true - } - - for _, addr := range a.AllowedDepositors { - if addr.Equals(account) { - return true - } - } - - return false -} - -// AllowedVaults is a slice of AllowedVault. -type AllowedVaults []AllowedVault - -// Validate returns an error if the AllowedVaults is invalid. -func (a AllowedVaults) Validate() error { - denoms := make(map[string]bool) - - for _, v := range a { - if err := v.Validate(); err != nil { - return err - } - - if denoms[v.Denom] { - return fmt.Errorf("duplicate vault denom %s", v.Denom) - } - - denoms[v.Denom] = true - } - - return nil -} diff --git a/x/earn/types/vault.pb.go b/x/earn/types/vault.pb.go deleted file mode 100644 index 55b37c2e..00000000 --- a/x/earn/types/vault.pb.go +++ /dev/null @@ -1,1174 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/earn/v1beta1/vault.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// AllowedVault is a vault that is allowed to be created. These can be -// modified via parameter governance. -type AllowedVault struct { - // Denom is the only supported denomination of the vault for deposits and withdrawals. - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - // VaultStrategy is the strategy used for this vault. - Strategies StrategyTypes `protobuf:"varint,2,rep,packed,name=strategies,proto3,enum=kava.earn.v1beta1.StrategyType,castrepeated=StrategyTypes" json:"strategies,omitempty"` - // IsPrivateVault is true if the vault only allows depositors contained in - // AllowedDepositors. - IsPrivateVault bool `protobuf:"varint,3,opt,name=is_private_vault,json=isPrivateVault,proto3" json:"is_private_vault,omitempty"` - // AllowedDepositors is a list of addresses that are allowed to deposit to - // this vault if IsPrivateVault is true. Addresses not contained in this list - // are not allowed to deposit into this vault. If IsPrivateVault is false, - // this should be empty and ignored. - AllowedDepositors []github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,4,rep,name=allowed_depositors,json=allowedDepositors,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"allowed_depositors,omitempty"` -} - -func (m *AllowedVault) Reset() { *m = AllowedVault{} } -func (m *AllowedVault) String() string { return proto.CompactTextString(m) } -func (*AllowedVault) ProtoMessage() {} -func (*AllowedVault) Descriptor() ([]byte, []int) { - return fileDescriptor_884eb89509fbdc04, []int{0} -} -func (m *AllowedVault) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AllowedVault) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AllowedVault.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 *AllowedVault) XXX_Merge(src proto.Message) { - xxx_messageInfo_AllowedVault.Merge(m, src) -} -func (m *AllowedVault) XXX_Size() int { - return m.Size() -} -func (m *AllowedVault) XXX_DiscardUnknown() { - xxx_messageInfo_AllowedVault.DiscardUnknown(m) -} - -var xxx_messageInfo_AllowedVault proto.InternalMessageInfo - -func (m *AllowedVault) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *AllowedVault) GetStrategies() StrategyTypes { - if m != nil { - return m.Strategies - } - return nil -} - -func (m *AllowedVault) GetIsPrivateVault() bool { - if m != nil { - return m.IsPrivateVault - } - return false -} - -func (m *AllowedVault) GetAllowedDepositors() []github_com_cosmos_cosmos_sdk_types.AccAddress { - if m != nil { - return m.AllowedDepositors - } - return nil -} - -// VaultRecord is the state of a vault. -type VaultRecord struct { - // TotalShares is the total distributed number of shares in the vault. - TotalShares VaultShare `protobuf:"bytes,1,opt,name=total_shares,json=totalShares,proto3" json:"total_shares"` -} - -func (m *VaultRecord) Reset() { *m = VaultRecord{} } -func (m *VaultRecord) String() string { return proto.CompactTextString(m) } -func (*VaultRecord) ProtoMessage() {} -func (*VaultRecord) Descriptor() ([]byte, []int) { - return fileDescriptor_884eb89509fbdc04, []int{1} -} -func (m *VaultRecord) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *VaultRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_VaultRecord.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 *VaultRecord) XXX_Merge(src proto.Message) { - xxx_messageInfo_VaultRecord.Merge(m, src) -} -func (m *VaultRecord) XXX_Size() int { - return m.Size() -} -func (m *VaultRecord) XXX_DiscardUnknown() { - xxx_messageInfo_VaultRecord.DiscardUnknown(m) -} - -var xxx_messageInfo_VaultRecord proto.InternalMessageInfo - -func (m *VaultRecord) GetTotalShares() VaultShare { - if m != nil { - return m.TotalShares - } - return VaultShare{} -} - -// VaultShareRecord defines the vault shares owned by a depositor. -type VaultShareRecord struct { - // Depositor represents the owner of the shares - Depositor github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=depositor,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"depositor,omitempty"` - // Shares represent the vault shares owned by the depositor. - Shares VaultShares `protobuf:"bytes,2,rep,name=shares,proto3,castrepeated=VaultShares" json:"shares"` -} - -func (m *VaultShareRecord) Reset() { *m = VaultShareRecord{} } -func (m *VaultShareRecord) String() string { return proto.CompactTextString(m) } -func (*VaultShareRecord) ProtoMessage() {} -func (*VaultShareRecord) Descriptor() ([]byte, []int) { - return fileDescriptor_884eb89509fbdc04, []int{2} -} -func (m *VaultShareRecord) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *VaultShareRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_VaultShareRecord.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 *VaultShareRecord) XXX_Merge(src proto.Message) { - xxx_messageInfo_VaultShareRecord.Merge(m, src) -} -func (m *VaultShareRecord) XXX_Size() int { - return m.Size() -} -func (m *VaultShareRecord) XXX_DiscardUnknown() { - xxx_messageInfo_VaultShareRecord.DiscardUnknown(m) -} - -var xxx_messageInfo_VaultShareRecord proto.InternalMessageInfo - -func (m *VaultShareRecord) GetDepositor() github_com_cosmos_cosmos_sdk_types.AccAddress { - if m != nil { - return m.Depositor - } - return nil -} - -func (m *VaultShareRecord) GetShares() VaultShares { - if m != nil { - return m.Shares - } - return nil -} - -// VaultShare defines shares of a vault owned by a depositor. -type VaultShare struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=amount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"amount"` -} - -func (m *VaultShare) Reset() { *m = VaultShare{} } -func (*VaultShare) ProtoMessage() {} -func (*VaultShare) Descriptor() ([]byte, []int) { - return fileDescriptor_884eb89509fbdc04, []int{3} -} -func (m *VaultShare) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *VaultShare) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_VaultShare.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 *VaultShare) XXX_Merge(src proto.Message) { - xxx_messageInfo_VaultShare.Merge(m, src) -} -func (m *VaultShare) XXX_Size() int { - return m.Size() -} -func (m *VaultShare) XXX_DiscardUnknown() { - xxx_messageInfo_VaultShare.DiscardUnknown(m) -} - -var xxx_messageInfo_VaultShare proto.InternalMessageInfo - -func (m *VaultShare) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func init() { - proto.RegisterType((*AllowedVault)(nil), "kava.earn.v1beta1.AllowedVault") - proto.RegisterType((*VaultRecord)(nil), "kava.earn.v1beta1.VaultRecord") - proto.RegisterType((*VaultShareRecord)(nil), "kava.earn.v1beta1.VaultShareRecord") - proto.RegisterType((*VaultShare)(nil), "kava.earn.v1beta1.VaultShare") -} - -func init() { proto.RegisterFile("kava/earn/v1beta1/vault.proto", fileDescriptor_884eb89509fbdc04) } - -var fileDescriptor_884eb89509fbdc04 = []byte{ - // 487 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x53, 0x3f, 0x6f, 0xd3, 0x40, - 0x14, 0xb7, 0x93, 0x10, 0xd1, 0x4b, 0xa8, 0x1a, 0xb7, 0x83, 0xa9, 0x54, 0xdb, 0xca, 0x80, 0xbc, - 0xd8, 0x56, 0xcb, 0x86, 0x18, 0x88, 0x15, 0x21, 0xc4, 0x84, 0xae, 0x85, 0x81, 0x25, 0xba, 0xd8, - 0x47, 0x6a, 0xd5, 0xc9, 0x45, 0x7e, 0x17, 0x97, 0x2c, 0x7c, 0x06, 0x46, 0x24, 0x16, 0xe6, 0xce, - 0xfd, 0x0c, 0xa8, 0x63, 0xd5, 0x09, 0x31, 0xa4, 0x28, 0xf9, 0x16, 0x4c, 0xe8, 0xfe, 0xa8, 0x8e, - 0x14, 0x10, 0x0c, 0x4c, 0xb9, 0xfb, 0xbd, 0xf7, 0x7e, 0x7f, 0x5e, 0x7c, 0xe8, 0xe0, 0x8c, 0x94, - 0x24, 0xa2, 0xa4, 0x98, 0x44, 0xe5, 0xe1, 0x90, 0x72, 0x72, 0x18, 0x95, 0x64, 0x96, 0xf3, 0x70, - 0x5a, 0x30, 0xce, 0xac, 0x8e, 0x28, 0x87, 0xa2, 0x1c, 0xea, 0xf2, 0xfe, 0xc3, 0x84, 0xc1, 0x98, - 0xc1, 0x40, 0x36, 0x44, 0xea, 0xa2, 0xba, 0xf7, 0xf7, 0x46, 0x6c, 0xc4, 0x14, 0x2e, 0x4e, 0x1a, - 0xf5, 0x36, 0x25, 0x80, 0x17, 0x84, 0xd3, 0xd1, 0x5c, 0x75, 0x74, 0x3f, 0xd7, 0x50, 0xbb, 0x97, - 0xe7, 0xec, 0x9c, 0xa6, 0x6f, 0x84, 0xb8, 0xb5, 0x87, 0xee, 0xa5, 0x74, 0xc2, 0xc6, 0xb6, 0xe9, - 0x99, 0xfe, 0x16, 0x56, 0x17, 0x0b, 0x23, 0xa4, 0x07, 0x33, 0x0a, 0x76, 0xcd, 0xab, 0xfb, 0xdb, - 0x47, 0x6e, 0xb8, 0xe1, 0x30, 0x3c, 0xd6, 0xec, 0x27, 0xf3, 0x29, 0x8d, 0x3b, 0x17, 0xb7, 0xee, - 0x83, 0x75, 0x04, 0xf0, 0x1a, 0x8b, 0xe5, 0xa3, 0x9d, 0x4c, 0x64, 0xc9, 0x4a, 0xc2, 0xe9, 0x40, - 0x46, 0xb7, 0xeb, 0x9e, 0xe9, 0xdf, 0xc7, 0xdb, 0x19, 0xbc, 0x52, 0xb0, 0xf2, 0x74, 0x8e, 0x2c, - 0xa2, 0x3c, 0x0e, 0x52, 0x3a, 0x65, 0x90, 0x71, 0x56, 0x80, 0xdd, 0xf0, 0xea, 0x7e, 0x3b, 0x7e, - 0xf1, 0x73, 0xe1, 0x06, 0xa3, 0x8c, 0x9f, 0xce, 0x86, 0x61, 0xc2, 0xc6, 0x7a, 0x2b, 0xfa, 0x27, - 0x80, 0xf4, 0x2c, 0xe2, 0x42, 0x39, 0xec, 0x25, 0x49, 0x2f, 0x4d, 0x0b, 0x0a, 0x70, 0x73, 0x19, - 0xec, 0xea, 0xdd, 0x69, 0x24, 0x9e, 0x73, 0x0a, 0xb8, 0xa3, 0x35, 0xfa, 0x77, 0x12, 0xdd, 0xd7, - 0xa8, 0x25, 0x1d, 0x60, 0x9a, 0xb0, 0x22, 0xb5, 0x9e, 0xa3, 0x36, 0x67, 0x9c, 0xe4, 0x03, 0x38, - 0x25, 0x05, 0x05, 0xb9, 0xa2, 0xd6, 0xd1, 0xc1, 0x6f, 0xf6, 0x20, 0xa7, 0x8e, 0x45, 0x57, 0xdc, - 0xb8, 0x5a, 0xb8, 0x06, 0x6e, 0xc9, 0x41, 0x89, 0x40, 0xf7, 0xab, 0x89, 0x76, 0xaa, 0x0e, 0x4d, - 0xfe, 0x0e, 0x6d, 0xdd, 0x85, 0x93, 0xcc, 0xff, 0x33, 0x5b, 0x45, 0x6d, 0xbd, 0x44, 0x4d, 0x6d, - 0x5f, 0xfc, 0x8d, 0x7f, 0xb5, 0xbf, 0x2b, 0xec, 0x5f, 0xdc, 0xba, 0xad, 0x0a, 0x03, 0xac, 0x19, - 0xba, 0x1f, 0x10, 0xaa, 0xe0, 0x3f, 0x7c, 0x3a, 0x27, 0xa8, 0x49, 0xc6, 0x6c, 0x36, 0xe1, 0x76, - 0x4d, 0xc0, 0xf1, 0x53, 0x41, 0xf8, 0x7d, 0xe1, 0x3e, 0xfa, 0x87, 0x60, 0x7d, 0x9a, 0xdc, 0x5c, - 0x06, 0x48, 0x27, 0xea, 0xd3, 0x04, 0x6b, 0xae, 0x27, 0x8d, 0x4f, 0x5f, 0x5c, 0x23, 0x7e, 0x76, - 0xb5, 0x74, 0xcc, 0xeb, 0xa5, 0x63, 0xfe, 0x58, 0x3a, 0xe6, 0xc7, 0x95, 0x63, 0x5c, 0xaf, 0x1c, - 0xe3, 0xdb, 0xca, 0x31, 0xde, 0xae, 0xb3, 0x8b, 0x7c, 0x41, 0x4e, 0x86, 0x20, 0x4f, 0xd1, 0x7b, - 0xf5, 0x20, 0xa4, 0xc2, 0xb0, 0x29, 0x9f, 0xc1, 0xe3, 0x5f, 0x01, 0x00, 0x00, 0xff, 0xff, 0xa0, - 0xa9, 0xba, 0x64, 0x8d, 0x03, 0x00, 0x00, -} - -func (m *AllowedVault) 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 *AllowedVault) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AllowedVault) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.AllowedDepositors) > 0 { - for iNdEx := len(m.AllowedDepositors) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.AllowedDepositors[iNdEx]) - copy(dAtA[i:], m.AllowedDepositors[iNdEx]) - i = encodeVarintVault(dAtA, i, uint64(len(m.AllowedDepositors[iNdEx]))) - i-- - dAtA[i] = 0x22 - } - } - if m.IsPrivateVault { - i-- - if m.IsPrivateVault { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x18 - } - if len(m.Strategies) > 0 { - dAtA2 := make([]byte, len(m.Strategies)*10) - var j1 int - for _, num := range m.Strategies { - for num >= 1<<7 { - dAtA2[j1] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j1++ - } - dAtA2[j1] = uint8(num) - j1++ - } - i -= j1 - copy(dAtA[i:], dAtA2[:j1]) - i = encodeVarintVault(dAtA, i, uint64(j1)) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintVault(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *VaultRecord) 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 *VaultRecord) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *VaultRecord) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.TotalShares.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintVault(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *VaultShareRecord) 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 *VaultShareRecord) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *VaultShareRecord) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Shares) > 0 { - for iNdEx := len(m.Shares) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Shares[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintVault(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintVault(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *VaultShare) 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 *VaultShare) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *VaultShare) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Amount.Size() - i -= size - if _, err := m.Amount.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintVault(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintVault(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintVault(dAtA []byte, offset int, v uint64) int { - offset -= sovVault(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *AllowedVault) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovVault(uint64(l)) - } - if len(m.Strategies) > 0 { - l = 0 - for _, e := range m.Strategies { - l += sovVault(uint64(e)) - } - n += 1 + sovVault(uint64(l)) + l - } - if m.IsPrivateVault { - n += 2 - } - if len(m.AllowedDepositors) > 0 { - for _, b := range m.AllowedDepositors { - l = len(b) - n += 1 + l + sovVault(uint64(l)) - } - } - return n -} - -func (m *VaultRecord) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.TotalShares.Size() - n += 1 + l + sovVault(uint64(l)) - return n -} - -func (m *VaultShareRecord) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovVault(uint64(l)) - } - if len(m.Shares) > 0 { - for _, e := range m.Shares { - l = e.Size() - n += 1 + l + sovVault(uint64(l)) - } - } - return n -} - -func (m *VaultShare) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovVault(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovVault(uint64(l)) - return n -} - -func sovVault(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozVault(x uint64) (n int) { - return sovVault(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *AllowedVault) 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 ErrIntOverflowVault - } - 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: AllowedVault: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AllowedVault: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - 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 ErrInvalidLengthVault - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthVault - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType == 0 { - var v StrategyType - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= StrategyType(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Strategies = append(m.Strategies, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthVault - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthVault - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - if elementCount != 0 && len(m.Strategies) == 0 { - m.Strategies = make([]StrategyType, 0, elementCount) - } - for iNdEx < postIndex { - var v StrategyType - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= StrategyType(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Strategies = append(m.Strategies, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field Strategies", wireType) - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field IsPrivateVault", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.IsPrivateVault = bool(v != 0) - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AllowedDepositors", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthVault - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthVault - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AllowedDepositors = append(m.AllowedDepositors, make([]byte, postIndex-iNdEx)) - copy(m.AllowedDepositors[len(m.AllowedDepositors)-1], dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipVault(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthVault - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *VaultRecord) 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 ErrIntOverflowVault - } - 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: VaultRecord: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: VaultRecord: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - 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 ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthVault - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthVault - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TotalShares.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipVault(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthVault - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *VaultShareRecord) 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 ErrIntOverflowVault - } - 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: VaultShareRecord: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: VaultShareRecord: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthVault - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthVault - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = append(m.Depositor[:0], dAtA[iNdEx:postIndex]...) - if m.Depositor == nil { - m.Depositor = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Shares", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthVault - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthVault - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Shares = append(m.Shares, VaultShare{}) - if err := m.Shares[len(m.Shares)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipVault(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthVault - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *VaultShare) 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 ErrIntOverflowVault - } - 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: VaultShare: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: VaultShare: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - 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 ErrInvalidLengthVault - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthVault - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - 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 ErrInvalidLengthVault - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthVault - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipVault(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthVault - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipVault(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, ErrIntOverflowVault - } - 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, ErrIntOverflowVault - } - 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, ErrIntOverflowVault - } - 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, ErrInvalidLengthVault - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupVault - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthVault - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthVault = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowVault = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupVault = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/earn/types/vault_test.go b/x/earn/types/vault_test.go deleted file mode 100644 index f56b78d9..00000000 --- a/x/earn/types/vault_test.go +++ /dev/null @@ -1,385 +0,0 @@ -package types_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/earn/types" -) - -func TestVaultRecordValidate(t *testing.T) { - type errArgs struct { - expectPass bool - contains string - } - - tests := []struct { - name string - vaultRecords types.VaultRecords - errArgs errArgs - }{ - { - name: "valid vault records", - vaultRecords: types.VaultRecords{ - { - TotalShares: types.NewVaultShare("usdx", sdk.NewDec(0)), - }, - { - TotalShares: types.NewVaultShare("ukava", sdk.NewDec(5)), - }, - }, - errArgs: errArgs{ - expectPass: true, - }, - }, - { - name: "invalid - duplicate denom", - vaultRecords: types.VaultRecords{ - { - TotalShares: types.NewVaultShare("usdx", sdk.NewDec(0)), - }, - { - TotalShares: types.NewVaultShare("usdx", sdk.NewDec(5)), - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "duplicate vault denom usdx", - }, - }, - { - name: "invalid - invalid denom", - vaultRecords: types.VaultRecords{ - { - TotalShares: types.VaultShare{Denom: "", Amount: sdk.NewDec(0)}, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "invalid denom", - }, - }, - { - name: "invalid - negative", - vaultRecords: types.VaultRecords{ - { - TotalShares: types.VaultShare{"usdx", sdk.NewDec(-5)}, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "vault share amount -5.000000000000000000 is negative", - }, - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - err := test.vaultRecords.Validate() - - if test.errArgs.expectPass { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), test.errArgs.contains) - } - }) - } -} - -func TestVaultShareRecordsValidate(t *testing.T) { - _, addrs := app.GeneratePrivKeyAddressPairs(2) - - type errArgs struct { - expectPass bool - contains string - } - - tests := []struct { - name string - vaultRecords types.VaultShareRecords - errArgs errArgs - }{ - { - name: "valid vault share records", - vaultRecords: types.VaultShareRecords{ - { - Depositor: addrs[0], - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(0)), - ), - }, - { - Depositor: addrs[1], - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(0)), - types.NewVaultShare("ukava", sdk.NewDec(5)), - ), - }, - }, - errArgs: errArgs{ - expectPass: true, - }, - }, - { - name: "invalid - duplicate address", - vaultRecords: types.VaultShareRecords{ - { - Depositor: addrs[0], - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(0)), - ), - }, - { - Depositor: addrs[0], - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(0)), - types.NewVaultShare("ukava", sdk.NewDec(5)), - ), - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "duplicate address", - }, - }, - { - name: "invalid - invalid address", - vaultRecords: types.VaultShareRecords{ - { - Depositor: sdk.AccAddress{}, - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(0)), - ), - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "depositor is empty", - }, - }, - { - name: "invalid - negative", - vaultRecords: types.VaultShareRecords{ - { - Depositor: addrs[0], - // Direct slice, not NewVaultShares() which panics - Shares: types.VaultShares{ - types.VaultShare{"usdx", sdk.NewDec(-5)}, - }, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "invalid vault share record shares: share -5.000000000000000000usdx amount is not positive", - }, - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - err := test.vaultRecords.Validate() - - if test.errArgs.expectPass { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), test.errArgs.contains) - } - }) - } -} - -func TestAllowedVaultsValidate(t *testing.T) { - type errArgs struct { - expectPass bool - contains string - } - - tests := []struct { - name string - vaultRecords types.AllowedVaults - errArgs errArgs - }{ - { - name: "valid vault share records", - vaultRecords: types.AllowedVaults{ - { - Denom: "usdx", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: []sdk.AccAddress{}, - }, - { - Denom: "busd", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: []sdk.AccAddress{}, - }, - }, - errArgs: errArgs{ - expectPass: true, - }, - }, - { - name: "invalid - duplicate denom", - vaultRecords: types.AllowedVaults{ - { - Denom: "usdx", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: []sdk.AccAddress{}, - }, - { - Denom: "usdx", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: []sdk.AccAddress{}, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "duplicate vault denom usdx", - }, - }, - { - name: "invalid - invalid denom", - vaultRecords: types.AllowedVaults{ - { - Denom: "", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: []sdk.AccAddress{}, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "invalid denom", - }, - }, - { - name: "invalid - invalid strategy", - vaultRecords: types.AllowedVaults{ - { - Denom: "usdx", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_UNSPECIFIED}, - IsPrivateVault: false, - AllowedDepositors: []sdk.AccAddress{}, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "invalid strategy STRATEGY_TYPE_UNSPECIFIED", - }, - }, - { - name: "invalid - private with no allowed depositors", - vaultRecords: types.AllowedVaults{ - { - Denom: "usdx", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: true, - AllowedDepositors: []sdk.AccAddress{}, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "private vaults require non-empty AllowedDepositors", - }, - }, - { - name: "invalid - public with allowed depositors", - vaultRecords: types.AllowedVaults{ - { - Denom: "usdx", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: []sdk.AccAddress{ - sdk.AccAddress("asdfasdf"), - }, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "non-private vaults cannot have any AllowedDepositors", - }, - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - err := test.vaultRecords.Validate() - - if test.errArgs.expectPass { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), test.errArgs.contains) - } - }) - } -} - -func TestIsStrategyAllowed(t *testing.T) { - vault := types.NewAllowedVault( - "usdx", - []types.StrategyType{types.STRATEGY_TYPE_HARD}, - true, - []sdk.AccAddress{}, - ) - - require.True(t, vault.IsStrategyAllowed(types.STRATEGY_TYPE_HARD)) - require.False(t, vault.IsStrategyAllowed(types.STRATEGY_TYPE_SAVINGS)) - require.False(t, vault.IsStrategyAllowed(types.STRATEGY_TYPE_UNSPECIFIED)) - require.False(t, vault.IsStrategyAllowed(12345)) -} - -func TestIsAccountAllowed_Private(t *testing.T) { - acc1 := sdk.AccAddress("acc1") - acc2 := sdk.AccAddress("acc2") - acc3 := sdk.AccAddress("acc3") - - vault := types.NewAllowedVault( - "usdx", - []types.StrategyType{types.STRATEGY_TYPE_HARD}, - true, - []sdk.AccAddress{acc1, acc2}, - ) - - assert.True(t, vault.IsAccountAllowed(acc1)) - assert.True(t, vault.IsAccountAllowed(acc2)) - assert.False(t, vault.IsAccountAllowed(acc3)) -} - -func TestIsAccountAllowed_Public(t *testing.T) { - acc1 := sdk.AccAddress("acc1") - acc2 := sdk.AccAddress("acc2") - acc3 := sdk.AccAddress("acc3") - - vault := types.NewAllowedVault( - "usdx", - []types.StrategyType{types.STRATEGY_TYPE_HARD}, - false, - []sdk.AccAddress{}, - ) - - assert.True(t, vault.IsAccountAllowed(acc1)) - assert.True(t, vault.IsAccountAllowed(acc2)) - assert.True(t, vault.IsAccountAllowed(acc3)) -} - -func TestNewVaultShareRecord(t *testing.T) { - _, addrs := app.GeneratePrivKeyAddressPairs(1) - - shares := types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(0)), - types.NewVaultShare("ukava", sdk.NewDec(5)), - ) - - shareRecord := types.NewVaultShareRecord(addrs[0], shares) - require.Equal(t, shares, shareRecord.Shares) -} diff --git a/x/evmutil/client/cli/address.go b/x/evmutil/client/cli/address.go index f748c63f..8f95c22d 100644 --- a/x/evmutil/client/cli/address.go +++ b/x/evmutil/client/cli/address.go @@ -5,9 +5,9 @@ import ( "fmt" "strings" + "github.com/0glabs/0g-chain/x/evmutil/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/common" - "github.com/kava-labs/kava/x/evmutil/types" ) // ParseAddrFromHexOrBech32 parses a string address that can be either a hex or @@ -46,12 +46,12 @@ func ParseOrQueryConversionPairAddress( if err := sdk.ValidateDenom(addrOrDenom); err != nil { return common.Address{}, fmt.Errorf( - "Kava ERC20 '%s' is not a valid hex address or denom", + "0gChain ERC20 '%s' is not a valid hex address or denom", addrOrDenom, ) } - // Valid denom, try looking up as denom to get corresponding Kava ERC20 address + // Valid denom, try looking up as denom to get corresponding 0gChain ERC20 address paramsRes, err := queryClient.Params( context.Background(), &types.QueryParamsRequest{}, @@ -67,7 +67,7 @@ func ParseOrQueryConversionPairAddress( } return common.Address{}, fmt.Errorf( - "Kava ERC20 '%s' is not a valid hex address or denom (did not match any denoms in queried enabled conversion pairs)", + "0gChain ERC20 '%s' is not a valid hex address or denom (did not match any denoms in queried enabled conversion pairs)", addrOrDenom, ) } diff --git a/x/evmutil/client/cli/query.go b/x/evmutil/client/cli/query.go index e0539800..0b693364 100644 --- a/x/evmutil/client/cli/query.go +++ b/x/evmutil/client/cli/query.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/version" "github.com/spf13/cobra" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/types" ) // GetQueryCmd returns the cli query commands for this module diff --git a/x/evmutil/client/cli/tx.go b/x/evmutil/client/cli/tx.go index 22201af6..2608dbaf 100644 --- a/x/evmutil/client/cli/tx.go +++ b/x/evmutil/client/cli/tx.go @@ -14,7 +14,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/types" ) // GetTxCmd returns the transaction commands for this module @@ -45,7 +45,7 @@ func GetTxCmd() *cobra.Command { func getCmdConvertEvmERC20FromCoin() *cobra.Command { return &cobra.Command{ - Use: "convert-evm-erc20-from-coin [Kava EVM address] [coin]", + Use: "convert-evm-erc20-from-coin [0gChain EVM address] [coin]", Short: "EVM-native asset: converts a coin on Cosmos co-chain to an ERC20 on EVM co-chain", Example: fmt.Sprintf( `%s tx %s convert-evm-erc20-from-coin 0x7Bbf300890857b8c241b219C6a489431669b3aFA 500000000erc20/usdc --from --gas 2000000`, @@ -81,10 +81,10 @@ func getCmdConvertEvmERC20FromCoin() *cobra.Command { func getCmdConvertEvmERC20ToCoin() *cobra.Command { return &cobra.Command{ - Use: "convert-evm-erc20-to-coin [Kava receiver address] [Kava ERC20 address] [amount]", + Use: "convert-evm-erc20-to-coin [0gChain receiver address] [0gChain ERC20 address] [amount]", Short: "EVM-native asset: converts an ERC20 on EVM co-chain to a coin on Cosmos co-chain", Example: fmt.Sprintf(` -%[1]s tx %[2]s convert-evm-erc20-to-coin kava10wlnqzyss4accfqmyxwx5jy5x9nfkwh6qm7n4t 0xeA7100edA2f805356291B0E55DaD448599a72C6d 1000000000000000 --from --gas 1000000 +%[1]s tx %[2]s convert-evm-erc20-to-coin 0g10wlnqzyss4accfqmyxwx5jy5x9nfkwh6qm7n4t 0xeA7100edA2f805356291B0E55DaD448599a72C6d 1000000000000000 --from --gas 1000000 `, version.AppName, types.ModuleName, ), Args: cobra.ExactArgs(3), @@ -163,11 +163,11 @@ func getCmdMsgConvertCosmosCoinToERC20() *cobra.Command { func getCmdMsgConvertCosmosCoinFromERC20() *cobra.Command { return &cobra.Command{ - Use: "convert-cosmos-coin-from-erc20 [receiver_kava_address] [amount] [flags]", + Use: "convert-cosmos-coin-from-erc20 [receiver_0g_address] [amount] [flags]", Short: "Cosmos-native asset: converts an ERC20 on EVM co-chain back to a coin on Cosmos co-chain", Example: fmt.Sprintf( - `Convert ERC20 representation of 500 ATOM back to a Cosmos coin, sending to kava1q0dkky0505r555etn6u2nz4h4kjcg5y8dg863a: - %s tx %s convert-cosmos-coin-from-erc20 kava1q0dkky0505r555etn6u2nz4h4kjcg5y8dg863a 500000000ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 --from --gas 2000000`, + `Convert ERC20 representation of 500 ATOM back to a Cosmos coin, sending to 0g1q0dkky0505r555etn6u2nz4h4kjcg5y8dg863a: + %s tx %s convert-cosmos-coin-from-erc20 0g1q0dkky0505r555etn6u2nz4h4kjcg5y8dg863a 500000000ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 --from --gas 2000000`, version.AppName, types.ModuleName, ), Args: cobra.ExactArgs(2), @@ -179,7 +179,7 @@ func getCmdMsgConvertCosmosCoinFromERC20() *cobra.Command { receiver, err := sdk.AccAddressFromBech32(args[0]) if err != nil { - return fmt.Errorf("receiver '%s' is an invalid kava address", args[0]) + return fmt.Errorf("receiver '%s' is an invalid 0g-chain address", args[0]) } amount, err := sdk.ParseCoinNormalized(args[1]) diff --git a/x/evmutil/genesis.go b/x/evmutil/genesis.go index 209dda25..8099da14 100644 --- a/x/evmutil/genesis.go +++ b/x/evmutil/genesis.go @@ -5,8 +5,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/evmutil/keeper" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/keeper" + "github.com/0glabs/0g-chain/x/evmutil/types" ) // InitGenesis initializes the store state from a genesis state. diff --git a/x/evmutil/genesis_test.go b/x/evmutil/genesis_test.go index 0c71f9ff..5a97c558 100644 --- a/x/evmutil/genesis_test.go +++ b/x/evmutil/genesis_test.go @@ -6,10 +6,10 @@ import ( "github.com/stretchr/testify/suite" sdkmath "cosmossdk.io/math" + "github.com/0glabs/0g-chain/x/evmutil" + "github.com/0glabs/0g-chain/x/evmutil/testutil" + "github.com/0glabs/0g-chain/x/evmutil/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/kava-labs/kava/x/evmutil" - "github.com/kava-labs/kava/x/evmutil/testutil" - "github.com/kava-labs/kava/x/evmutil/types" ) type genesisTestSuite struct { @@ -40,8 +40,8 @@ func (s *genesisTestSuite) TestInitGenesis_SetAccounts() { func (s *genesisTestSuite) TestInitGenesis_SetParams() { params := types.DefaultParams() conversionPair := types.ConversionPair{ - KavaERC20Address: testutil.MustNewInternalEVMAddressFromString("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").Bytes(), - Denom: "weth", + ZgchainERC20Address: testutil.MustNewInternalEVMAddressFromString("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").Bytes(), + Denom: "weth", } params.EnabledConversionPairs = []types.ConversionPair{conversionPair} gs := types.NewGenesisState( @@ -92,13 +92,13 @@ func (s *genesisTestSuite) TestExportGenesis() { params := types.DefaultParams() params.EnabledConversionPairs = []types.ConversionPair{ { - KavaERC20Address: testutil.MustNewInternalEVMAddressFromString("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").Bytes(), - Denom: "weth"}, + ZgchainERC20Address: testutil.MustNewInternalEVMAddressFromString("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").Bytes(), + Denom: "weth"}, } params.AllowedCosmosDenoms = []types.AllowedCosmosCoinERC20Token{ { CosmosDenom: "hard", - Name: "Kava EVM HARD", + Name: "0gChain EVM HARD", Symbol: "HARD", Decimals: 6, }, diff --git a/x/evmutil/keeper/bank_keeper.go b/x/evmutil/keeper/bank_keeper.go index 8061561b..7d3d9bf1 100644 --- a/x/evmutil/keeper/bank_keeper.go +++ b/x/evmutil/keeper/bank_keeper.go @@ -9,56 +9,49 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" evmtypes "github.com/evmos/ethermint/x/evm/types" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/chaincfg" + "github.com/0glabs/0g-chain/x/evmutil/types" ) -const ( - // EvmDenom is the gas denom used by the evm - EvmDenom = "akava" - - // CosmosDenom is the gas denom used by the kava app - CosmosDenom = "ukava" -) - -// ConversionMultiplier is the conversion multiplier between akava and ukava -var ConversionMultiplier = sdkmath.NewInt(1_000_000_000_000) +// ConversionMultiplier is the conversion multiplier between neuron and a0gi +var ConversionMultiplier = sdkmath.NewInt(chaincfg.ConversionMultiplier) var _ evmtypes.BankKeeper = EvmBankKeeper{} // EvmBankKeeper is a BankKeeper wrapper for the x/evm module to allow the use -// of the 18 decimal akava coin on the evm. -// x/evm consumes gas and send coins by minting and burning akava coins in its module +// of the 18 decimal neuron coin on the evm. +// x/evm consumes gas and send coins by minting and burning neuron coins in its module // account and then sending the funds to the target account. -// This keeper uses both the ukava coin and a separate akava balance to manage the +// This keeper uses both the a0gi coin and a separate neuron balance to manage the // extra percision needed by the evm. type EvmBankKeeper struct { - akavaKeeper Keeper - bk types.BankKeeper - ak types.AccountKeeper + baseKeeper Keeper + bk types.BankKeeper + ak types.AccountKeeper } -func NewEvmBankKeeper(akavaKeeper Keeper, bk types.BankKeeper, ak types.AccountKeeper) EvmBankKeeper { +func NewEvmBankKeeper(baseKeeper Keeper, bk types.BankKeeper, ak types.AccountKeeper) EvmBankKeeper { return EvmBankKeeper{ - akavaKeeper: akavaKeeper, - bk: bk, - ak: ak, + baseKeeper: baseKeeper, + bk: bk, + ak: ak, } } -// GetBalance returns the total **spendable** balance of akava for a given account by address. +// GetBalance returns the total **spendable** balance of neuron for a given account by address. func (k EvmBankKeeper) GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin { - if denom != EvmDenom { - panic(fmt.Errorf("only evm denom %s is supported by EvmBankKeeper", EvmDenom)) + if denom != chaincfg.BaseDenom { + panic(fmt.Errorf("only evm denom %s is supported by EvmBankKeeper", chaincfg.BaseDenom)) } spendableCoins := k.bk.SpendableCoins(ctx, addr) - ukava := spendableCoins.AmountOf(CosmosDenom) - akava := k.akavaKeeper.GetBalance(ctx, addr) - total := ukava.Mul(ConversionMultiplier).Add(akava) - return sdk.NewCoin(EvmDenom, total) + a0gi := spendableCoins.AmountOf(chaincfg.DisplayDenom) + neuron := k.baseKeeper.GetBalance(ctx, addr) + total := a0gi.Mul(ConversionMultiplier).Add(neuron) + return sdk.NewCoin(chaincfg.BaseDenom, total) } -// SendCoins transfers akava coins from a AccAddress to an AccAddress. +// SendCoins transfers neuron coins from a AccAddress to an AccAddress. func (k EvmBankKeeper) SendCoins(ctx sdk.Context, senderAddr sdk.AccAddress, recipientAddr sdk.AccAddress, amt sdk.Coins) error { // SendCoins method is not used by the evm module, but is required by the // evmtypes.BankKeeper interface. This must be updated if the evm module @@ -66,101 +59,101 @@ func (k EvmBankKeeper) SendCoins(ctx sdk.Context, senderAddr sdk.AccAddress, rec panic("not implemented") } -// SendCoinsFromModuleToAccount transfers akava coins from a ModuleAccount to an AccAddress. +// SendCoinsFromModuleToAccount transfers neuron coins from a ModuleAccount to an AccAddress. // It will panic if the module account does not exist. An error is returned if the recipient // address is black-listed or if sending the tokens fails. func (k EvmBankKeeper) SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error { - ukava, akava, err := SplitAkavaCoins(amt) + a0gi, neuron, err := SplitNeuronCoins(amt) if err != nil { return err } - if ukava.Amount.IsPositive() { - if err := k.bk.SendCoinsFromModuleToAccount(ctx, senderModule, recipientAddr, sdk.NewCoins(ukava)); err != nil { + if a0gi.Amount.IsPositive() { + if err := k.bk.SendCoinsFromModuleToAccount(ctx, senderModule, recipientAddr, sdk.NewCoins(a0gi)); err != nil { return err } } senderAddr := k.GetModuleAddress(senderModule) - if err := k.ConvertOneUkavaToAkavaIfNeeded(ctx, senderAddr, akava); err != nil { + if err := k.ConvertOneA0giToNeuronIfNeeded(ctx, senderAddr, neuron); err != nil { return err } - if err := k.akavaKeeper.SendBalance(ctx, senderAddr, recipientAddr, akava); err != nil { + if err := k.baseKeeper.SendBalance(ctx, senderAddr, recipientAddr, neuron); err != nil { return err } - return k.ConvertAkavaToUkava(ctx, recipientAddr) + return k.ConvertNeuronToA0gi(ctx, recipientAddr) } -// SendCoinsFromAccountToModule transfers akava coins from an AccAddress to a ModuleAccount. +// SendCoinsFromAccountToModule transfers neuron coins from an AccAddress to a ModuleAccount. // It will panic if the module account does not exist. func (k EvmBankKeeper) SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error { - ukava, akavaNeeded, err := SplitAkavaCoins(amt) + a0gi, neuronNeeded, err := SplitNeuronCoins(amt) if err != nil { return err } - if ukava.IsPositive() { - if err := k.bk.SendCoinsFromAccountToModule(ctx, senderAddr, recipientModule, sdk.NewCoins(ukava)); err != nil { + if a0gi.IsPositive() { + if err := k.bk.SendCoinsFromAccountToModule(ctx, senderAddr, recipientModule, sdk.NewCoins(a0gi)); err != nil { return err } } - if err := k.ConvertOneUkavaToAkavaIfNeeded(ctx, senderAddr, akavaNeeded); err != nil { + if err := k.ConvertOneA0giToNeuronIfNeeded(ctx, senderAddr, neuronNeeded); err != nil { return err } recipientAddr := k.GetModuleAddress(recipientModule) - if err := k.akavaKeeper.SendBalance(ctx, senderAddr, recipientAddr, akavaNeeded); err != nil { + if err := k.baseKeeper.SendBalance(ctx, senderAddr, recipientAddr, neuronNeeded); err != nil { return err } - return k.ConvertAkavaToUkava(ctx, recipientAddr) + return k.ConvertNeuronToA0gi(ctx, recipientAddr) } -// MintCoins mints akava coins by minting the equivalent ukava coins and any remaining akava coins. +// MintCoins mints neuron coins by minting the equivalent a0gi coins and any remaining neuron coins. // It will panic if the module account does not exist or is unauthorized. func (k EvmBankKeeper) MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error { - ukava, akava, err := SplitAkavaCoins(amt) + a0gi, neuron, err := SplitNeuronCoins(amt) if err != nil { return err } - if ukava.IsPositive() { - if err := k.bk.MintCoins(ctx, moduleName, sdk.NewCoins(ukava)); err != nil { + if a0gi.IsPositive() { + if err := k.bk.MintCoins(ctx, moduleName, sdk.NewCoins(a0gi)); err != nil { return err } } recipientAddr := k.GetModuleAddress(moduleName) - if err := k.akavaKeeper.AddBalance(ctx, recipientAddr, akava); err != nil { + if err := k.baseKeeper.AddBalance(ctx, recipientAddr, neuron); err != nil { return err } - return k.ConvertAkavaToUkava(ctx, recipientAddr) + return k.ConvertNeuronToA0gi(ctx, recipientAddr) } -// BurnCoins burns akava coins by burning the equivalent ukava coins and any remaining akava coins. +// BurnCoins burns neuron coins by burning the equivalent a0gi coins and any remaining neuron coins. // It will panic if the module account does not exist or is unauthorized. func (k EvmBankKeeper) BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error { - ukava, akava, err := SplitAkavaCoins(amt) + a0gi, neuron, err := SplitNeuronCoins(amt) if err != nil { return err } - if ukava.IsPositive() { - if err := k.bk.BurnCoins(ctx, moduleName, sdk.NewCoins(ukava)); err != nil { + if a0gi.IsPositive() { + if err := k.bk.BurnCoins(ctx, moduleName, sdk.NewCoins(a0gi)); err != nil { return err } } moduleAddr := k.GetModuleAddress(moduleName) - if err := k.ConvertOneUkavaToAkavaIfNeeded(ctx, moduleAddr, akava); err != nil { + if err := k.ConvertOneA0giToNeuronIfNeeded(ctx, moduleAddr, neuron); err != nil { return err } - return k.akavaKeeper.RemoveBalance(ctx, moduleAddr, akava) + return k.baseKeeper.RemoveBalance(ctx, moduleAddr, neuron) } // IsSendEnabledCoins checks the coins provided and returns an ErrSendDisabled @@ -173,51 +166,51 @@ func (k EvmBankKeeper) IsSendEnabledCoins(ctx sdk.Context, coins ...sdk.Coin) er panic("not implemented") } -// ConvertOneUkavaToAkavaIfNeeded converts 1 ukava to akava for an address if -// its akava balance is smaller than the akavaNeeded amount. -func (k EvmBankKeeper) ConvertOneUkavaToAkavaIfNeeded(ctx sdk.Context, addr sdk.AccAddress, akavaNeeded sdkmath.Int) error { - akavaBal := k.akavaKeeper.GetBalance(ctx, addr) - if akavaBal.GTE(akavaNeeded) { +// ConvertOneA0giToNeuronIfNeeded converts 1 a0gi to neuron for an address if +// its neuron balance is smaller than the neuronNeeded amount. +func (k EvmBankKeeper) ConvertOneA0giToNeuronIfNeeded(ctx sdk.Context, addr sdk.AccAddress, neuronNeeded sdkmath.Int) error { + neuronBal := k.baseKeeper.GetBalance(ctx, addr) + if neuronBal.GTE(neuronNeeded) { return nil } - ukavaToStore := sdk.NewCoins(sdk.NewCoin(CosmosDenom, sdk.OneInt())) - if err := k.bk.SendCoinsFromAccountToModule(ctx, addr, types.ModuleName, ukavaToStore); err != nil { + a0giToStore := sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdk.OneInt())) + if err := k.bk.SendCoinsFromAccountToModule(ctx, addr, types.ModuleName, a0giToStore); err != nil { return err } - // add 1ukava equivalent of akava to addr - akavaToReceive := ConversionMultiplier - if err := k.akavaKeeper.AddBalance(ctx, addr, akavaToReceive); err != nil { + // add 1a0gi equivalent of neuron to addr + neuronToReceive := ConversionMultiplier + if err := k.baseKeeper.AddBalance(ctx, addr, neuronToReceive); err != nil { return err } return nil } -// ConvertAkavaToUkava converts all available akava to ukava for a given AccAddress. -func (k EvmBankKeeper) ConvertAkavaToUkava(ctx sdk.Context, addr sdk.AccAddress) error { - totalAkava := k.akavaKeeper.GetBalance(ctx, addr) - ukava, _, err := SplitAkavaCoins(sdk.NewCoins(sdk.NewCoin(EvmDenom, totalAkava))) +// ConvertNeuronToA0gi converts all available neuron to a0gi for a given AccAddress. +func (k EvmBankKeeper) ConvertNeuronToA0gi(ctx sdk.Context, addr sdk.AccAddress) error { + totalNeuron := k.baseKeeper.GetBalance(ctx, addr) + a0gi, _, err := SplitNeuronCoins(sdk.NewCoins(sdk.NewCoin(chaincfg.BaseDenom, totalNeuron))) if err != nil { return err } - // do nothing if account does not have enough akava for a single ukava - ukavaToReceive := ukava.Amount - if !ukavaToReceive.IsPositive() { + // do nothing if account does not have enough neuron for a single a0gi + a0giToReceive := a0gi.Amount + if !a0giToReceive.IsPositive() { return nil } - // remove akava used for converting to ukava - akavaToBurn := ukavaToReceive.Mul(ConversionMultiplier) - finalBal := totalAkava.Sub(akavaToBurn) - if err := k.akavaKeeper.SetBalance(ctx, addr, finalBal); err != nil { + // remove neuron used for converting to a0gi + neuronToBurn := a0giToReceive.Mul(ConversionMultiplier) + finalBal := totalNeuron.Sub(neuronToBurn) + if err := k.baseKeeper.SetBalance(ctx, addr, finalBal); err != nil { return err } fromAddr := k.GetModuleAddress(types.ModuleName) - if err := k.bk.SendCoins(ctx, fromAddr, addr, sdk.NewCoins(ukava)); err != nil { + if err := k.bk.SendCoins(ctx, fromAddr, addr, sdk.NewCoins(a0gi)); err != nil { return err } @@ -232,35 +225,35 @@ func (k EvmBankKeeper) GetModuleAddress(moduleName string) sdk.AccAddress { return addr } -// SplitAkavaCoins splits akava coins to the equivalent ukava coins and any remaining akava balance. -// An error will be returned if the coins are not valid or if the coins are not the akava denom. -func SplitAkavaCoins(coins sdk.Coins) (sdk.Coin, sdkmath.Int, error) { - akava := sdk.ZeroInt() - ukava := sdk.NewCoin(CosmosDenom, sdk.ZeroInt()) +// SplitNeuronCoins splits neuron coins to the equivalent a0gi coins and any remaining neuron balance. +// An error will be returned if the coins are not valid or if the coins are not the neuron denom. +func SplitNeuronCoins(coins sdk.Coins) (sdk.Coin, sdkmath.Int, error) { + neuron := sdk.ZeroInt() + a0gi := sdk.NewCoin(chaincfg.DisplayDenom, sdk.ZeroInt()) if len(coins) == 0 { - return ukava, akava, nil + return a0gi, neuron, nil } if err := ValidateEvmCoins(coins); err != nil { - return ukava, akava, err + return a0gi, neuron, err } // note: we should always have len(coins) == 1 here since coins cannot have dup denoms after we validate. coin := coins[0] remainingBalance := coin.Amount.Mod(ConversionMultiplier) if remainingBalance.IsPositive() { - akava = remainingBalance + neuron = remainingBalance } - ukavaAmount := coin.Amount.Quo(ConversionMultiplier) - if ukavaAmount.IsPositive() { - ukava = sdk.NewCoin(CosmosDenom, ukavaAmount) + a0giAmount := coin.Amount.Quo(ConversionMultiplier) + if a0giAmount.IsPositive() { + a0gi = sdk.NewCoin(chaincfg.DisplayDenom, a0giAmount) } - return ukava, akava, nil + return a0gi, neuron, nil } -// ValidateEvmCoins validates the coins from evm is valid and is the EvmDenom (akava). +// ValidateEvmCoins validates the coins from evm is valid and is the chaincfg.BaseDenom (neuron). func ValidateEvmCoins(coins sdk.Coins) error { if len(coins) == 0 { return nil @@ -271,9 +264,9 @@ func ValidateEvmCoins(coins sdk.Coins) error { return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, coins.String()) } - // validate that coin denom is akava - if len(coins) != 1 || coins[0].Denom != EvmDenom { - errMsg := fmt.Sprintf("invalid evm coin denom, only %s is supported", EvmDenom) + // validate that coin denom is neuron + if len(coins) != 1 || coins[0].Denom != chaincfg.BaseDenom { + errMsg := fmt.Sprintf("invalid evm coin denom, only %s is supported", chaincfg.BaseDenom) return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, errMsg) } diff --git a/x/evmutil/keeper/bank_keeper_test.go b/x/evmutil/keeper/bank_keeper_test.go index 96b3b747..fa8a3558 100644 --- a/x/evmutil/keeper/bank_keeper_test.go +++ b/x/evmutil/keeper/bank_keeper_test.go @@ -13,9 +13,10 @@ import ( vesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" evmtypes "github.com/evmos/ethermint/x/evm/types" - "github.com/kava-labs/kava/x/evmutil/keeper" - "github.com/kava-labs/kava/x/evmutil/testutil" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/chaincfg" + "github.com/0glabs/0g-chain/x/evmutil/keeper" + "github.com/0glabs/0g-chain/x/evmutil/testutil" + "github.com/0glabs/0g-chain/x/evmutil/types" ) type evmBankKeeperTestSuite struct { @@ -27,8 +28,8 @@ func (suite *evmBankKeeperTestSuite) SetupTest() { } func (suite *evmBankKeeperTestSuite) TestGetBalance_ReturnsSpendable() { - startingCoins := sdk.NewCoins(sdk.NewInt64Coin("ukava", 10)) - startingAkava := sdkmath.NewInt(100) + startingCoins := sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 10)) + startingNeuron := sdkmath.NewInt(100) now := tmtime.Now() endTime := now.Add(24 * time.Hour) @@ -38,20 +39,20 @@ func (suite *evmBankKeeperTestSuite) TestGetBalance_ReturnsSpendable() { err := suite.App.FundAccount(suite.Ctx, suite.Addrs[0], startingCoins) suite.Require().NoError(err) - err = suite.Keeper.SetBalance(suite.Ctx, suite.Addrs[0], startingAkava) + err = suite.Keeper.SetBalance(suite.Ctx, suite.Addrs[0], startingNeuron) suite.Require().NoError(err) - coin := suite.EvmBankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], "akava") - suite.Require().Equal(startingAkava, coin.Amount) + coin := suite.EvmBankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], chaincfg.BaseDenom) + suite.Require().Equal(startingNeuron, coin.Amount) ctx := suite.Ctx.WithBlockTime(now.Add(12 * time.Hour)) - coin = suite.EvmBankKeeper.GetBalance(ctx, suite.Addrs[0], "akava") + coin = suite.EvmBankKeeper.GetBalance(ctx, suite.Addrs[0], chaincfg.BaseDenom) suite.Require().Equal(sdkmath.NewIntFromUint64(5_000_000_000_100), coin.Amount) } func (suite *evmBankKeeperTestSuite) TestGetBalance_NotEvmDenom() { suite.Require().Panics(func() { - suite.EvmBankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], "ukava") + suite.EvmBankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], chaincfg.DisplayDenom) }) suite.Require().Panics(func() { suite.EvmBankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], "busd") @@ -65,39 +66,39 @@ func (suite *evmBankKeeperTestSuite) TestGetBalance() { expAmount sdkmath.Int }{ { - "ukava with akava", + "a0gi with neuron", sdk.NewCoins( - sdk.NewInt64Coin("akava", 100), - sdk.NewInt64Coin("ukava", 10), + sdk.NewInt64Coin(chaincfg.BaseDenom, 100), + sdk.NewInt64Coin(chaincfg.DisplayDenom, 10), ), sdkmath.NewInt(10_000_000_000_100), }, { - "just akava", + "just neuron", sdk.NewCoins( - sdk.NewInt64Coin("akava", 100), + sdk.NewInt64Coin(chaincfg.BaseDenom, 100), sdk.NewInt64Coin("busd", 100), ), sdkmath.NewInt(100), }, { - "just ukava", + "just a0gi", sdk.NewCoins( - sdk.NewInt64Coin("ukava", 10), + sdk.NewInt64Coin(chaincfg.DisplayDenom, 10), sdk.NewInt64Coin("busd", 100), ), sdkmath.NewInt(10_000_000_000_000), }, { - "no ukava or akava", + "no a0gi or neuron", sdk.NewCoins(), sdk.ZeroInt(), }, { - "with avaka that is more than 1 ukava", + "with avaka that is more than 1 a0gi", sdk.NewCoins( - sdk.NewInt64Coin("akava", 20_000_000_000_220), - sdk.NewInt64Coin("ukava", 11), + sdk.NewInt64Coin(chaincfg.BaseDenom, 20_000_000_000_220), + sdk.NewInt64Coin(chaincfg.DisplayDenom, 11), ), sdkmath.NewInt(31_000_000_000_220), }, @@ -107,8 +108,8 @@ func (suite *evmBankKeeperTestSuite) TestGetBalance() { suite.Run(tt.name, func() { suite.SetupTest() - suite.FundAccountWithKava(suite.Addrs[0], tt.startingAmount) - coin := suite.EvmBankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], "akava") + suite.FundAccountWithZgChain(suite.Addrs[0], tt.startingAmount) + coin := suite.EvmBankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], chaincfg.BaseDenom) suite.Require().Equal(tt.expAmount, coin.Amount) }) } @@ -116,8 +117,8 @@ func (suite *evmBankKeeperTestSuite) TestGetBalance() { func (suite *evmBankKeeperTestSuite) TestSendCoinsFromModuleToAccount() { startingModuleCoins := sdk.NewCoins( - sdk.NewInt64Coin("akava", 200), - sdk.NewInt64Coin("ukava", 100), + sdk.NewInt64Coin(chaincfg.BaseDenom, 200), + sdk.NewInt64Coin(chaincfg.DisplayDenom, 100), ) tests := []struct { name string @@ -127,102 +128,102 @@ func (suite *evmBankKeeperTestSuite) TestSendCoinsFromModuleToAccount() { hasErr bool }{ { - "send more than 1 ukava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 12_000_000_000_010)), + "send more than 1 a0gi", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 12_000_000_000_010)), sdk.Coins{}, sdk.NewCoins( - sdk.NewInt64Coin("akava", 10), - sdk.NewInt64Coin("ukava", 12), + sdk.NewInt64Coin(chaincfg.BaseDenom, 10), + sdk.NewInt64Coin(chaincfg.DisplayDenom, 12), ), false, }, { - "send less than 1 ukava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 122)), + "send less than 1 a0gi", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 122)), sdk.Coins{}, sdk.NewCoins( - sdk.NewInt64Coin("akava", 122), - sdk.NewInt64Coin("ukava", 0), + sdk.NewInt64Coin(chaincfg.BaseDenom, 122), + sdk.NewInt64Coin(chaincfg.DisplayDenom, 0), ), false, }, { - "send an exact amount of ukava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 98_000_000_000_000)), + "send an exact amount of a0gi", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 98_000_000_000_000)), sdk.Coins{}, sdk.NewCoins( - sdk.NewInt64Coin("akava", 0o0), - sdk.NewInt64Coin("ukava", 98), + sdk.NewInt64Coin(chaincfg.BaseDenom, 0o0), + sdk.NewInt64Coin(chaincfg.DisplayDenom, 98), ), false, }, { - "send no akava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 0)), + "send no neuron", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 0)), sdk.Coins{}, sdk.NewCoins( - sdk.NewInt64Coin("akava", 0), - sdk.NewInt64Coin("ukava", 0), + sdk.NewInt64Coin(chaincfg.BaseDenom, 0), + sdk.NewInt64Coin(chaincfg.DisplayDenom, 0), ), false, }, { "errors if sending other coins", - sdk.NewCoins(sdk.NewInt64Coin("akava", 500), sdk.NewInt64Coin("busd", 1000)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 500), sdk.NewInt64Coin("busd", 1000)), sdk.Coins{}, sdk.Coins{}, true, }, { - "errors if not enough total akava to cover", - sdk.NewCoins(sdk.NewInt64Coin("akava", 100_000_000_001_000)), + "errors if not enough total neuron to cover", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 100_000_000_001_000)), sdk.Coins{}, sdk.Coins{}, true, }, { - "errors if not enough ukava to cover", - sdk.NewCoins(sdk.NewInt64Coin("akava", 200_000_000_000_000)), + "errors if not enough a0gi to cover", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 200_000_000_000_000)), sdk.Coins{}, sdk.Coins{}, true, }, { - "converts receiver's akava to ukava if there's enough akava after the transfer", - sdk.NewCoins(sdk.NewInt64Coin("akava", 99_000_000_000_200)), + "converts receiver's neuron to a0gi if there's enough neuron after the transfer", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 99_000_000_000_200)), sdk.NewCoins( - sdk.NewInt64Coin("akava", 999_999_999_900), - sdk.NewInt64Coin("ukava", 1), + sdk.NewInt64Coin(chaincfg.BaseDenom, 999_999_999_900), + sdk.NewInt64Coin(chaincfg.DisplayDenom, 1), ), sdk.NewCoins( - sdk.NewInt64Coin("akava", 100), - sdk.NewInt64Coin("ukava", 101), + sdk.NewInt64Coin(chaincfg.BaseDenom, 100), + sdk.NewInt64Coin(chaincfg.DisplayDenom, 101), ), false, }, { - "converts all of receiver's akava to ukava even if somehow receiver has more than 1ukava of akava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 12_000_000_000_100)), + "converts all of receiver's neuron to a0gi even if somehow receiver has more than 1a0gi of neuron", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 12_000_000_000_100)), sdk.NewCoins( - sdk.NewInt64Coin("akava", 5_999_999_999_990), - sdk.NewInt64Coin("ukava", 1), + sdk.NewInt64Coin(chaincfg.BaseDenom, 5_999_999_999_990), + sdk.NewInt64Coin(chaincfg.DisplayDenom, 1), ), sdk.NewCoins( - sdk.NewInt64Coin("akava", 90), - sdk.NewInt64Coin("ukava", 19), + sdk.NewInt64Coin(chaincfg.BaseDenom, 90), + sdk.NewInt64Coin(chaincfg.DisplayDenom, 19), ), false, }, { - "swap 1 ukava for akava if module account doesn't have enough akava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 99_000_000_001_000)), + "swap 1 a0gi for neuron if module account doesn't have enough neuron", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 99_000_000_001_000)), sdk.NewCoins( - sdk.NewInt64Coin("akava", 200), - sdk.NewInt64Coin("ukava", 1), + sdk.NewInt64Coin(chaincfg.BaseDenom, 200), + sdk.NewInt64Coin(chaincfg.DisplayDenom, 1), ), sdk.NewCoins( - sdk.NewInt64Coin("akava", 1200), - sdk.NewInt64Coin("ukava", 100), + sdk.NewInt64Coin(chaincfg.BaseDenom, 1200), + sdk.NewInt64Coin(chaincfg.DisplayDenom, 100), ), false, }, @@ -232,11 +233,11 @@ func (suite *evmBankKeeperTestSuite) TestSendCoinsFromModuleToAccount() { suite.Run(tt.name, func() { suite.SetupTest() - suite.FundAccountWithKava(suite.Addrs[0], tt.startingAccBal) - suite.FundModuleAccountWithKava(evmtypes.ModuleName, startingModuleCoins) + suite.FundAccountWithZgChain(suite.Addrs[0], tt.startingAccBal) + suite.FundModuleAccountWithZgChain(evmtypes.ModuleName, startingModuleCoins) - // fund our module with some ukava to account for converting extra akava back to ukava - suite.FundModuleAccountWithKava(types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin("ukava", 10))) + // fund our module with some a0gi to account for converting extra neuron back to a0gi + suite.FundModuleAccountWithZgChain(types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 10))) err := suite.EvmBankKeeper.SendCoinsFromModuleToAccount(suite.Ctx, evmtypes.ModuleName, suite.Addrs[0], tt.sendCoins) if tt.hasErr { @@ -246,24 +247,24 @@ func (suite *evmBankKeeperTestSuite) TestSendCoinsFromModuleToAccount() { suite.Require().NoError(err) } - // check ukava - ukavaSender := suite.BankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], "ukava") - suite.Require().Equal(tt.expAccBal.AmountOf("ukava").Int64(), ukavaSender.Amount.Int64()) + // check a0gi + a0giSender := suite.BankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], chaincfg.DisplayDenom) + suite.Require().Equal(tt.expAccBal.AmountOf(chaincfg.DisplayDenom).Int64(), a0giSender.Amount.Int64()) - // check akava - actualAkava := suite.Keeper.GetBalance(suite.Ctx, suite.Addrs[0]) - suite.Require().Equal(tt.expAccBal.AmountOf("akava").Int64(), actualAkava.Int64()) + // check neuron + actualNeuron := suite.Keeper.GetBalance(suite.Ctx, suite.Addrs[0]) + suite.Require().Equal(tt.expAccBal.AmountOf(chaincfg.BaseDenom).Int64(), actualNeuron.Int64()) }) } } func (suite *evmBankKeeperTestSuite) TestSendCoinsFromAccountToModule() { startingAccCoins := sdk.NewCoins( - sdk.NewInt64Coin("akava", 200), - sdk.NewInt64Coin("ukava", 100), + sdk.NewInt64Coin(chaincfg.BaseDenom, 200), + sdk.NewInt64Coin(chaincfg.DisplayDenom, 100), ) startingModuleCoins := sdk.NewCoins( - sdk.NewInt64Coin("akava", 100_000_000_000), + sdk.NewInt64Coin(chaincfg.BaseDenom, 100_000_000_000), ) tests := []struct { name string @@ -273,36 +274,36 @@ func (suite *evmBankKeeperTestSuite) TestSendCoinsFromAccountToModule() { hasErr bool }{ { - "send more than 1 ukava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 12_000_000_000_010)), - sdk.NewCoins(sdk.NewInt64Coin("akava", 190), sdk.NewInt64Coin("ukava", 88)), - sdk.NewCoins(sdk.NewInt64Coin("akava", 100_000_000_010), sdk.NewInt64Coin("ukava", 12)), + "send more than 1 a0gi", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 12_000_000_000_010)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 190), sdk.NewInt64Coin(chaincfg.DisplayDenom, 88)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 100_000_000_010), sdk.NewInt64Coin(chaincfg.DisplayDenom, 12)), false, }, { - "send less than 1 ukava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 122)), - sdk.NewCoins(sdk.NewInt64Coin("akava", 78), sdk.NewInt64Coin("ukava", 100)), - sdk.NewCoins(sdk.NewInt64Coin("akava", 100_000_000_122), sdk.NewInt64Coin("ukava", 0)), + "send less than 1 a0gi", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 122)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 78), sdk.NewInt64Coin(chaincfg.DisplayDenom, 100)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 100_000_000_122), sdk.NewInt64Coin(chaincfg.DisplayDenom, 0)), false, }, { - "send an exact amount of ukava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 98_000_000_000_000)), - sdk.NewCoins(sdk.NewInt64Coin("akava", 200), sdk.NewInt64Coin("ukava", 2)), - sdk.NewCoins(sdk.NewInt64Coin("akava", 100_000_000_000), sdk.NewInt64Coin("ukava", 98)), + "send an exact amount of a0gi", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 98_000_000_000_000)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 200), sdk.NewInt64Coin(chaincfg.DisplayDenom, 2)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 100_000_000_000), sdk.NewInt64Coin(chaincfg.DisplayDenom, 98)), false, }, { - "send no akava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 0)), - sdk.NewCoins(sdk.NewInt64Coin("akava", 200), sdk.NewInt64Coin("ukava", 100)), - sdk.NewCoins(sdk.NewInt64Coin("akava", 100_000_000_000), sdk.NewInt64Coin("ukava", 0)), + "send no neuron", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 0)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 200), sdk.NewInt64Coin(chaincfg.DisplayDenom, 100)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 100_000_000_000), sdk.NewInt64Coin(chaincfg.DisplayDenom, 0)), false, }, { "errors if sending other coins", - sdk.NewCoins(sdk.NewInt64Coin("akava", 500), sdk.NewInt64Coin("busd", 1000)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 500), sdk.NewInt64Coin("busd", 1000)), sdk.Coins{}, sdk.Coins{}, true, @@ -310,39 +311,39 @@ func (suite *evmBankKeeperTestSuite) TestSendCoinsFromAccountToModule() { { "errors if have dup coins", sdk.Coins{ - sdk.NewInt64Coin("akava", 12_000_000_000_000), - sdk.NewInt64Coin("akava", 2_000_000_000_000), + sdk.NewInt64Coin(chaincfg.BaseDenom, 12_000_000_000_000), + sdk.NewInt64Coin(chaincfg.BaseDenom, 2_000_000_000_000), }, sdk.Coins{}, sdk.Coins{}, true, }, { - "errors if not enough total akava to cover", - sdk.NewCoins(sdk.NewInt64Coin("akava", 100_000_000_001_000)), + "errors if not enough total neuron to cover", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 100_000_000_001_000)), sdk.Coins{}, sdk.Coins{}, true, }, { - "errors if not enough ukava to cover", - sdk.NewCoins(sdk.NewInt64Coin("akava", 200_000_000_000_000)), + "errors if not enough a0gi to cover", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 200_000_000_000_000)), sdk.Coins{}, sdk.Coins{}, true, }, { - "converts 1 ukava to akava if not enough akava to cover", - sdk.NewCoins(sdk.NewInt64Coin("akava", 99_001_000_000_000)), - sdk.NewCoins(sdk.NewInt64Coin("akava", 999_000_000_200), sdk.NewInt64Coin("ukava", 0)), - sdk.NewCoins(sdk.NewInt64Coin("akava", 101_000_000_000), sdk.NewInt64Coin("ukava", 99)), + "converts 1 a0gi to neuron if not enough neuron to cover", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 99_001_000_000_000)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 999_000_000_200), sdk.NewInt64Coin(chaincfg.DisplayDenom, 0)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 101_000_000_000), sdk.NewInt64Coin(chaincfg.DisplayDenom, 99)), false, }, { - "converts receiver's akava to ukava if there's enough akava after the transfer", - sdk.NewCoins(sdk.NewInt64Coin("akava", 5_900_000_000_200)), - sdk.NewCoins(sdk.NewInt64Coin("akava", 100_000_000_000), sdk.NewInt64Coin("ukava", 94)), - sdk.NewCoins(sdk.NewInt64Coin("akava", 200), sdk.NewInt64Coin("ukava", 6)), + "converts receiver's neuron to a0gi if there's enough neuron after the transfer", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 5_900_000_000_200)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 100_000_000_000), sdk.NewInt64Coin(chaincfg.DisplayDenom, 94)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 200), sdk.NewInt64Coin(chaincfg.DisplayDenom, 6)), false, }, } @@ -350,8 +351,8 @@ func (suite *evmBankKeeperTestSuite) TestSendCoinsFromAccountToModule() { for _, tt := range tests { suite.Run(tt.name, func() { suite.SetupTest() - suite.FundAccountWithKava(suite.Addrs[0], startingAccCoins) - suite.FundModuleAccountWithKava(evmtypes.ModuleName, startingModuleCoins) + suite.FundAccountWithZgChain(suite.Addrs[0], startingAccCoins) + suite.FundModuleAccountWithZgChain(evmtypes.ModuleName, startingModuleCoins) err := suite.EvmBankKeeper.SendCoinsFromAccountToModule(suite.Ctx, suite.Addrs[0], evmtypes.ModuleName, tt.sendCoins) if tt.hasErr { @@ -362,67 +363,67 @@ func (suite *evmBankKeeperTestSuite) TestSendCoinsFromAccountToModule() { } // check sender balance - ukavaSender := suite.BankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], "ukava") - suite.Require().Equal(tt.expSenderCoins.AmountOf("ukava").Int64(), ukavaSender.Amount.Int64()) - actualAkava := suite.Keeper.GetBalance(suite.Ctx, suite.Addrs[0]) - suite.Require().Equal(tt.expSenderCoins.AmountOf("akava").Int64(), actualAkava.Int64()) + a0giSender := suite.BankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], chaincfg.DisplayDenom) + suite.Require().Equal(tt.expSenderCoins.AmountOf(chaincfg.DisplayDenom).Int64(), a0giSender.Amount.Int64()) + actualNeuron := suite.Keeper.GetBalance(suite.Ctx, suite.Addrs[0]) + suite.Require().Equal(tt.expSenderCoins.AmountOf(chaincfg.BaseDenom).Int64(), actualNeuron.Int64()) // check module balance moduleAddr := suite.AccountKeeper.GetModuleAddress(evmtypes.ModuleName) - ukavaSender = suite.BankKeeper.GetBalance(suite.Ctx, moduleAddr, "ukava") - suite.Require().Equal(tt.expModuleCoins.AmountOf("ukava").Int64(), ukavaSender.Amount.Int64()) - actualAkava = suite.Keeper.GetBalance(suite.Ctx, moduleAddr) - suite.Require().Equal(tt.expModuleCoins.AmountOf("akava").Int64(), actualAkava.Int64()) + a0giSender = suite.BankKeeper.GetBalance(suite.Ctx, moduleAddr, chaincfg.DisplayDenom) + suite.Require().Equal(tt.expModuleCoins.AmountOf(chaincfg.DisplayDenom).Int64(), a0giSender.Amount.Int64()) + actualNeuron = suite.Keeper.GetBalance(suite.Ctx, moduleAddr) + suite.Require().Equal(tt.expModuleCoins.AmountOf(chaincfg.BaseDenom).Int64(), actualNeuron.Int64()) }) } } func (suite *evmBankKeeperTestSuite) TestBurnCoins() { - startingUkava := sdkmath.NewInt(100) + startingA0gi := sdkmath.NewInt(100) tests := []struct { - name string - burnCoins sdk.Coins - expUkava sdkmath.Int - expAkava sdkmath.Int - hasErr bool - akavaStart sdkmath.Int + name string + burnCoins sdk.Coins + expA0gi sdkmath.Int + expNeuron sdkmath.Int + hasErr bool + neuronStart sdkmath.Int }{ { - "burn more than 1 ukava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 12_021_000_000_002)), + "burn more than 1 a0gi", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 12_021_000_000_002)), sdkmath.NewInt(88), sdkmath.NewInt(100_000_000_000), false, sdkmath.NewInt(121_000_000_002), }, { - "burn less than 1 ukava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 122)), + "burn less than 1 a0gi", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 122)), sdkmath.NewInt(100), sdkmath.NewInt(878), false, sdkmath.NewInt(1000), }, { - "burn an exact amount of ukava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 98_000_000_000_000)), + "burn an exact amount of a0gi", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 98_000_000_000_000)), sdkmath.NewInt(2), sdkmath.NewInt(10), false, sdkmath.NewInt(10), }, { - "burn no akava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 0)), - startingUkava, + "burn no neuron", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 0)), + startingA0gi, sdk.ZeroInt(), false, sdk.ZeroInt(), }, { "errors if burning other coins", - sdk.NewCoins(sdk.NewInt64Coin("akava", 500), sdk.NewInt64Coin("busd", 1000)), - startingUkava, + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 500), sdk.NewInt64Coin("busd", 1000)), + startingA0gi, sdkmath.NewInt(100), true, sdkmath.NewInt(100), @@ -430,41 +431,41 @@ func (suite *evmBankKeeperTestSuite) TestBurnCoins() { { "errors if have dup coins", sdk.Coins{ - sdk.NewInt64Coin("akava", 12_000_000_000_000), - sdk.NewInt64Coin("akava", 2_000_000_000_000), + sdk.NewInt64Coin(chaincfg.BaseDenom, 12_000_000_000_000), + sdk.NewInt64Coin(chaincfg.BaseDenom, 2_000_000_000_000), }, - startingUkava, + startingA0gi, sdk.ZeroInt(), true, sdk.ZeroInt(), }, { "errors if burn amount is negative", - sdk.Coins{sdk.Coin{Denom: "akava", Amount: sdkmath.NewInt(-100)}}, - startingUkava, + sdk.Coins{sdk.Coin{Denom: chaincfg.BaseDenom, Amount: sdkmath.NewInt(-100)}}, + startingA0gi, sdkmath.NewInt(50), true, sdkmath.NewInt(50), }, { - "errors if not enough akava to cover burn", - sdk.NewCoins(sdk.NewInt64Coin("akava", 100_999_000_000_000)), + "errors if not enough neuron to cover burn", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 100_999_000_000_000)), sdkmath.NewInt(0), sdkmath.NewInt(99_000_000_000), true, sdkmath.NewInt(99_000_000_000), }, { - "errors if not enough ukava to cover burn", - sdk.NewCoins(sdk.NewInt64Coin("akava", 200_000_000_000_000)), + "errors if not enough a0gi to cover burn", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 200_000_000_000_000)), sdkmath.NewInt(100), sdk.ZeroInt(), true, sdk.ZeroInt(), }, { - "converts 1 ukava to akava if not enough akava to cover", - sdk.NewCoins(sdk.NewInt64Coin("akava", 12_021_000_000_002)), + "converts 1 a0gi to neuron if not enough neuron to cover", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 12_021_000_000_002)), sdkmath.NewInt(87), sdkmath.NewInt(980_000_000_000), false, @@ -476,10 +477,10 @@ func (suite *evmBankKeeperTestSuite) TestBurnCoins() { suite.Run(tt.name, func() { suite.SetupTest() startingCoins := sdk.NewCoins( - sdk.NewCoin("ukava", startingUkava), - sdk.NewCoin("akava", tt.akavaStart), + sdk.NewCoin(chaincfg.DisplayDenom, startingA0gi), + sdk.NewCoin(chaincfg.BaseDenom, tt.neuronStart), ) - suite.FundModuleAccountWithKava(evmtypes.ModuleName, startingCoins) + suite.FundModuleAccountWithZgChain(evmtypes.ModuleName, startingCoins) err := suite.EvmBankKeeper.BurnCoins(suite.Ctx, evmtypes.ModuleName, tt.burnCoins) if tt.hasErr { @@ -489,53 +490,53 @@ func (suite *evmBankKeeperTestSuite) TestBurnCoins() { suite.Require().NoError(err) } - // check ukava - ukavaActual := suite.BankKeeper.GetBalance(suite.Ctx, suite.EvmModuleAddr, "ukava") - suite.Require().Equal(tt.expUkava, ukavaActual.Amount) + // check a0gi + a0giActual := suite.BankKeeper.GetBalance(suite.Ctx, suite.EvmModuleAddr, chaincfg.DisplayDenom) + suite.Require().Equal(tt.expA0gi, a0giActual.Amount) - // check akava - akavaActual := suite.Keeper.GetBalance(suite.Ctx, suite.EvmModuleAddr) - suite.Require().Equal(tt.expAkava, akavaActual) + // check neuron + neuronActual := suite.Keeper.GetBalance(suite.Ctx, suite.EvmModuleAddr) + suite.Require().Equal(tt.expNeuron, neuronActual) }) } } func (suite *evmBankKeeperTestSuite) TestMintCoins() { tests := []struct { - name string - mintCoins sdk.Coins - ukava sdkmath.Int - akava sdkmath.Int - hasErr bool - akavaStart sdkmath.Int + name string + mintCoins sdk.Coins + a0gi sdkmath.Int + neuron sdkmath.Int + hasErr bool + neuronStart sdkmath.Int }{ { - "mint more than 1 ukava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 12_021_000_000_002)), + "mint more than 1 a0gi", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 12_021_000_000_002)), sdkmath.NewInt(12), sdkmath.NewInt(21_000_000_002), false, sdk.ZeroInt(), }, { - "mint less than 1 ukava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 901_000_000_001)), + "mint less than 1 a0gi", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 901_000_000_001)), sdk.ZeroInt(), sdkmath.NewInt(901_000_000_001), false, sdk.ZeroInt(), }, { - "mint an exact amount of ukava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 123_000_000_000_000_000)), + "mint an exact amount of a0gi", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 123_000_000_000_000_000)), sdkmath.NewInt(123_000), sdk.ZeroInt(), false, sdk.ZeroInt(), }, { - "mint no akava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 0)), + "mint no neuron", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 0)), sdk.ZeroInt(), sdk.ZeroInt(), false, @@ -543,7 +544,7 @@ func (suite *evmBankKeeperTestSuite) TestMintCoins() { }, { "errors if minting other coins", - sdk.NewCoins(sdk.NewInt64Coin("akava", 500), sdk.NewInt64Coin("busd", 1000)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 500), sdk.NewInt64Coin("busd", 1000)), sdk.ZeroInt(), sdkmath.NewInt(100), true, @@ -552,8 +553,8 @@ func (suite *evmBankKeeperTestSuite) TestMintCoins() { { "errors if have dup coins", sdk.Coins{ - sdk.NewInt64Coin("akava", 12_000_000_000_000), - sdk.NewInt64Coin("akava", 2_000_000_000_000), + sdk.NewInt64Coin(chaincfg.BaseDenom, 12_000_000_000_000), + sdk.NewInt64Coin(chaincfg.BaseDenom, 2_000_000_000_000), }, sdk.ZeroInt(), sdk.ZeroInt(), @@ -562,23 +563,23 @@ func (suite *evmBankKeeperTestSuite) TestMintCoins() { }, { "errors if mint amount is negative", - sdk.Coins{sdk.Coin{Denom: "akava", Amount: sdkmath.NewInt(-100)}}, + sdk.Coins{sdk.Coin{Denom: chaincfg.BaseDenom, Amount: sdkmath.NewInt(-100)}}, sdk.ZeroInt(), sdkmath.NewInt(50), true, sdkmath.NewInt(50), }, { - "adds to existing akava balance", - sdk.NewCoins(sdk.NewInt64Coin("akava", 12_021_000_000_002)), + "adds to existing neuron balance", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 12_021_000_000_002)), sdkmath.NewInt(12), sdkmath.NewInt(21_000_000_102), false, sdkmath.NewInt(100), }, { - "convert akava balance to ukava if it exceeds 1 ukava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 10_999_000_000_000)), + "convert neuron balance to a0gi if it exceeds 1 a0gi", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 10_999_000_000_000)), sdkmath.NewInt(12), sdkmath.NewInt(1_200_000_001), false, @@ -589,8 +590,8 @@ func (suite *evmBankKeeperTestSuite) TestMintCoins() { for _, tt := range tests { suite.Run(tt.name, func() { suite.SetupTest() - suite.FundModuleAccountWithKava(types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin("ukava", 10))) - suite.FundModuleAccountWithKava(evmtypes.ModuleName, sdk.NewCoins(sdk.NewCoin("akava", tt.akavaStart))) + suite.FundModuleAccountWithZgChain(types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 10))) + suite.FundModuleAccountWithZgChain(evmtypes.ModuleName, sdk.NewCoins(sdk.NewCoin(chaincfg.BaseDenom, tt.neuronStart))) err := suite.EvmBankKeeper.MintCoins(suite.Ctx, evmtypes.ModuleName, tt.mintCoins) if tt.hasErr { @@ -600,13 +601,13 @@ func (suite *evmBankKeeperTestSuite) TestMintCoins() { suite.Require().NoError(err) } - // check ukava - ukavaActual := suite.BankKeeper.GetBalance(suite.Ctx, suite.EvmModuleAddr, "ukava") - suite.Require().Equal(tt.ukava, ukavaActual.Amount) + // check a0gi + a0giActual := suite.BankKeeper.GetBalance(suite.Ctx, suite.EvmModuleAddr, chaincfg.DisplayDenom) + suite.Require().Equal(tt.a0gi, a0giActual.Amount) - // check akava - akavaActual := suite.Keeper.GetBalance(suite.Ctx, suite.EvmModuleAddr) - suite.Require().Equal(tt.akava, akavaActual) + // check neuron + neuronActual := suite.Keeper.GetBalance(suite.Ctx, suite.EvmModuleAddr) + suite.Require().Equal(tt.neuron, neuronActual) }) } } @@ -619,22 +620,22 @@ func (suite *evmBankKeeperTestSuite) TestValidateEvmCoins() { }{ { "valid coins", - sdk.NewCoins(sdk.NewInt64Coin("akava", 500)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 500)), false, }, { "dup coins", - sdk.Coins{sdk.NewInt64Coin("akava", 500), sdk.NewInt64Coin("akava", 500)}, + sdk.Coins{sdk.NewInt64Coin(chaincfg.BaseDenom, 500), sdk.NewInt64Coin(chaincfg.BaseDenom, 500)}, true, }, { "not evm coins", - sdk.NewCoins(sdk.NewInt64Coin("ukava", 500)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 500)), true, }, { "negative coins", - sdk.Coins{sdk.Coin{Denom: "akava", Amount: sdkmath.NewInt(-500)}}, + sdk.Coins{sdk.Coin{Denom: chaincfg.BaseDenom, Amount: sdkmath.NewInt(-500)}}, true, }, } @@ -650,8 +651,8 @@ func (suite *evmBankKeeperTestSuite) TestValidateEvmCoins() { } } -func (suite *evmBankKeeperTestSuite) TestConvertOneUkavaToAkavaIfNeeded() { - akavaNeeded := sdkmath.NewInt(200) +func (suite *evmBankKeeperTestSuite) TestConvertOneA0giToNeuronIfNeeded() { + neuronNeeded := sdkmath.NewInt(200) tests := []struct { name string startingCoins sdk.Coins @@ -659,21 +660,21 @@ func (suite *evmBankKeeperTestSuite) TestConvertOneUkavaToAkavaIfNeeded() { success bool }{ { - "not enough ukava for conversion", - sdk.NewCoins(sdk.NewInt64Coin("akava", 100)), - sdk.NewCoins(sdk.NewInt64Coin("akava", 100)), + "not enough a0gi for conversion", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 100)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 100)), false, }, { - "converts 1 ukava to akava", - sdk.NewCoins(sdk.NewInt64Coin("ukava", 10), sdk.NewInt64Coin("akava", 100)), - sdk.NewCoins(sdk.NewInt64Coin("ukava", 9), sdk.NewInt64Coin("akava", 1_000_000_000_100)), + "converts 1 a0gi to neuron", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 10), sdk.NewInt64Coin(chaincfg.BaseDenom, 100)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 9), sdk.NewInt64Coin(chaincfg.BaseDenom, 1_000_000_000_100)), true, }, { "conversion not needed", - sdk.NewCoins(sdk.NewInt64Coin("ukava", 10), sdk.NewInt64Coin("akava", 200)), - sdk.NewCoins(sdk.NewInt64Coin("ukava", 10), sdk.NewInt64Coin("akava", 200)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 10), sdk.NewInt64Coin(chaincfg.BaseDenom, 200)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 10), sdk.NewInt64Coin(chaincfg.BaseDenom, 200)), true, }, } @@ -681,67 +682,67 @@ func (suite *evmBankKeeperTestSuite) TestConvertOneUkavaToAkavaIfNeeded() { suite.Run(tt.name, func() { suite.SetupTest() - suite.FundAccountWithKava(suite.Addrs[0], tt.startingCoins) - err := suite.EvmBankKeeper.ConvertOneUkavaToAkavaIfNeeded(suite.Ctx, suite.Addrs[0], akavaNeeded) - moduleKava := suite.BankKeeper.GetBalance(suite.Ctx, suite.AccountKeeper.GetModuleAddress(types.ModuleName), "ukava") + suite.FundAccountWithZgChain(suite.Addrs[0], tt.startingCoins) + err := suite.EvmBankKeeper.ConvertOneA0giToNeuronIfNeeded(suite.Ctx, suite.Addrs[0], neuronNeeded) + moduleZgChain := suite.BankKeeper.GetBalance(suite.Ctx, suite.AccountKeeper.GetModuleAddress(types.ModuleName), chaincfg.DisplayDenom) if tt.success { suite.Require().NoError(err) - if tt.startingCoins.AmountOf("akava").LT(akavaNeeded) { - suite.Require().Equal(sdk.OneInt(), moduleKava.Amount) + if tt.startingCoins.AmountOf(chaincfg.BaseDenom).LT(neuronNeeded) { + suite.Require().Equal(sdk.OneInt(), moduleZgChain.Amount) } } else { suite.Require().Error(err) - suite.Require().Equal(sdk.ZeroInt(), moduleKava.Amount) + suite.Require().Equal(sdk.ZeroInt(), moduleZgChain.Amount) } - akava := suite.Keeper.GetBalance(suite.Ctx, suite.Addrs[0]) - suite.Require().Equal(tt.expectedCoins.AmountOf("akava"), akava) - ukava := suite.BankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], "ukava") - suite.Require().Equal(tt.expectedCoins.AmountOf("ukava"), ukava.Amount) + neuron := suite.Keeper.GetBalance(suite.Ctx, suite.Addrs[0]) + suite.Require().Equal(tt.expectedCoins.AmountOf(chaincfg.BaseDenom), neuron) + a0gi := suite.BankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], chaincfg.DisplayDenom) + suite.Require().Equal(tt.expectedCoins.AmountOf(chaincfg.DisplayDenom), a0gi.Amount) }) } } -func (suite *evmBankKeeperTestSuite) TestConvertAkavaToUkava() { +func (suite *evmBankKeeperTestSuite) TestConvertNeuronToA0gi() { tests := []struct { name string startingCoins sdk.Coins expectedCoins sdk.Coins }{ { - "not enough ukava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 100)), - sdk.NewCoins(sdk.NewInt64Coin("akava", 100), sdk.NewInt64Coin("ukava", 0)), + "not enough a0gi", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 100)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 100), sdk.NewInt64Coin(chaincfg.DisplayDenom, 0)), }, { - "converts akava for 1 ukava", - sdk.NewCoins(sdk.NewInt64Coin("ukava", 10), sdk.NewInt64Coin("akava", 1_000_000_000_003)), - sdk.NewCoins(sdk.NewInt64Coin("ukava", 11), sdk.NewInt64Coin("akava", 3)), + "converts neuron for 1 a0gi", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 10), sdk.NewInt64Coin(chaincfg.BaseDenom, 1_000_000_000_003)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 11), sdk.NewInt64Coin(chaincfg.BaseDenom, 3)), }, { - "converts more than 1 ukava of akava", - sdk.NewCoins(sdk.NewInt64Coin("ukava", 10), sdk.NewInt64Coin("akava", 8_000_000_000_123)), - sdk.NewCoins(sdk.NewInt64Coin("ukava", 18), sdk.NewInt64Coin("akava", 123)), + "converts more than 1 a0gi of neuron", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 10), sdk.NewInt64Coin(chaincfg.BaseDenom, 8_000_000_000_123)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 18), sdk.NewInt64Coin(chaincfg.BaseDenom, 123)), }, } for _, tt := range tests { suite.Run(tt.name, func() { suite.SetupTest() - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin("ukava", 10))) + err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 10))) suite.Require().NoError(err) - suite.FundAccountWithKava(suite.Addrs[0], tt.startingCoins) - err = suite.EvmBankKeeper.ConvertAkavaToUkava(suite.Ctx, suite.Addrs[0]) + suite.FundAccountWithZgChain(suite.Addrs[0], tt.startingCoins) + err = suite.EvmBankKeeper.ConvertNeuronToA0gi(suite.Ctx, suite.Addrs[0]) suite.Require().NoError(err) - akava := suite.Keeper.GetBalance(suite.Ctx, suite.Addrs[0]) - suite.Require().Equal(tt.expectedCoins.AmountOf("akava"), akava) - ukava := suite.BankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], "ukava") - suite.Require().Equal(tt.expectedCoins.AmountOf("ukava"), ukava.Amount) + neuron := suite.Keeper.GetBalance(suite.Ctx, suite.Addrs[0]) + suite.Require().Equal(tt.expectedCoins.AmountOf(chaincfg.BaseDenom), neuron) + a0gi := suite.BankKeeper.GetBalance(suite.Ctx, suite.Addrs[0], chaincfg.DisplayDenom) + suite.Require().Equal(tt.expectedCoins.AmountOf(chaincfg.DisplayDenom), a0gi.Amount) }) } } -func (suite *evmBankKeeperTestSuite) TestSplitAkavaCoins() { +func (suite *evmBankKeeperTestSuite) TestSplitNeuronCoins() { tests := []struct { name string coins sdk.Coins @@ -750,7 +751,7 @@ func (suite *evmBankKeeperTestSuite) TestSplitAkavaCoins() { }{ { "invalid coins", - sdk.NewCoins(sdk.NewInt64Coin("ukava", 500)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 500)), nil, true, }, @@ -761,33 +762,33 @@ func (suite *evmBankKeeperTestSuite) TestSplitAkavaCoins() { false, }, { - "ukava & akava coins", - sdk.NewCoins(sdk.NewInt64Coin("akava", 8_000_000_000_123)), - sdk.NewCoins(sdk.NewInt64Coin("ukava", 8), sdk.NewInt64Coin("akava", 123)), + "a0gi & neuron coins", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 8_000_000_000_123)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 8), sdk.NewInt64Coin(chaincfg.BaseDenom, 123)), false, }, { - "only akava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 10_123)), - sdk.NewCoins(sdk.NewInt64Coin("akava", 10_123)), + "only neuron", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 10_123)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 10_123)), false, }, { - "only ukava", - sdk.NewCoins(sdk.NewInt64Coin("akava", 5_000_000_000_000)), - sdk.NewCoins(sdk.NewInt64Coin("ukava", 5)), + "only a0gi", + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.BaseDenom, 5_000_000_000_000)), + sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 5)), false, }, } for _, tt := range tests { suite.Run(tt.name, func() { - ukava, akava, err := keeper.SplitAkavaCoins(tt.coins) + a0gi, neuron, err := keeper.SplitNeuronCoins(tt.coins) if tt.shouldErr { suite.Require().Error(err) } else { suite.Require().NoError(err) - suite.Require().Equal(tt.expectedCoins.AmountOf("ukava"), ukava.Amount) - suite.Require().Equal(tt.expectedCoins.AmountOf("akava"), akava) + suite.Require().Equal(tt.expectedCoins.AmountOf(chaincfg.DisplayDenom), a0gi.Amount) + suite.Require().Equal(tt.expectedCoins.AmountOf(chaincfg.BaseDenom), neuron) } }) } diff --git a/x/evmutil/keeper/conversion_cosmos_native.go b/x/evmutil/keeper/conversion_cosmos_native.go index 6c8c813a..5e1d7289 100644 --- a/x/evmutil/keeper/conversion_cosmos_native.go +++ b/x/evmutil/keeper/conversion_cosmos_native.go @@ -7,7 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/types" ) // ConvertCosmosCoinToERC20 locks the initiator's sdk.Coin in the module account diff --git a/x/evmutil/keeper/conversion_cosmos_native_test.go b/x/evmutil/keeper/conversion_cosmos_native_test.go index 15857957..5f393182 100644 --- a/x/evmutil/keeper/conversion_cosmos_native_test.go +++ b/x/evmutil/keeper/conversion_cosmos_native_test.go @@ -10,9 +10,9 @@ import ( sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/evmutil/testutil" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/x/evmutil/testutil" + "github.com/0glabs/0g-chain/x/evmutil/types" ) type convertCosmosCoinToERC20Suite struct { @@ -51,7 +51,7 @@ func (suite *convertCosmosCoinToERC20Suite) TestConvertCosmosCoinToERC20() { caller, key := testutil.RandomEvmAccount() query := func(method string, args ...interface{}) ([]interface{}, error) { return suite.QueryContract( - types.ERC20KavaWrappedCosmosCoinContract.ABI, + types.ERC20ZgChainWrappedCosmosCoinContract.ABI, caller, key, contractAddress, @@ -90,7 +90,7 @@ func (suite *convertCosmosCoinToERC20Suite) TestConvertCosmosCoinToERC20() { // make the denom allowed for conversion params := suite.Keeper.GetParams(suite.Ctx) params.AllowedCosmosDenoms = types.NewAllowedCosmosCoinERC20Tokens( - types.NewAllowedCosmosCoinERC20Token(allowedDenom, "Kava EVM Atom", "ATOM", 6), + types.NewAllowedCosmosCoinERC20Token(allowedDenom, "0gChain EVM Atom", "ATOM", 6), ) suite.Keeper.SetParams(suite.Ctx, params) @@ -215,7 +215,7 @@ func (suite *convertCosmosCoinFromERC20Suite) SetupTest() { caller, key := testutil.RandomEvmAccount() suite.query = func(method string, args ...interface{}) ([]interface{}, error) { return suite.QueryContract( - types.ERC20KavaWrappedCosmosCoinContract.ABI, + types.ERC20ZgChainWrappedCosmosCoinContract.ABI, caller, key, suite.contractAddress, diff --git a/x/evmutil/keeper/conversion_evm_native.go b/x/evmutil/keeper/conversion_evm_native.go index 69a97de2..edb0ff49 100644 --- a/x/evmutil/keeper/conversion_evm_native.go +++ b/x/evmutil/keeper/conversion_evm_native.go @@ -7,7 +7,7 @@ import ( sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/types" ) // MintConversionPairCoin mints the given amount of a ConversionPair denom and diff --git a/x/evmutil/keeper/conversion_evm_native_bep3.go b/x/evmutil/keeper/conversion_evm_native_bep3.go index b727996d..c63465ab 100644 --- a/x/evmutil/keeper/conversion_evm_native_bep3.go +++ b/x/evmutil/keeper/conversion_evm_native_bep3.go @@ -4,7 +4,7 @@ import ( "math/big" errorsmod "cosmossdk.io/errors" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/types" ) var ( diff --git a/x/evmutil/keeper/conversion_evm_native_bep3_test.go b/x/evmutil/keeper/conversion_evm_native_bep3_test.go index c2d06128..7ff8d9db 100644 --- a/x/evmutil/keeper/conversion_evm_native_bep3_test.go +++ b/x/evmutil/keeper/conversion_evm_native_bep3_test.go @@ -8,8 +8,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" - "github.com/kava-labs/kava/x/evmutil/testutil" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/testutil" + "github.com/0glabs/0g-chain/x/evmutil/types" ) type Bep3ConversionTestSuite struct { @@ -43,7 +43,7 @@ func (suite *Bep3ConversionTestSuite) setEnabledConversionPairDenom(denom string } func (suite *Bep3ConversionTestSuite) testConvertBep3CoinToERC20(denom string) { - invoker, err := sdk.AccAddressFromBech32("kava123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz") + invoker, err := sdk.AccAddressFromBech32("0g123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz") receiverAddr := testutil.MustNewInternalEVMAddressFromString("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2") suite.Require().NoError(err) diff --git a/x/evmutil/keeper/conversion_evm_native_test.go b/x/evmutil/keeper/conversion_evm_native_test.go index 3cd9d1c7..8e7555d9 100644 --- a/x/evmutil/keeper/conversion_evm_native_test.go +++ b/x/evmutil/keeper/conversion_evm_native_test.go @@ -9,8 +9,8 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/suite" - "github.com/kava-labs/kava/x/evmutil/testutil" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/testutil" + "github.com/0glabs/0g-chain/x/evmutil/types" ) type ConversionTestSuite struct { diff --git a/x/evmutil/keeper/erc20.go b/x/evmutil/keeper/erc20.go index a4b7fe5d..bbca64a1 100644 --- a/x/evmutil/keeper/erc20.go +++ b/x/evmutil/keeper/erc20.go @@ -13,7 +13,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/types" ) const ( @@ -68,10 +68,10 @@ func (k Keeper) DeployTestMintableERC20Contract( return types.NewInternalEVMAddress(contractAddr), nil } -// DeployKavaWrappedCosmosCoinERC20Contract validates token details and then deploys an ERC20 +// DeployZgChainWrappedCosmosCoinERC20Contract validates token details and then deploys an ERC20 // contract with the token metadata. // This method does NOT check if a token for the provided SdkDenom has already been deployed. -func (k Keeper) DeployKavaWrappedCosmosCoinERC20Contract( +func (k Keeper) DeployZgChainWrappedCosmosCoinERC20Contract( ctx sdk.Context, token types.AllowedCosmosCoinERC20Token, ) (types.InternalEVMAddress, error) { @@ -79,7 +79,7 @@ func (k Keeper) DeployKavaWrappedCosmosCoinERC20Contract( return types.InternalEVMAddress{}, errorsmod.Wrapf(err, "failed to deploy erc20 for sdk denom %s", token.CosmosDenom) } - packedAbi, err := types.ERC20KavaWrappedCosmosCoinContract.ABI.Pack( + packedAbi, err := types.ERC20ZgChainWrappedCosmosCoinContract.ABI.Pack( "", // Empty string for contract constructor token.Name, token.Symbol, @@ -89,13 +89,13 @@ func (k Keeper) DeployKavaWrappedCosmosCoinERC20Contract( return types.InternalEVMAddress{}, errorsmod.Wrapf(err, "failed to pack token with details %+v", token) } - data := make([]byte, len(types.ERC20KavaWrappedCosmosCoinContract.Bin)+len(packedAbi)) + data := make([]byte, len(types.ERC20ZgChainWrappedCosmosCoinContract.Bin)+len(packedAbi)) copy( - data[:len(types.ERC20KavaWrappedCosmosCoinContract.Bin)], - types.ERC20KavaWrappedCosmosCoinContract.Bin, + data[:len(types.ERC20ZgChainWrappedCosmosCoinContract.Bin)], + types.ERC20ZgChainWrappedCosmosCoinContract.Bin, ) copy( - data[len(types.ERC20KavaWrappedCosmosCoinContract.Bin):], + data[len(types.ERC20ZgChainWrappedCosmosCoinContract.Bin):], packedAbi, ) @@ -126,7 +126,7 @@ func (k *Keeper) GetOrDeployCosmosCoinERC20Contract( } // deploy a new contract - contractAddress, err := k.DeployKavaWrappedCosmosCoinERC20Contract(ctx, tokenInfo) + contractAddress, err := k.DeployZgChainWrappedCosmosCoinERC20Contract(ctx, tokenInfo) if err != nil { return contractAddress, err } @@ -170,7 +170,7 @@ func (k Keeper) BurnERC20( ) error { _, err := k.CallEVM( ctx, - types.ERC20KavaWrappedCosmosCoinContract.ABI, + types.ERC20ZgChainWrappedCosmosCoinContract.ABI, types.ModuleEVMAddress, contractAddr, erc20BurnMethod, @@ -213,7 +213,7 @@ func (k Keeper) QueryERC20TotalSupply( ) (*big.Int, error) { res, err := k.CallEVM( ctx, - types.ERC20KavaWrappedCosmosCoinContract.ABI, + types.ERC20ZgChainWrappedCosmosCoinContract.ABI, types.ModuleEVMAddress, contractAddr, erc20TotalSupplyMethod, diff --git a/x/evmutil/keeper/erc20_test.go b/x/evmutil/keeper/erc20_test.go index 5cfcd52a..3e24748a 100644 --- a/x/evmutil/keeper/erc20_test.go +++ b/x/evmutil/keeper/erc20_test.go @@ -7,9 +7,9 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/suite" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/evmutil/testutil" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/x/evmutil/testutil" + "github.com/0glabs/0g-chain/x/evmutil/types" ) type ERC20TestSuite struct { @@ -107,11 +107,11 @@ func (suite *ERC20TestSuite) TestQueryERC20TotalSupply() { }) } -func (suite *ERC20TestSuite) TestDeployKavaWrappedCosmosCoinERC20Contract() { +func (suite *ERC20TestSuite) TestDeployZgChainWrappedCosmosCoinERC20Contract() { suite.Run("fails to deploy invalid contract", func() { // empty other fields means this token is invalid. invalidToken := types.AllowedCosmosCoinERC20Token{CosmosDenom: "nope"} - _, err := suite.Keeper.DeployKavaWrappedCosmosCoinERC20Contract(suite.Ctx, invalidToken) + _, err := suite.Keeper.DeployZgChainWrappedCosmosCoinERC20Contract(suite.Ctx, invalidToken) suite.ErrorContains(err, "token's name cannot be empty") }) @@ -119,13 +119,13 @@ func (suite *ERC20TestSuite) TestDeployKavaWrappedCosmosCoinERC20Contract() { caller, privKey := testutil.RandomEvmAccount() token := types.NewAllowedCosmosCoinERC20Token("hard", "EVM HARD", "HARD", 6) - addr, err := suite.Keeper.DeployKavaWrappedCosmosCoinERC20Contract(suite.Ctx, token) + addr, err := suite.Keeper.DeployZgChainWrappedCosmosCoinERC20Contract(suite.Ctx, token) suite.NoError(err) suite.NotNil(addr) callContract := func(method string, args ...interface{}) ([]interface{}, error) { return suite.QueryContract( - types.ERC20KavaWrappedCosmosCoinContract.ABI, + types.ERC20ZgChainWrappedCosmosCoinContract.ABI, caller, privKey, addr, diff --git a/x/evmutil/keeper/evm.go b/x/evmutil/keeper/evm.go index 43829dd4..32d948ff 100644 --- a/x/evmutil/keeper/evm.go +++ b/x/evmutil/keeper/evm.go @@ -28,7 +28,7 @@ import ( "github.com/evmos/ethermint/server/config" evmtypes "github.com/evmos/ethermint/x/evm/types" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/types" ) // CallEVM performs a smart contract method call using given args diff --git a/x/evmutil/keeper/evm_test.go b/x/evmutil/keeper/evm_test.go index c4fba03d..343d8a6c 100644 --- a/x/evmutil/keeper/evm_test.go +++ b/x/evmutil/keeper/evm_test.go @@ -17,7 +17,7 @@ import ( "github.com/evmos/ethermint/x/evm/statedb" "github.com/evmos/ethermint/x/evm/types" - "github.com/kava-labs/kava/x/evmutil/testutil" + "github.com/0glabs/0g-chain/x/evmutil/testutil" ) type evmKeeperTestSuite struct { diff --git a/x/evmutil/keeper/grpc_query.go b/x/evmutil/keeper/grpc_query.go index 0ff2d0e9..8485ce1f 100644 --- a/x/evmutil/keeper/grpc_query.go +++ b/x/evmutil/keeper/grpc_query.go @@ -10,7 +10,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/types" ) type queryServer struct { diff --git a/x/evmutil/keeper/grpc_query_test.go b/x/evmutil/keeper/grpc_query_test.go index 4f6c6c05..95341089 100644 --- a/x/evmutil/keeper/grpc_query_test.go +++ b/x/evmutil/keeper/grpc_query_test.go @@ -11,10 +11,10 @@ import ( "github.com/cosmos/cosmos-sdk/types/query" "github.com/stretchr/testify/suite" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/evmutil/keeper" - "github.com/kava-labs/kava/x/evmutil/testutil" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/x/evmutil/keeper" + "github.com/0glabs/0g-chain/x/evmutil/testutil" + "github.com/0glabs/0g-chain/x/evmutil/types" ) type grpcQueryTestSuite struct { diff --git a/x/evmutil/keeper/invariants.go b/x/evmutil/keeper/invariants.go index b8c880b1..6d9ac93b 100644 --- a/x/evmutil/keeper/invariants.go +++ b/x/evmutil/keeper/invariants.go @@ -6,7 +6,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/chaincfg" + "github.com/0glabs/0g-chain/x/evmutil/types" ) // RegisterInvariants registers the swap module invariants @@ -50,7 +51,7 @@ func FullyBackedInvariant(bankK types.BankKeeper, k Keeper) sdk.Invariant { }) bankAddr := authtypes.NewModuleAddress(types.ModuleName) - bankBalance := bankK.GetBalance(ctx, bankAddr, CosmosDenom).Amount.Mul(ConversionMultiplier) + bankBalance := bankK.GetBalance(ctx, bankAddr, chaincfg.DisplayDenom).Amount.Mul(ConversionMultiplier) broken = totalMinorBalances.GT(bankBalance) diff --git a/x/evmutil/keeper/invariants_test.go b/x/evmutil/keeper/invariants_test.go index 3b3867c0..41e7b23a 100644 --- a/x/evmutil/keeper/invariants_test.go +++ b/x/evmutil/keeper/invariants_test.go @@ -11,10 +11,11 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/stretchr/testify/suite" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/evmutil/keeper" - "github.com/kava-labs/kava/x/evmutil/testutil" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/chaincfg" + "github.com/0glabs/0g-chain/x/evmutil/keeper" + "github.com/0glabs/0g-chain/x/evmutil/testutil" + "github.com/0glabs/0g-chain/x/evmutil/types" ) type invariantTestSuite struct { @@ -46,10 +47,10 @@ func (suite *invariantTestSuite) SetupValidState() { keeper.ConversionMultiplier.QuoRaw(2), )) } - suite.FundModuleAccountWithKava( + suite.FundModuleAccountWithZgChain( types.ModuleName, sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(2)), // ( sum of all minor balances ) / conversion multiplier + sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(2)), // ( sum of all minor balances ) / conversion multiplier ), ) @@ -159,8 +160,8 @@ func (suite *invariantTestSuite) TestSmallBalances() { // increase minor balance at least above conversion multiplier suite.Keeper.AddBalance(suite.Ctx, suite.Addrs[0], keeper.ConversionMultiplier) - // add same number of ukava to avoid breaking other invariants - amt := sdk.NewCoins(sdk.NewInt64Coin(keeper.CosmosDenom, 1)) + // add same number of a0gi to avoid breaking other invariants + amt := sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 1)) suite.Require().NoError( suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, amt), ) @@ -190,7 +191,7 @@ func (suite *invariantTestSuite) TestSendToModuleAccountNotAllowed() { ToAddress: maccAddress.String(), Amount: coins, }) - suite.ErrorContains(err, "kava1w9vxuke5dz6hyza2j932qgmxltnfxwl78u920k is not allowed to receive funds: unauthorized") + suite.ErrorContains(err, "0g1w9vxuke5dz6hyza2j932qgmxltnfxwl78u920k is not allowed to receive funds: unauthorized") } func (suite *invariantTestSuite) TestCosmosCoinsFullyBackedInvariant() { diff --git a/x/evmutil/keeper/keeper.go b/x/evmutil/keeper/keeper.go index 02098c8d..967021c3 100644 --- a/x/evmutil/keeper/keeper.go +++ b/x/evmutil/keeper/keeper.go @@ -11,7 +11,7 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/types" ) // Keeper of the evmutil store. @@ -115,7 +115,7 @@ func (k Keeper) SetAccount(ctx sdk.Context, account types.Account) error { return nil } -// GetBalance returns the total balance of akava for a given account by address. +// GetBalance returns the total balance of neuron for a given account by address. func (k Keeper) GetBalance(ctx sdk.Context, addr sdk.AccAddress) sdkmath.Int { account := k.GetAccount(ctx, addr) if account == nil { @@ -124,7 +124,7 @@ func (k Keeper) GetBalance(ctx sdk.Context, addr sdk.AccAddress) sdkmath.Int { return account.Balance } -// SetBalance sets the total balance of akava for a given account by address. +// SetBalance sets the total balance of neuron for a given account by address. func (k Keeper) SetBalance(ctx sdk.Context, addr sdk.AccAddress, bal sdkmath.Int) error { account := k.GetAccount(ctx, addr) if account == nil { @@ -140,10 +140,10 @@ func (k Keeper) SetBalance(ctx sdk.Context, addr sdk.AccAddress, bal sdkmath.Int return k.SetAccount(ctx, *account) } -// SendBalance transfers the akava balance from sender addr to recipient addr. +// SendBalance transfers the neuron balance from sender addr to recipient addr. func (k Keeper) SendBalance(ctx sdk.Context, senderAddr sdk.AccAddress, recipientAddr sdk.AccAddress, amt sdkmath.Int) error { if amt.IsNegative() { - return fmt.Errorf("cannot send a negative amount of akava: %d", amt) + return fmt.Errorf("cannot send a negative amount of neuron: %d", amt) } if amt.IsZero() { @@ -162,13 +162,13 @@ func (k Keeper) SendBalance(ctx sdk.Context, senderAddr sdk.AccAddress, recipien return k.SetBalance(ctx, recipientAddr, receiverBal) } -// AddBalance increments the akava balance of an address. +// AddBalance increments the neuron balance of an address. func (k Keeper) AddBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdkmath.Int) error { bal := k.GetBalance(ctx, addr) return k.SetBalance(ctx, addr, amt.Add(bal)) } -// RemoveBalance decrements the akava balance of an address. +// RemoveBalance decrements the neuron balance of an address. func (k Keeper) RemoveBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdkmath.Int) error { if amt.IsNegative() { return fmt.Errorf("cannot remove a negative amount from balance: %d", amt) @@ -184,7 +184,7 @@ func (k Keeper) RemoveBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdkmath. return k.SetBalance(ctx, addr, finalBal) } -// SetDeployedCosmosCoinContract stores a single deployed ERC20KavaWrappedCosmosCoin contract address +// SetDeployedCosmosCoinContract stores a single deployed ERC20ZgChainWrappedCosmosCoin contract address func (k *Keeper) SetDeployedCosmosCoinContract(ctx sdk.Context, cosmosDenom string, contractAddress types.InternalEVMAddress) error { if err := sdk.ValidateDenom(cosmosDenom); err != nil { return errorsmod.Wrap(types.ErrInvalidCosmosDenom, cosmosDenom) @@ -203,7 +203,7 @@ func (k *Keeper) SetDeployedCosmosCoinContract(ctx sdk.Context, cosmosDenom stri return nil } -// SetDeployedCosmosCoinContract gets a deployed ERC20KavaWrappedCosmosCoin contract address by cosmos denom +// SetDeployedCosmosCoinContract gets a deployed ERC20ZgChainWrappedCosmosCoin contract address by cosmos denom // Returns the stored address and a bool indicating if it was found or not func (k *Keeper) GetDeployedCosmosCoinContract(ctx sdk.Context, cosmosDenom string) (types.InternalEVMAddress, bool) { store := ctx.KVStore(k.storeKey) diff --git a/x/evmutil/keeper/keeper_test.go b/x/evmutil/keeper/keeper_test.go index a5ea5c6e..bdbd6ad5 100644 --- a/x/evmutil/keeper/keeper_test.go +++ b/x/evmutil/keeper/keeper_test.go @@ -7,8 +7,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" - "github.com/kava-labs/kava/x/evmutil/testutil" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/testutil" + "github.com/0glabs/0g-chain/x/evmutil/types" ) type keeperTestSuite struct { diff --git a/x/evmutil/keeper/migrations.go b/x/evmutil/keeper/migrations.go index f74aa0ca..518b5f3e 100644 --- a/x/evmutil/keeper/migrations.go +++ b/x/evmutil/keeper/migrations.go @@ -1,8 +1,8 @@ package keeper import ( + v2 "github.com/0glabs/0g-chain/x/evmutil/migrations/v2" sdk "github.com/cosmos/cosmos-sdk/types" - v2 "github.com/kava-labs/kava/x/evmutil/migrations/v2" ) // Migrator is a struct for handling in-place store migrations. diff --git a/x/evmutil/keeper/msg_server.go b/x/evmutil/keeper/msg_server.go index 6d843500..cc8f3b7b 100644 --- a/x/evmutil/keeper/msg_server.go +++ b/x/evmutil/keeper/msg_server.go @@ -6,7 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/types" ) type msgServer struct { @@ -26,7 +26,7 @@ var _ types.MsgServer = msgServer{} //////////////////////////// // ConvertCoinToERC20 handles a MsgConvertCoinToERC20 message to convert -// sdk.Coin to Kava EVM tokens. +// sdk.Coin to 0gChain EVM tokens. func (s msgServer) ConvertCoinToERC20( goCtx context.Context, msg *types.MsgConvertCoinToERC20, @@ -64,7 +64,7 @@ func (s msgServer) ConvertCoinToERC20( } // ConvertERC20ToCoin handles a MsgConvertERC20ToCoin message to convert -// sdk.Coin to Kava EVM tokens. +// sdk.Coin to 0gChain EVM tokens. func (s msgServer) ConvertERC20ToCoin( goCtx context.Context, msg *types.MsgConvertERC20ToCoin, @@ -81,7 +81,7 @@ func (s msgServer) ConvertERC20ToCoin( return nil, fmt.Errorf("invalid receiver address: %w", err) } - contractAddr, err := types.NewInternalEVMAddressFromString(msg.KavaERC20Address) + contractAddr, err := types.NewInternalEVMAddressFromString(msg.ZgchainERC20Address) if err != nil { return nil, fmt.Errorf("invalid contract address: %w", err) } diff --git a/x/evmutil/keeper/msg_server_bep3_test.go b/x/evmutil/keeper/msg_server_bep3_test.go index d36c68fd..c50bd054 100644 --- a/x/evmutil/keeper/msg_server_bep3_test.go +++ b/x/evmutil/keeper/msg_server_bep3_test.go @@ -4,12 +4,12 @@ import ( sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/evmutil/testutil" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/testutil" + "github.com/0glabs/0g-chain/x/evmutil/types" ) func (suite *MsgServerSuite) TestConvertCoinToERC20_Bep3() { - invoker, err := sdk.AccAddressFromBech32("kava123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz") + invoker, err := sdk.AccAddressFromBech32("0g123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz") receiverAddr := testutil.MustNewInternalEVMAddressFromString("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2") suite.Require().NoError(err) @@ -198,10 +198,10 @@ func (suite *MsgServerSuite) TestConvertERC20ToCoin_Bep3() { { name: "invalid - invalid initiator address", msg: types.MsgConvertERC20ToCoin{ - Initiator: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc", - Receiver: invokerCosmosAddr.String(), - KavaERC20Address: contractAddr.String(), - Amount: sdkmath.NewInt(12e8), + Initiator: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc", + Receiver: invokerCosmosAddr.String(), + ZgchainERC20Address: contractAddr.String(), + Amount: sdkmath.NewInt(12e8), }, userErc20Balance: sdkmath.NewInt(2e18), errArgs: errArgs{ @@ -212,10 +212,10 @@ func (suite *MsgServerSuite) TestConvertERC20ToCoin_Bep3() { { name: "invalid - invalid receiver address", msg: types.MsgConvertERC20ToCoin{ - Initiator: invoker.String(), - Receiver: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc", - KavaERC20Address: contractAddr.String(), - Amount: sdkmath.NewInt(12e8), + Initiator: invoker.String(), + Receiver: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc", + ZgchainERC20Address: contractAddr.String(), + Amount: sdkmath.NewInt(12e8), }, userErc20Balance: sdkmath.NewInt(2e18), errArgs: errArgs{ @@ -226,10 +226,10 @@ func (suite *MsgServerSuite) TestConvertERC20ToCoin_Bep3() { { name: "invalid - invalid contract address", msg: types.MsgConvertERC20ToCoin{ - Initiator: invoker.String(), - Receiver: invokerCosmosAddr.String(), - KavaERC20Address: invokerCosmosAddr.String(), - Amount: sdkmath.NewInt(12e8), + Initiator: invoker.String(), + Receiver: invokerCosmosAddr.String(), + ZgchainERC20Address: invokerCosmosAddr.String(), + Amount: sdkmath.NewInt(12e8), }, userErc20Balance: sdkmath.NewInt(2e18), errArgs: errArgs{ diff --git a/x/evmutil/keeper/msg_server_test.go b/x/evmutil/keeper/msg_server_test.go index 89c7c04a..92015fb0 100644 --- a/x/evmutil/keeper/msg_server_test.go +++ b/x/evmutil/keeper/msg_server_test.go @@ -12,10 +12,10 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/math" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/evmutil/keeper" - "github.com/kava-labs/kava/x/evmutil/testutil" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/x/evmutil/keeper" + "github.com/0glabs/0g-chain/x/evmutil/testutil" + "github.com/0glabs/0g-chain/x/evmutil/types" ) type MsgServerSuite struct { @@ -34,7 +34,7 @@ func TestMsgServerSuite(t *testing.T) { } func (suite *MsgServerSuite) TestConvertCoinToERC20() { - invoker, err := sdk.AccAddressFromBech32("kava123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz") + invoker, err := sdk.AccAddressFromBech32("0g123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz") suite.Require().NoError(err) err = suite.App.FundAccount(suite.Ctx, invoker, sdk.NewCoins(sdk.NewCoin("erc20/usdc", sdkmath.NewInt(10000)))) @@ -185,10 +185,10 @@ func (suite *MsgServerSuite) TestConvertERC20ToCoin() { { "invalid - invalid hex address", types.MsgConvertERC20ToCoin{ - Initiator: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc", - Receiver: invokerCosmosAddr.String(), - KavaERC20Address: contractAddr.String(), - Amount: sdkmath.NewInt(10_000), + Initiator: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc", + Receiver: invokerCosmosAddr.String(), + ZgchainERC20Address: contractAddr.String(), + Amount: sdkmath.NewInt(10_000), }, math.MaxBig256, errArgs{ @@ -282,7 +282,7 @@ func (suite *MsgServerSuite) TestConvertCosmosCoinToERC20_InitialContractDeploy( // make the denom allowed for conversion params := suite.Keeper.GetParams(suite.Ctx) params.AllowedCosmosDenoms = types.NewAllowedCosmosCoinERC20Tokens( - types.NewAllowedCosmosCoinERC20Token(allowedDenom, "Kava EVM Atom", "ATOM", 6), + types.NewAllowedCosmosCoinERC20Token(allowedDenom, "0gChain EVM Atom", "ATOM", 6), ) suite.Keeper.SetParams(suite.Ctx, params) @@ -331,7 +331,7 @@ func (suite *MsgServerSuite) TestConvertCosmosCoinToERC20_InitialContractDeploy( { name: "invalid - bad initiator", msg: types.NewMsgConvertCosmosCoinToERC20( - "invalid-kava-address", + "invalid-0g-address", testutil.RandomEvmAddress().Hex(), sdk.NewInt64Coin(allowedDenom, 1e4), ), @@ -452,7 +452,7 @@ func (suite *MsgServerSuite) TestConvertCosmosCoinToERC20_AlreadyDeployedContrac // make the denom allowed for conversion params := suite.Keeper.GetParams(suite.Ctx) params.AllowedCosmosDenoms = types.NewAllowedCosmosCoinERC20Tokens( - types.NewAllowedCosmosCoinERC20Token(allowedDenom, "Kava EVM Atom", "ATOM", 6), + types.NewAllowedCosmosCoinERC20Token(allowedDenom, "0gChain EVM Atom", "ATOM", 6), ) suite.Keeper.SetParams(suite.Ctx, params) @@ -499,7 +499,7 @@ func (suite *MsgServerSuite) TestConvertCosmosCoinToERC20_AlreadyDeployedContrac // check total supply caller, key := testutil.RandomEvmAccount() totalSupply, err := suite.QueryContract( - types.ERC20KavaWrappedCosmosCoinContract.ABI, + types.ERC20ZgChainWrappedCosmosCoinContract.ABI, caller, key, contractAddress, @@ -639,7 +639,7 @@ func (suite *MsgServerSuite) TestConvertCosmosCoinFromERC20() { // expect erc20 total supply to reflect new value caller, key := testutil.RandomEvmAccount() totalSupply, err := suite.QueryContract( - types.ERC20KavaWrappedCosmosCoinContract.ABI, + types.ERC20ZgChainWrappedCosmosCoinContract.ABI, caller, key, contractAddress, diff --git a/x/evmutil/keeper/params.go b/x/evmutil/keeper/params.go index 2b13cb1a..76fabd21 100644 --- a/x/evmutil/keeper/params.go +++ b/x/evmutil/keeper/params.go @@ -6,7 +6,7 @@ import ( errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/types" ) // GetParams returns the total set of evm parameters. @@ -39,7 +39,7 @@ func (k Keeper) GetEnabledConversionPairFromERC20Address( ) (types.ConversionPair, error) { params := k.GetParams(ctx) for _, pair := range params.EnabledConversionPairs { - if bytes.Equal(pair.KavaERC20Address, address.Bytes()) { + if bytes.Equal(pair.ZgchainERC20Address, address.Bytes()) { return pair, nil } } diff --git a/x/evmutil/keeper/params_test.go b/x/evmutil/keeper/params_test.go index 4a1a016a..2839bc13 100644 --- a/x/evmutil/keeper/params_test.go +++ b/x/evmutil/keeper/params_test.go @@ -7,9 +7,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/evmutil/keeper" - "github.com/kava-labs/kava/x/evmutil/testutil" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/keeper" + "github.com/0glabs/0g-chain/x/evmutil/testutil" + "github.com/0glabs/0g-chain/x/evmutil/types" ) type ParamsTestSuite struct { @@ -23,8 +23,8 @@ func TestParamsSuite(t *testing.T) { func (suite *ParamsTestSuite) TestEnabledConversionPair() { pairAddr := testutil.MustNewInternalEVMAddressFromString("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2") expPair := types.ConversionPair{ - KavaERC20Address: pairAddr.Bytes(), - Denom: "weth", + ZgchainERC20Address: pairAddr.Bytes(), + Denom: "weth", } params := types.DefaultParams() params.EnabledConversionPairs = []types.ConversionPair{expPair} @@ -66,9 +66,9 @@ func (suite *keeperTestSuite) TestGetAllowedTokenMetadata() { atom := types.NewAllowedCosmosCoinERC20Token( "ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2", - "Kava EVM ATOM", "ATOM", 6, + "0gChain EVM ATOM", "ATOM", 6, ) - hard := types.NewAllowedCosmosCoinERC20Token("hard", "Kava EVM Hard", "HARD", 6) + hard := types.NewAllowedCosmosCoinERC20Token("hard", "0gChain EVM Hard", "HARD", 6) // init state with some allowed tokens params := suite.Keeper.GetParams(suite.Ctx) diff --git a/x/evmutil/migrations/v2/store.go b/x/evmutil/migrations/v2/store.go index aa506e16..493e0ea2 100644 --- a/x/evmutil/migrations/v2/store.go +++ b/x/evmutil/migrations/v2/store.go @@ -4,7 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/types" ) // MigrateStore performs in-place store migrations for consensus version 2 diff --git a/x/evmutil/migrations/v2/store_test.go b/x/evmutil/migrations/v2/store_test.go index 69a6cd99..3d3160d7 100644 --- a/x/evmutil/migrations/v2/store_test.go +++ b/x/evmutil/migrations/v2/store_test.go @@ -10,8 +10,8 @@ import ( moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - v2evmutil "github.com/kava-labs/kava/x/evmutil/migrations/v2" - "github.com/kava-labs/kava/x/evmutil/types" + v2evmutil "github.com/0glabs/0g-chain/x/evmutil/migrations/v2" + "github.com/0glabs/0g-chain/x/evmutil/types" ) func TestStoreMigrationAddsKeyTableIncludingNewParam(t *testing.T) { diff --git a/x/evmutil/module.go b/x/evmutil/module.go index 09ed8b11..c7e0ce64 100644 --- a/x/evmutil/module.go +++ b/x/evmutil/module.go @@ -15,9 +15,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/kava-labs/kava/x/evmutil/client/cli" - "github.com/kava-labs/kava/x/evmutil/keeper" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/client/cli" + "github.com/0glabs/0g-chain/x/evmutil/keeper" + "github.com/0glabs/0g-chain/x/evmutil/types" ) // ConsensusVersion defines the current module consensus version. diff --git a/x/evmutil/testutil/suite.go b/x/evmutil/testutil/suite.go index c09ec153..8b727c6d 100644 --- a/x/evmutil/testutil/suite.go +++ b/x/evmutil/testutil/suite.go @@ -36,9 +36,10 @@ import ( feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" "github.com/stretchr/testify/suite" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/evmutil/keeper" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/chaincfg" + "github.com/0glabs/0g-chain/x/evmutil/keeper" + "github.com/0glabs/0g-chain/x/evmutil/types" ) type Suite struct { @@ -81,14 +82,14 @@ func (suite *Suite) SetupTest() { suite.Addrs = addrs evmGenesis := evmtypes.DefaultGenesisState() - evmGenesis.Params.EvmDenom = "akava" + evmGenesis.Params.EvmDenom = chaincfg.BaseDenom feemarketGenesis := feemarkettypes.DefaultGenesisState() feemarketGenesis.Params.EnableHeight = 1 feemarketGenesis.Params.NoBaseFee = false cdc := suite.App.AppCodec() - coins := sdk.NewCoins(sdk.NewInt64Coin("ukava", 1000_000_000_000_000_000)) + coins := sdk.NewCoins(sdk.NewInt64Coin(chaincfg.DisplayDenom, 1000_000_000_000_000_000)) authGS := app.NewFundedGenStateWithSameCoins(cdc, coins, []sdk.AccAddress{ sdk.AccAddress(suite.Key1.PubKey().Address()), sdk.AccAddress(suite.Key2.PubKey().Address()), @@ -184,29 +185,29 @@ func (suite *Suite) ModuleBalance(denom string) sdk.Int { return suite.App.GetModuleAccountBalance(suite.Ctx, types.ModuleName, denom) } -func (suite *Suite) FundAccountWithKava(addr sdk.AccAddress, coins sdk.Coins) { - ukava := coins.AmountOf("ukava") - if ukava.IsPositive() { - err := suite.App.FundAccount(suite.Ctx, addr, sdk.NewCoins(sdk.NewCoin("ukava", ukava))) +func (suite *Suite) FundAccountWithZgChain(addr sdk.AccAddress, coins sdk.Coins) { + a0gi := coins.AmountOf(chaincfg.DisplayDenom) + if a0gi.IsPositive() { + err := suite.App.FundAccount(suite.Ctx, addr, sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, a0gi))) suite.Require().NoError(err) } - akava := coins.AmountOf("akava") - if akava.IsPositive() { - err := suite.Keeper.SetBalance(suite.Ctx, addr, akava) + neuron := coins.AmountOf(chaincfg.BaseDenom) + if neuron.IsPositive() { + err := suite.Keeper.SetBalance(suite.Ctx, addr, neuron) suite.Require().NoError(err) } } -func (suite *Suite) FundModuleAccountWithKava(moduleName string, coins sdk.Coins) { - ukava := coins.AmountOf("ukava") - if ukava.IsPositive() { - err := suite.App.FundModuleAccount(suite.Ctx, moduleName, sdk.NewCoins(sdk.NewCoin("ukava", ukava))) +func (suite *Suite) FundModuleAccountWithZgChain(moduleName string, coins sdk.Coins) { + a0gi := coins.AmountOf(chaincfg.DisplayDenom) + if a0gi.IsPositive() { + err := suite.App.FundModuleAccount(suite.Ctx, moduleName, sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, a0gi))) suite.Require().NoError(err) } - akava := coins.AmountOf("akava") - if akava.IsPositive() { + neuron := coins.AmountOf(chaincfg.BaseDenom) + if neuron.IsPositive() { addr := suite.AccountKeeper.GetModuleAddress(moduleName) - err := suite.Keeper.SetBalance(suite.Ctx, addr, akava) + err := suite.Keeper.SetBalance(suite.Ctx, addr, neuron) suite.Require().NoError(err) } } @@ -217,7 +218,7 @@ func (suite *Suite) DeployERC20() types.InternalEVMAddress { suite.App.FundModuleAccount( suite.Ctx, types.ModuleName, - sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(0))), + sdk.NewCoins(sdk.NewCoin(chaincfg.DisplayDenom, sdkmath.NewInt(0))), ) contractAddr, err := suite.Keeper.DeployTestMintableERC20Contract(suite.Ctx, "USDC", "USDC", uint8(18)) @@ -318,7 +319,7 @@ func (suite *Suite) SendTx( // Mint the max gas to the FeeCollector to ensure balance in case of refund suite.MintFeeCollector(sdk.NewCoins( sdk.NewCoin( - "ukava", + chaincfg.DisplayDenom, sdkmath.NewInt(baseFee.Int64()*int64(gasRes.Gas*2)), ))) diff --git a/x/evmutil/types/address.go b/x/evmutil/types/address.go index 859b4b80..e5e2238e 100644 --- a/x/evmutil/types/address.go +++ b/x/evmutil/types/address.go @@ -9,7 +9,7 @@ import ( ) // InternalEVMAddress is a type alias of common.Address to represent an address -// on the Kava EVM. +// on the 0gChain EVM. type InternalEVMAddress struct { common.Address } diff --git a/x/evmutil/types/address_test.go b/x/evmutil/types/address_test.go index bc8e80bb..aa4b842c 100644 --- a/x/evmutil/types/address_test.go +++ b/x/evmutil/types/address_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/kava-labs/kava/x/evmutil/testutil" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/testutil" + "github.com/0glabs/0g-chain/x/evmutil/types" "github.com/stretchr/testify/require" ) diff --git a/x/evmutil/types/bytes_test.go b/x/evmutil/types/bytes_test.go index 1109180c..317eb9f8 100644 --- a/x/evmutil/types/bytes_test.go +++ b/x/evmutil/types/bytes_test.go @@ -5,7 +5,7 @@ import ( "fmt" "testing" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/types" "github.com/stretchr/testify/require" ) diff --git a/x/evmutil/types/contract.go b/x/evmutil/types/contract.go index 115802dc..e5c78766 100644 --- a/x/evmutil/types/contract.go +++ b/x/evmutil/types/contract.go @@ -34,11 +34,11 @@ var ( // ERC20MintableBurnableAddress is the erc20 module address ERC20MintableBurnableAddress common.Address - //go:embed ethermint_json/ERC20KavaWrappedCosmosCoin.json - ERC20KavaWrappedCosmosCoinJSON []byte + //go:embed ethermint_json/ERC20ZgChainWrappedCosmosCoin.json + ERC20ZgChainWrappedCosmosCoinJSON []byte - // ERC20KavaWrappedCosmosCoinContract is the compiled erc20 contract - ERC20KavaWrappedCosmosCoinContract evmtypes.CompiledContract + // ERC20ZgChainWrappedCosmosCoinContract is the compiled erc20 contract + ERC20ZgChainWrappedCosmosCoinContract evmtypes.CompiledContract ) func init() { @@ -53,12 +53,12 @@ func init() { panic("loading ERC20MintableBurnable contract failed") } - err = json.Unmarshal(ERC20KavaWrappedCosmosCoinJSON, &ERC20KavaWrappedCosmosCoinContract) + err = json.Unmarshal(ERC20ZgChainWrappedCosmosCoinJSON, &ERC20ZgChainWrappedCosmosCoinContract) if err != nil { - panic(fmt.Sprintf("failed to unmarshal ERC20KavaWrappedCosmosCoinJSON: %s. %s", err, string(ERC20KavaWrappedCosmosCoinJSON))) + panic(fmt.Sprintf("failed to unmarshal ERC20ZgChainWrappedCosmosCoinJSON: %s. %s", err, string(ERC20ZgChainWrappedCosmosCoinJSON))) } - if len(ERC20KavaWrappedCosmosCoinContract.Bin) == 0 { - panic("loading ERC20KavaWrappedCosmosCoin contract failed") + if len(ERC20ZgChainWrappedCosmosCoinContract.Bin) == 0 { + panic("loading ERC20ZgChainWrappedCosmosCoin contract failed") } } diff --git a/x/evmutil/types/conversion_pair.go b/x/evmutil/types/conversion_pair.go index eab8b318..e2ead284 100644 --- a/x/evmutil/types/conversion_pair.go +++ b/x/evmutil/types/conversion_pair.go @@ -18,14 +18,14 @@ import ( // NewConversionPair returns a new ConversionPair. func NewConversionPair(address InternalEVMAddress, denom string) ConversionPair { return ConversionPair{ - KavaERC20Address: address.Address.Bytes(), - Denom: denom, + ZgchainERC20Address: address.Address.Bytes(), + Denom: denom, } } -// GetAddress returns the InternalEVMAddress of the Kava ERC20 address. +// GetAddress returns the InternalEVMAddress of the 0gChain ERC20 address. func (pair ConversionPair) GetAddress() InternalEVMAddress { - return NewInternalEVMAddress(common.BytesToAddress(pair.KavaERC20Address)) + return NewInternalEVMAddress(common.BytesToAddress(pair.ZgchainERC20Address)) } // Validate returns an error if the ConversionPair is invalid. @@ -34,12 +34,12 @@ func (pair ConversionPair) Validate() error { return fmt.Errorf("conversion pair denom invalid: %v", err) } - if len(pair.KavaERC20Address) != common.AddressLength { - return fmt.Errorf("address length is %v but expected %v", len(pair.KavaERC20Address), common.AddressLength) + if len(pair.ZgchainERC20Address) != common.AddressLength { + return fmt.Errorf("address length is %v but expected %v", len(pair.ZgchainERC20Address), common.AddressLength) } - if bytes.Equal(pair.KavaERC20Address, common.Address{}.Bytes()) { - return fmt.Errorf("address cannot be zero value %v", hex.EncodeToString(pair.KavaERC20Address)) + if bytes.Equal(pair.ZgchainERC20Address, common.Address{}.Bytes()) { + return fmt.Errorf("address cannot be zero value %v", hex.EncodeToString(pair.ZgchainERC20Address)) } return nil @@ -59,10 +59,10 @@ func (pairs ConversionPairs) Validate() error { denoms := map[string]bool{} for _, pair := range pairs { - if addrs[hex.EncodeToString(pair.KavaERC20Address)] { + if addrs[hex.EncodeToString(pair.ZgchainERC20Address)] { return fmt.Errorf( "found duplicate enabled conversion pair internal ERC20 address %s", - hex.EncodeToString(pair.KavaERC20Address), + hex.EncodeToString(pair.ZgchainERC20Address), ) } @@ -77,7 +77,7 @@ func (pairs ConversionPairs) Validate() error { return err } - addrs[hex.EncodeToString(pair.KavaERC20Address)] = true + addrs[hex.EncodeToString(pair.ZgchainERC20Address)] = true denoms[pair.Denom] = true } diff --git a/x/evmutil/types/conversion_pair.pb.go b/x/evmutil/types/conversion_pair.pb.go index 637dd783..1e62ae26 100644 --- a/x/evmutil/types/conversion_pair.pb.go +++ b/x/evmutil/types/conversion_pair.pb.go @@ -1,5 +1,5 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/evmutil/v1beta1/conversion_pair.proto +// source: zgc/evmutil/v1beta1/conversion_pair.proto package types @@ -24,11 +24,11 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package -// ConversionPair defines a Kava ERC20 address and corresponding denom that is +// ConversionPair defines a 0g-chain ERC20 address and corresponding denom that is // allowed to be converted between ERC20 and sdk.Coin type ConversionPair struct { - // ERC20 address of the token on the Kava EVM - KavaERC20Address HexBytes `protobuf:"bytes,1,opt,name=kava_erc20_address,json=kavaErc20Address,proto3,casttype=HexBytes" json:"kava_erc20_address,omitempty"` + // ERC20 address of the token on the 0g-chain EVM + ZgchainERC20Address HexBytes `protobuf:"bytes,1,opt,name=zgchain_erc20_address,json=zgchainErc20Address,proto3,casttype=HexBytes" json:"zgchain_erc20_address,omitempty"` // Denom of the corresponding sdk.Coin Denom string `protobuf:"bytes,2,opt,name=denom,proto3" json:"denom,omitempty"` } @@ -37,7 +37,7 @@ func (m *ConversionPair) Reset() { *m = ConversionPair{} } func (m *ConversionPair) String() string { return proto.CompactTextString(m) } func (*ConversionPair) ProtoMessage() {} func (*ConversionPair) Descriptor() ([]byte, []int) { - return fileDescriptor_e1396d08199817d0, []int{0} + return fileDescriptor_6bad9d4ffa6874ec, []int{0} } func (m *ConversionPair) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -85,7 +85,7 @@ func (m *AllowedCosmosCoinERC20Token) Reset() { *m = AllowedCosmosCoinER func (m *AllowedCosmosCoinERC20Token) String() string { return proto.CompactTextString(m) } func (*AllowedCosmosCoinERC20Token) ProtoMessage() {} func (*AllowedCosmosCoinERC20Token) Descriptor() ([]byte, []int) { - return fileDescriptor_e1396d08199817d0, []int{1} + return fileDescriptor_6bad9d4ffa6874ec, []int{1} } func (m *AllowedCosmosCoinERC20Token) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -115,39 +115,39 @@ func (m *AllowedCosmosCoinERC20Token) XXX_DiscardUnknown() { var xxx_messageInfo_AllowedCosmosCoinERC20Token proto.InternalMessageInfo func init() { - proto.RegisterType((*ConversionPair)(nil), "kava.evmutil.v1beta1.ConversionPair") - proto.RegisterType((*AllowedCosmosCoinERC20Token)(nil), "kava.evmutil.v1beta1.AllowedCosmosCoinERC20Token") + proto.RegisterType((*ConversionPair)(nil), "zgc.evmutil.v1beta1.ConversionPair") + proto.RegisterType((*AllowedCosmosCoinERC20Token)(nil), "zgc.evmutil.v1beta1.AllowedCosmosCoinERC20Token") } func init() { - proto.RegisterFile("kava/evmutil/v1beta1/conversion_pair.proto", fileDescriptor_e1396d08199817d0) + proto.RegisterFile("zgc/evmutil/v1beta1/conversion_pair.proto", fileDescriptor_6bad9d4ffa6874ec) } -var fileDescriptor_e1396d08199817d0 = []byte{ - // 356 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x3c, 0x91, 0xcf, 0x4a, 0xeb, 0x40, - 0x18, 0xc5, 0x33, 0xf7, 0xf6, 0x96, 0xde, 0xb1, 0x4a, 0x19, 0x8a, 0x84, 0x0a, 0xd3, 0xd8, 0x55, - 0x15, 0x4c, 0xda, 0xba, 0x73, 0xd7, 0xc6, 0x82, 0x50, 0x10, 0x09, 0xae, 0xdc, 0x84, 0x49, 0x32, - 0xd4, 0xd0, 0x24, 0x5f, 0xc9, 0xa4, 0xb1, 0x05, 0x1f, 0xc0, 0x95, 0xf8, 0x08, 0x2e, 0x7d, 0x14, - 0x97, 0x5d, 0xba, 0x2a, 0x35, 0x7d, 0x0b, 0x57, 0x92, 0x49, 0xe8, 0xee, 0x3b, 0xe7, 0x3b, 0xe7, - 0xc7, 0xfc, 0xc1, 0xe7, 0x33, 0x96, 0x32, 0x83, 0xa7, 0xe1, 0x22, 0xf1, 0x03, 0x23, 0xed, 0x3b, - 0x3c, 0x61, 0x7d, 0xc3, 0x85, 0x28, 0xe5, 0xb1, 0xf0, 0x21, 0xb2, 0xe7, 0xcc, 0x8f, 0xf5, 0x79, - 0x0c, 0x09, 0x90, 0x66, 0x9e, 0xd5, 0xcb, 0xac, 0x5e, 0x66, 0x5b, 0xcd, 0x29, 0x4c, 0x41, 0x06, - 0x8c, 0x7c, 0x2a, 0xb2, 0x9d, 0x67, 0x7c, 0x64, 0xee, 0x21, 0x77, 0xcc, 0x8f, 0xc9, 0x2d, 0x26, - 0x79, 0xdf, 0xe6, 0xb1, 0x3b, 0xe8, 0xd9, 0xcc, 0xf3, 0x62, 0x2e, 0x84, 0x8a, 0x34, 0xd4, 0xad, - 0x8f, 0xb4, 0x6c, 0xd3, 0x6e, 0x4c, 0x58, 0xca, 0xc6, 0x96, 0x39, 0xe8, 0x0d, 0x8b, 0xdd, 0xcf, - 0xa6, 0x5d, 0xbb, 0xe1, 0xcb, 0xd1, 0x2a, 0xe1, 0xc2, 0x6a, 0xe4, 0xdd, 0x71, 0x5e, 0x2d, 0xb7, - 0xa4, 0x89, 0xff, 0x79, 0x3c, 0x82, 0x50, 0xfd, 0xa3, 0xa1, 0xee, 0x7f, 0xab, 0x10, 0x57, 0x95, - 0x97, 0xf7, 0xb6, 0xd2, 0x79, 0x45, 0xf8, 0x64, 0x18, 0x04, 0xf0, 0xc4, 0x3d, 0x13, 0x44, 0x08, - 0xc2, 0x04, 0x3f, 0x92, 0xec, 0x7b, 0x98, 0xf1, 0x88, 0x9c, 0xe2, 0xba, 0x2b, 0x7d, 0xbb, 0x40, - 0x20, 0x89, 0x38, 0x28, 0xbc, 0xeb, 0xdc, 0x22, 0x04, 0x57, 0x22, 0x16, 0xf2, 0x92, 0x2e, 0x67, - 0x72, 0x8c, 0xab, 0x62, 0x15, 0x3a, 0x10, 0xa8, 0x7f, 0xa5, 0x5b, 0x2a, 0xd2, 0xc2, 0x35, 0x8f, - 0xbb, 0x7e, 0xc8, 0x02, 0xa1, 0x56, 0x34, 0xd4, 0x3d, 0xb4, 0xf6, 0xba, 0x38, 0xd0, 0x68, 0xb2, - 0xfd, 0xa6, 0xe8, 0x23, 0xa3, 0xe8, 0x33, 0xa3, 0x68, 0x9d, 0x51, 0xb4, 0xcd, 0x28, 0x7a, 0xdb, - 0x51, 0x65, 0xbd, 0xa3, 0xca, 0xd7, 0x8e, 0x2a, 0x0f, 0x67, 0x53, 0x3f, 0x79, 0x5c, 0x38, 0xba, - 0x0b, 0xa1, 0x91, 0xdf, 0xf5, 0x22, 0x60, 0x8e, 0x90, 0x93, 0xb1, 0xdc, 0xff, 0x4f, 0xb2, 0x9a, - 0x73, 0xe1, 0x54, 0xe5, 0x13, 0x5f, 0xfe, 0x06, 0x00, 0x00, 0xff, 0xff, 0x95, 0x40, 0xc5, 0x63, - 0xbc, 0x01, 0x00, 0x00, +var fileDescriptor_6bad9d4ffa6874ec = []byte{ + // 359 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x3c, 0x91, 0x3f, 0x4f, 0xc2, 0x40, + 0x18, 0xc6, 0x7b, 0x8a, 0x04, 0x4f, 0x74, 0x38, 0xd0, 0x34, 0x98, 0x1c, 0x88, 0x0b, 0x9a, 0xd8, + 0x16, 0xdc, 0xdc, 0xa0, 0x92, 0x38, 0x38, 0x98, 0xc6, 0xc4, 0x84, 0xa5, 0xb9, 0x5e, 0x2f, 0x47, + 0x63, 0xdb, 0x23, 0xbd, 0x82, 0xc0, 0x6e, 0xe2, 0x64, 0xfc, 0x08, 0x8e, 0x7e, 0x14, 0x47, 0x46, + 0x27, 0x82, 0xe5, 0x5b, 0x38, 0x19, 0xda, 0x86, 0xed, 0x7d, 0x9e, 0xf7, 0x97, 0x5f, 0xee, 0x0f, + 0xbc, 0x98, 0x73, 0xaa, 0xb3, 0x49, 0x30, 0x8e, 0x3d, 0x5f, 0x9f, 0xb4, 0x1d, 0x16, 0x93, 0xb6, + 0x4e, 0x45, 0x38, 0x61, 0x91, 0xf4, 0x44, 0x68, 0x8f, 0x88, 0x17, 0x69, 0xa3, 0x48, 0xc4, 0x02, + 0x55, 0xe6, 0x9c, 0x6a, 0x39, 0xaa, 0xe5, 0x68, 0xad, 0xca, 0x05, 0x17, 0xe9, 0x5e, 0xdf, 0x4c, + 0x19, 0xda, 0x7c, 0x05, 0xf0, 0xc8, 0xdc, 0x4a, 0x1e, 0x88, 0x17, 0xa1, 0x27, 0x78, 0x3c, 0xe7, + 0x74, 0x48, 0xbc, 0xd0, 0x66, 0x11, 0xed, 0x18, 0x36, 0x71, 0xdd, 0x88, 0x49, 0xa9, 0x82, 0x06, + 0x68, 0x95, 0x7b, 0xe7, 0xc9, 0xb2, 0x5e, 0x19, 0x64, 0x40, 0xdf, 0x32, 0x3b, 0x46, 0x37, 0x5b, + 0xff, 0x2d, 0xeb, 0xa5, 0x3b, 0x36, 0xed, 0xcd, 0x62, 0x26, 0xad, 0x4a, 0x6e, 0xe8, 0x6f, 0x04, + 0x39, 0x80, 0xaa, 0x70, 0xcf, 0x65, 0xa1, 0x08, 0xd4, 0x9d, 0x06, 0x68, 0xed, 0x5b, 0x59, 0xb8, + 0x29, 0xbc, 0x7d, 0xd6, 0x95, 0xe6, 0x3b, 0x80, 0xa7, 0x5d, 0xdf, 0x17, 0x2f, 0xcc, 0x35, 0x85, + 0x0c, 0x84, 0x34, 0x45, 0xae, 0x7f, 0x14, 0xcf, 0x2c, 0x44, 0x67, 0xb0, 0x4c, 0xd3, 0xde, 0xce, + 0x14, 0x20, 0x55, 0x1c, 0x64, 0xdd, 0xed, 0xa6, 0x42, 0x08, 0x16, 0x42, 0x12, 0xb0, 0xdc, 0x9e, + 0xce, 0xe8, 0x04, 0x16, 0xe5, 0x2c, 0x70, 0x84, 0xaf, 0xee, 0xa6, 0x6d, 0x9e, 0x50, 0x0d, 0x96, + 0x5c, 0x46, 0xbd, 0x80, 0xf8, 0x52, 0x2d, 0x34, 0x40, 0xeb, 0xd0, 0xda, 0xe6, 0xec, 0x40, 0xbd, + 0xfb, 0xd5, 0x2f, 0x06, 0x5f, 0x09, 0x06, 0xdf, 0x09, 0x06, 0x8b, 0x04, 0x83, 0x55, 0x82, 0xc1, + 0xc7, 0x1a, 0x2b, 0x8b, 0x35, 0x56, 0x7e, 0xd6, 0x58, 0x19, 0x5c, 0x72, 0x2f, 0x1e, 0x8e, 0x1d, + 0x8d, 0x8a, 0x40, 0x37, 0xb8, 0x4f, 0x1c, 0xa9, 0x1b, 0xfc, 0x2a, 0xbd, 0xb6, 0x3e, 0xdd, 0xfe, + 0x54, 0x3c, 0x1b, 0x31, 0xe9, 0x14, 0xd3, 0xd7, 0xbe, 0xfe, 0x0f, 0x00, 0x00, 0xff, 0xff, 0x3f, + 0x0a, 0x22, 0xb3, 0xc5, 0x01, 0x00, 0x00, } func (this *ConversionPair) VerboseEqual(that interface{}) error { @@ -175,8 +175,8 @@ func (this *ConversionPair) VerboseEqual(that interface{}) error { } else if this == nil { return fmt.Errorf("that is type *ConversionPair but is not nil && this == nil") } - if !bytes.Equal(this.KavaERC20Address, that1.KavaERC20Address) { - return fmt.Errorf("KavaERC20Address this(%v) Not Equal that(%v)", this.KavaERC20Address, that1.KavaERC20Address) + if !bytes.Equal(this.ZgchainERC20Address, that1.ZgchainERC20Address) { + return fmt.Errorf("ZgchainERC20Address this(%v) Not Equal that(%v)", this.ZgchainERC20Address, that1.ZgchainERC20Address) } if this.Denom != that1.Denom { return fmt.Errorf("Denom this(%v) Not Equal that(%v)", this.Denom, that1.Denom) @@ -202,7 +202,7 @@ func (this *ConversionPair) Equal(that interface{}) bool { } else if this == nil { return false } - if !bytes.Equal(this.KavaERC20Address, that1.KavaERC20Address) { + if !bytes.Equal(this.ZgchainERC20Address, that1.ZgchainERC20Address) { return false } if this.Denom != that1.Denom { @@ -309,10 +309,10 @@ func (m *ConversionPair) MarshalToSizedBuffer(dAtA []byte) (int, error) { i-- dAtA[i] = 0x12 } - if len(m.KavaERC20Address) > 0 { - i -= len(m.KavaERC20Address) - copy(dAtA[i:], m.KavaERC20Address) - i = encodeVarintConversionPair(dAtA, i, uint64(len(m.KavaERC20Address))) + if len(m.ZgchainERC20Address) > 0 { + i -= len(m.ZgchainERC20Address) + copy(dAtA[i:], m.ZgchainERC20Address) + i = encodeVarintConversionPair(dAtA, i, uint64(len(m.ZgchainERC20Address))) i-- dAtA[i] = 0xa } @@ -385,7 +385,7 @@ func (m *ConversionPair) Size() (n int) { } var l int _ = l - l = len(m.KavaERC20Address) + l = len(m.ZgchainERC20Address) if l > 0 { n += 1 + l + sovConversionPair(uint64(l)) } @@ -457,7 +457,7 @@ func (m *ConversionPair) Unmarshal(dAtA []byte) error { switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field KavaERC20Address", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ZgchainERC20Address", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { @@ -484,9 +484,9 @@ func (m *ConversionPair) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.KavaERC20Address = append(m.KavaERC20Address[:0], dAtA[iNdEx:postIndex]...) - if m.KavaERC20Address == nil { - m.KavaERC20Address = []byte{} + m.ZgchainERC20Address = append(m.ZgchainERC20Address[:0], dAtA[iNdEx:postIndex]...) + if m.ZgchainERC20Address == nil { + m.ZgchainERC20Address = []byte{} } iNdEx = postIndex case 2: diff --git a/x/evmutil/types/conversion_pairs_test.go b/x/evmutil/types/conversion_pairs_test.go index 70f0ba5c..6fa1abc8 100644 --- a/x/evmutil/types/conversion_pairs_test.go +++ b/x/evmutil/types/conversion_pairs_test.go @@ -3,8 +3,9 @@ package types_test import ( "testing" - "github.com/kava-labs/kava/x/evmutil/testutil" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/chaincfg" + "github.com/0glabs/0g-chain/x/evmutil/testutil" + "github.com/0glabs/0g-chain/x/evmutil/types" "github.com/stretchr/testify/require" ) @@ -76,8 +77,8 @@ func TestConversionPairValidate_Direct(t *testing.T) { { "valid", types.ConversionPair{ - KavaERC20Address: testutil.MustNewInternalEVMAddressFromString("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").Bytes(), - Denom: "weth", + ZgchainERC20Address: testutil.MustNewInternalEVMAddressFromString("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").Bytes(), + Denom: "weth", }, errArgs{ expectPass: true, @@ -87,8 +88,8 @@ func TestConversionPairValidate_Direct(t *testing.T) { { "invalid - length", types.ConversionPair{ - KavaERC20Address: []byte{1}, - Denom: "weth", + ZgchainERC20Address: []byte{1}, + Denom: "weth", }, errArgs{ expectPass: false, @@ -119,7 +120,7 @@ func TestConversionPair_GetAddress(t *testing.T) { "weth", ) - require.Equal(t, types.HexBytes(addr.Bytes()), pair.KavaERC20Address, "struct address should match input bytes") + require.Equal(t, types.HexBytes(addr.Bytes()), pair.ZgchainERC20Address, "struct address should match input bytes") require.Equal(t, addr, pair.GetAddress(), "get internal address should match input bytes") } @@ -142,7 +143,7 @@ func TestConversionPairs_Validate(t *testing.T) { ), types.NewConversionPair( testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000A"), - "kava", + chaincfg.DisplayDenom, ), types.NewConversionPair( testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000B"), @@ -162,7 +163,7 @@ func TestConversionPairs_Validate(t *testing.T) { ), types.NewConversionPair( testutil.MustNewInternalEVMAddressFromString("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"), - "kava", + chaincfg.DisplayDenom, ), types.NewConversionPair( testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000B"), @@ -183,16 +184,16 @@ func TestConversionPairs_Validate(t *testing.T) { ), types.NewConversionPair( testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000A"), - "kava", + chaincfg.DisplayDenom, ), types.NewConversionPair( testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000B"), - "kava", + chaincfg.DisplayDenom, ), ), errArgs{ expectPass: false, - contains: "found duplicate enabled conversion pair denom kava", + contains: "found duplicate enabled conversion pair denom a0gi", }, }, { @@ -208,7 +209,7 @@ func TestConversionPairs_Validate(t *testing.T) { ), types.NewConversionPair( testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000B"), - "kava", + chaincfg.DisplayDenom, ), ), errArgs{ @@ -240,12 +241,12 @@ func TestAllowedCosmosCoinERC20Token_Validate(t *testing.T) { }{ { name: "valid token", - token: types.NewAllowedCosmosCoinERC20Token("uatom", "Kava-wrapped ATOM", "kATOM", 6), + token: types.NewAllowedCosmosCoinERC20Token("uatom", "0gChain-wrapped ATOM", "kATOM", 6), expErr: "", }, { name: "valid - highest allowed decimals", - token: types.NewAllowedCosmosCoinERC20Token("uatom", "Kava-wrapped ATOM", "kATOM", 255), + token: types.NewAllowedCosmosCoinERC20Token("uatom", "0gChain-wrapped ATOM", "kATOM", 255), expErr: "", }, { @@ -280,7 +281,7 @@ func TestAllowedCosmosCoinERC20Token_Validate(t *testing.T) { }, { name: "invalid - decimals higher than uint8", - token: types.NewAllowedCosmosCoinERC20Token("uatom", "Kava-wrapped ATOM", "kATOM", 256), + token: types.NewAllowedCosmosCoinERC20Token("uatom", "0gChain-wrapped ATOM", "kATOM", 256), expErr: "decimals must be less than 256", }, } diff --git a/x/evmutil/types/ethermint_json/ERC20MintableBurnable.json b/x/evmutil/types/ethermint_json/ERC20MintableBurnable.json index 4a86254c..8c3249e9 100644 --- a/x/evmutil/types/ethermint_json/ERC20MintableBurnable.json +++ b/x/evmutil/types/ethermint_json/ERC20MintableBurnable.json @@ -1,4 +1,4 @@ { - "abi": "[{\"inputs\":[{\"internalType\":\"string\",\"name\":\"name\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"symbol\",\"type\":\"string\"},{\"internalType\":\"uint8\",\"name\":\"decimals_\",\"type\":\"uint8\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"toKavaAddr\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"ConvertToCoin\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"toAddr\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"Withdraw\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"toKavaAddr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"convertToCoin\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"subtractedValue\",\"type\":\"uint256\"}],\"name\":\"decreaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"addedValue\",\"type\":\"uint256\"}],\"name\":\"increaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"mint\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"toAddr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"withdraw\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"toAddr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"withdrawFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", + "abi": "[{\"inputs\":[{\"internalType\":\"string\",\"name\":\"name\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"symbol\",\"type\":\"string\"},{\"internalType\":\"uint8\",\"name\":\"decimals_\",\"type\":\"uint8\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to0gChainAddr\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"ConvertToCoin\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"toAddr\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"Withdraw\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to0gChainAddr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"convertToCoin\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"subtractedValue\",\"type\":\"uint256\"}],\"name\":\"decreaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"addedValue\",\"type\":\"uint256\"}],\"name\":\"increaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"mint\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"toAddr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"withdraw\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"toAddr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"withdrawFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", "bin": "60a06040523480156200001157600080fd5b5060405162002430380380620024308339818101604052810190620000379190620003fd565b828281600390805190602001906200005192919062000172565b5080600490805190602001906200006a92919062000172565b5050506200008d62000081620000a460201b60201c565b620000ac60201b60201c565b8060ff1660808160ff1681525050505050620004fc565b600033905090565b6000600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905081600560006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508173ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a35050565b8280546200018090620004c6565b90600052602060002090601f016020900481019282620001a45760008555620001f0565b82601f10620001bf57805160ff1916838001178555620001f0565b82800160010185558215620001f0579182015b82811115620001ef578251825591602001919060010190620001d2565b5b509050620001ff919062000203565b5090565b5b808211156200021e57600081600090555060010162000204565b5090565b6000604051905090565b600080fd5b600080fd5b600080fd5b600080fd5b6000601f19601f8301169050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b6200028b8262000240565b810181811067ffffffffffffffff82111715620002ad57620002ac62000251565b5b80604052505050565b6000620002c262000222565b9050620002d0828262000280565b919050565b600067ffffffffffffffff821115620002f357620002f262000251565b5b620002fe8262000240565b9050602081019050919050565b60005b838110156200032b5780820151818401526020810190506200030e565b838111156200033b576000848401525b50505050565b6000620003586200035284620002d5565b620002b6565b9050828152602081018484840111156200037757620003766200023b565b5b620003848482856200030b565b509392505050565b600082601f830112620003a457620003a362000236565b5b8151620003b684826020860162000341565b91505092915050565b600060ff82169050919050565b620003d781620003bf565b8114620003e357600080fd5b50565b600081519050620003f781620003cc565b92915050565b6000806000606084860312156200041957620004186200022c565b5b600084015167ffffffffffffffff8111156200043a576200043962000231565b5b62000448868287016200038c565b935050602084015167ffffffffffffffff8111156200046c576200046b62000231565b5b6200047a868287016200038c565b92505060406200048d86828701620003e6565b9150509250925092565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b60006002820490506001821680620004df57607f821691505b60208210811415620004f657620004f562000497565b5b50919050565b608051611f186200051860003960006104890152611f186000f3fe608060405234801561001057600080fd5b50600436106101165760003560e01c8063715018a6116100a2578063a457c2d711610071578063a457c2d7146102cf578063a9059cbb146102ff578063dd62ed3e1461032f578063f2fde38b1461035f578063f3fef3a31461037b57610116565b8063715018a61461026d5780638da5cb5b146102775780639555a9421461029557806395d89b41146102b157610116565b8063313ce567116100e9578063313ce567146101b757806339509351146101d55780633ffb6de41461020557806340c10f191461022157806370a082311461023d57610116565b806306fdde031461011b578063095ea7b31461013957806318160ddd1461016957806323b872dd14610187575b600080fd5b610123610397565b60405161013091906114e6565b60405180910390f35b610153600480360381019061014e91906115a1565b610429565b60405161016091906115fc565b60405180910390f35b61017161044c565b60405161017e9190611626565b60405180910390f35b6101a1600480360381019061019c9190611641565b610456565b6040516101ae91906115fc565b60405180910390f35b6101bf610485565b6040516101cc91906116b0565b60405180910390f35b6101ef60048036038101906101ea91906115a1565b6104ad565b6040516101fc91906115fc565b60405180910390f35b61021f600480360381019061021a91906115a1565b610557565b005b61023b600480360381019061023691906115a1565b6105d2565b005b610257600480360381019061025291906116cb565b61065c565b6040516102649190611626565b60405180910390f35b6102756106a4565b005b61027f61072c565b60405161028c9190611707565b60405180910390f35b6102af60048036038101906102aa9190611641565b610756565b005b6102b96107d5565b6040516102c691906114e6565b60405180910390f35b6102e960048036038101906102e491906115a1565b610867565b6040516102f691906115fc565b60405180910390f35b610319600480360381019061031491906115a1565b610951565b60405161032691906115fc565b60405180910390f35b61034960048036038101906103449190611722565b610974565b6040516103569190611626565b60405180910390f35b610379600480360381019061037491906116cb565b6109fb565b005b610395600480360381019061039091906115a1565b610af3565b005b6060600380546103a690611791565b80601f01602080910402602001604051908101604052809291908181526020018280546103d290611791565b801561041f5780601f106103f45761010080835404028352916020019161041f565b820191906000526020600020905b81548152906001019060200180831161040257829003601f168201915b5050505050905090565b600080610434610b66565b9050610441818585610b6e565b600191505092915050565b6000600254905090565b600080610461610b66565b905061046e858285610d39565b610479858585610dc5565b60019150509392505050565b60007f0000000000000000000000000000000000000000000000000000000000000000905090565b6000806104b8610b66565b905061054c818585600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461054791906117f2565b610b6e565b600191505092915050565b6105693361056361072c565b83610dc5565b8173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fe8854061d746326f096b71ed157108719c11403892b4ed81e2ec551e842edcf7836040516105c69190611626565b60405180910390a35050565b6105da610b66565b73ffffffffffffffffffffffffffffffffffffffff166105f861072c565b73ffffffffffffffffffffffffffffffffffffffff161461064e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161064590611894565b60405180910390fd5b6106588282611046565b5050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b6106ac610b66565b73ffffffffffffffffffffffffffffffffffffffff166106ca61072c565b73ffffffffffffffffffffffffffffffffffffffff1614610720576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161071790611894565b60405180910390fd5b61072a60006111a6565b565b6000600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b610761833383610d39565b61076b838261126c565b8173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f9b1bfa7fa9ee420a16e124f794c35ac9f90472acc99140eb2f6447c714cad8eb836040516107c89190611626565b60405180910390a3505050565b6060600480546107e490611791565b80601f016020809104026020016040519081016040528092919081815260200182805461081090611791565b801561085d5780601f106108325761010080835404028352916020019161085d565b820191906000526020600020905b81548152906001019060200180831161084057829003601f168201915b5050505050905090565b600080610872610b66565b90506000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905083811015610938576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161092f90611926565b60405180910390fd5b6109458286868403610b6e565b60019250505092915050565b60008061095c610b66565b9050610969818585610dc5565b600191505092915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b610a03610b66565b73ffffffffffffffffffffffffffffffffffffffff16610a2161072c565b73ffffffffffffffffffffffffffffffffffffffff1614610a77576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610a6e90611894565b60405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161415610ae7576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610ade906119b8565b60405180910390fd5b610af0816111a6565b50565b610afd338261126c565b8173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f9b1bfa7fa9ee420a16e124f794c35ac9f90472acc99140eb2f6447c714cad8eb83604051610b5a9190611626565b60405180910390a35050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610bde576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610bd590611a4a565b60405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610c4e576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610c4590611adc565b60405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92583604051610d2c9190611626565b60405180910390a3505050565b6000610d458484610974565b90507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8114610dbf5781811015610db1576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610da890611b48565b60405180910390fd5b610dbe8484848403610b6e565b5b50505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610e35576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610e2c90611bda565b60405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610ea5576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610e9c90611c6c565b60405180910390fd5b610eb0838383611443565b60008060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905081811015610f36576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610f2d90611cfe565b60405180910390fd5b8181036000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254610fc991906117f2565b925050819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161102d9190611626565b60405180910390a3611040848484611448565b50505050565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614156110b6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016110ad90611d6a565b60405180910390fd5b6110c260008383611443565b80600260008282546110d491906117f2565b92505081905550806000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825461112991906117f2565b925050819055508173ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8360405161118e9190611626565b60405180910390a36111a260008383611448565b5050565b6000600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905081600560006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508173ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a35050565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614156112dc576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016112d390611dfc565b60405180910390fd5b6112e882600083611443565b60008060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490508181101561136e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161136590611e8e565b60405180910390fd5b8181036000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555081600260008282546113c59190611eae565b92505081905550600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161142a9190611626565b60405180910390a361143e83600084611448565b505050565b505050565b505050565b600081519050919050565b600082825260208201905092915050565b60005b8381101561148757808201518184015260208101905061146c565b83811115611496576000848401525b50505050565b6000601f19601f8301169050919050565b60006114b88261144d565b6114c28185611458565b93506114d2818560208601611469565b6114db8161149c565b840191505092915050565b6000602082019050818103600083015261150081846114ad565b905092915050565b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60006115388261150d565b9050919050565b6115488161152d565b811461155357600080fd5b50565b6000813590506115658161153f565b92915050565b6000819050919050565b61157e8161156b565b811461158957600080fd5b50565b60008135905061159b81611575565b92915050565b600080604083850312156115b8576115b7611508565b5b60006115c685828601611556565b92505060206115d78582860161158c565b9150509250929050565b60008115159050919050565b6115f6816115e1565b82525050565b600060208201905061161160008301846115ed565b92915050565b6116208161156b565b82525050565b600060208201905061163b6000830184611617565b92915050565b60008060006060848603121561165a57611659611508565b5b600061166886828701611556565b935050602061167986828701611556565b925050604061168a8682870161158c565b9150509250925092565b600060ff82169050919050565b6116aa81611694565b82525050565b60006020820190506116c560008301846116a1565b92915050565b6000602082840312156116e1576116e0611508565b5b60006116ef84828501611556565b91505092915050565b6117018161152d565b82525050565b600060208201905061171c60008301846116f8565b92915050565b6000806040838503121561173957611738611508565b5b600061174785828601611556565b925050602061175885828601611556565b9150509250929050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b600060028204905060018216806117a957607f821691505b602082108114156117bd576117bc611762565b5b50919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b60006117fd8261156b565b91506118088361156b565b9250827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0382111561183d5761183c6117c3565b5b828201905092915050565b7f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572600082015250565b600061187e602083611458565b915061188982611848565b602082019050919050565b600060208201905081810360008301526118ad81611871565b9050919050565b7f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f7760008201527f207a65726f000000000000000000000000000000000000000000000000000000602082015250565b6000611910602583611458565b915061191b826118b4565b604082019050919050565b6000602082019050818103600083015261193f81611903565b9050919050565b7f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160008201527f6464726573730000000000000000000000000000000000000000000000000000602082015250565b60006119a2602683611458565b91506119ad82611946565b604082019050919050565b600060208201905081810360008301526119d181611995565b9050919050565b7f45524332303a20617070726f76652066726f6d20746865207a65726f2061646460008201527f7265737300000000000000000000000000000000000000000000000000000000602082015250565b6000611a34602483611458565b9150611a3f826119d8565b604082019050919050565b60006020820190508181036000830152611a6381611a27565b9050919050565b7f45524332303a20617070726f766520746f20746865207a65726f20616464726560008201527f7373000000000000000000000000000000000000000000000000000000000000602082015250565b6000611ac6602283611458565b9150611ad182611a6a565b604082019050919050565b60006020820190508181036000830152611af581611ab9565b9050919050565b7f45524332303a20696e73756666696369656e7420616c6c6f77616e6365000000600082015250565b6000611b32601d83611458565b9150611b3d82611afc565b602082019050919050565b60006020820190508181036000830152611b6181611b25565b9050919050565b7f45524332303a207472616e736665722066726f6d20746865207a65726f20616460008201527f6472657373000000000000000000000000000000000000000000000000000000602082015250565b6000611bc4602583611458565b9150611bcf82611b68565b604082019050919050565b60006020820190508181036000830152611bf381611bb7565b9050919050565b7f45524332303a207472616e7366657220746f20746865207a65726f206164647260008201527f6573730000000000000000000000000000000000000000000000000000000000602082015250565b6000611c56602383611458565b9150611c6182611bfa565b604082019050919050565b60006020820190508181036000830152611c8581611c49565b9050919050565b7f45524332303a207472616e7366657220616d6f756e742065786365656473206260008201527f616c616e63650000000000000000000000000000000000000000000000000000602082015250565b6000611ce8602683611458565b9150611cf382611c8c565b604082019050919050565b60006020820190508181036000830152611d1781611cdb565b9050919050565b7f45524332303a206d696e7420746f20746865207a65726f206164647265737300600082015250565b6000611d54601f83611458565b9150611d5f82611d1e565b602082019050919050565b60006020820190508181036000830152611d8381611d47565b9050919050565b7f45524332303a206275726e2066726f6d20746865207a65726f2061646472657360008201527f7300000000000000000000000000000000000000000000000000000000000000602082015250565b6000611de6602183611458565b9150611df182611d8a565b604082019050919050565b60006020820190508181036000830152611e1581611dd9565b9050919050565b7f45524332303a206275726e20616d6f756e7420657863656564732062616c616e60008201527f6365000000000000000000000000000000000000000000000000000000000000602082015250565b6000611e78602283611458565b9150611e8382611e1c565b604082019050919050565b60006020820190508181036000830152611ea781611e6b565b9050919050565b6000611eb98261156b565b9150611ec48361156b565b925082821015611ed757611ed66117c3565b5b82820390509291505056fea26469706673582212205e81ecf22949f6494b0e01ec43283836589d0f6b691b8c0558b33a68e74084e964736f6c63430008090033" } diff --git a/x/evmutil/types/ethermint_json/ERC20KavaWrappedCosmosCoin.json b/x/evmutil/types/ethermint_json/ERC20ZgChainWrappedCosmosCoin.json similarity index 100% rename from x/evmutil/types/ethermint_json/ERC20KavaWrappedCosmosCoin.json rename to x/evmutil/types/ethermint_json/ERC20ZgChainWrappedCosmosCoin.json diff --git a/x/evmutil/types/genesis.pb.go b/x/evmutil/types/genesis.pb.go index 93aa0b97..3f3064f7 100644 --- a/x/evmutil/types/genesis.pb.go +++ b/x/evmutil/types/genesis.pb.go @@ -1,5 +1,5 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/evmutil/v1beta1/genesis.proto +// source: zgc/evmutil/v1beta1/genesis.proto package types @@ -37,7 +37,7 @@ 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_d916ab97b8e628c2, []int{0} + return fileDescriptor_7bf39927f71414e6, []int{0} } func (m *GenesisState) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -69,7 +69,7 @@ var xxx_messageInfo_GenesisState proto.InternalMessageInfo // BalanceAccount defines an account in the evmutil module. type Account struct { Address github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=address,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"address,omitempty"` - // balance indicates the amount of akava owned by the address. + // balance indicates the amount of neuron owned by the address. Balance github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=balance,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"balance"` } @@ -77,7 +77,7 @@ func (m *Account) Reset() { *m = Account{} } func (m *Account) String() string { return proto.CompactTextString(m) } func (*Account) ProtoMessage() {} func (*Account) Descriptor() ([]byte, []int) { - return fileDescriptor_d916ab97b8e628c2, []int{1} + return fileDescriptor_7bf39927f71414e6, []int{1} } func (m *Account) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -109,7 +109,7 @@ var xxx_messageInfo_Account proto.InternalMessageInfo // Params defines the evmutil module params type Params struct { // enabled_conversion_pairs defines the list of conversion pairs allowed to be - // converted between Kava ERC20 and sdk.Coin + // converted between 0g-chain ERC20 and sdk.Coin EnabledConversionPairs ConversionPairs `protobuf:"bytes,4,rep,name=enabled_conversion_pairs,json=enabledConversionPairs,proto3,castrepeated=ConversionPairs" json:"enabled_conversion_pairs"` // allowed_cosmos_denoms is a list of denom & erc20 token metadata pairs. // if a denom is in the list, it is allowed to be converted to an erc20 in the evm. @@ -120,7 +120,7 @@ func (m *Params) Reset() { *m = Params{} } func (m *Params) String() string { return proto.CompactTextString(m) } func (*Params) ProtoMessage() {} func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_d916ab97b8e628c2, []int{2} + return fileDescriptor_7bf39927f71414e6, []int{2} } func (m *Params) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -164,48 +164,46 @@ func (m *Params) GetAllowedCosmosDenoms() AllowedCosmosCoinERC20Tokens { } func init() { - proto.RegisterType((*GenesisState)(nil), "kava.evmutil.v1beta1.GenesisState") - proto.RegisterType((*Account)(nil), "kava.evmutil.v1beta1.Account") - proto.RegisterType((*Params)(nil), "kava.evmutil.v1beta1.Params") + proto.RegisterType((*GenesisState)(nil), "zgc.evmutil.v1beta1.GenesisState") + proto.RegisterType((*Account)(nil), "zgc.evmutil.v1beta1.Account") + proto.RegisterType((*Params)(nil), "zgc.evmutil.v1beta1.Params") } -func init() { - proto.RegisterFile("kava/evmutil/v1beta1/genesis.proto", fileDescriptor_d916ab97b8e628c2) -} +func init() { proto.RegisterFile("zgc/evmutil/v1beta1/genesis.proto", fileDescriptor_7bf39927f71414e6) } -var fileDescriptor_d916ab97b8e628c2 = []byte{ - // 489 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x52, 0x41, 0x6b, 0x13, 0x41, - 0x14, 0xde, 0xa9, 0x21, 0xd1, 0x69, 0x41, 0xd8, 0x56, 0x8d, 0xa5, 0xce, 0x96, 0x50, 0x24, 0x0a, - 0xbb, 0x6b, 0xe2, 0xad, 0x08, 0xd2, 0x8d, 0xa2, 0xc5, 0x4b, 0x59, 0xc5, 0x83, 0x97, 0xf0, 0x76, - 0x77, 0x88, 0x4b, 0x76, 0x67, 0xc2, 0xce, 0x24, 0xb5, 0xff, 0x40, 0xf0, 0xa0, 0xfe, 0x03, 0x8f, - 0xe2, 0xb9, 0x3f, 0xa2, 0xe0, 0xa5, 0xf4, 0x24, 0x1e, 0x62, 0x4d, 0xfe, 0x85, 0x27, 0xd9, 0x99, - 0x49, 0xa8, 0x21, 0x8a, 0xa7, 0x9d, 0x7d, 0xf3, 0x7d, 0xef, 0xfb, 0xe6, 0x7b, 0x0f, 0x37, 0xfa, - 0x30, 0x02, 0x9f, 0x8e, 0xf2, 0xa1, 0x4c, 0x33, 0x7f, 0xd4, 0x8a, 0xa8, 0x84, 0x96, 0xdf, 0xa3, - 0x8c, 0x8a, 0x54, 0x78, 0x83, 0x82, 0x4b, 0x6e, 0x6f, 0x94, 0x18, 0xcf, 0x60, 0x3c, 0x83, 0xd9, - 0xbc, 0x19, 0x73, 0x91, 0x73, 0xd1, 0x55, 0x18, 0x5f, 0xff, 0x68, 0xc2, 0xe6, 0x46, 0x8f, 0xf7, - 0xb8, 0xae, 0x97, 0x27, 0x53, 0xbd, 0xbb, 0x54, 0x2a, 0xe6, 0x6c, 0x44, 0x0b, 0x91, 0x72, 0xd6, - 0x1d, 0x40, 0x5a, 0x68, 0x6c, 0xe3, 0x23, 0xc2, 0x6b, 0x4f, 0xb4, 0x89, 0xe7, 0x12, 0x24, 0xb5, - 0x1f, 0xe2, 0xcb, 0x10, 0xc7, 0x7c, 0xc8, 0xa4, 0xa8, 0xa3, 0xed, 0x4b, 0xcd, 0xd5, 0xf6, 0x2d, - 0x6f, 0x99, 0x2d, 0x6f, 0x4f, 0xa3, 0x82, 0xca, 0xc9, 0xd8, 0xb1, 0xc2, 0x39, 0xc9, 0xde, 0xc5, - 0xd5, 0x01, 0x14, 0x90, 0x8b, 0xfa, 0xca, 0x36, 0x6a, 0xae, 0xb6, 0xb7, 0x96, 0xd3, 0x0f, 0x14, - 0xc6, 0xb0, 0x0d, 0x63, 0xb7, 0xf2, 0xf6, 0x93, 0x63, 0x35, 0xbe, 0x22, 0x5c, 0x33, 0xdd, 0xed, - 0x08, 0xd7, 0x20, 0x49, 0x0a, 0x2a, 0x4a, 0x37, 0xa8, 0xb9, 0x16, 0x3c, 0xfd, 0x35, 0x76, 0xdc, - 0x5e, 0x2a, 0x5f, 0x0f, 0x23, 0x2f, 0xe6, 0xb9, 0xc9, 0xc3, 0x7c, 0x5c, 0x91, 0xf4, 0x7d, 0x79, - 0x34, 0xa0, 0xa2, 0xb4, 0xb7, 0xa7, 0x89, 0x67, 0xc7, 0xee, 0xba, 0x49, 0xcd, 0x54, 0x82, 0x23, - 0x49, 0x45, 0x38, 0x6b, 0x6c, 0xbf, 0xc4, 0xb5, 0x08, 0x32, 0x60, 0x31, 0x55, 0x96, 0xaf, 0x04, - 0x0f, 0x4a, 0x53, 0xdf, 0xc7, 0xce, 0xed, 0xff, 0xd0, 0xd9, 0x67, 0xf2, 0xec, 0xd8, 0xc5, 0x46, - 0x60, 0x9f, 0xc9, 0x70, 0xd6, 0xcc, 0xbc, 0xe6, 0xfd, 0x0a, 0xae, 0xea, 0xc7, 0xda, 0x87, 0xb8, - 0x4e, 0x19, 0x44, 0x19, 0x4d, 0xba, 0x0b, 0xd3, 0x10, 0xf5, 0x8a, 0xca, 0x7a, 0x67, 0x79, 0x58, - 0x9d, 0x39, 0xfa, 0x00, 0xd2, 0x22, 0xb8, 0x51, 0xfa, 0xfb, 0xf2, 0xc3, 0xb9, 0xfa, 0x67, 0x5d, - 0x84, 0xd7, 0x4d, 0xfb, 0x85, 0xba, 0xfd, 0x0e, 0xe1, 0x6b, 0x90, 0x65, 0xfc, 0x50, 0x29, 0xab, - 0x6d, 0x4a, 0x28, 0xe3, 0xf9, 0x6c, 0xc4, 0xad, 0xbf, 0x8c, 0x58, 0x53, 0x3a, 0x8a, 0xd1, 0xe1, - 0x29, 0x7b, 0x1c, 0x76, 0xda, 0xf7, 0x5e, 0xf0, 0x3e, 0x65, 0xc1, 0x8e, 0xf1, 0xb0, 0xf5, 0x0f, - 0x90, 0x08, 0xd7, 0xe1, 0xe2, 0xed, 0x23, 0xa5, 0x19, 0x3c, 0x3b, 0xff, 0x49, 0xd0, 0xe7, 0x09, - 0x41, 0x27, 0x13, 0x82, 0x4e, 0x27, 0x04, 0x9d, 0x4f, 0x08, 0xfa, 0x30, 0x25, 0xd6, 0xe9, 0x94, - 0x58, 0xdf, 0xa6, 0xc4, 0x7a, 0x75, 0xe7, 0x42, 0xf0, 0xa5, 0x33, 0x37, 0x83, 0x48, 0xa8, 0x93, - 0xff, 0x66, 0xbe, 0xd8, 0x2a, 0xff, 0xa8, 0xaa, 0xf6, 0xf8, 0xfe, 0xef, 0x00, 0x00, 0x00, 0xff, - 0xff, 0xa1, 0xec, 0x74, 0x78, 0x60, 0x03, 0x00, 0x00, +var fileDescriptor_7bf39927f71414e6 = []byte{ + // 494 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x52, 0x4f, 0x6b, 0xd4, 0x40, + 0x1c, 0xcd, 0xd4, 0x65, 0x57, 0xa7, 0x05, 0x21, 0xeb, 0x9f, 0xb5, 0x96, 0xa4, 0x56, 0x91, 0x55, + 0x48, 0xb2, 0x5d, 0x4f, 0x8a, 0x08, 0xcd, 0x2a, 0x5a, 0xf0, 0x50, 0xa2, 0x78, 0xf0, 0xb2, 0x4c, + 0x26, 0x43, 0x3a, 0x34, 0x99, 0x59, 0x32, 0xb3, 0xab, 0xed, 0x27, 0x10, 0x41, 0xf4, 0x23, 0x78, + 0x14, 0xcf, 0xfd, 0x10, 0x05, 0x2f, 0xa5, 0x27, 0xf1, 0xb0, 0xd6, 0xdd, 0x6f, 0xe1, 0x49, 0x32, + 0x33, 0xbb, 0xd4, 0x25, 0x88, 0xa7, 0x24, 0x2f, 0xef, 0xfd, 0xde, 0x9b, 0x37, 0x3f, 0x78, 0xe3, + 0x20, 0xc5, 0x01, 0x19, 0xe5, 0x43, 0x49, 0xb3, 0x60, 0xb4, 0x19, 0x13, 0x89, 0x36, 0x83, 0x94, + 0x30, 0x22, 0xa8, 0xf0, 0x07, 0x05, 0x97, 0xdc, 0x6e, 0x1e, 0xa4, 0xd8, 0x37, 0x14, 0xdf, 0x50, + 0x56, 0xaf, 0x61, 0x2e, 0x72, 0x2e, 0xfa, 0x8a, 0x12, 0xe8, 0x0f, 0xcd, 0x5f, 0xbd, 0x94, 0xf2, + 0x94, 0x6b, 0xbc, 0x7c, 0x33, 0xe8, 0x9d, 0x2a, 0x23, 0xcc, 0xd9, 0x88, 0x14, 0x82, 0x72, 0xd6, + 0x1f, 0x20, 0x5a, 0x68, 0xea, 0xc6, 0x47, 0x00, 0x57, 0x9e, 0xea, 0x08, 0x2f, 0x24, 0x92, 0xc4, + 0x7e, 0x04, 0xcf, 0x23, 0x8c, 0xf9, 0x90, 0x49, 0xd1, 0x02, 0xeb, 0xe7, 0xda, 0xcb, 0xdd, 0x35, + 0xbf, 0x22, 0x94, 0xbf, 0xa5, 0x49, 0x61, 0xed, 0x68, 0xec, 0x5a, 0xd1, 0x5c, 0x63, 0xdf, 0x87, + 0xf5, 0x01, 0x2a, 0x50, 0x2e, 0x5a, 0x4b, 0xeb, 0xa0, 0xbd, 0xdc, 0xbd, 0x5e, 0xa9, 0xde, 0x51, + 0x14, 0x23, 0x36, 0x82, 0x07, 0xb5, 0x77, 0x9f, 0x5d, 0x6b, 0xe3, 0x1b, 0x80, 0x0d, 0x33, 0xdc, + 0x8e, 0x61, 0x03, 0x25, 0x49, 0x41, 0x44, 0x99, 0x05, 0xb4, 0x57, 0xc2, 0x67, 0xbf, 0xc7, 0xae, + 0x97, 0x52, 0xb9, 0x3b, 0x8c, 0x7d, 0xcc, 0x73, 0x53, 0x86, 0x79, 0x78, 0x22, 0xd9, 0x0b, 0xe4, + 0xfe, 0x80, 0x88, 0x32, 0xdd, 0x96, 0x16, 0x9e, 0x1c, 0x7a, 0x4d, 0x53, 0x99, 0x41, 0xc2, 0x7d, + 0x49, 0x44, 0x34, 0x1b, 0x6c, 0xbf, 0x82, 0x8d, 0x18, 0x65, 0x88, 0x61, 0xa2, 0x12, 0x5f, 0x08, + 0x1f, 0x96, 0xa1, 0x7e, 0x8c, 0xdd, 0xdb, 0xff, 0xe1, 0xb3, 0xcd, 0xe4, 0xc9, 0xa1, 0x07, 0x8d, + 0xc1, 0x36, 0x93, 0xd1, 0x6c, 0x98, 0x39, 0xcd, 0x87, 0x25, 0x58, 0xd7, 0x87, 0xb5, 0x47, 0xb0, + 0x45, 0x18, 0x8a, 0x33, 0x92, 0xf4, 0x17, 0xee, 0x42, 0xb4, 0x6a, 0xaa, 0xe9, 0x9b, 0x95, 0x5d, + 0xf5, 0xe6, 0xe4, 0x1d, 0x44, 0x8b, 0xf0, 0x6a, 0x19, 0xef, 0xeb, 0x4f, 0xf7, 0xe2, 0xdf, 0xb8, + 0x88, 0xae, 0x98, 0xe9, 0x0b, 0xb8, 0xfd, 0x1e, 0xc0, 0xcb, 0x28, 0xcb, 0xf8, 0x1b, 0x65, 0xac, + 0x36, 0x29, 0x21, 0x8c, 0xe7, 0xb3, 0xfb, 0xed, 0x54, 0xdf, 0xaf, 0x56, 0xf4, 0x94, 0xa0, 0xc7, + 0x29, 0x7b, 0x12, 0xf5, 0xba, 0x9d, 0x97, 0x7c, 0x8f, 0xb0, 0xf0, 0x96, 0x89, 0xb0, 0xf6, 0x0f, + 0x92, 0x88, 0x9a, 0xe8, 0xec, 0xdf, 0xc7, 0xca, 0x32, 0x7c, 0x7e, 0xfa, 0xcb, 0x01, 0x5f, 0x26, + 0x0e, 0x38, 0x9a, 0x38, 0xe0, 0x78, 0xe2, 0x80, 0xd3, 0x89, 0x03, 0x3e, 0x4d, 0x1d, 0xeb, 0x78, + 0xea, 0x58, 0xdf, 0xa7, 0x8e, 0xf5, 0xfa, 0xee, 0x99, 0xda, 0x3b, 0x69, 0x86, 0x62, 0x11, 0x74, + 0x52, 0x0f, 0xef, 0x22, 0xca, 0x82, 0xb7, 0xf3, 0xad, 0x56, 0xf5, 0xc7, 0x75, 0xb5, 0xc4, 0xf7, + 0xfe, 0x04, 0x00, 0x00, 0xff, 0xff, 0x55, 0x8b, 0x5d, 0xb5, 0x5a, 0x03, 0x00, 0x00, } func (this *GenesisState) VerboseEqual(that interface{}) error { diff --git a/x/evmutil/types/genesis_test.go b/x/evmutil/types/genesis_test.go index 5ec5cded..55037691 100644 --- a/x/evmutil/types/genesis_test.go +++ b/x/evmutil/types/genesis_test.go @@ -7,8 +7,8 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/x/evmutil/types" ) func TestGenesisState_Validate(t *testing.T) { diff --git a/x/evmutil/types/keys.go b/x/evmutil/types/keys.go index 3fdab90a..0d5830a3 100644 --- a/x/evmutil/types/keys.go +++ b/x/evmutil/types/keys.go @@ -21,7 +21,7 @@ const ( var ( // AccountStoreKeyPrefix is the prefix for keys that store accounts AccountStoreKeyPrefix = []byte{0x00} - // DeployedCosmosCoinContractKeyPrefix is the key for storing deployed KavaWrappedCosmosCoinERC20s contract addresses + // DeployedCosmosCoinContractKeyPrefix is the key for storing deployed ZgChainWrappedCosmosCoinERC20s contract addresses DeployedCosmosCoinContractKeyPrefix = []byte{0x01} ) diff --git a/x/evmutil/types/keys_test.go b/x/evmutil/types/keys_test.go index e102da19..9dcefbff 100644 --- a/x/evmutil/types/keys_test.go +++ b/x/evmutil/types/keys_test.go @@ -5,7 +5,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/x/evmutil/types" ) func TestDeployedCosmosCoinContractKey(t *testing.T) { diff --git a/x/evmutil/types/msg.go b/x/evmutil/types/msg.go index 8c9b5650..16b9ac70 100644 --- a/x/evmutil/types/msg.go +++ b/x/evmutil/types/msg.go @@ -102,10 +102,10 @@ func NewMsgConvertERC20ToCoin( amount sdkmath.Int, ) MsgConvertERC20ToCoin { return MsgConvertERC20ToCoin{ - Initiator: initiator.String(), - Receiver: receiver.String(), - KavaERC20Address: contractAddr.String(), - Amount: amount, + Initiator: initiator.String(), + Receiver: receiver.String(), + ZgchainERC20Address: contractAddr.String(), + Amount: amount, } } @@ -125,7 +125,7 @@ func (msg MsgConvertERC20ToCoin) ValidateBasic() error { ) } - if !common.IsHexAddress(msg.KavaERC20Address) { + if !common.IsHexAddress(msg.ZgchainERC20Address) { return errorsmod.Wrap( sdkerrors.ErrInvalidAddress, "erc20 contract address is not a valid hex address", diff --git a/x/evmutil/types/msg_test.go b/x/evmutil/types/msg_test.go index 1a73fdaa..1a323387 100644 --- a/x/evmutil/types/msg_test.go +++ b/x/evmutil/types/msg_test.go @@ -3,9 +3,10 @@ package types_test import ( "testing" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/evmutil/testutil" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/chaincfg" + "github.com/0glabs/0g-chain/x/evmutil/testutil" + "github.com/0glabs/0g-chain/x/evmutil/types" "github.com/stretchr/testify/require" sdkmath "cosmossdk.io/math" @@ -13,7 +14,7 @@ import ( ) func TestMsgConvertCoinToERC20(t *testing.T) { - app.SetSDKConfig() + chaincfg.SetSDKConfig() type errArgs struct { expectPass bool @@ -29,7 +30,7 @@ func TestMsgConvertCoinToERC20(t *testing.T) { }{ { "valid", - "kava123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", + "0g123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", sdk.NewCoin("erc20/weth", sdkmath.NewInt(1234)), errArgs{ @@ -38,7 +39,7 @@ func TestMsgConvertCoinToERC20(t *testing.T) { }, { "valid-bnb", - "kava123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", + "0g123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", sdk.NewCoin("bnb", sdkmath.NewInt(1234)), errArgs{ @@ -47,7 +48,7 @@ func TestMsgConvertCoinToERC20(t *testing.T) { }, { "invalid - odd length hex address", - "kava123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", + "0g123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc", sdk.NewCoin("erc20/weth", sdkmath.NewInt(1234)), errArgs{ @@ -57,7 +58,7 @@ func TestMsgConvertCoinToERC20(t *testing.T) { }, { "invalid - zero amount", - "kava123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", + "0g123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", sdk.NewCoin("erc20/weth", sdkmath.NewInt(0)), errArgs{ @@ -67,7 +68,7 @@ func TestMsgConvertCoinToERC20(t *testing.T) { }, { "invalid - negative amount", - "kava123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", + "0g123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", // Create manually so there is no validation sdk.Coin{Denom: "erc20/weth", Amount: sdkmath.NewInt(-1234)}, @@ -78,7 +79,7 @@ func TestMsgConvertCoinToERC20(t *testing.T) { }, { "invalid - empty denom", - "kava123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", + "0g123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", sdk.Coin{Denom: "", Amount: sdkmath.NewInt(-1234)}, errArgs{ @@ -88,7 +89,7 @@ func TestMsgConvertCoinToERC20(t *testing.T) { }, { "invalid - invalid denom", - "kava123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", + "0g123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", sdk.Coin{Denom: "h", Amount: sdkmath.NewInt(-1234)}, errArgs{ @@ -118,7 +119,7 @@ func TestMsgConvertCoinToERC20(t *testing.T) { } func TestMsgConvertERC20ToCoin(t *testing.T) { - app.SetSDKConfig() + chaincfg.SetSDKConfig() type errArgs struct { expectPass bool @@ -135,7 +136,7 @@ func TestMsgConvertERC20ToCoin(t *testing.T) { }{ { "valid", - "kava123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", + "0g123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", "0x404F9466d758eA33eA84CeBE9E444b06533b369e", sdkmath.NewInt(1234), @@ -145,7 +146,7 @@ func TestMsgConvertERC20ToCoin(t *testing.T) { }, { "invalid - odd length hex address", - "kava123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", + "0g123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc", "0x404F9466d758eA33eA84CeBE9E444b06533b369e", sdkmath.NewInt(1234), @@ -156,7 +157,7 @@ func TestMsgConvertERC20ToCoin(t *testing.T) { }, { "invalid - zero amount", - "kava123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", + "0g123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", "0x404F9466d758eA33eA84CeBE9E444b06533b369e", sdkmath.NewInt(0), @@ -167,7 +168,7 @@ func TestMsgConvertERC20ToCoin(t *testing.T) { }, { "invalid - negative amount", - "kava123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", + "0g123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", "0x404F9466d758eA33eA84CeBE9E444b06533b369e", sdkmath.NewInt(-1234), @@ -178,7 +179,7 @@ func TestMsgConvertERC20ToCoin(t *testing.T) { }, { "invalid - invalid contract address", - "kava123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", + "0g123fxg0l602etulhhcdm0vt7l57qya5wjcrwhzz", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", "0x404F9466d758eA33eA84CeBE9E444b06533b369", sdkmath.NewInt(1234), @@ -192,10 +193,10 @@ func TestMsgConvertERC20ToCoin(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { msg := types.MsgConvertERC20ToCoin{ - Initiator: tc.initiator, - Receiver: tc.receiver, - KavaERC20Address: tc.contractAddr, - Amount: tc.amount, + Initiator: tc.initiator, + Receiver: tc.receiver, + ZgchainERC20Address: tc.contractAddr, + Amount: tc.amount, } err := msg.ValidateBasic() @@ -210,7 +211,7 @@ func TestMsgConvertERC20ToCoin(t *testing.T) { } func TestConvertCosmosCoinToERC20_ValidateBasic(t *testing.T) { - validKavaAddr := app.RandomAddress() + validZgChainAddr := app.RandomAddress() validHexAddr, _ := testutil.RandomEvmAccount() invalidAddr := "not-an-address" validAmount := sdk.NewInt64Coin("hard", 5e3) @@ -224,14 +225,14 @@ func TestConvertCosmosCoinToERC20_ValidateBasic(t *testing.T) { }{ { name: "valid", - initiator: validKavaAddr.String(), + initiator: validZgChainAddr.String(), receiver: validHexAddr.String(), amount: validAmount, expectedErr: "", }, { - name: "invalid - sending to kava addr", - initiator: validKavaAddr.String(), + name: "invalid - sending to 0g addr", + initiator: validZgChainAddr.String(), receiver: app.RandomAddress().String(), amount: validAmount, expectedErr: "receiver is not a valid hex address", @@ -245,35 +246,35 @@ func TestConvertCosmosCoinToERC20_ValidateBasic(t *testing.T) { }, { name: "invalid - invalid receiver", - initiator: validKavaAddr.String(), + initiator: validZgChainAddr.String(), receiver: invalidAddr, amount: validAmount, expectedErr: "receiver is not a valid hex address", }, { name: "invalid - invalid amount - nil", - initiator: validKavaAddr.String(), + initiator: validZgChainAddr.String(), receiver: validHexAddr.String(), amount: sdk.Coin{}, expectedErr: "invalid coins", }, { name: "invalid - invalid amount - zero", - initiator: validKavaAddr.String(), + initiator: validZgChainAddr.String(), receiver: validHexAddr.String(), amount: sdk.NewInt64Coin("magic", 0), expectedErr: "invalid coins", }, { name: "invalid - invalid amount - negative", - initiator: validKavaAddr.String(), + initiator: validZgChainAddr.String(), receiver: validHexAddr.String(), amount: sdk.Coin{Denom: "magic", Amount: sdkmath.NewInt(-42)}, expectedErr: "invalid coins", }, { name: "invalid - invalid amount - invalid denom", - initiator: validKavaAddr.String(), + initiator: validZgChainAddr.String(), receiver: validHexAddr.String(), amount: sdk.Coin{Denom: "", Amount: sdkmath.NewInt(42)}, expectedErr: "invalid coins", @@ -322,7 +323,7 @@ func TestConvertCosmosCoinToERC20_GetSigners(t *testing.T) { func TestConvertCosmosCoinFromERC20_ValidateBasic(t *testing.T) { validHexAddr := testutil.RandomEvmAddress() - validKavaAddr := app.RandomAddress() + validZgChainAddr := app.RandomAddress() invalidAddr := "not-an-address" validAmount := sdk.NewInt64Coin("hard", 5e3) @@ -336,7 +337,7 @@ func TestConvertCosmosCoinFromERC20_ValidateBasic(t *testing.T) { { name: "valid", initiator: validHexAddr.String(), - receiver: validKavaAddr.String(), + receiver: validZgChainAddr.String(), amount: validAmount, expectedErr: "", }, @@ -364,28 +365,28 @@ func TestConvertCosmosCoinFromERC20_ValidateBasic(t *testing.T) { { name: "invalid - invalid amount - nil", initiator: validHexAddr.String(), - receiver: validKavaAddr.String(), + receiver: validZgChainAddr.String(), amount: sdk.Coin{}, expectedErr: "invalid coins", }, { name: "invalid - invalid amount - zero", initiator: validHexAddr.String(), - receiver: validKavaAddr.String(), + receiver: validZgChainAddr.String(), amount: sdk.NewInt64Coin("magic", 0), expectedErr: "invalid coins", }, { name: "invalid - invalid amount - negative", initiator: validHexAddr.String(), - receiver: validKavaAddr.String(), + receiver: validZgChainAddr.String(), amount: sdk.Coin{Denom: "magic", Amount: sdkmath.NewInt(-42)}, expectedErr: "invalid coins", }, { name: "invalid - invalid amount - invalid denom", initiator: validHexAddr.String(), - receiver: validKavaAddr.String(), + receiver: validZgChainAddr.String(), amount: sdk.Coin{Denom: "", Amount: sdkmath.NewInt(42)}, expectedErr: "invalid coins", }, diff --git a/x/evmutil/types/params_test.go b/x/evmutil/types/params_test.go index 75850686..c4997a0a 100644 --- a/x/evmutil/types/params_test.go +++ b/x/evmutil/types/params_test.go @@ -9,9 +9,9 @@ import ( paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/evmutil/testutil" - "github.com/kava-labs/kava/x/evmutil/types" + "github.com/0glabs/0g-chain/chaincfg" + "github.com/0glabs/0g-chain/x/evmutil/testutil" + "github.com/0glabs/0g-chain/x/evmutil/types" ) type ParamsTestSuite struct { @@ -19,7 +19,7 @@ type ParamsTestSuite struct { } func (suite *ParamsTestSuite) SetupTest() { - app.SetSDKConfig() + chaincfg.SetSDKConfig() } func (suite *ParamsTestSuite) TestDefault() { @@ -107,11 +107,11 @@ func (suite *ParamsTestSuite) TestParams_Validate() { invalidConversionPairs := types.NewConversionPairs( types.NewConversionPair( testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000A"), - "kava", + chaincfg.DisplayDenom, ), types.NewConversionPair( testutil.MustNewInternalEVMAddressFromString("0x000000000000000000000000000000000000000B"), - "kava", // duplicate denom! + chaincfg.DisplayDenom, // duplicate denom! ), ) validAllowedCosmosDenoms := types.NewAllowedCosmosCoinERC20Tokens( diff --git a/x/evmutil/types/query.pb.go b/x/evmutil/types/query.pb.go index 9336d95d..8f743d1b 100644 --- a/x/evmutil/types/query.pb.go +++ b/x/evmutil/types/query.pb.go @@ -1,5 +1,5 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/evmutil/v1beta1/query.proto +// source: zgc/evmutil/v1beta1/query.proto package types @@ -38,7 +38,7 @@ 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_4a8d0512331709e7, []int{0} + return fileDescriptor_f7cba1d0f1a293ad, []int{0} } func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -76,7 +76,7 @@ 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_4a8d0512331709e7, []int{1} + return fileDescriptor_f7cba1d0f1a293ad, []int{1} } func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -128,7 +128,7 @@ func (m *QueryDeployedCosmosCoinContractsRequest) Reset() { func (m *QueryDeployedCosmosCoinContractsRequest) String() string { return proto.CompactTextString(m) } func (*QueryDeployedCosmosCoinContractsRequest) ProtoMessage() {} func (*QueryDeployedCosmosCoinContractsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_4a8d0512331709e7, []int{2} + return fileDescriptor_f7cba1d0f1a293ad, []int{2} } func (m *QueryDeployedCosmosCoinContractsRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -171,7 +171,7 @@ func (m *QueryDeployedCosmosCoinContractsResponse) Reset() { func (m *QueryDeployedCosmosCoinContractsResponse) String() string { return proto.CompactTextString(m) } func (*QueryDeployedCosmosCoinContractsResponse) ProtoMessage() {} func (*QueryDeployedCosmosCoinContractsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4a8d0512331709e7, []int{3} + return fileDescriptor_f7cba1d0f1a293ad, []int{3} } func (m *QueryDeployedCosmosCoinContractsResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -224,7 +224,7 @@ func (m *DeployedCosmosCoinContract) Reset() { *m = DeployedCosmosCoinCo func (m *DeployedCosmosCoinContract) String() string { return proto.CompactTextString(m) } func (*DeployedCosmosCoinContract) ProtoMessage() {} func (*DeployedCosmosCoinContract) Descriptor() ([]byte, []int) { - return fileDescriptor_4a8d0512331709e7, []int{4} + return fileDescriptor_f7cba1d0f1a293ad, []int{4} } func (m *DeployedCosmosCoinContract) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -261,51 +261,52 @@ func (m *DeployedCosmosCoinContract) GetCosmosDenom() string { } func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.evmutil.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.evmutil.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryDeployedCosmosCoinContractsRequest)(nil), "kava.evmutil.v1beta1.QueryDeployedCosmosCoinContractsRequest") - proto.RegisterType((*QueryDeployedCosmosCoinContractsResponse)(nil), "kava.evmutil.v1beta1.QueryDeployedCosmosCoinContractsResponse") - proto.RegisterType((*DeployedCosmosCoinContract)(nil), "kava.evmutil.v1beta1.DeployedCosmosCoinContract") + proto.RegisterType((*QueryParamsRequest)(nil), "zgc.evmutil.v1beta1.QueryParamsRequest") + proto.RegisterType((*QueryParamsResponse)(nil), "zgc.evmutil.v1beta1.QueryParamsResponse") + proto.RegisterType((*QueryDeployedCosmosCoinContractsRequest)(nil), "zgc.evmutil.v1beta1.QueryDeployedCosmosCoinContractsRequest") + proto.RegisterType((*QueryDeployedCosmosCoinContractsResponse)(nil), "zgc.evmutil.v1beta1.QueryDeployedCosmosCoinContractsResponse") + proto.RegisterType((*DeployedCosmosCoinContract)(nil), "zgc.evmutil.v1beta1.DeployedCosmosCoinContract") } -func init() { proto.RegisterFile("kava/evmutil/v1beta1/query.proto", fileDescriptor_4a8d0512331709e7) } +func init() { proto.RegisterFile("zgc/evmutil/v1beta1/query.proto", fileDescriptor_f7cba1d0f1a293ad) } -var fileDescriptor_4a8d0512331709e7 = []byte{ - // 542 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x54, 0x4f, 0x6f, 0xd3, 0x30, - 0x14, 0x8f, 0x0b, 0x14, 0xea, 0x8e, 0x8b, 0xa9, 0xd0, 0xd4, 0x55, 0xe9, 0x08, 0x88, 0x75, 0x48, - 0x38, 0x5b, 0x41, 0x1c, 0x26, 0x40, 0xa2, 0x1d, 0x20, 0x0e, 0x48, 0x2c, 0x07, 0x0e, 0x5c, 0x2a, - 0x27, 0xb1, 0x42, 0x44, 0x6a, 0xa7, 0xb1, 0x5b, 0x51, 0x71, 0x83, 0x0b, 0x47, 0x24, 0xbe, 0x40, - 0x3f, 0xce, 0x8e, 0x93, 0xb8, 0xa0, 0x1d, 0x26, 0xd4, 0x72, 0x40, 0x9c, 0xf8, 0x08, 0xa8, 0xb6, - 0xbb, 0x15, 0x91, 0xb6, 0x88, 0x9b, 0xf5, 0xfc, 0x7b, 0xfe, 0xfd, 0x79, 0x2f, 0x81, 0x9b, 0x6f, - 0xc8, 0x80, 0xb8, 0x74, 0xd0, 0xed, 0xcb, 0x38, 0x71, 0x07, 0xbb, 0x3e, 0x95, 0x64, 0xd7, 0xed, - 0xf5, 0x69, 0x36, 0xc4, 0x69, 0xc6, 0x25, 0x47, 0x95, 0x29, 0x02, 0x1b, 0x04, 0x36, 0x88, 0xea, - 0xad, 0x80, 0x8b, 0x2e, 0x17, 0xae, 0x4f, 0x04, 0xd5, 0xf0, 0xd3, 0xe6, 0x94, 0x44, 0x31, 0x23, - 0x32, 0xe6, 0x4c, 0xbf, 0x50, 0xad, 0x44, 0x3c, 0xe2, 0xea, 0xe8, 0x4e, 0x4f, 0xa6, 0x5a, 0x8b, - 0x38, 0x8f, 0x12, 0xea, 0x92, 0x34, 0x76, 0x09, 0x63, 0x5c, 0xaa, 0x16, 0x61, 0x6e, 0x9d, 0x5c, - 0x5d, 0x11, 0x65, 0x54, 0xc4, 0x06, 0xe3, 0x54, 0x20, 0x3a, 0x98, 0x32, 0xbf, 0x20, 0x19, 0xe9, - 0x0a, 0x8f, 0xf6, 0xfa, 0x54, 0x48, 0xe7, 0x00, 0x5e, 0xf9, 0xa3, 0x2a, 0x52, 0xce, 0x04, 0x45, - 0x7b, 0xb0, 0x98, 0xaa, 0xca, 0x3a, 0xd8, 0x04, 0x8d, 0x72, 0xb3, 0x86, 0xf3, 0x7c, 0x61, 0xdd, - 0xd5, 0x3a, 0x7f, 0x78, 0x52, 0xb7, 0x3c, 0xd3, 0xe1, 0x8c, 0x00, 0xdc, 0x52, 0x6f, 0xee, 0xd3, - 0x34, 0xe1, 0x43, 0x1a, 0xb6, 0x95, 0xf9, 0x36, 0x8f, 0x59, 0x9b, 0x33, 0x99, 0x91, 0x40, 0xce, - 0xe8, 0xd1, 0x75, 0x78, 0x59, 0x47, 0xd3, 0x09, 0x29, 0xe3, 0x8a, 0xee, 0x5c, 0xa3, 0xe4, 0xad, - 0xe9, 0xe2, 0xbe, 0xaa, 0xa1, 0x27, 0x10, 0x9e, 0xa5, 0xb4, 0x5e, 0x50, 0x82, 0x6e, 0x62, 0x0d, - 0xc1, 0xd3, 0x48, 0xb1, 0x9e, 0xc0, 0x99, 0xaa, 0x88, 0x1a, 0x02, 0x6f, 0xae, 0x73, 0xef, 0xd2, - 0xc7, 0x51, 0xdd, 0xfa, 0x31, 0xaa, 0x5b, 0xce, 0x2f, 0x00, 0x1b, 0xab, 0x25, 0x9a, 0x2c, 0xde, - 0x41, 0x3b, 0x34, 0xb0, 0x8e, 0x11, 0x1b, 0xf0, 0x98, 0x75, 0x82, 0x19, 0x52, 0x89, 0x2e, 0x37, - 0x77, 0xf2, 0x33, 0x5a, 0x4c, 0x61, 0x72, 0xdb, 0x08, 0x17, 0x8b, 0x40, 0x4f, 0x73, 0xbc, 0x6f, - 0xad, 0xf4, 0xae, 0x95, 0xcf, 0x9b, 0x77, 0x7a, 0xb0, 0xba, 0x58, 0x09, 0xba, 0x06, 0xd7, 0xe6, - 0xe7, 0xa0, 0xa6, 0x5e, 0xf2, 0xca, 0x73, 0x63, 0x40, 0x3b, 0xf0, 0x22, 0x09, 0xc3, 0x8c, 0x0a, - 0xa1, 0x64, 0x94, 0x5a, 0x57, 0x8f, 0x4f, 0xea, 0xe8, 0x19, 0x93, 0x34, 0x63, 0x24, 0x79, 0xfc, - 0xf2, 0xf9, 0x23, 0x7d, 0xeb, 0xcd, 0x60, 0xcd, 0x9f, 0x05, 0x78, 0x41, 0xa5, 0x8c, 0x3e, 0x00, - 0x58, 0xd4, 0xbb, 0x82, 0x1a, 0xf9, 0x29, 0xfd, 0xbd, 0x9a, 0xd5, 0xed, 0x7f, 0x40, 0x6a, 0xa3, - 0xce, 0x8d, 0xf7, 0x5f, 0xbe, 0x7f, 0x2e, 0xd8, 0xa8, 0xe6, 0xe6, 0x7e, 0x08, 0x7a, 0x31, 0xd1, - 0x31, 0x80, 0x1b, 0x4b, 0x06, 0x8e, 0x1e, 0x2c, 0x21, 0x5c, 0xbd, 0xcb, 0xd5, 0x87, 0xff, 0xdb, - 0x6e, 0x4c, 0xdc, 0x57, 0x26, 0xee, 0xa1, 0xbb, 0xf9, 0x26, 0x96, 0xef, 0x60, 0xab, 0x7d, 0x38, - 0xb6, 0xc1, 0xd1, 0xd8, 0x06, 0xdf, 0xc6, 0x36, 0xf8, 0x34, 0xb1, 0xad, 0xa3, 0x89, 0x6d, 0x7d, - 0x9d, 0xd8, 0xd6, 0xab, 0xed, 0x28, 0x96, 0xaf, 0xfb, 0x3e, 0x0e, 0x78, 0x57, 0xbd, 0x7c, 0x3b, - 0x21, 0xbe, 0xd0, 0x1c, 0x6f, 0x4f, 0x59, 0xe4, 0x30, 0xa5, 0xc2, 0x2f, 0xaa, 0x5f, 0xc5, 0x9d, - 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x1f, 0xfa, 0x86, 0x41, 0xe8, 0x04, 0x00, 0x00, +var fileDescriptor_f7cba1d0f1a293ad = []byte{ + // 546 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x54, 0x4f, 0x6b, 0x13, 0x41, + 0x14, 0xdf, 0x8d, 0x1a, 0xcd, 0xa4, 0x5e, 0xa6, 0x45, 0x4a, 0x22, 0x9b, 0x76, 0x05, 0x13, 0x0a, + 0xee, 0xa4, 0xf1, 0xa2, 0x45, 0x41, 0x93, 0xa8, 0x78, 0x10, 0xea, 0x1e, 0x3c, 0x78, 0x09, 0x93, + 0xdd, 0x61, 0xba, 0x90, 0xcc, 0x6c, 0x76, 0x26, 0xc5, 0xe4, 0x28, 0x08, 0x1e, 0x05, 0xbf, 0x40, + 0x3e, 0x4e, 0x8f, 0x05, 0x2f, 0x22, 0x52, 0x24, 0xf1, 0xe0, 0x49, 0xbf, 0x82, 0x64, 0x66, 0xd2, + 0x44, 0xba, 0xdb, 0x80, 0xb7, 0xe1, 0xcd, 0xef, 0xcd, 0xef, 0xcf, 0x7b, 0xbb, 0xa0, 0x32, 0xa6, + 0x01, 0x22, 0xc7, 0xfd, 0xa1, 0x8c, 0x7a, 0xe8, 0x78, 0xbf, 0x4b, 0x24, 0xde, 0x47, 0x83, 0x21, + 0x49, 0x46, 0x5e, 0x9c, 0x70, 0xc9, 0xe1, 0xe6, 0x98, 0x06, 0x9e, 0x01, 0x78, 0x06, 0x50, 0xda, + 0x0b, 0xb8, 0xe8, 0x73, 0x81, 0xba, 0x58, 0x10, 0x8d, 0x3e, 0xef, 0x8d, 0x31, 0x8d, 0x18, 0x96, + 0x11, 0x67, 0xfa, 0x81, 0xd2, 0x16, 0xe5, 0x94, 0xab, 0x23, 0x9a, 0x9f, 0x4c, 0xf5, 0x36, 0xe5, + 0x9c, 0xf6, 0x08, 0xc2, 0x71, 0x84, 0x30, 0x63, 0x5c, 0xaa, 0x16, 0x61, 0x6e, 0x77, 0xd3, 0x54, + 0x51, 0xc2, 0x88, 0x88, 0x0c, 0xc4, 0xdd, 0x02, 0xf0, 0xf5, 0x9c, 0xf8, 0x10, 0x27, 0xb8, 0x2f, + 0x7c, 0x32, 0x18, 0x12, 0x21, 0xdd, 0x43, 0xb0, 0xf9, 0x4f, 0x55, 0xc4, 0x9c, 0x09, 0x02, 0x1f, + 0x82, 0x7c, 0xac, 0x2a, 0xdb, 0xf6, 0x8e, 0x5d, 0x2b, 0x36, 0xca, 0x5e, 0x8a, 0x2b, 0x4f, 0x37, + 0x35, 0xaf, 0x9e, 0x9c, 0x55, 0x2c, 0xdf, 0x34, 0xb8, 0x13, 0x1b, 0x54, 0xd5, 0x93, 0x6d, 0x12, + 0xf7, 0xf8, 0x88, 0x84, 0x2d, 0x65, 0xbd, 0xc5, 0x23, 0xd6, 0xe2, 0x4c, 0x26, 0x38, 0x90, 0x0b, + 0x76, 0x78, 0x07, 0xdc, 0xd4, 0xc1, 0x74, 0x42, 0xc2, 0xb8, 0x62, 0xbb, 0x52, 0x2b, 0xf8, 0x1b, + 0xba, 0xd8, 0x56, 0x35, 0xf8, 0x1c, 0x80, 0x65, 0x46, 0xdb, 0x39, 0xa5, 0xe7, 0xae, 0xa7, 0x21, + 0xde, 0x3c, 0x50, 0x4f, 0xc7, 0xbf, 0x54, 0x45, 0x89, 0x21, 0xf0, 0x57, 0x3a, 0x0f, 0x6e, 0x7c, + 0x9c, 0x54, 0xac, 0x5f, 0x93, 0x8a, 0xe5, 0xfe, 0xb1, 0x41, 0x6d, 0xbd, 0x44, 0x13, 0xc5, 0x18, + 0x38, 0xa1, 0x81, 0x75, 0x8c, 0xd8, 0x80, 0x47, 0xac, 0x13, 0x2c, 0x90, 0x4a, 0x74, 0xb1, 0x81, + 0x52, 0x23, 0xca, 0x66, 0x30, 0xb1, 0x95, 0xc3, 0x6c, 0x0d, 0xf0, 0x45, 0x8a, 0xf5, 0xea, 0x5a, + 0xeb, 0x5a, 0xf8, 0xaa, 0x77, 0x77, 0x00, 0x4a, 0xd9, 0x4a, 0xe0, 0x2e, 0xd8, 0x58, 0x1d, 0x83, + 0x9a, 0x79, 0xc1, 0x2f, 0xae, 0x4c, 0x01, 0xd6, 0xc1, 0x75, 0x1c, 0x86, 0x09, 0x11, 0x42, 0xc9, + 0x28, 0x34, 0x6f, 0x7d, 0x3b, 0xab, 0xc0, 0x97, 0x4c, 0x92, 0x84, 0xe1, 0xde, 0xb3, 0x37, 0xaf, + 0x9e, 0xea, 0x5b, 0x7f, 0x01, 0x6b, 0xfc, 0xce, 0x81, 0x6b, 0x2a, 0x64, 0xf8, 0xc1, 0x06, 0x79, + 0xbd, 0x2a, 0xb0, 0x9a, 0x1a, 0xd2, 0xc5, 0xbd, 0x2c, 0xd5, 0xd6, 0x03, 0xb5, 0x4d, 0xb7, 0xf6, + 0xfe, 0xcb, 0xcf, 0xcf, 0x39, 0x17, 0xee, 0xa0, 0x3a, 0xbd, 0x17, 0x1c, 0xe1, 0x88, 0x5d, 0xf8, + 0x10, 0xf4, 0x66, 0xc2, 0xef, 0x36, 0x28, 0x5f, 0x32, 0x71, 0xf8, 0x28, 0x9b, 0x73, 0xfd, 0x2e, + 0x97, 0x1e, 0xff, 0x67, 0xb7, 0xb1, 0xf1, 0x44, 0xd9, 0x38, 0x80, 0x0f, 0xb2, 0x6d, 0x5c, 0xbe, + 0x86, 0xcd, 0xf6, 0xc9, 0xd4, 0xb1, 0x4f, 0xa7, 0x8e, 0xfd, 0x63, 0xea, 0xd8, 0x9f, 0x66, 0x8e, + 0x75, 0x3a, 0x73, 0xac, 0xaf, 0x33, 0xc7, 0x7a, 0xbb, 0x47, 0x23, 0x79, 0x34, 0xec, 0x7a, 0x01, + 0xef, 0xa3, 0x3a, 0xed, 0xe1, 0xae, 0x58, 0x92, 0xbc, 0x3b, 0xa7, 0x91, 0xa3, 0x98, 0x88, 0x6e, + 0x5e, 0xfd, 0x2d, 0xee, 0xff, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x2d, 0x70, 0xa1, 0x5b, 0xe8, 0x04, + 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -336,7 +337,7 @@ func NewQueryClient(cc grpc1.ClientConn) QueryClient { func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/kava.evmutil.v1beta1.Query/Params", in, out, opts...) + err := c.cc.Invoke(ctx, "/zgc.evmutil.v1beta1.Query/Params", in, out, opts...) if err != nil { return nil, err } @@ -345,7 +346,7 @@ func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts . func (c *queryClient) DeployedCosmosCoinContracts(ctx context.Context, in *QueryDeployedCosmosCoinContractsRequest, opts ...grpc.CallOption) (*QueryDeployedCosmosCoinContractsResponse, error) { out := new(QueryDeployedCosmosCoinContractsResponse) - err := c.cc.Invoke(ctx, "/kava.evmutil.v1beta1.Query/DeployedCosmosCoinContracts", in, out, opts...) + err := c.cc.Invoke(ctx, "/zgc.evmutil.v1beta1.Query/DeployedCosmosCoinContracts", in, out, opts...) if err != nil { return nil, err } @@ -385,7 +386,7 @@ func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interf } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/kava.evmutil.v1beta1.Query/Params", + FullMethod: "/zgc.evmutil.v1beta1.Query/Params", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) @@ -403,7 +404,7 @@ func _Query_DeployedCosmosCoinContracts_Handler(srv interface{}, ctx context.Con } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/kava.evmutil.v1beta1.Query/DeployedCosmosCoinContracts", + FullMethod: "/zgc.evmutil.v1beta1.Query/DeployedCosmosCoinContracts", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).DeployedCosmosCoinContracts(ctx, req.(*QueryDeployedCosmosCoinContractsRequest)) @@ -412,7 +413,7 @@ func _Query_DeployedCosmosCoinContracts_Handler(srv interface{}, ctx context.Con } var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.evmutil.v1beta1.Query", + ServiceName: "zgc.evmutil.v1beta1.Query", HandlerType: (*QueryServer)(nil), Methods: []grpc.MethodDesc{ { @@ -425,7 +426,7 @@ var _Query_serviceDesc = grpc.ServiceDesc{ }, }, Streams: []grpc.StreamDesc{}, - Metadata: "kava/evmutil/v1beta1/query.proto", + Metadata: "zgc/evmutil/v1beta1/query.proto", } func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { diff --git a/x/evmutil/types/query.pb.gw.go b/x/evmutil/types/query.pb.gw.go index e9c9b1df..36fd0ec1 100644 --- a/x/evmutil/types/query.pb.gw.go +++ b/x/evmutil/types/query.pb.gw.go @@ -1,5 +1,5 @@ // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/evmutil/v1beta1/query.proto +// source: zgc/evmutil/v1beta1/query.proto /* Package types is a reverse proxy. @@ -224,9 +224,9 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } var ( - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "evmutil", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"0g-chain", "evmutil", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_DeployedCosmosCoinContracts_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "evmutil", "v1beta1", "deployed_cosmos_coin_contracts"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_DeployedCosmosCoinContracts_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"0g-chain", "evmutil", "v1beta1", "deployed_cosmos_coin_contracts"}, "", runtime.AssumeColonVerbOpt(false))) ) var ( diff --git a/x/evmutil/types/tx.pb.go b/x/evmutil/types/tx.pb.go index d4aa63b4..32bef31f 100644 --- a/x/evmutil/types/tx.pb.go +++ b/x/evmutil/types/tx.pb.go @@ -1,5 +1,5 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/evmutil/v1beta1/tx.proto +// source: zgc/evmutil/v1beta1/tx.proto package types @@ -31,11 +31,11 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package -// MsgConvertCoinToERC20 defines a conversion from sdk.Coin to Kava ERC20 for EVM-native assets. +// MsgConvertCoinToERC20 defines a conversion from sdk.Coin to 0g-chain ERC20 for EVM-native assets. type MsgConvertCoinToERC20 struct { - // Kava bech32 address initiating the conversion. + // 0g-chain bech32 address initiating the conversion. Initiator string `protobuf:"bytes,1,opt,name=initiator,proto3" json:"initiator,omitempty"` - // EVM 0x hex address that will receive the converted Kava ERC20 tokens. + // EVM 0x hex address that will receive the converted 0g-chain ERC20 tokens. Receiver string `protobuf:"bytes,2,opt,name=receiver,proto3" json:"receiver,omitempty"` // Amount is the sdk.Coin amount to convert. Amount *types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount,omitempty"` @@ -45,7 +45,7 @@ func (m *MsgConvertCoinToERC20) Reset() { *m = MsgConvertCoinToERC20{} } func (m *MsgConvertCoinToERC20) String() string { return proto.CompactTextString(m) } func (*MsgConvertCoinToERC20) ProtoMessage() {} func (*MsgConvertCoinToERC20) Descriptor() ([]byte, []int) { - return fileDescriptor_6e82783c6c58f89c, []int{0} + return fileDescriptor_b60fa1a7a6ac0cc3, []int{0} } func (m *MsgConvertCoinToERC20) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -103,7 +103,7 @@ func (m *MsgConvertCoinToERC20Response) Reset() { *m = MsgConvertCoinToE func (m *MsgConvertCoinToERC20Response) String() string { return proto.CompactTextString(m) } func (*MsgConvertCoinToERC20Response) ProtoMessage() {} func (*MsgConvertCoinToERC20Response) Descriptor() ([]byte, []int) { - return fileDescriptor_6e82783c6c58f89c, []int{1} + return fileDescriptor_b60fa1a7a6ac0cc3, []int{1} } func (m *MsgConvertCoinToERC20Response) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -132,14 +132,14 @@ func (m *MsgConvertCoinToERC20Response) XXX_DiscardUnknown() { var xxx_messageInfo_MsgConvertCoinToERC20Response proto.InternalMessageInfo -// MsgConvertERC20ToCoin defines a conversion from Kava ERC20 to sdk.Coin for EVM-native assets. +// MsgConvertERC20ToCoin defines a conversion from 0g-chain ERC20 to sdk.Coin for EVM-native assets. type MsgConvertERC20ToCoin struct { // EVM 0x hex address initiating the conversion. Initiator string `protobuf:"bytes,1,opt,name=initiator,proto3" json:"initiator,omitempty"` - // Kava bech32 address that will receive the converted sdk.Coin. + // 0g-chain bech32 address that will receive the converted sdk.Coin. Receiver string `protobuf:"bytes,2,opt,name=receiver,proto3" json:"receiver,omitempty"` // EVM 0x hex address of the ERC20 contract. - KavaERC20Address string `protobuf:"bytes,3,opt,name=kava_erc20_address,json=kavaErc20Address,proto3" json:"kava_erc20_address,omitempty"` + ZgchainERC20Address string `protobuf:"bytes,3,opt,name=zgchain_erc20_address,json=zgchainErc20Address,proto3" json:"zgchain_erc20_address,omitempty"` // ERC20 token amount to convert. Amount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,4,opt,name=amount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"amount"` } @@ -148,7 +148,7 @@ func (m *MsgConvertERC20ToCoin) Reset() { *m = MsgConvertERC20ToCoin{} } func (m *MsgConvertERC20ToCoin) String() string { return proto.CompactTextString(m) } func (*MsgConvertERC20ToCoin) ProtoMessage() {} func (*MsgConvertERC20ToCoin) Descriptor() ([]byte, []int) { - return fileDescriptor_6e82783c6c58f89c, []int{2} + return fileDescriptor_b60fa1a7a6ac0cc3, []int{2} } func (m *MsgConvertERC20ToCoin) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -191,9 +191,9 @@ func (m *MsgConvertERC20ToCoin) GetReceiver() string { return "" } -func (m *MsgConvertERC20ToCoin) GetKavaERC20Address() string { +func (m *MsgConvertERC20ToCoin) GetZgchainERC20Address() string { if m != nil { - return m.KavaERC20Address + return m.ZgchainERC20Address } return "" } @@ -207,7 +207,7 @@ func (m *MsgConvertERC20ToCoinResponse) Reset() { *m = MsgConvertERC20To func (m *MsgConvertERC20ToCoinResponse) String() string { return proto.CompactTextString(m) } func (*MsgConvertERC20ToCoinResponse) ProtoMessage() {} func (*MsgConvertERC20ToCoinResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_6e82783c6c58f89c, []int{3} + return fileDescriptor_b60fa1a7a6ac0cc3, []int{3} } func (m *MsgConvertERC20ToCoinResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -238,7 +238,7 @@ var xxx_messageInfo_MsgConvertERC20ToCoinResponse proto.InternalMessageInfo // MsgConvertCosmosCoinToERC20 defines a conversion from cosmos sdk.Coin to ERC20 for cosmos-native assets. type MsgConvertCosmosCoinToERC20 struct { - // Kava bech32 address initiating the conversion. + // 0g-chain bech32 address initiating the conversion. Initiator string `protobuf:"bytes,1,opt,name=initiator,proto3" json:"initiator,omitempty"` // EVM hex address that will receive the ERC20 tokens. Receiver string `protobuf:"bytes,2,opt,name=receiver,proto3" json:"receiver,omitempty"` @@ -250,7 +250,7 @@ func (m *MsgConvertCosmosCoinToERC20) Reset() { *m = MsgConvertCosmosCoi func (m *MsgConvertCosmosCoinToERC20) String() string { return proto.CompactTextString(m) } func (*MsgConvertCosmosCoinToERC20) ProtoMessage() {} func (*MsgConvertCosmosCoinToERC20) Descriptor() ([]byte, []int) { - return fileDescriptor_6e82783c6c58f89c, []int{4} + return fileDescriptor_b60fa1a7a6ac0cc3, []int{4} } func (m *MsgConvertCosmosCoinToERC20) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -308,7 +308,7 @@ func (m *MsgConvertCosmosCoinToERC20Response) Reset() { *m = MsgConvertC func (m *MsgConvertCosmosCoinToERC20Response) String() string { return proto.CompactTextString(m) } func (*MsgConvertCosmosCoinToERC20Response) ProtoMessage() {} func (*MsgConvertCosmosCoinToERC20Response) Descriptor() ([]byte, []int) { - return fileDescriptor_6e82783c6c58f89c, []int{5} + return fileDescriptor_b60fa1a7a6ac0cc3, []int{5} } func (m *MsgConvertCosmosCoinToERC20Response) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -341,7 +341,7 @@ var xxx_messageInfo_MsgConvertCosmosCoinToERC20Response proto.InternalMessageInf type MsgConvertCosmosCoinFromERC20 struct { // EVM hex address initiating the conversion. Initiator string `protobuf:"bytes,1,opt,name=initiator,proto3" json:"initiator,omitempty"` - // Kava bech32 address that will receive the cosmos coins. + // 0g-chain bech32 address that will receive the cosmos coins. Receiver string `protobuf:"bytes,2,opt,name=receiver,proto3" json:"receiver,omitempty"` // Amount is the amount to convert, expressed as a Cosmos coin. Amount *types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount,omitempty"` @@ -351,7 +351,7 @@ func (m *MsgConvertCosmosCoinFromERC20) Reset() { *m = MsgConvertCosmosC func (m *MsgConvertCosmosCoinFromERC20) String() string { return proto.CompactTextString(m) } func (*MsgConvertCosmosCoinFromERC20) ProtoMessage() {} func (*MsgConvertCosmosCoinFromERC20) Descriptor() ([]byte, []int) { - return fileDescriptor_6e82783c6c58f89c, []int{6} + return fileDescriptor_b60fa1a7a6ac0cc3, []int{6} } func (m *MsgConvertCosmosCoinFromERC20) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -409,7 +409,7 @@ func (m *MsgConvertCosmosCoinFromERC20Response) Reset() { *m = MsgConver func (m *MsgConvertCosmosCoinFromERC20Response) String() string { return proto.CompactTextString(m) } func (*MsgConvertCosmosCoinFromERC20Response) ProtoMessage() {} func (*MsgConvertCosmosCoinFromERC20Response) Descriptor() ([]byte, []int) { - return fileDescriptor_6e82783c6c58f89c, []int{7} + return fileDescriptor_b60fa1a7a6ac0cc3, []int{7} } func (m *MsgConvertCosmosCoinFromERC20Response) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -439,55 +439,56 @@ func (m *MsgConvertCosmosCoinFromERC20Response) XXX_DiscardUnknown() { var xxx_messageInfo_MsgConvertCosmosCoinFromERC20Response proto.InternalMessageInfo func init() { - proto.RegisterType((*MsgConvertCoinToERC20)(nil), "kava.evmutil.v1beta1.MsgConvertCoinToERC20") - proto.RegisterType((*MsgConvertCoinToERC20Response)(nil), "kava.evmutil.v1beta1.MsgConvertCoinToERC20Response") - proto.RegisterType((*MsgConvertERC20ToCoin)(nil), "kava.evmutil.v1beta1.MsgConvertERC20ToCoin") - proto.RegisterType((*MsgConvertERC20ToCoinResponse)(nil), "kava.evmutil.v1beta1.MsgConvertERC20ToCoinResponse") - proto.RegisterType((*MsgConvertCosmosCoinToERC20)(nil), "kava.evmutil.v1beta1.MsgConvertCosmosCoinToERC20") - proto.RegisterType((*MsgConvertCosmosCoinToERC20Response)(nil), "kava.evmutil.v1beta1.MsgConvertCosmosCoinToERC20Response") - proto.RegisterType((*MsgConvertCosmosCoinFromERC20)(nil), "kava.evmutil.v1beta1.MsgConvertCosmosCoinFromERC20") - proto.RegisterType((*MsgConvertCosmosCoinFromERC20Response)(nil), "kava.evmutil.v1beta1.MsgConvertCosmosCoinFromERC20Response") + proto.RegisterType((*MsgConvertCoinToERC20)(nil), "zgc.evmutil.v1beta1.MsgConvertCoinToERC20") + proto.RegisterType((*MsgConvertCoinToERC20Response)(nil), "zgc.evmutil.v1beta1.MsgConvertCoinToERC20Response") + proto.RegisterType((*MsgConvertERC20ToCoin)(nil), "zgc.evmutil.v1beta1.MsgConvertERC20ToCoin") + proto.RegisterType((*MsgConvertERC20ToCoinResponse)(nil), "zgc.evmutil.v1beta1.MsgConvertERC20ToCoinResponse") + proto.RegisterType((*MsgConvertCosmosCoinToERC20)(nil), "zgc.evmutil.v1beta1.MsgConvertCosmosCoinToERC20") + proto.RegisterType((*MsgConvertCosmosCoinToERC20Response)(nil), "zgc.evmutil.v1beta1.MsgConvertCosmosCoinToERC20Response") + proto.RegisterType((*MsgConvertCosmosCoinFromERC20)(nil), "zgc.evmutil.v1beta1.MsgConvertCosmosCoinFromERC20") + proto.RegisterType((*MsgConvertCosmosCoinFromERC20Response)(nil), "zgc.evmutil.v1beta1.MsgConvertCosmosCoinFromERC20Response") } -func init() { proto.RegisterFile("kava/evmutil/v1beta1/tx.proto", fileDescriptor_6e82783c6c58f89c) } +func init() { proto.RegisterFile("zgc/evmutil/v1beta1/tx.proto", fileDescriptor_b60fa1a7a6ac0cc3) } -var fileDescriptor_6e82783c6c58f89c = []byte{ - // 559 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x55, 0x41, 0x6b, 0xd4, 0x4c, - 0x18, 0xde, 0x69, 0x4b, 0xf9, 0x76, 0xbe, 0x4b, 0x19, 0x56, 0x48, 0xa3, 0xcd, 0x96, 0x95, 0x6a, - 0x45, 0x36, 0xe9, 0xee, 0x8a, 0x20, 0x7a, 0x71, 0x97, 0x0a, 0xa5, 0xf4, 0x12, 0xf7, 0xe4, 0x65, - 0x99, 0x64, 0x87, 0x18, 0xda, 0x64, 0x96, 0xcc, 0x6c, 0xa8, 0x3f, 0x40, 0x10, 0x11, 0xd1, 0x3f, - 0xe0, 0xd9, 0x1f, 0xd0, 0x1f, 0xd1, 0x63, 0xe9, 0x49, 0x3c, 0x2c, 0x35, 0xfb, 0x47, 0x64, 0x92, - 0x49, 0x3a, 0xd6, 0x98, 0xb5, 0x22, 0x78, 0xda, 0xcc, 0xbc, 0xcf, 0xf3, 0xbe, 0xcf, 0xf3, 0xbe, - 0x33, 0xb3, 0x70, 0xe3, 0x10, 0xc7, 0xd8, 0x22, 0x71, 0x30, 0xe5, 0xfe, 0x91, 0x15, 0x77, 0x1c, - 0xc2, 0x71, 0xc7, 0xe2, 0xc7, 0xe6, 0x24, 0xa2, 0x9c, 0xa2, 0x86, 0x08, 0x9b, 0x32, 0x6c, 0xca, - 0xb0, 0x6e, 0xb8, 0x94, 0x05, 0x94, 0x59, 0x0e, 0x66, 0xa4, 0xe0, 0xb8, 0xd4, 0x0f, 0x33, 0x96, - 0xbe, 0x9e, 0xc5, 0x47, 0xe9, 0xca, 0xca, 0x16, 0x32, 0xd4, 0xf0, 0xa8, 0x47, 0xb3, 0x7d, 0xf1, - 0x95, 0xed, 0xb6, 0x3e, 0x01, 0x78, 0xe3, 0x80, 0x79, 0x03, 0x1a, 0xc6, 0x24, 0xe2, 0x03, 0xea, - 0x87, 0x43, 0xba, 0x6b, 0x0f, 0xba, 0x3b, 0xe8, 0x21, 0xac, 0xfb, 0xa1, 0xcf, 0x7d, 0xcc, 0x69, - 0xa4, 0x81, 0x4d, 0xb0, 0x5d, 0xef, 0x6b, 0xe7, 0x27, 0xed, 0x86, 0x4c, 0xfa, 0x74, 0x3c, 0x8e, - 0x08, 0x63, 0xcf, 0x79, 0xe4, 0x87, 0x9e, 0x7d, 0x09, 0x45, 0x3a, 0xfc, 0x2f, 0x22, 0x2e, 0xf1, - 0x63, 0x12, 0x69, 0x4b, 0x82, 0x66, 0x17, 0x6b, 0xd4, 0x81, 0xab, 0x38, 0xa0, 0xd3, 0x90, 0x6b, - 0xcb, 0x9b, 0x60, 0xfb, 0xff, 0xee, 0xba, 0x29, 0xb3, 0x09, 0x3f, 0xb9, 0x49, 0x53, 0xa8, 0xb0, - 0x25, 0xb0, 0xd5, 0x84, 0x1b, 0xa5, 0xfa, 0x6c, 0xc2, 0x26, 0x34, 0x64, 0xa4, 0xf5, 0x7a, 0x49, - 0x75, 0x90, 0xc6, 0x86, 0x54, 0x00, 0xd1, 0xad, 0x9f, 0x1c, 0xa8, 0x3a, 0x1f, 0x5c, 0xd5, 0x59, - 0x61, 0xef, 0xd2, 0x41, 0x1f, 0x22, 0x31, 0x98, 0x11, 0x89, 0xdc, 0xee, 0xce, 0x08, 0x67, 0xa8, - 0xd4, 0x4d, 0xbd, 0xdf, 0x48, 0x66, 0xcd, 0xb5, 0x7d, 0x1c, 0xe3, 0x54, 0x84, 0xcc, 0x60, 0xaf, - 0x09, 0xfc, 0xae, 0x80, 0xcb, 0x1d, 0x34, 0x2c, 0xba, 0xb0, 0x92, 0xf2, 0x9e, 0x9c, 0xce, 0x9a, - 0xb5, 0xaf, 0xb3, 0xe6, 0x1d, 0xcf, 0xe7, 0x2f, 0xa7, 0x8e, 0xe9, 0xd2, 0x40, 0x8e, 0x4e, 0xfe, - 0xb4, 0xd9, 0xf8, 0xd0, 0xe2, 0xaf, 0x26, 0x84, 0x99, 0x7b, 0x21, 0x3f, 0x3f, 0x69, 0x43, 0xa9, - 0x72, 0x2f, 0xe4, 0xe5, 0x8d, 0x52, 0xda, 0x50, 0x34, 0xea, 0x2d, 0x80, 0x37, 0xd5, 0x56, 0x8a, - 0x0c, 0xea, 0xc0, 0xab, 0xdb, 0xf5, 0x97, 0xc7, 0xba, 0x05, 0x6f, 0x57, 0x68, 0x29, 0x34, 0xbf, - 0x03, 0x3f, 0x8e, 0x3f, 0xc7, 0x3d, 0x8b, 0x68, 0xf0, 0x0f, 0x54, 0xdf, 0x85, 0x5b, 0x95, 0x6a, - 0x72, 0xdd, 0xdd, 0x8f, 0x2b, 0x70, 0xf9, 0x80, 0x79, 0x28, 0x86, 0xa8, 0xe4, 0x6a, 0xdd, 0x37, - 0xcb, 0x2e, 0xb7, 0x59, 0x7a, 0xce, 0xf5, 0xde, 0x35, 0xc0, 0x79, 0x7d, 0xa5, 0xae, 0x7a, 0x21, - 0x16, 0xd6, 0x55, 0xc0, 0x8b, 0xeb, 0x96, 0x9c, 0x31, 0xf4, 0x06, 0x40, 0xed, 0x97, 0x07, 0xac, - 0xb3, 0xd8, 0xc9, 0x15, 0x8a, 0xfe, 0xe8, 0xda, 0x94, 0x42, 0xca, 0x7b, 0x00, 0xf5, 0x8a, 0x73, - 0xd3, 0xfb, 0xfd, 0xcc, 0x05, 0x49, 0x7f, 0xfc, 0x07, 0xa4, 0x5c, 0x50, 0x7f, 0xff, 0xe2, 0x9b, - 0x01, 0x3e, 0x27, 0x06, 0x38, 0x4d, 0x0c, 0x70, 0x96, 0x18, 0xe0, 0x22, 0x31, 0xc0, 0x87, 0xb9, - 0x51, 0x3b, 0x9b, 0x1b, 0xb5, 0x2f, 0x73, 0xa3, 0xf6, 0xe2, 0x9e, 0xf2, 0x00, 0x88, 0x42, 0xed, - 0x23, 0xec, 0xb0, 0xf4, 0xcb, 0x3a, 0x2e, 0xfe, 0x29, 0xd2, 0x77, 0xc0, 0x59, 0x4d, 0x9f, 0xef, - 0xde, 0xf7, 0x00, 0x00, 0x00, 0xff, 0xff, 0xa2, 0x5a, 0x1f, 0x90, 0x46, 0x06, 0x00, 0x00, +var fileDescriptor_b60fa1a7a6ac0cc3 = []byte{ + // 562 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x55, 0xc1, 0x6e, 0xd3, 0x30, + 0x18, 0xae, 0xb7, 0x69, 0xa2, 0xe6, 0x96, 0x6e, 0xa2, 0x0b, 0x23, 0x9d, 0x8a, 0x06, 0xd3, 0xa4, + 0x26, 0x69, 0x40, 0x08, 0x21, 0x2e, 0xb4, 0x1a, 0xd2, 0x04, 0xbb, 0x84, 0x9e, 0x76, 0xa9, 0x92, + 0xd4, 0xf2, 0x2c, 0x16, 0xbb, 0x8a, 0xdd, 0x6a, 0xf4, 0x01, 0x90, 0x40, 0x13, 0xe2, 0x09, 0x38, + 0xf3, 0x00, 0x7b, 0x88, 0x1d, 0xa7, 0x9d, 0x10, 0x87, 0x6a, 0xa4, 0x2f, 0x82, 0x92, 0x38, 0x59, + 0x18, 0x21, 0xdd, 0x24, 0xa4, 0x9d, 0x5a, 0xfb, 0xff, 0xbe, 0xdf, 0xdf, 0xf7, 0xfb, 0xff, 0x1d, + 0xb8, 0x3e, 0xc1, 0x9e, 0x81, 0xc6, 0xfe, 0x48, 0x90, 0x43, 0x63, 0xdc, 0x76, 0x91, 0x70, 0xda, + 0x86, 0x38, 0xd2, 0x87, 0x01, 0x13, 0x4c, 0xa9, 0x4d, 0xb0, 0xa7, 0xcb, 0xa8, 0x2e, 0xa3, 0xaa, + 0xe6, 0x31, 0xee, 0x33, 0x6e, 0xb8, 0x0e, 0x47, 0x19, 0xc5, 0x63, 0x84, 0x26, 0x24, 0x75, 0x2d, + 0x89, 0xf7, 0xe3, 0x95, 0x91, 0x2c, 0x64, 0x68, 0x05, 0x33, 0xcc, 0x92, 0xfd, 0xe8, 0x5f, 0xb2, + 0xdb, 0xfc, 0x06, 0xe0, 0xea, 0x1e, 0xc7, 0x5d, 0x46, 0xc7, 0x28, 0x10, 0x5d, 0x46, 0x68, 0x8f, + 0xed, 0xd8, 0x5d, 0xcb, 0x54, 0x9e, 0xc1, 0x2a, 0xa1, 0x44, 0x10, 0x47, 0xb0, 0xa0, 0x0e, 0x36, + 0xc0, 0x56, 0xb5, 0x53, 0x3f, 0x3f, 0x69, 0xad, 0xc8, 0xa4, 0xaf, 0x06, 0x83, 0x00, 0x71, 0xfe, + 0x4e, 0x04, 0x84, 0x62, 0xfb, 0x12, 0xaa, 0xa8, 0xf0, 0x4e, 0x80, 0x3c, 0x44, 0xc6, 0x28, 0xa8, + 0x2f, 0x44, 0x34, 0x3b, 0x5b, 0x2b, 0x6d, 0xb8, 0xec, 0xf8, 0x6c, 0x44, 0x45, 0x7d, 0x71, 0x03, + 0x6c, 0xdd, 0xb5, 0xd6, 0x74, 0x99, 0x2d, 0xf2, 0x93, 0x9a, 0xd4, 0x23, 0x15, 0xb6, 0x04, 0x36, + 0x1b, 0xf0, 0x41, 0xa1, 0x3e, 0x1b, 0xf1, 0x21, 0xa3, 0x1c, 0x35, 0xbf, 0x2c, 0xe4, 0x1d, 0xc4, + 0xb1, 0x1e, 0x8b, 0x80, 0xca, 0xfa, 0x5f, 0x0e, 0xf2, 0x3a, 0x9f, 0x5e, 0xd5, 0x59, 0x62, 0xef, + 0xd2, 0xc1, 0x1b, 0xb8, 0x3a, 0xc1, 0xde, 0x81, 0x43, 0x68, 0x1f, 0x05, 0x9e, 0x65, 0xf6, 0x9d, + 0x04, 0x18, 0x1b, 0xaa, 0x76, 0xee, 0x85, 0xd3, 0x46, 0x6d, 0x3f, 0x01, 0xc4, 0x52, 0x64, 0x1e, + 0xbb, 0x26, 0x59, 0x3b, 0x11, 0x49, 0x6e, 0x2a, 0xbd, 0xac, 0x1c, 0x4b, 0x31, 0xfb, 0xe5, 0xe9, + 0xb4, 0x51, 0xf9, 0x39, 0x6d, 0x3c, 0xc2, 0x44, 0x1c, 0x8c, 0x5c, 0xdd, 0x63, 0xbe, 0xbc, 0x43, + 0xf9, 0xd3, 0xe2, 0x83, 0xf7, 0x86, 0xf8, 0x30, 0x44, 0x5c, 0xdf, 0xa5, 0xe2, 0xfc, 0xa4, 0x05, + 0xa5, 0xdc, 0x5d, 0x2a, 0x8a, 0x2b, 0x96, 0xab, 0x47, 0x56, 0xb1, 0xcf, 0x00, 0xde, 0xcf, 0xd7, + 0x34, 0xca, 0x90, 0xbf, 0xf9, 0xf2, 0xba, 0xfd, 0xe7, 0xfb, 0xdd, 0x84, 0x0f, 0x4b, 0xb4, 0x64, + 0x9a, 0x8f, 0xc1, 0x9f, 0x7d, 0x90, 0xe2, 0x5e, 0x07, 0xcc, 0xbf, 0x05, 0xd5, 0x8f, 0xe1, 0x66, + 0xa9, 0x9a, 0x54, 0xb7, 0xf5, 0x69, 0x09, 0x2e, 0xee, 0x71, 0xac, 0x08, 0xa8, 0x14, 0xcc, 0xd8, + 0xb6, 0x5e, 0x30, 0xe4, 0x7a, 0x61, 0xbf, 0xab, 0xd6, 0xf5, 0xb1, 0xe9, 0xe9, 0xb9, 0x53, 0xf3, + 0x73, 0x31, 0xef, 0xd4, 0x1c, 0x76, 0xee, 0xa9, 0x05, 0xfd, 0xa5, 0x7c, 0x04, 0xb0, 0xfe, 0xcf, + 0xe6, 0x32, 0xe7, 0xda, 0xb8, 0xc2, 0x50, 0x9f, 0xdf, 0x94, 0x91, 0x09, 0x39, 0x06, 0x50, 0x2d, + 0xe9, 0x18, 0xeb, 0xda, 0x89, 0x33, 0x8e, 0xfa, 0xe2, 0xe6, 0x9c, 0x54, 0x4e, 0xe7, 0xed, 0xc5, + 0x2f, 0x0d, 0x7c, 0x0f, 0x35, 0x70, 0x1a, 0x6a, 0xe0, 0x2c, 0xd4, 0xc0, 0x45, 0xa8, 0x81, 0xaf, + 0x33, 0xad, 0x72, 0x36, 0xd3, 0x2a, 0x3f, 0x66, 0x5a, 0x65, 0x7f, 0x3b, 0x37, 0xf8, 0x26, 0x3e, + 0x74, 0x5c, 0x6e, 0x98, 0xb8, 0x15, 0x3f, 0x1c, 0xc6, 0x51, 0xf6, 0xa9, 0x88, 0x1f, 0x00, 0x77, + 0x39, 0x7e, 0xc0, 0x9f, 0xfc, 0x0e, 0x00, 0x00, 0xff, 0xff, 0xc2, 0x01, 0xd4, 0x2a, 0x46, 0x06, + 0x00, 0x00, } func (this *MsgConvertCoinToERC20) VerboseEqual(that interface{}) error { @@ -635,8 +636,8 @@ func (this *MsgConvertERC20ToCoin) VerboseEqual(that interface{}) error { if this.Receiver != that1.Receiver { return fmt.Errorf("Receiver this(%v) Not Equal that(%v)", this.Receiver, that1.Receiver) } - if this.KavaERC20Address != that1.KavaERC20Address { - return fmt.Errorf("KavaERC20Address this(%v) Not Equal that(%v)", this.KavaERC20Address, that1.KavaERC20Address) + if this.ZgchainERC20Address != that1.ZgchainERC20Address { + return fmt.Errorf("ZgchainERC20Address this(%v) Not Equal that(%v)", this.ZgchainERC20Address, that1.ZgchainERC20Address) } if !this.Amount.Equal(that1.Amount) { return fmt.Errorf("Amount this(%v) Not Equal that(%v)", this.Amount, that1.Amount) @@ -668,7 +669,7 @@ func (this *MsgConvertERC20ToCoin) Equal(that interface{}) bool { if this.Receiver != that1.Receiver { return false } - if this.KavaERC20Address != that1.KavaERC20Address { + if this.ZgchainERC20Address != that1.ZgchainERC20Address { return false } if !this.Amount.Equal(that1.Amount) { @@ -965,9 +966,9 @@ const _ = grpc.SupportPackageIsVersion4 // // 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 { - // ConvertCoinToERC20 defines a method for converting sdk.Coin to Kava ERC20. + // ConvertCoinToERC20 defines a method for converting sdk.Coin to 0g-chain ERC20. ConvertCoinToERC20(ctx context.Context, in *MsgConvertCoinToERC20, opts ...grpc.CallOption) (*MsgConvertCoinToERC20Response, error) - // ConvertERC20ToCoin defines a method for converting Kava ERC20 to sdk.Coin. + // ConvertERC20ToCoin defines a method for converting 0g-chain ERC20 to sdk.Coin. ConvertERC20ToCoin(ctx context.Context, in *MsgConvertERC20ToCoin, opts ...grpc.CallOption) (*MsgConvertERC20ToCoinResponse, error) // ConvertCosmosCoinToERC20 defines a method for converting a cosmos sdk.Coin to an ERC20. ConvertCosmosCoinToERC20(ctx context.Context, in *MsgConvertCosmosCoinToERC20, opts ...grpc.CallOption) (*MsgConvertCosmosCoinToERC20Response, error) @@ -985,7 +986,7 @@ func NewMsgClient(cc grpc1.ClientConn) MsgClient { func (c *msgClient) ConvertCoinToERC20(ctx context.Context, in *MsgConvertCoinToERC20, opts ...grpc.CallOption) (*MsgConvertCoinToERC20Response, error) { out := new(MsgConvertCoinToERC20Response) - err := c.cc.Invoke(ctx, "/kava.evmutil.v1beta1.Msg/ConvertCoinToERC20", in, out, opts...) + err := c.cc.Invoke(ctx, "/zgc.evmutil.v1beta1.Msg/ConvertCoinToERC20", in, out, opts...) if err != nil { return nil, err } @@ -994,7 +995,7 @@ func (c *msgClient) ConvertCoinToERC20(ctx context.Context, in *MsgConvertCoinTo func (c *msgClient) ConvertERC20ToCoin(ctx context.Context, in *MsgConvertERC20ToCoin, opts ...grpc.CallOption) (*MsgConvertERC20ToCoinResponse, error) { out := new(MsgConvertERC20ToCoinResponse) - err := c.cc.Invoke(ctx, "/kava.evmutil.v1beta1.Msg/ConvertERC20ToCoin", in, out, opts...) + err := c.cc.Invoke(ctx, "/zgc.evmutil.v1beta1.Msg/ConvertERC20ToCoin", in, out, opts...) if err != nil { return nil, err } @@ -1003,7 +1004,7 @@ func (c *msgClient) ConvertERC20ToCoin(ctx context.Context, in *MsgConvertERC20T func (c *msgClient) ConvertCosmosCoinToERC20(ctx context.Context, in *MsgConvertCosmosCoinToERC20, opts ...grpc.CallOption) (*MsgConvertCosmosCoinToERC20Response, error) { out := new(MsgConvertCosmosCoinToERC20Response) - err := c.cc.Invoke(ctx, "/kava.evmutil.v1beta1.Msg/ConvertCosmosCoinToERC20", in, out, opts...) + err := c.cc.Invoke(ctx, "/zgc.evmutil.v1beta1.Msg/ConvertCosmosCoinToERC20", in, out, opts...) if err != nil { return nil, err } @@ -1012,7 +1013,7 @@ func (c *msgClient) ConvertCosmosCoinToERC20(ctx context.Context, in *MsgConvert func (c *msgClient) ConvertCosmosCoinFromERC20(ctx context.Context, in *MsgConvertCosmosCoinFromERC20, opts ...grpc.CallOption) (*MsgConvertCosmosCoinFromERC20Response, error) { out := new(MsgConvertCosmosCoinFromERC20Response) - err := c.cc.Invoke(ctx, "/kava.evmutil.v1beta1.Msg/ConvertCosmosCoinFromERC20", in, out, opts...) + err := c.cc.Invoke(ctx, "/zgc.evmutil.v1beta1.Msg/ConvertCosmosCoinFromERC20", in, out, opts...) if err != nil { return nil, err } @@ -1021,9 +1022,9 @@ func (c *msgClient) ConvertCosmosCoinFromERC20(ctx context.Context, in *MsgConve // MsgServer is the server API for Msg service. type MsgServer interface { - // ConvertCoinToERC20 defines a method for converting sdk.Coin to Kava ERC20. + // ConvertCoinToERC20 defines a method for converting sdk.Coin to 0g-chain ERC20. ConvertCoinToERC20(context.Context, *MsgConvertCoinToERC20) (*MsgConvertCoinToERC20Response, error) - // ConvertERC20ToCoin defines a method for converting Kava ERC20 to sdk.Coin. + // ConvertERC20ToCoin defines a method for converting 0g-chain ERC20 to sdk.Coin. ConvertERC20ToCoin(context.Context, *MsgConvertERC20ToCoin) (*MsgConvertERC20ToCoinResponse, error) // ConvertCosmosCoinToERC20 defines a method for converting a cosmos sdk.Coin to an ERC20. ConvertCosmosCoinToERC20(context.Context, *MsgConvertCosmosCoinToERC20) (*MsgConvertCosmosCoinToERC20Response, error) @@ -1062,7 +1063,7 @@ func _Msg_ConvertCoinToERC20_Handler(srv interface{}, ctx context.Context, dec f } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/kava.evmutil.v1beta1.Msg/ConvertCoinToERC20", + FullMethod: "/zgc.evmutil.v1beta1.Msg/ConvertCoinToERC20", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MsgServer).ConvertCoinToERC20(ctx, req.(*MsgConvertCoinToERC20)) @@ -1080,7 +1081,7 @@ func _Msg_ConvertERC20ToCoin_Handler(srv interface{}, ctx context.Context, dec f } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/kava.evmutil.v1beta1.Msg/ConvertERC20ToCoin", + FullMethod: "/zgc.evmutil.v1beta1.Msg/ConvertERC20ToCoin", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MsgServer).ConvertERC20ToCoin(ctx, req.(*MsgConvertERC20ToCoin)) @@ -1098,7 +1099,7 @@ func _Msg_ConvertCosmosCoinToERC20_Handler(srv interface{}, ctx context.Context, } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/kava.evmutil.v1beta1.Msg/ConvertCosmosCoinToERC20", + FullMethod: "/zgc.evmutil.v1beta1.Msg/ConvertCosmosCoinToERC20", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MsgServer).ConvertCosmosCoinToERC20(ctx, req.(*MsgConvertCosmosCoinToERC20)) @@ -1116,7 +1117,7 @@ func _Msg_ConvertCosmosCoinFromERC20_Handler(srv interface{}, ctx context.Contex } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/kava.evmutil.v1beta1.Msg/ConvertCosmosCoinFromERC20", + FullMethod: "/zgc.evmutil.v1beta1.Msg/ConvertCosmosCoinFromERC20", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MsgServer).ConvertCosmosCoinFromERC20(ctx, req.(*MsgConvertCosmosCoinFromERC20)) @@ -1125,7 +1126,7 @@ func _Msg_ConvertCosmosCoinFromERC20_Handler(srv interface{}, ctx context.Contex } var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.evmutil.v1beta1.Msg", + ServiceName: "zgc.evmutil.v1beta1.Msg", HandlerType: (*MsgServer)(nil), Methods: []grpc.MethodDesc{ { @@ -1146,7 +1147,7 @@ var _Msg_serviceDesc = grpc.ServiceDesc{ }, }, Streams: []grpc.StreamDesc{}, - Metadata: "kava/evmutil/v1beta1/tx.proto", + Metadata: "zgc/evmutil/v1beta1/tx.proto", } func (m *MsgConvertCoinToERC20) Marshal() (dAtA []byte, err error) { @@ -1251,10 +1252,10 @@ func (m *MsgConvertERC20ToCoin) MarshalToSizedBuffer(dAtA []byte) (int, error) { } i-- dAtA[i] = 0x22 - if len(m.KavaERC20Address) > 0 { - i -= len(m.KavaERC20Address) - copy(dAtA[i:], m.KavaERC20Address) - i = encodeVarintTx(dAtA, i, uint64(len(m.KavaERC20Address))) + if len(m.ZgchainERC20Address) > 0 { + i -= len(m.ZgchainERC20Address) + copy(dAtA[i:], m.ZgchainERC20Address) + i = encodeVarintTx(dAtA, i, uint64(len(m.ZgchainERC20Address))) i-- dAtA[i] = 0x1a } @@ -1497,7 +1498,7 @@ func (m *MsgConvertERC20ToCoin) Size() (n int) { if l > 0 { n += 1 + l + sovTx(uint64(l)) } - l = len(m.KavaERC20Address) + l = len(m.ZgchainERC20Address) if l > 0 { n += 1 + l + sovTx(uint64(l)) } @@ -1876,7 +1877,7 @@ func (m *MsgConvertERC20ToCoin) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field KavaERC20Address", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ZgchainERC20Address", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -1904,7 +1905,7 @@ func (m *MsgConvertERC20ToCoin) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.KavaERC20Address = string(dAtA[iNdEx:postIndex]) + m.ZgchainERC20Address = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 4: if wireType != 2 { diff --git a/x/hard/abci.go b/x/hard/abci.go deleted file mode 100644 index 8041011e..00000000 --- a/x/hard/abci.go +++ /dev/null @@ -1,17 +0,0 @@ -package hard - -import ( - "time" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/hard/keeper" - "github.com/kava-labs/kava/x/hard/types" -) - -// BeginBlocker updates interest rates -func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - - k.ApplyInterestRateUpdates(ctx) -} diff --git a/x/hard/client/cli/query.go b/x/hard/client/cli/query.go deleted file mode 100644 index f0703bd5..00000000 --- a/x/hard/client/cli/query.go +++ /dev/null @@ -1,534 +0,0 @@ -package cli - -import ( - "context" - "fmt" - - "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/cosmos/cosmos-sdk/version" - - "github.com/kava-labs/kava/x/hard/types" -) - -// flags for cli queries -const ( - flagName = "name" - flagDenom = "denom" - flagOwner = "owner" -) - -// GetQueryCmd returns the cli query commands for the module -func GetQueryCmd() *cobra.Command { - hardQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the hard module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - queryParamsCmd(), - queryAccountsCmd(), - queryDepositsCmd(), - queryUnsyncedDepositsCmd(), - queryTotalDepositedCmd(), - queryBorrowsCmd(), - queryUnsyncedBorrowsCmd(), - queryTotalBorrowedCmd(), - queryInterestRateCmd(), - queryReserves(), - queryInterestFactorsCmd(), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - hardQueryCmd.AddCommand(cmds...) - - return hardQueryCmd -} - -func queryParamsCmd() *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: "get the hard module parameters", - Long: "Get the current global hard module parameters.", - 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(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } -} - -func queryAccountsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "accounts", - Short: "query hard module accounts", - Long: "Query for all hard module accounts", - Example: fmt.Sprintf(`%[1]s q %[2]s accounts -%[1]s q %[2]s accounts`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - req := &types.QueryAccountsRequest{} - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Accounts(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - return cmd -} - -func queryUnsyncedDepositsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "unsynced-deposits", - Short: "query hard module unsynced deposits with optional filters", - Long: "query for all hard module unsynced deposits or a specific unsynced deposit using flags", - Example: fmt.Sprintf(`%[1]s q %[2]s unsynced-deposits -%[1]s q %[2]s unsynced-deposits --owner kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny --denom bnb -%[1]s q %[2]s unsynced-deposits --denom ukava -%[1]s q %[2]s unsynced-deposits --denom btcb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - ownerBech, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - req := &types.QueryUnsyncedDepositsRequest{ - Denom: denom, - Pagination: pageReq, - } - - if len(ownerBech) != 0 { - depositOwner, err := sdk.AccAddressFromBech32(ownerBech) - if err != nil { - return err - } - req.Owner = depositOwner.String() - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.UnsyncedDeposits(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, "unsynced-deposits") - - cmd.Flags().String(flagOwner, "", "(optional) filter for unsynced deposits by owner address") - cmd.Flags().String(flagDenom, "", "(optional) filter for unsynced deposits by denom") - - return cmd -} - -func queryDepositsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "deposits", - Short: "query hard module deposits with optional filters", - Long: "query for all hard module deposits or a specific deposit using flags", - Example: fmt.Sprintf(`%[1]s q %[2]s deposits -%[1]s q %[2]s deposits --owner kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny --denom bnb -%[1]s q %[2]s deposits --denom ukava -%[1]s q %[2]s deposits --denom btcb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - ownerBech, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - req := &types.QueryDepositsRequest{ - Denom: denom, - Pagination: pageReq, - } - - if len(ownerBech) != 0 { - depositOwner, err := sdk.AccAddressFromBech32(ownerBech) - if err != nil { - return err - } - req.Owner = depositOwner.String() - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Deposits(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, "deposits") - - cmd.Flags().String(flagOwner, "", "(optional) filter for deposits by owner address") - cmd.Flags().String(flagDenom, "", "(optional) filter for deposits by denom") - - return cmd -} - -func queryUnsyncedBorrowsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "unsynced-borrows", - Short: "query hard module unsynced borrows with optional filters", - Long: "query for all hard module unsynced borrows or a specific unsynced borrow using flags", - Example: fmt.Sprintf(`%[1]s q %[2]s unsynced-borrows -%[1]s q %[2]s unsynced-borrows --owner kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny -%[1]s q %[2]s unsynced-borrows --denom bnb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - ownerBech, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - req := &types.QueryUnsyncedBorrowsRequest{ - Denom: denom, - Pagination: pageReq, - } - - if len(ownerBech) != 0 { - borrowOwner, err := sdk.AccAddressFromBech32(ownerBech) - if err != nil { - return err - } - req.Owner = borrowOwner.String() - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.UnsyncedBorrows(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, "unsynced borrows") - - cmd.Flags().String(flagOwner, "", "(optional) filter for unsynced borrows by owner address") - cmd.Flags().String(flagDenom, "", "(optional) filter for unsynced borrows by denom") - - return cmd -} - -func queryBorrowsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "borrows", - Short: "query hard module borrows with optional filters", - Long: "query for all hard module borrows or a specific borrow using flags", - Example: fmt.Sprintf(`%[1]s q %[2]s borrows -%[1]s q %[2]s borrows --owner kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny -%[1]s q %[2]s borrows --denom bnb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - ownerBech, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - req := &types.QueryBorrowsRequest{ - Denom: denom, - Pagination: pageReq, - } - - if len(ownerBech) != 0 { - borrowOwner, err := sdk.AccAddressFromBech32(ownerBech) - if err != nil { - return err - } - req.Owner = borrowOwner.String() - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.Borrows(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, "borrows") - - cmd.Flags().String(flagOwner, "", "(optional) filter for borrows by owner address") - cmd.Flags().String(flagDenom, "", "(optional) filter for borrows by denom") - - return cmd -} - -func queryTotalBorrowedCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "total-borrowed", - Short: "get total current borrowed amount", - Long: "get the total amount of coins currently borrowed using flags", - Example: fmt.Sprintf(`%[1]s q %[2]s total-borrowed -%[1]s q %[2]s total-borrowed --denom bnb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.TotalBorrowed(context.Background(), &types.QueryTotalBorrowedRequest{ - Denom: denom, - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - cmd.Flags().String(flagDenom, "", "(optional) filter total borrowed coins by denom") - - return cmd -} - -func queryTotalDepositedCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "total-deposited", - Short: "get total current deposited amount", - Long: "get the total amount of coins currently deposited using flags", - Example: fmt.Sprintf(`%[1]s q %[2]s total-deposited -%[1]s q %[2]s total-deposited --denom bnb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.TotalDeposited(context.Background(), &types.QueryTotalDepositedRequest{ - Denom: denom, - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - cmd.Flags().String(flagDenom, "", "(optional) filter total deposited coins by denom") - - return cmd -} - -func queryInterestRateCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "interest-rate", - Short: "get current money market interest rates", - Long: "get current money market interest rates", - Example: fmt.Sprintf(`%[1]s q %[2]s interest-rate -%[1]s q %[2]s interest-rate --denom bnb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.InterestRate(context.Background(), &types.QueryInterestRateRequest{ - Denom: denom, - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - cmd.Flags().String(flagDenom, "", "(optional) filter interest rates by denom") - - return cmd -} - -func queryReserves() *cobra.Command { - cmd := &cobra.Command{ - Use: "reserves", - Short: "get total current Hard module reserves", - Long: "get the total amount of coins currently held as reserve by the Hard module", - Example: fmt.Sprintf(`%[1]s q %[2]s reserves -%[1]s q %[2]s reserves --denom bnb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.Reserves(context.Background(), &types.QueryReservesRequest{ - Denom: denom, - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - cmd.Flags().String(flagDenom, "", "(optional) filter reserve coins by denom") - - return cmd -} - -func queryInterestFactorsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "interest-factors", - Short: "get current global interest factors", - Long: "get current global interest factors", - Example: fmt.Sprintf(`%[1]s q %[2]s interest-factors -%[1]s q %[2]s interest-factors --denom bnb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.InterestFactors(context.Background(), &types.QueryInterestFactorsRequest{ - Denom: denom, - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - cmd.Flags().String(flagDenom, "", "(optional) filter interest factors by denom") - - return cmd -} diff --git a/x/hard/client/cli/tx.go b/x/hard/client/cli/tx.go deleted file mode 100644 index 8c71f7dd..00000000 --- a/x/hard/client/cli/tx.go +++ /dev/null @@ -1,205 +0,0 @@ -package cli - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/kava-labs/kava/x/hard/types" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - hardTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName), - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - getCmdDeposit(), - getCmdWithdraw(), - getCmdBorrow(), - getCmdRepay(), - getCmdLiquidate(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - hardTxCmd.AddCommand(cmds...) - - return hardTxCmd -} - -func getCmdDeposit() *cobra.Command { - return &cobra.Command{ - Use: "deposit [amount]", - Short: "deposit coins to hard", - Example: fmt.Sprintf( - `%s tx %s deposit 10000000bnb --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - amount, err := sdk.ParseCoinsNormalized(args[0]) - if err != nil { - return err - } - msg := types.NewMsgDeposit(clientCtx.GetFromAddress(), amount) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -func getCmdWithdraw() *cobra.Command { - return &cobra.Command{ - Use: "withdraw [amount]", - Short: "withdraw coins from hard", - Args: cobra.ExactArgs(1), - Example: fmt.Sprintf( - `%s tx %s withdraw 10000000bnb --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - amount, err := sdk.ParseCoinsNormalized(args[0]) - if err != nil { - return err - } - msg := types.NewMsgWithdraw(clientCtx.GetFromAddress(), amount) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -func getCmdBorrow() *cobra.Command { - return &cobra.Command{ - Use: "borrow [amount]", - Short: "borrow tokens from the hard protocol", - Long: strings.TrimSpace(`borrows tokens from the hard protocol`), - Args: cobra.ExactArgs(1), - Example: fmt.Sprintf( - `%s tx %s borrow 1000000000ukava --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - coins, err := sdk.ParseCoinsNormalized(args[0]) - if err != nil { - return err - } - - msg := types.NewMsgBorrow(clientCtx.GetFromAddress(), coins) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -func getCmdRepay() *cobra.Command { - cmd := &cobra.Command{ - Use: "repay [amount]", - Short: "repay tokens to the hard protocol", - Long: strings.TrimSpace(`repay tokens to the hard protocol with optional --owner param to repay another account's loan`), - Args: cobra.ExactArgs(1), - Example: fmt.Sprintf(` -%[1]s tx %[2]s repay 1000000000ukava --from -%[1]s tx %[2]s repay 1000000000ukava,25000000000bnb --from -%[1]s tx %[2]s repay 1000000000ukava,25000000000bnb --owner --from `, version.AppName, types.ModuleName), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - var owner sdk.AccAddress - ownerStr, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - - // Parse optional owner argument or default to sender - if len(ownerStr) > 0 { - ownerAddr, err := sdk.AccAddressFromBech32(ownerStr) - if err != nil { - return err - } - owner = ownerAddr - } else { - owner = clientCtx.GetFromAddress() - } - - coins, err := sdk.ParseCoinsNormalized(args[0]) - if err != nil { - return err - } - - msg := types.NewMsgRepay(clientCtx.GetFromAddress(), owner, coins) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } - - cmd.Flags().String(flagOwner, "", "original borrower's address whose loan will be repaid") - - return cmd -} - -func getCmdLiquidate() *cobra.Command { - return &cobra.Command{ - Use: "liquidate [borrower-addr]", - Short: "liquidate a borrower that's over their loan-to-value ratio", - Long: strings.TrimSpace(`liquidate a borrower that's over their loan-to-value ratio`), - Args: cobra.ExactArgs(1), - Example: fmt.Sprintf( - `%s tx %s liquidate kava1hgcfsuwc889wtdmt8pjy7qffua9dd2tralu64j --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - borrower, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - msg := types.NewMsgLiquidate(clientCtx.GetFromAddress(), borrower) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} diff --git a/x/hard/genesis.go b/x/hard/genesis.go deleted file mode 100644 index fa491e8f..00000000 --- a/x/hard/genesis.go +++ /dev/null @@ -1,116 +0,0 @@ -package hard - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/hard/keeper" - "github.com/kava-labs/kava/x/hard/types" -) - -// InitGenesis initializes the store state from a genesis state. -func InitGenesis(ctx sdk.Context, k keeper.Keeper, accountKeeper types.AccountKeeper, gs types.GenesisState) { - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - k.SetParams(ctx, gs.Params) - - for _, mm := range gs.Params.MoneyMarkets { - k.SetMoneyMarket(ctx, mm.Denom, mm) - } - - for _, gat := range gs.PreviousAccumulationTimes { - k.SetPreviousAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - k.SetSupplyInterestFactor(ctx, gat.CollateralType, gat.SupplyInterestFactor) - k.SetBorrowInterestFactor(ctx, gat.CollateralType, gat.BorrowInterestFactor) - } - - for _, deposit := range gs.Deposits { - k.SetDeposit(ctx, deposit) - } - - for _, borrow := range gs.Borrows { - k.SetBorrow(ctx, borrow) - } - - k.SetSuppliedCoins(ctx, gs.TotalSupplied) - k.SetBorrowedCoins(ctx, gs.TotalBorrowed) - k.SetTotalReserves(ctx, gs.TotalReserves) - - // check if the module account exists - DepositModuleAccount := accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - if DepositModuleAccount == nil { - panic(fmt.Sprintf("%s module account has not been set", DepositModuleAccount)) - } -} - -// ExportGenesis export genesis state for hard module -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { - params := k.GetParams(ctx) - - gats := types.GenesisAccumulationTimes{} - deposits := types.Deposits{} - borrows := types.Borrows{} - - k.IterateDeposits(ctx, func(d types.Deposit) bool { - k.BeforeDepositModified(ctx, d) - syncedDeposit, found := k.GetSyncedDeposit(ctx, d.Depositor) - if !found { - panic(fmt.Sprintf("syncable deposit not found for %s", d.Depositor)) - } - deposits = append(deposits, syncedDeposit) - return false - }) - - k.IterateBorrows(ctx, func(b types.Borrow) bool { - k.BeforeBorrowModified(ctx, b) - syncedBorrow, found := k.GetSyncedBorrow(ctx, b.Borrower) - if !found { - panic(fmt.Sprintf("syncable borrow not found for %s", b.Borrower)) - } - borrows = append(borrows, syncedBorrow) - return false - }) - - totalSupplied, found := k.GetSuppliedCoins(ctx) - if !found { - totalSupplied = types.DefaultTotalSupplied - } - totalBorrowed, found := k.GetBorrowedCoins(ctx) - if !found { - totalBorrowed = types.DefaultTotalBorrowed - } - totalReserves, found := k.GetTotalReserves(ctx) - if !found { - totalReserves = types.DefaultTotalReserves - } - - for _, mm := range params.MoneyMarkets { - supplyFactor, f := k.GetSupplyInterestFactor(ctx, mm.Denom) - if !f { - supplyFactor = sdk.OneDec() - } - borrowFactor, f := k.GetBorrowInterestFactor(ctx, mm.Denom) - if !f { - borrowFactor = sdk.OneDec() - } - previousAccrualTime, f := k.GetPreviousAccrualTime(ctx, mm.Denom) - if !f { - // Goverance adds new params at end of block, but mm's previous accrual time is set in begin blocker. - // If a new money market is added and chain is exported before begin blocker runs, then the previous - // accrual time will not be found. We can't set it here because our ctx doesn't contain current block - // time; if we set it to ctx.BlockTime() then on the next block it could accrue interest from Jan 1st - // 0001 to now. To avoid setting up a bad state, we panic. - panic(fmt.Sprintf("expected previous accrual time to be set in state for %s", mm.Denom)) - } - gat := types.NewGenesisAccumulationTime(mm.Denom, previousAccrualTime, supplyFactor, borrowFactor) - gats = append(gats, gat) - - } - return types.NewGenesisState( - params, gats, deposits, borrows, - totalSupplied, totalBorrowed, totalReserves, - ) -} diff --git a/x/hard/genesis_test.go b/x/hard/genesis_test.go deleted file mode 100644 index 8d8b923a..00000000 --- a/x/hard/genesis_test.go +++ /dev/null @@ -1,202 +0,0 @@ -package hard_test - -import ( - "fmt" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/hard" - "github.com/kava-labs/kava/x/hard/keeper" - "github.com/kava-labs/kava/x/hard/types" -) - -type GenesisTestSuite struct { - suite.Suite - - app app.TestApp - genTime time.Time - ctx sdk.Context - keeper keeper.Keeper - addrs []sdk.AccAddress -} - -func (suite *GenesisTestSuite) SetupTest() { - tApp := app.NewTestApp() - suite.genTime = tmtime.Canonical(time.Date(2021, 1, 1, 1, 1, 1, 1, time.UTC)) - suite.ctx = tApp.NewContext(true, tmproto.Header{Height: 1, Time: suite.genTime}) - suite.keeper = tApp.GetHardKeeper() - suite.app = tApp - - _, addrs := app.GeneratePrivKeyAddressPairs(3) - suite.addrs = addrs -} - -func (suite *GenesisTestSuite) Test_InitExportGenesis() { - loanToValue, _ := sdk.NewDecFromStr("0.6") - params := types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket( - "ukava", - types.NewBorrowLimit( - false, - sdk.NewDec(1e15), - loanToValue, - ), - "kava:usd", - sdkmath.NewInt(1e6), - types.NewInterestRateModel( - sdk.MustNewDecFromStr("0.05"), - sdk.MustNewDecFromStr("2"), - sdk.MustNewDecFromStr("0.8"), - sdk.MustNewDecFromStr("10"), - ), - sdk.MustNewDecFromStr("0.05"), - sdk.ZeroDec(), - ), - }, - sdk.NewDec(10), - ) - - deposits := types.Deposits{ - types.NewDeposit( - suite.addrs[0], - sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e8))), // 100 ukava - types.SupplyInterestFactors{ - { - Denom: "ukava", - Value: sdk.NewDec(1), - }, - }, - ), - } - - var totalSupplied sdk.Coins - for _, deposit := range deposits { - totalSupplied = totalSupplied.Add(deposit.Amount...) - } - - borrows := types.Borrows{ - types.NewBorrow( - suite.addrs[1], - sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e7))), // 10 ukava - types.BorrowInterestFactors{ - { - Denom: "ukava", - Value: sdk.NewDec(1), - }, - }, - ), - } - - var totalBorrowed sdk.Coins - for _, borrow := range borrows { - totalBorrowed = totalBorrowed.Add(borrow.Amount...) - } - - supplyInterestFactor := sdk.MustNewDecFromStr("1.0001") - borrowInterestFactor := sdk.MustNewDecFromStr("1.1234") - accuralTimes := types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime("ukava", suite.genTime, supplyInterestFactor, borrowInterestFactor), - } - - hardGenesis := types.NewGenesisState( - params, - accuralTimes, - deposits, - borrows, - totalSupplied, - totalBorrowed, - sdk.Coins{}, - ) - - suite.NotPanics( - func() { - suite.app.InitializeFromGenesisStatesWithTime( - suite.genTime, - app.GenesisState{types.ModuleName: suite.app.AppCodec().MustMarshalJSON(&hardGenesis)}, - ) - }, - ) - - var expectedDeposits types.Deposits - for _, deposit := range deposits { - // Deposit coin amounts - var depositAmount sdk.Coins - for _, coin := range deposit.Amount { - accrualTime, found := getGenesisAccumulationTime(coin.Denom, accuralTimes) - if !found { - panic(fmt.Sprintf("accrual time not found %s", coin.Denom)) - } - expectedAmt := accrualTime.SupplyInterestFactor.MulInt(coin.Amount).RoundInt() - depositAmount = depositAmount.Add(sdk.NewCoin(coin.Denom, expectedAmt)) - } - deposit.Amount = depositAmount - // Deposit interest factor indexes - var indexes types.SupplyInterestFactors - for _, index := range deposit.Index { - accrualTime, found := getGenesisAccumulationTime(index.Denom, accuralTimes) - if !found { - panic(fmt.Sprintf("accrual time not found %s", index.Denom)) - } - index.Value = accrualTime.SupplyInterestFactor - indexes = append(indexes, index) - } - deposit.Index = indexes - expectedDeposits = append(expectedDeposits, deposit) - } - - var expectedBorrows types.Borrows - for _, borrow := range borrows { - // Borrow coin amounts - var borrowAmount sdk.Coins - for _, coin := range borrow.Amount { - accrualTime, found := getGenesisAccumulationTime(coin.Denom, accuralTimes) - if !found { - panic(fmt.Sprintf("accrual time not found %s", coin.Denom)) - } - expectedAmt := accrualTime.BorrowInterestFactor.MulInt(coin.Amount).RoundInt() - borrowAmount = borrowAmount.Add(sdk.NewCoin(coin.Denom, expectedAmt)) - - } - borrow.Amount = borrowAmount - // Borrow interest factor indexes - var indexes types.BorrowInterestFactors - for _, index := range borrow.Index { - accrualTime, found := getGenesisAccumulationTime(index.Denom, accuralTimes) - if !found { - panic(fmt.Sprintf("accrual time not found %s", index.Denom)) - } - index.Value = accrualTime.BorrowInterestFactor - indexes = append(indexes, index) - } - borrow.Index = indexes - expectedBorrows = append(expectedBorrows, borrow) - } - - expectedGenesis := hardGenesis - expectedGenesis.Deposits = expectedDeposits - expectedGenesis.Borrows = expectedBorrows - exportedGenesis := hard.ExportGenesis(suite.ctx, suite.keeper) - suite.Equal(expectedGenesis, exportedGenesis) -} - -func getGenesisAccumulationTime(denom string, ts types.GenesisAccumulationTimes) (types.GenesisAccumulationTime, bool) { - for _, t := range ts { - if t.CollateralType == denom { - return t, true - } - } - return types.GenesisAccumulationTime{}, false -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(GenesisTestSuite)) -} diff --git a/x/hard/keeper/borrow.go b/x/hard/keeper/borrow.go deleted file mode 100644 index 6c198d45..00000000 --- a/x/hard/keeper/borrow.go +++ /dev/null @@ -1,302 +0,0 @@ -package keeper - -import ( - "errors" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/kava-labs/kava/x/hard/types" -) - -// Borrow funds -func (k Keeper) Borrow(ctx sdk.Context, borrower sdk.AccAddress, coins sdk.Coins) error { - // Set any new denoms' global borrow index to 1.0 - for _, coin := range coins { - _, foundInterestFactor := k.GetBorrowInterestFactor(ctx, coin.Denom) - if !foundInterestFactor { - _, foundMm := k.GetMoneyMarket(ctx, coin.Denom) - if foundMm { - k.SetBorrowInterestFactor(ctx, coin.Denom, sdk.OneDec()) - } - } - } - - // Call incentive hooks - existingDeposit, hasExistingDeposit := k.GetDeposit(ctx, borrower) - if hasExistingDeposit { - k.BeforeDepositModified(ctx, existingDeposit) - } - existingBorrow, hasExistingBorrow := k.GetBorrow(ctx, borrower) - if hasExistingBorrow { - k.BeforeBorrowModified(ctx, existingBorrow) - } - - k.SyncSupplyInterest(ctx, borrower) - k.SyncBorrowInterest(ctx, borrower) - - // Validate borrow amount within user and protocol limits - err := k.ValidateBorrow(ctx, borrower, coins) - if err != nil { - return err - } - - // Sends coins from Hard module account to user - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, borrower, coins) - if err != nil { - if errors.Is(err, sdkerrors.ErrInsufficientFunds) { - macc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - modAccCoins := k.bankKeeper.GetAllBalances(ctx, macc.GetAddress()) - for _, coin := range coins { - _, isNegative := modAccCoins.SafeSub(coin) - if isNegative { - return errorsmod.Wrapf(types.ErrBorrowExceedsAvailableBalance, - "the requested borrow amount of %s exceeds the total amount of %s%s available to borrow", - coin, modAccCoins.AmountOf(coin.Denom), coin.Denom, - ) - } - } - } - return err - } - - interestFactors := types.BorrowInterestFactors{} - currBorrow, foundBorrow := k.GetBorrow(ctx, borrower) - if foundBorrow { - interestFactors = currBorrow.Index - } - for _, coin := range coins { - interestFactorValue, foundValue := k.GetBorrowInterestFactor(ctx, coin.Denom) - if foundValue { - interestFactors = interestFactors.SetInterestFactor(coin.Denom, interestFactorValue) - } - } - - // Calculate new borrow amount - var amount sdk.Coins - if foundBorrow { - amount = currBorrow.Amount.Add(coins...) - } else { - amount = coins - } - - // Construct the user's new/updated borrow with amount and interest factors - borrow := types.NewBorrow(borrower, amount, interestFactors) - if borrow.Amount.Empty() { - k.DeleteBorrow(ctx, borrow) - } else { - k.SetBorrow(ctx, borrow) - } - - // Update total borrowed amount by newly borrowed coins. Don't add user's pending interest as - // it has already been included in the total borrowed coins by the BeginBlocker. - k.IncrementBorrowedCoins(ctx, coins) - - if !hasExistingBorrow { - k.AfterBorrowCreated(ctx, borrow) - } else { - k.AfterBorrowModified(ctx, borrow) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeHardBorrow, - sdk.NewAttribute(types.AttributeKeyBorrower, borrower.String()), - sdk.NewAttribute(types.AttributeKeyBorrowCoins, coins.String()), - ), - ) - - return nil -} - -// ValidateBorrow validates a borrow request against borrower and protocol requirements -func (k Keeper) ValidateBorrow(ctx sdk.Context, borrower sdk.AccAddress, amount sdk.Coins) error { - if amount.IsZero() { - return types.ErrBorrowEmptyCoins - } - - // The reserve coins aren't available for users to borrow - macc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - hardMaccCoins := k.bankKeeper.GetAllBalances(ctx, macc.GetAddress()) - reserveCoins, foundReserveCoins := k.GetTotalReserves(ctx) - if !foundReserveCoins { - reserveCoins = sdk.NewCoins() - } - fundsAvailableToBorrow, isNegative := hardMaccCoins.SafeSub(reserveCoins...) - if isNegative { - return errorsmod.Wrapf(types.ErrReservesExceedCash, "reserves %s > cash %s", reserveCoins, hardMaccCoins) - } - if amount.IsAnyGT(fundsAvailableToBorrow) { - return errorsmod.Wrapf(types.ErrExceedsProtocolBorrowableBalance, "requested borrow %s > available to borrow %s", amount, fundsAvailableToBorrow) - } - - // Get the proposed borrow USD value - proprosedBorrowUSDValue := sdk.ZeroDec() - for _, coin := range amount { - moneyMarket, found := k.GetMoneyMarket(ctx, coin.Denom) - if !found { - return errorsmod.Wrapf(types.ErrMarketNotFound, "no money market found for denom %s", coin.Denom) - } - - // Calculate this coin's USD value and add it borrow's total USD value - assetPriceInfo, err := k.pricefeedKeeper.GetCurrentPrice(ctx, moneyMarket.SpotMarketID) - if err != nil { - return errorsmod.Wrapf(types.ErrPriceNotFound, "no price found for market %s", moneyMarket.SpotMarketID) - } - coinUSDValue := sdk.NewDecFromInt(coin.Amount).Quo(sdk.NewDecFromInt(moneyMarket.ConversionFactor)).Mul(assetPriceInfo.Price) - - // Validate the requested borrow value for the asset against the money market's global borrow limit - if moneyMarket.BorrowLimit.HasMaxLimit { - var assetTotalBorrowedAmount sdkmath.Int - totalBorrowedCoins, found := k.GetBorrowedCoins(ctx) - if !found { - assetTotalBorrowedAmount = sdk.ZeroInt() - } else { - assetTotalBorrowedAmount = totalBorrowedCoins.AmountOf(coin.Denom) - } - newProposedAssetTotalBorrowedAmount := sdk.NewDecFromInt(assetTotalBorrowedAmount.Add(coin.Amount)) - if newProposedAssetTotalBorrowedAmount.GT(moneyMarket.BorrowLimit.MaximumLimit) { - return errorsmod.Wrapf(types.ErrGreaterThanAssetBorrowLimit, - "proposed borrow would result in %s borrowed, but the maximum global asset borrow limit is %s", - newProposedAssetTotalBorrowedAmount, moneyMarket.BorrowLimit.MaximumLimit) - } - } - proprosedBorrowUSDValue = proprosedBorrowUSDValue.Add(coinUSDValue) - } - - // Get the total borrowable USD amount at user's existing deposits - deposit, found := k.GetDeposit(ctx, borrower) - if !found { - return errorsmod.Wrapf(types.ErrDepositsNotFound, "no deposits found for %s", borrower) - } - totalBorrowableAmount := sdk.ZeroDec() - for _, coin := range deposit.Amount { - moneyMarket, found := k.GetMoneyMarket(ctx, coin.Denom) - if !found { - return errorsmod.Wrapf(types.ErrMarketNotFound, "no money market found for denom %s", coin.Denom) - } - - // Calculate the borrowable amount and add it to the user's total borrowable amount - assetPriceInfo, err := k.pricefeedKeeper.GetCurrentPrice(ctx, moneyMarket.SpotMarketID) - if err != nil { - return errorsmod.Wrapf(types.ErrPriceNotFound, "no price found for market %s", moneyMarket.SpotMarketID) - } - depositUSDValue := sdk.NewDecFromInt(coin.Amount).Quo(sdk.NewDecFromInt(moneyMarket.ConversionFactor)).Mul(assetPriceInfo.Price) - borrowableAmountForDeposit := depositUSDValue.Mul(moneyMarket.BorrowLimit.LoanToValue) - totalBorrowableAmount = totalBorrowableAmount.Add(borrowableAmountForDeposit) - } - - // Get the total USD value of user's existing borrows - existingBorrowUSDValue := sdk.ZeroDec() - existingBorrow, found := k.GetBorrow(ctx, borrower) - if found { - for _, coin := range existingBorrow.Amount { - moneyMarket, found := k.GetMoneyMarket(ctx, coin.Denom) - if !found { - return errorsmod.Wrapf(types.ErrMarketNotFound, "no money market found for denom %s", coin.Denom) - } - - // Calculate this borrow coin's USD value and add it to the total previous borrowed USD value - assetPriceInfo, err := k.pricefeedKeeper.GetCurrentPrice(ctx, moneyMarket.SpotMarketID) - if err != nil { - return errorsmod.Wrapf(types.ErrPriceNotFound, "no price found for market %s", moneyMarket.SpotMarketID) - } - coinUSDValue := sdk.NewDecFromInt(coin.Amount).Quo(sdk.NewDecFromInt(moneyMarket.ConversionFactor)).Mul(assetPriceInfo.Price) - existingBorrowUSDValue = existingBorrowUSDValue.Add(coinUSDValue) - } - } - - // Borrow's updated total USD value must be greater than the minimum global USD borrow limit - totalBorrowUSDValue := proprosedBorrowUSDValue.Add(existingBorrowUSDValue) - if totalBorrowUSDValue.LT(k.GetMinimumBorrowUSDValue(ctx)) { - return errorsmod.Wrapf(types.ErrBelowMinimumBorrowValue, "the proposed borrow's USD value $%s is below the minimum borrow limit $%s", totalBorrowUSDValue, k.GetMinimumBorrowUSDValue(ctx)) - } - - // Validate that the proposed borrow's USD value is within user's borrowable limit - if proprosedBorrowUSDValue.GT(totalBorrowableAmount.Sub(existingBorrowUSDValue)) { - return errorsmod.Wrapf(types.ErrInsufficientLoanToValue, "requested borrow %s exceeds the allowable amount as determined by the collateralization ratio", amount) - } - return nil -} - -// IncrementBorrowedCoins increments the total amount of borrowed coins by the newCoins parameter -func (k Keeper) IncrementBorrowedCoins(ctx sdk.Context, newCoins sdk.Coins) { - borrowedCoins, found := k.GetBorrowedCoins(ctx) - if !found { - if !newCoins.Empty() { - k.SetBorrowedCoins(ctx, newCoins) - } - } else { - k.SetBorrowedCoins(ctx, borrowedCoins.Add(newCoins...)) - } -} - -// DecrementBorrowedCoins decrements the total amount of borrowed coins by the coins parameter -func (k Keeper) DecrementBorrowedCoins(ctx sdk.Context, coins sdk.Coins) error { - borrowedCoins, found := k.GetBorrowedCoins(ctx) - if !found { - return errorsmod.Wrapf(types.ErrBorrowedCoinsNotFound, "cannot repay coins if no coins are currently borrowed") - } - - updatedBorrowedCoins, isNegative := borrowedCoins.SafeSub(coins...) - if isNegative { - coinsToSubtract := sdk.NewCoins() - for _, coin := range coins { - if borrowedCoins.AmountOf(coin.Denom).LT(coin.Amount) { - if borrowedCoins.AmountOf(coin.Denom).GT(sdk.ZeroInt()) { - coinsToSubtract = coinsToSubtract.Add(sdk.NewCoin(coin.Denom, borrowedCoins.AmountOf(coin.Denom))) - } - } else { - coinsToSubtract = coinsToSubtract.Add(coin) - } - } - updatedBorrowedCoins = borrowedCoins.Sub(coinsToSubtract...) - } - - k.SetBorrowedCoins(ctx, updatedBorrowedCoins) - return nil -} - -// GetSyncedBorrow returns a borrow object containing current balances and indexes -func (k Keeper) GetSyncedBorrow(ctx sdk.Context, borrower sdk.AccAddress) (types.Borrow, bool) { - borrow, found := k.GetBorrow(ctx, borrower) - if !found { - return types.Borrow{}, false - } - - return k.loadSyncedBorrow(ctx, borrow), true -} - -// loadSyncedBorrow calculates a user's synced borrow, but does not update state -func (k Keeper) loadSyncedBorrow(ctx sdk.Context, borrow types.Borrow) types.Borrow { - totalNewInterest := sdk.Coins{} - newBorrowIndexes := types.BorrowInterestFactors{} - for _, coin := range borrow.Amount { - interestFactorValue, foundInterestFactorValue := k.GetBorrowInterestFactor(ctx, coin.Denom) - if foundInterestFactorValue { - // Locate the interest factor by coin denom in the user's list of interest factors - foundAtIndex := -1 - for i := range borrow.Index { - if borrow.Index[i].Denom == coin.Denom { - foundAtIndex = i - break - } - } - - // Calculate interest owed by user for this asset - if foundAtIndex != -1 { - storedAmount := sdk.NewDecFromInt(borrow.Amount.AmountOf(coin.Denom)) - userLastInterestFactor := borrow.Index[foundAtIndex].Value - coinInterest := (storedAmount.Quo(userLastInterestFactor).Mul(interestFactorValue)).Sub(storedAmount) - totalNewInterest = totalNewInterest.Add(sdk.NewCoin(coin.Denom, coinInterest.TruncateInt())) - } - } - - borrowIndex := types.NewBorrowInterestFactor(coin.Denom, interestFactorValue) - newBorrowIndexes = append(newBorrowIndexes, borrowIndex) - } - - return types.NewBorrow(borrow.Borrower, borrow.Amount.Add(totalNewInterest...), newBorrowIndexes) -} diff --git a/x/hard/keeper/borrow_test.go b/x/hard/keeper/borrow_test.go deleted file mode 100644 index 3d254cc2..00000000 --- a/x/hard/keeper/borrow_test.go +++ /dev/null @@ -1,564 +0,0 @@ -package keeper_test - -import ( - "strings" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/hard" - "github.com/kava-labs/kava/x/hard/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -const ( - USDX_CF = 1000000 - KAVA_CF = 1000000 - BTCB_CF = 100000000 - BNB_CF = 100000000 - BUSD_CF = 100000000 -) - -func (suite *KeeperTestSuite) TestBorrow() { - type args struct { - usdxBorrowLimit sdk.Dec - priceKAVA sdk.Dec - loanToValueKAVA sdk.Dec - priceBTCB sdk.Dec - loanToValueBTCB sdk.Dec - priceBNB sdk.Dec - loanToValueBNB sdk.Dec - borrower sdk.AccAddress - depositCoins []sdk.Coin - previousBorrowCoins sdk.Coins - borrowCoins sdk.Coins - expectedAccountBalance sdk.Coins - expectedModAccountBalance sdk.Coins - } - type errArgs struct { - expectPass bool - contains string - } - type borrowTest struct { - name string - args args - errArgs errArgs - } - testCases := []borrowTest{ - { - "valid", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("100000000000"), - priceKAVA: sdk.MustNewDecFromStr("5.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.6"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: []sdk.Coin{sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))}, - previousBorrowCoins: sdk.NewCoins(), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF)), sdk.NewCoin("btcb", sdkmath.NewInt(100*BTCB_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(100*BNB_CF)), sdk.NewCoin("xyz", sdkmath.NewInt(1))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1080*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(200*USDX_CF)), sdk.NewCoin("busd", sdkmath.NewInt(100*BUSD_CF))), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid: loan-to-value limited", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("100000000000"), - priceKAVA: sdk.MustNewDecFromStr("5.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.6"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: []sdk.Coin{sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))}, // 20 KAVA x $5.00 price = $100 - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(61*USDX_CF))), // 61 USDX x $1 price = $61 - expectedAccountBalance: sdk.NewCoins(), - expectedModAccountBalance: sdk.NewCoins(), - }, - errArgs{ - expectPass: false, - contains: "exceeds the allowable amount as determined by the collateralization ratio", - }, - }, - { - "valid: multiple deposits", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("100000000000"), - priceKAVA: sdk.MustNewDecFromStr("2.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.80"), - priceBTCB: sdk.MustNewDecFromStr("10000.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.10"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF)), sdk.NewCoin("btcb", sdkmath.NewInt(0.1*BTCB_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(180*USDX_CF))), - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF)), sdk.NewCoin("btcb", sdkmath.NewInt(99.9*BTCB_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(180*USDX_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(100*BNB_CF)), sdk.NewCoin("xyz", sdkmath.NewInt(1))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1050*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(20*USDX_CF)), sdk.NewCoin("btcb", sdkmath.NewInt(0.1*BTCB_CF)), sdk.NewCoin("busd", sdkmath.NewInt(100*BUSD_CF))), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid: multiple deposits", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("100000000000"), - priceKAVA: sdk.MustNewDecFromStr("2.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.80"), - priceBTCB: sdk.MustNewDecFromStr("10000.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.10"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF)), sdk.NewCoin("btcb", sdkmath.NewInt(0.1*BTCB_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(181*USDX_CF))), - expectedAccountBalance: sdk.NewCoins(), - expectedModAccountBalance: sdk.NewCoins(), - }, - errArgs{ - expectPass: false, - contains: "exceeds the allowable amount as determined by the collateralization ratio", - }, - }, - { - "valid: multiple previous borrows", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("100000000000"), - priceKAVA: sdk.MustNewDecFromStr("2.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.8"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("5.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.8"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(30*BNB_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), // (50 KAVA x $2.00 price = $100) + (30 BNB x $5.00 price = $150) = $250 - previousBorrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(99*USDX_CF)), sdk.NewCoin("busd", sdkmath.NewInt(100*BUSD_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(1*USDX_CF))), - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF)), sdk.NewCoin("btcb", sdkmath.NewInt(100*BTCB_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF)), sdk.NewCoin("busd", sdkmath.NewInt(100*BUSD_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(70*BNB_CF)), sdk.NewCoin("xyz", sdkmath.NewInt(1))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1050*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(30*BUSD_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF))), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid: over loan-to-value with multiple previous borrows", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("100000000000"), - priceKAVA: sdk.MustNewDecFromStr("2.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.8"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("5.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.8"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(30*BNB_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), // (50 KAVA x $2.00 price = $100) + (30 BNB x $5.00 price = $150) = $250 - previousBorrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF)), sdk.NewCoin("busd", sdkmath.NewInt(100*BUSD_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(1*USDX_CF))), - expectedAccountBalance: sdk.NewCoins(), - expectedModAccountBalance: sdk.NewCoins(), - }, - errArgs{ - expectPass: false, - contains: "exceeds the allowable amount as determined by the collateralization ratio", - }, - }, - { - "invalid: no price for asset", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("100000000000"), - priceKAVA: sdk.MustNewDecFromStr("5.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.6"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - previousBorrowCoins: sdk.NewCoins(), - borrowCoins: sdk.NewCoins(sdk.NewCoin("xyz", sdkmath.NewInt(1))), - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF)), sdk.NewCoin("btcb", sdkmath.NewInt(100*BTCB_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(100*BNB_CF)), sdk.NewCoin("xyz", sdkmath.NewInt(1))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1080*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(200*USDX_CF)), sdk.NewCoin("busd", sdkmath.NewInt(100*BUSD_CF))), - }, - errArgs{ - expectPass: false, - contains: "no price found for market", - }, - }, - { - "invalid: borrow exceed module account balance", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("100000000000"), - priceKAVA: sdk.MustNewDecFromStr("2.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.8"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - previousBorrowCoins: sdk.NewCoins(), - borrowCoins: sdk.NewCoins(sdk.NewCoin("busd", sdkmath.NewInt(101*BUSD_CF))), - expectedAccountBalance: sdk.NewCoins(), - expectedModAccountBalance: sdk.NewCoins(), - }, - errArgs{ - expectPass: false, - contains: "exceeds borrowable module account balance", - }, - }, - { - "invalid: over global asset borrow limit", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("20000000"), - priceKAVA: sdk.MustNewDecFromStr("2.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.8"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - previousBorrowCoins: sdk.NewCoins(), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(25*USDX_CF))), - expectedAccountBalance: sdk.NewCoins(), - expectedModAccountBalance: sdk.NewCoins(), - }, - errArgs{ - expectPass: false, - contains: "fails global asset borrow limit validation", - }, - }, - { - "invalid: borrowing an individual coin type results in a borrow that's under the minimum USD borrow limit", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("20000000"), - priceKAVA: sdk.MustNewDecFromStr("2.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.8"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - previousBorrowCoins: sdk.NewCoins(), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(5*USDX_CF))), - expectedAccountBalance: sdk.NewCoins(), - expectedModAccountBalance: sdk.NewCoins(), - }, - errArgs{ - expectPass: false, - contains: "below the minimum borrow limit", - }, - }, - { - "invalid: borrowing multiple coins results in a borrow that's under the minimum USD borrow limit", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("20000000"), - priceKAVA: sdk.MustNewDecFromStr("2.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.8"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - previousBorrowCoins: sdk.NewCoins(), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(5*USDX_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(2*USDX_CF))), - expectedAccountBalance: sdk.NewCoins(), - expectedModAccountBalance: sdk.NewCoins(), - }, - errArgs{ - expectPass: false, - contains: "below the minimum borrow limit", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - // Auth module genesis state - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{ - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF)), - sdk.NewCoin("btcb", sdkmath.NewInt(100*BTCB_CF)), - sdk.NewCoin("bnb", sdkmath.NewInt(100*BNB_CF)), - sdk.NewCoin("xyz", sdkmath.NewInt(1)), - ), - }, - []sdk.AccAddress{tc.args.borrower}, - ) - - // hard module genesis state - hardGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("usdx", types.NewBorrowLimit(true, tc.args.usdxBorrowLimit, sdk.MustNewDecFromStr("1")), "usdx:usd", sdkmath.NewInt(USDX_CF), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("busd", types.NewBorrowLimit(false, sdk.NewDec(100000000*BUSD_CF), sdk.MustNewDecFromStr("1")), "busd:usd", sdkmath.NewInt(BUSD_CF), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("ukava", types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), tc.args.loanToValueKAVA), "kava:usd", sdkmath.NewInt(KAVA_CF), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("btcb", types.NewBorrowLimit(false, sdk.NewDec(100000000*BTCB_CF), tc.args.loanToValueBTCB), "btcb:usd", sdkmath.NewInt(BTCB_CF), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("bnb", types.NewBorrowLimit(false, sdk.NewDec(100000000*BNB_CF), tc.args.loanToValueBNB), "bnb:usd", sdkmath.NewInt(BNB_CF), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("xyz", types.NewBorrowLimit(false, sdk.NewDec(1), tc.args.loanToValueBNB), "xyz:usd", sdkmath.NewInt(1), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - }, - sdk.NewDec(10), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "busd:usd", BaseAsset: "busd", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "btcb:usd", BaseAsset: "btcb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "xyz:usd", BaseAsset: "xyz", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "busd:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: tc.args.priceKAVA, - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "btcb:usd", - OracleAddress: sdk.AccAddress{}, - Price: tc.args.priceBTCB, - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: tc.args.priceBNB, - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - - // Initialize test application - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}) - - // Mint coins to hard module account - bankKeeper := tApp.GetBankKeeper() - hardMaccCoins := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), - sdk.NewCoin("usdx", sdkmath.NewInt(200*USDX_CF)), sdk.NewCoin("busd", sdkmath.NewInt(100*BUSD_CF))) - err := bankKeeper.MintCoins(ctx, types.ModuleAccountName, hardMaccCoins) - suite.Require().NoError(err) - - keeper := tApp.GetHardKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - - // Run BeginBlocker once to transition MoneyMarkets - hard.BeginBlocker(suite.ctx, suite.keeper) - - err = suite.keeper.Deposit(suite.ctx, tc.args.borrower, tc.args.depositCoins) - suite.Require().NoError(err) - - // Execute user's previous borrows - err = suite.keeper.Borrow(suite.ctx, tc.args.borrower, tc.args.previousBorrowCoins) - if tc.args.previousBorrowCoins.IsZero() { - suite.Require().True(strings.Contains(err.Error(), "cannot borrow zero coins")) - } else { - suite.Require().NoError(err) - } - - // Now that our state is properly set up, execute the last borrow - err = suite.keeper.Borrow(suite.ctx, tc.args.borrower, tc.args.borrowCoins) - - if tc.errArgs.expectPass { - suite.Require().NoError(err) - - // Check borrower balance - acc := suite.getAccount(tc.args.borrower) - suite.Require().Equal(tc.args.expectedAccountBalance, suite.getAccountCoins(acc)) - - // Check module account balance - mAcc := suite.getModuleAccount(types.ModuleAccountName) - suite.Require().Equal(tc.args.expectedModAccountBalance, suite.getAccountCoins(mAcc)) - - // Check that borrow struct is in store - _, f := suite.keeper.GetBorrow(suite.ctx, tc.args.borrower) - suite.Require().True(f) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *KeeperTestSuite) TestValidateBorrow() { - blockDuration := time.Second * 3600 * 24 // long blocks to accumulate larger interest - - _, addrs := app.GeneratePrivKeyAddressPairs(5) - borrower := addrs[0] - initialBorrowerBalance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), - sdk.NewCoin("usdx", sdkmath.NewInt(1000*KAVA_CF)), - ) - - model := types.NewInterestRateModel(sdk.MustNewDecFromStr("1.0"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")) - - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - // Auth module genesis state - authGS := app.NewFundedGenStateWithSameCoins( - tApp.AppCodec(), - initialBorrowerBalance, - []sdk.AccAddress{borrower}, - ) - - // Hard module genesis state - hardGS := types.NewGenesisState( - types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("usdx", - types.NewBorrowLimit(false, sdk.NewDec(100000000*USDX_CF), sdk.MustNewDecFromStr("1")), // Borrow Limit - "usdx:usd", // Market ID - sdkmath.NewInt(USDX_CF), // Conversion Factor - model, // Interest Rate Model - sdk.MustNewDecFromStr("1.0"), // Reserve Factor (high) - sdk.MustNewDecFromStr("0.05")), // Keeper Reward Percent - types.NewMoneyMarket("ukava", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "kava:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - sdk.MustNewDecFromStr("1.0"), // Reserve Factor (high) - sdk.MustNewDecFromStr("0.05")), // Keeper Reward Percent - }, - sdk.NewDec(10), - ), - types.DefaultAccumulationTimes, - types.DefaultDeposits, - types.DefaultBorrows, - types.DefaultTotalSupplied, - types.DefaultTotalBorrowed, - types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - - // Initialize test application - tApp.InitializeFromGenesisStates( - authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}, - ) - - keeper := tApp.GetHardKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - - var err error - - // Run BeginBlocker once to transition MoneyMarkets - hard.BeginBlocker(suite.ctx, suite.keeper) - - // Setup borrower with some collateral to borrow against, and some reserve in the protocol. - depositCoins := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF)), - sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF)), - ) - err = suite.keeper.Deposit(suite.ctx, borrower, depositCoins) - suite.Require().NoError(err) - - initialBorrowCoins := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(70*KAVA_CF))) - err = suite.keeper.Borrow(suite.ctx, borrower, initialBorrowCoins) - suite.Require().NoError(err) - - runAtTime := suite.ctx.BlockTime().Add(blockDuration) - suite.ctx = suite.ctx.WithBlockTime(runAtTime) - hard.BeginBlocker(suite.ctx, suite.keeper) - - repayCoins := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))) // repay everything including accumulated interest - err = suite.keeper.Repay(suite.ctx, borrower, borrower, repayCoins) - suite.Require().NoError(err) - - // Get the total borrowable amount from the protocol, taking into account the reserves. - modAccBalance := suite.getAccountCoins(suite.getModuleAccountAtCtx(types.ModuleAccountName, suite.ctx)) - reserves, found := suite.keeper.GetTotalReserves(suite.ctx) - suite.Require().True(found) - availableToBorrow := modAccBalance.Sub(reserves...) - - // Test borrowing one over the available amount (try to borrow from the reserves) - err = suite.keeper.Borrow( - suite.ctx, - borrower, - sdk.NewCoins(sdk.NewCoin("ukava", availableToBorrow.AmountOf("ukava").Add(sdk.OneInt()))), - ) - suite.Require().Error(err) - - // Test borrowing exactly the limit - err = suite.keeper.Borrow( - suite.ctx, - borrower, - sdk.NewCoins(sdk.NewCoin("ukava", availableToBorrow.AmountOf("ukava"))), - ) - suite.Require().NoError(err) -} diff --git a/x/hard/keeper/deposit.go b/x/hard/keeper/deposit.go deleted file mode 100644 index e4cd5315..00000000 --- a/x/hard/keeper/deposit.go +++ /dev/null @@ -1,203 +0,0 @@ -package keeper - -import ( - "errors" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/kava-labs/kava/x/hard/types" -) - -// Deposit deposit -func (k Keeper) Deposit(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error { - // Set any new denoms' global supply index to 1.0 - for _, coin := range coins { - _, foundInterestFactor := k.GetSupplyInterestFactor(ctx, coin.Denom) - if !foundInterestFactor { - _, foundMm := k.GetMoneyMarket(ctx, coin.Denom) - if foundMm { - k.SetSupplyInterestFactor(ctx, coin.Denom, sdk.OneDec()) - } - } - } - - // Call incentive hook - existingDeposit, hasExistingDeposit := k.GetDeposit(ctx, depositor) - if hasExistingDeposit { - k.BeforeDepositModified(ctx, existingDeposit) - } - - // Sync any outstanding interest - k.SyncSupplyInterest(ctx, depositor) - - err := k.ValidateDeposit(ctx, coins) - if err != nil { - return err - } - - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, depositor, types.ModuleAccountName, coins) - if err != nil { - if errors.Is(err, sdkerrors.ErrInsufficientFunds) { - acc := k.accountKeeper.GetAccount(ctx, depositor) - accCoins := k.bankKeeper.SpendableCoins(ctx, acc.GetAddress()) - for _, coin := range coins { - _, isNegative := accCoins.SafeSub(coin) - if isNegative { - return errorsmod.Wrapf(types.ErrBorrowExceedsAvailableBalance, - "insufficient funds: the requested deposit amount of %s exceeds the total available account funds of %s%s", - coin, accCoins.AmountOf(coin.Denom), coin.Denom, - ) - } - } - } - } - if err != nil { - return err - } - - interestFactors := types.SupplyInterestFactors{} - currDeposit, foundDeposit := k.GetDeposit(ctx, depositor) - if foundDeposit { - interestFactors = currDeposit.Index - } - for _, coin := range coins { - interestFactorValue, foundValue := k.GetSupplyInterestFactor(ctx, coin.Denom) - if foundValue { - interestFactors = interestFactors.SetInterestFactor(coin.Denom, interestFactorValue) - } - } - - // Calculate new deposit amount - var amount sdk.Coins - if foundDeposit { - amount = currDeposit.Amount.Add(coins...) - } else { - amount = coins - } - // Update the depositer's amount and supply interest factors in the store - deposit := types.NewDeposit(depositor, amount, interestFactors) - - if deposit.Amount.Empty() { - k.DeleteDeposit(ctx, deposit) - } else { - k.SetDeposit(ctx, deposit) - } - - k.IncrementSuppliedCoins(ctx, coins) - if !foundDeposit { // User's first deposit - k.AfterDepositCreated(ctx, deposit) - } else { - k.AfterDepositModified(ctx, deposit) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeHardDeposit, - sdk.NewAttribute(sdk.AttributeKeyAmount, coins.String()), - sdk.NewAttribute(types.AttributeKeyDepositor, deposit.Depositor.String()), - ), - ) - - return nil -} - -// ValidateDeposit validates a deposit -func (k Keeper) ValidateDeposit(ctx sdk.Context, coins sdk.Coins) error { - for _, depCoin := range coins { - _, foundMm := k.GetMoneyMarket(ctx, depCoin.Denom) - if !foundMm { - return errorsmod.Wrapf(types.ErrInvalidDepositDenom, "money market denom %s not found", depCoin.Denom) - } - } - - return nil -} - -// GetTotalDeposited returns the total amount deposited for the input deposit type and deposit denom -func (k Keeper) GetTotalDeposited(ctx sdk.Context, depositDenom string) (total sdkmath.Int) { - macc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - return k.bankKeeper.GetBalance(ctx, macc.GetAddress(), depositDenom).Amount -} - -// IncrementSuppliedCoins increments the total amount of supplied coins by the newCoins parameter -func (k Keeper) IncrementSuppliedCoins(ctx sdk.Context, newCoins sdk.Coins) { - suppliedCoins, found := k.GetSuppliedCoins(ctx) - if !found { - if !newCoins.Empty() { - k.SetSuppliedCoins(ctx, newCoins) - } - } else { - k.SetSuppliedCoins(ctx, suppliedCoins.Add(newCoins...)) - } -} - -// DecrementSuppliedCoins decrements the total amount of supplied coins by the coins parameter -func (k Keeper) DecrementSuppliedCoins(ctx sdk.Context, coins sdk.Coins) error { - suppliedCoins, found := k.GetSuppliedCoins(ctx) - if !found { - return errorsmod.Wrapf(types.ErrSuppliedCoinsNotFound, "cannot withdraw if no coins are deposited") - } - - updatedSuppliedCoins, isNegative := suppliedCoins.SafeSub(coins...) - if isNegative { - coinsToSubtract := sdk.NewCoins() - for _, coin := range coins { - if suppliedCoins.AmountOf(coin.Denom).LT(coin.Amount) { - if suppliedCoins.AmountOf(coin.Denom).GT(sdk.ZeroInt()) { - coinsToSubtract = coinsToSubtract.Add(sdk.NewCoin(coin.Denom, suppliedCoins.AmountOf(coin.Denom))) - } - } else { - coinsToSubtract = coinsToSubtract.Add(coin) - } - } - updatedSuppliedCoins = suppliedCoins.Sub(coinsToSubtract...) - } - - k.SetSuppliedCoins(ctx, updatedSuppliedCoins) - return nil -} - -// GetSyncedDeposit returns a deposit object containing current balances and indexes -func (k Keeper) GetSyncedDeposit(ctx sdk.Context, depositor sdk.AccAddress) (types.Deposit, bool) { - deposit, found := k.GetDeposit(ctx, depositor) - if !found { - return types.Deposit{}, false - } - - return k.loadSyncedDeposit(ctx, deposit), true -} - -// loadSyncedDeposit calculates a user's synced deposit, but does not update state -func (k Keeper) loadSyncedDeposit(ctx sdk.Context, deposit types.Deposit) types.Deposit { - totalNewInterest := sdk.Coins{} - newSupplyIndexes := types.SupplyInterestFactors{} - for _, coin := range deposit.Amount { - interestFactorValue, foundInterestFactorValue := k.GetSupplyInterestFactor(ctx, coin.Denom) - if foundInterestFactorValue { - // Locate the interest factor by coin denom in the user's list of interest factors - foundAtIndex := -1 - for i := range deposit.Index { - if deposit.Index[i].Denom == coin.Denom { - foundAtIndex = i - break - } - } - - // Calculate interest that will be paid to user for this asset - if foundAtIndex != -1 { - storedAmount := sdk.NewDecFromInt(deposit.Amount.AmountOf(coin.Denom)) - userLastInterestFactor := deposit.Index[foundAtIndex].Value - coinInterest := (storedAmount.Quo(userLastInterestFactor).Mul(interestFactorValue)).Sub(storedAmount) - totalNewInterest = totalNewInterest.Add(sdk.NewCoin(coin.Denom, coinInterest.TruncateInt())) - } - } - - supplyIndex := types.NewSupplyInterestFactor(coin.Denom, interestFactorValue) - newSupplyIndexes = append(newSupplyIndexes, supplyIndex) - } - - return types.NewDeposit(deposit.Depositor, deposit.Amount.Add(totalNewInterest...), newSupplyIndexes) -} diff --git a/x/hard/keeper/deposit_test.go b/x/hard/keeper/deposit_test.go deleted file mode 100644 index 8eb7cdf1..00000000 --- a/x/hard/keeper/deposit_test.go +++ /dev/null @@ -1,344 +0,0 @@ -package keeper_test - -import ( - "strings" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/hard" - "github.com/kava-labs/kava/x/hard/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -func (suite *KeeperTestSuite) TestDeposit() { - type args struct { - depositor sdk.AccAddress - amount sdk.Coins - numberDeposits int - expectedAccountBalance sdk.Coins - expectedModAccountBalance sdk.Coins - expectedDepositCoins sdk.Coins - } - type errArgs struct { - expectPass bool - contains string - } - type depositTest struct { - name string - args args - errArgs errArgs - } - testCases := []depositTest{ - { - "valid", - args{ - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - numberDeposits: 1, - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(900)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - expectedDepositCoins: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid multi deposit", - args{ - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - numberDeposits: 2, - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(800)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - expectedDepositCoins: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid deposit denom", - args{ - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - amount: sdk.NewCoins(sdk.NewCoin("fake", sdkmath.NewInt(100))), - numberDeposits: 1, - expectedAccountBalance: sdk.Coins{}, - expectedModAccountBalance: sdk.Coins{}, - expectedDepositCoins: sdk.Coins{}, - }, - errArgs{ - expectPass: false, - contains: "invalid deposit denom", - }, - }, - { - "insufficient funds", - args{ - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10000))), - numberDeposits: 1, - expectedAccountBalance: sdk.Coins{}, - expectedModAccountBalance: sdk.Coins{}, - expectedDepositCoins: sdk.Coins{}, - }, - errArgs{ - expectPass: false, - contains: "insufficient funds: the requested deposit amount", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // create new app with one funded account - - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{ - sdk.NewCoins( - sdk.NewCoin("bnb", sdkmath.NewInt(1000)), - sdk.NewCoin("btcb", sdkmath.NewInt(1000)), - ), - }, - []sdk.AccAddress{tc.args.depositor}, - ) - loanToValue, _ := sdk.NewDecFromStr("0.6") - hardGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("usdx", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "usdx:usd", sdkmath.NewInt(1000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("ukava", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "kava:usd", sdkmath.NewInt(1000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("bnb", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "bnb:usd", sdkmath.NewInt(1000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("btcb", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "btcb:usd", sdkmath.NewInt(1000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - }, - sdk.NewDec(10), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "btcb:usd", BaseAsset: "btcb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "btcb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("100.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("10.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}, - ) - keeper := tApp.GetHardKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - - // Run BeginBlocker once to transition MoneyMarkets - hard.BeginBlocker(suite.ctx, suite.keeper) - - // run the test - var err error - for i := 0; i < tc.args.numberDeposits; i++ { - err = suite.keeper.Deposit(suite.ctx, tc.args.depositor, tc.args.amount) - } - - // verify results - if tc.errArgs.expectPass { - suite.Require().NoError(err) - acc := suite.getAccount(tc.args.depositor) - suite.Require().Equal(tc.args.expectedAccountBalance, suite.getAccountCoins(acc)) - mAcc := suite.getModuleAccount(types.ModuleAccountName) - suite.Require().Equal(tc.args.expectedModAccountBalance, suite.getAccountCoins(mAcc)) - dep, f := suite.keeper.GetDeposit(suite.ctx, tc.args.depositor) - suite.Require().True(f) - suite.Require().Equal(tc.args.expectedDepositCoins, dep.Amount) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *KeeperTestSuite) TestDecrementSuppliedCoins() { - type args struct { - suppliedInitial sdk.Coins - decrementCoins sdk.Coins - expectedSuppliedFinal sdk.Coins - } - type errArgs struct { - expectPass bool - contains string - } - type decrementTest struct { - name string - args args - errArgs errArgs - } - testCases := []decrementTest{ - { - "valid", - args{ - suppliedInitial: cs(c("bnb", 10000000000000), c("busd", 3000000000000), c("xrpb", 2500000000000)), - decrementCoins: cs(c("bnb", 5000000000000)), - expectedSuppliedFinal: cs(c("bnb", 5000000000000), c("busd", 3000000000000), c("xrpb", 2500000000000)), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid-negative", - args{ - suppliedInitial: cs(c("bnb", 10000000000000), c("busd", 3000000000000), c("xrpb", 2500000000000)), - decrementCoins: cs(c("bnb", 10000000000001)), - expectedSuppliedFinal: cs(c("busd", 3000000000000), c("xrpb", 2500000000000)), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid-multiple negative", - args{ - suppliedInitial: cs(c("bnb", 10000000000000), c("busd", 3000000000000), c("xrpb", 2500000000000)), - decrementCoins: cs(c("bnb", 10000000000001), c("busd", 5000000000000)), - expectedSuppliedFinal: cs(c("xrpb", 2500000000000)), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid-absent coin denom", - args{ - suppliedInitial: cs(c("bnb", 10000000000000), c("xrpb", 2500000000000)), - decrementCoins: cs(c("busd", 5)), - expectedSuppliedFinal: cs(c("bnb", 10000000000000), c("xrpb", 2500000000000)), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - loanToValue, _ := sdk.NewDecFromStr("0.6") - depositor := sdk.AccAddress(crypto.AddressHash([]byte("test"))) - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{tc.args.suppliedInitial}, - []sdk.AccAddress{depositor}, - ) - hardGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("bnb", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "bnb:usd", sdkmath.NewInt(100000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("busd", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "busd:usd", sdkmath.NewInt(100000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("xrpb", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "xrpb:usd", sdkmath.NewInt(100000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - }, - sdk.MustNewDecFromStr("10"), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "xrpb:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "busd:usd", BaseAsset: "btcb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "busd:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "xrpb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("200.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}, - ) - keeper := tApp.GetHardKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - - // Run BeginBlocker once to transition MoneyMarkets - hard.BeginBlocker(suite.ctx, suite.keeper) - - err := suite.keeper.Deposit(suite.ctx, depositor, tc.args.suppliedInitial) - suite.Require().NoError(err) - err = suite.keeper.DecrementSuppliedCoins(ctx, tc.args.decrementCoins) - suite.Require().NoError(err) - totalSuppliedActual, found := suite.keeper.GetSuppliedCoins(suite.ctx) - suite.Require().True(found) - suite.Require().Equal(totalSuppliedActual, tc.args.expectedSuppliedFinal) - }) - } -} - -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } diff --git a/x/hard/keeper/grpc_query.go b/x/hard/keeper/grpc_query.go deleted file mode 100644 index 85b6b6d0..00000000 --- a/x/hard/keeper/grpc_query.go +++ /dev/null @@ -1,546 +0,0 @@ -package keeper - -import ( - "context" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/types/query" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/kava-labs/kava/x/hard/types" -) - -type queryServer struct { - keeper Keeper - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(keeper Keeper, ak types.AccountKeeper, bk types.BankKeeper) types.QueryServer { - return &queryServer{ - keeper: keeper, - accountKeeper: ak, - bankKeeper: bk, - } -} - -var _ types.QueryServer = queryServer{} - -func (s queryServer) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - // Get params - params := s.keeper.GetParams(sdkCtx) - - return &types.QueryParamsResponse{ - Params: params, - }, nil -} - -func (s queryServer) Accounts(ctx context.Context, req *types.QueryAccountsRequest) (*types.QueryAccountsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - macc := s.accountKeeper.GetModuleAccount(sdkCtx, types.ModuleAccountName) - - accounts := []authtypes.ModuleAccount{ - *macc.(*authtypes.ModuleAccount), - } - - return &types.QueryAccountsResponse{ - Accounts: accounts, - }, nil -} - -func (s queryServer) Deposits(ctx context.Context, req *types.QueryDepositsRequest) (*types.QueryDepositsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - hasDenom := len(req.Denom) > 0 - hasOwner := len(req.Owner) > 0 - - var owner sdk.AccAddress - var err error - if hasOwner { - owner, err = sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - } - - var deposits types.Deposits - switch { - case hasOwner && hasDenom: - deposit, found := s.keeper.GetSyncedDeposit(sdkCtx, owner) - if found { - for _, coin := range deposit.Amount { - if coin.Denom == req.Denom { - deposits = append(deposits, deposit) - } - } - } - case hasOwner: - deposit, found := s.keeper.GetSyncedDeposit(sdkCtx, owner) - if found { - deposits = append(deposits, deposit) - } - case hasDenom: - s.keeper.IterateDeposits(sdkCtx, func(deposit types.Deposit) (stop bool) { - if deposit.Amount.AmountOf(req.Denom).IsPositive() { - deposits = append(deposits, deposit) - } - return false - }) - default: - s.keeper.IterateDeposits(sdkCtx, func(deposit types.Deposit) (stop bool) { - deposits = append(deposits, deposit) - return false - }) - } - - // If owner param was specified then deposits array already contains the user's synced deposit - if hasOwner { - return &types.QueryDepositsResponse{ - Deposits: deposits.ToResponse(), - Pagination: nil, - }, nil - } - - // Otherwise we need to simulate syncing of each deposit - var syncedDeposits types.Deposits - for _, deposit := range deposits { - syncedDeposit, _ := s.keeper.GetSyncedDeposit(sdkCtx, deposit.Depositor) - syncedDeposits = append(syncedDeposits, syncedDeposit) - } - - // TODO: Use more optimal FilteredPaginate to directly iterate over the store - // and not fetch everything. This currently also ignores certain fields in - // the pagination request like Key, CountTotal, Reverse. - page, limit, err := query.ParsePagination(req.Pagination) - if err != nil { - return nil, err - } - - start, end := client.Paginate(len(syncedDeposits), page, limit, 100) - if start < 0 || end < 0 { - syncedDeposits = types.Deposits{} - } else { - syncedDeposits = syncedDeposits[start:end] - } - - return &types.QueryDepositsResponse{ - Deposits: syncedDeposits.ToResponse(), - Pagination: nil, - }, nil -} - -func (s queryServer) UnsyncedDeposits(ctx context.Context, req *types.QueryUnsyncedDepositsRequest) (*types.QueryUnsyncedDepositsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - hasDenom := len(req.Denom) > 0 - hasOwner := len(req.Owner) > 0 - - var owner sdk.AccAddress - var err error - if hasOwner { - owner, err = sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - } - - var deposits types.Deposits - switch { - case hasOwner && hasDenom: - deposit, found := s.keeper.GetDeposit(sdkCtx, owner) - if found { - for _, coin := range deposit.Amount { - if coin.Denom == req.Denom { - deposits = append(deposits, deposit) - } - } - } - case hasOwner: - deposit, found := s.keeper.GetDeposit(sdkCtx, owner) - if found { - deposits = append(deposits, deposit) - } - case hasDenom: - s.keeper.IterateDeposits(sdkCtx, func(deposit types.Deposit) (stop bool) { - if deposit.Amount.AmountOf(req.Denom).IsPositive() { - deposits = append(deposits, deposit) - } - return false - }) - default: - s.keeper.IterateDeposits(sdkCtx, func(deposit types.Deposit) (stop bool) { - deposits = append(deposits, deposit) - return false - }) - } - - page, limit, err := query.ParsePagination(req.Pagination) - if err != nil { - return nil, err - } - - start, end := client.Paginate(len(deposits), page, limit, 100) - if start < 0 || end < 0 { - deposits = types.Deposits{} - } else { - deposits = deposits[start:end] - } - - return &types.QueryUnsyncedDepositsResponse{ - Deposits: deposits.ToResponse(), - Pagination: nil, - }, nil -} - -func (s queryServer) Borrows(ctx context.Context, req *types.QueryBorrowsRequest) (*types.QueryBorrowsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - hasDenom := len(req.Denom) > 0 - hasOwner := len(req.Owner) > 0 - - var owner sdk.AccAddress - var err error - if hasOwner { - owner, err = sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - } - - var borrows types.Borrows - switch { - case hasOwner && hasDenom: - borrow, found := s.keeper.GetSyncedBorrow(sdkCtx, owner) - if found { - for _, coin := range borrow.Amount { - if coin.Denom == req.Denom { - borrows = append(borrows, borrow) - } - } - } - case hasOwner: - borrow, found := s.keeper.GetSyncedBorrow(sdkCtx, owner) - if found { - borrows = append(borrows, borrow) - } - case hasDenom: - s.keeper.IterateBorrows(sdkCtx, func(borrow types.Borrow) (stop bool) { - if borrow.Amount.AmountOf(req.Denom).IsPositive() { - borrows = append(borrows, borrow) - } - return false - }) - default: - s.keeper.IterateBorrows(sdkCtx, func(borrow types.Borrow) (stop bool) { - borrows = append(borrows, borrow) - return false - }) - } - - // If owner param was specified then borrows array already contains the user's synced borrow - if hasOwner { - return &types.QueryBorrowsResponse{ - Borrows: borrows.ToResponse(), - Pagination: nil, - }, nil - } - - // Otherwise we need to simulate syncing of each borrow - var syncedBorrows types.Borrows - for _, borrow := range borrows { - syncedBorrow, _ := s.keeper.GetSyncedBorrow(sdkCtx, borrow.Borrower) - syncedBorrows = append(syncedBorrows, syncedBorrow) - } - - page, limit, err := query.ParsePagination(req.Pagination) - if err != nil { - return nil, err - } - - start, end := client.Paginate(len(syncedBorrows), page, limit, 100) - if start < 0 || end < 0 { - syncedBorrows = types.Borrows{} - } else { - syncedBorrows = syncedBorrows[start:end] - } - - return &types.QueryBorrowsResponse{ - Borrows: syncedBorrows.ToResponse(), - }, nil -} - -func (s queryServer) UnsyncedBorrows(ctx context.Context, req *types.QueryUnsyncedBorrowsRequest) (*types.QueryUnsyncedBorrowsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - hasDenom := len(req.Denom) > 0 - hasOwner := len(req.Owner) > 0 - - var owner sdk.AccAddress - var err error - if hasOwner { - owner, err = sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - } - - var borrows types.Borrows - switch { - case hasOwner && hasDenom: - borrow, found := s.keeper.GetBorrow(sdkCtx, owner) - if found { - for _, coin := range borrow.Amount { - if coin.Denom == req.Denom { - borrows = append(borrows, borrow) - } - } - } - case hasOwner: - borrow, found := s.keeper.GetBorrow(sdkCtx, owner) - if found { - borrows = append(borrows, borrow) - } - case hasDenom: - s.keeper.IterateBorrows(sdkCtx, func(borrow types.Borrow) (stop bool) { - if borrow.Amount.AmountOf(req.Denom).IsPositive() { - borrows = append(borrows, borrow) - } - return false - }) - default: - s.keeper.IterateBorrows(sdkCtx, func(borrow types.Borrow) (stop bool) { - borrows = append(borrows, borrow) - return false - }) - } - - page, limit, err := query.ParsePagination(req.Pagination) - if err != nil { - return nil, err - } - - start, end := client.Paginate(len(borrows), page, limit, 100) - if start < 0 || end < 0 { - borrows = types.Borrows{} - } else { - borrows = borrows[start:end] - } - - return &types.QueryUnsyncedBorrowsResponse{ - Borrows: borrows.ToResponse(), - Pagination: nil, - }, nil -} - -func (s queryServer) TotalBorrowed(ctx context.Context, req *types.QueryTotalBorrowedRequest) (*types.QueryTotalBorrowedResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - borrowedCoins, found := s.keeper.GetBorrowedCoins(sdkCtx) - if !found { - // Use empty coins instead of returning an error - borrowedCoins = sdk.NewCoins() - } - - // If user specified a denom only return coins of that denom type - if len(req.Denom) > 0 { - borrowedCoins = sdk.NewCoins(sdk.NewCoin(req.Denom, borrowedCoins.AmountOf(req.Denom))) - } - - return &types.QueryTotalBorrowedResponse{ - BorrowedCoins: borrowedCoins, - }, nil -} - -func (s queryServer) TotalDeposited(ctx context.Context, req *types.QueryTotalDepositedRequest) (*types.QueryTotalDepositedResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - suppliedCoins, found := s.keeper.GetSuppliedCoins(sdkCtx) - if !found { - // Use empty coins instead of returning an error - suppliedCoins = sdk.NewCoins() - } - - // If user specified a denom only return coins of that denom type - if len(req.Denom) > 0 { - suppliedCoins = sdk.NewCoins(sdk.NewCoin(req.Denom, suppliedCoins.AmountOf(req.Denom))) - } - - return &types.QueryTotalDepositedResponse{ - SuppliedCoins: suppliedCoins, - }, nil -} - -func (s queryServer) InterestRate(ctx context.Context, req *types.QueryInterestRateRequest) (*types.QueryInterestRateResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - var moneyMarketInterestRates types.MoneyMarketInterestRates - var moneyMarkets types.MoneyMarkets - if len(req.Denom) > 0 { - moneyMarket, found := s.keeper.GetMoneyMarket(sdkCtx, req.Denom) - if !found { - return nil, types.ErrMoneyMarketNotFound - } - moneyMarkets = append(moneyMarkets, moneyMarket) - } else { - moneyMarkets = s.keeper.GetAllMoneyMarkets(sdkCtx) - } - - // Calculate the borrow and supply APY interest rates for each money market - for _, moneyMarket := range moneyMarkets { - denom := moneyMarket.Denom - macc := s.accountKeeper.GetModuleAccount(sdkCtx, types.ModuleName) - cash := s.bankKeeper.GetBalance(sdkCtx, macc.GetAddress(), denom).Amount - - borrowed := sdk.NewCoin(denom, sdk.ZeroInt()) - borrowedCoins, foundBorrowedCoins := s.keeper.GetBorrowedCoins(sdkCtx) - if foundBorrowedCoins { - borrowed = sdk.NewCoin(denom, borrowedCoins.AmountOf(denom)) - } - - reserves, foundReserves := s.keeper.GetTotalReserves(sdkCtx) - if !foundReserves { - reserves = sdk.NewCoins() - } - - // CalculateBorrowRate calculates the current interest rate based on utilization (the fraction of supply that has ien borrowed) - borrowAPY, err := CalculateBorrowRate(moneyMarket.InterestRateModel, sdk.NewDecFromInt(cash), sdk.NewDecFromInt(borrowed.Amount), sdk.NewDecFromInt(reserves.AmountOf(denom))) - if err != nil { - return nil, err - } - - utilRatio := CalculateUtilizationRatio(sdk.NewDecFromInt(cash), sdk.NewDecFromInt(borrowed.Amount), sdk.NewDecFromInt(reserves.AmountOf(denom))) - fullSupplyAPY := borrowAPY.Mul(utilRatio) - realSupplyAPY := fullSupplyAPY.Mul(sdk.OneDec().Sub(moneyMarket.ReserveFactor)) - - moneyMarketInterestRate := types.MoneyMarketInterestRate{ - Denom: denom, - SupplyInterestRate: realSupplyAPY.String(), - BorrowInterestRate: borrowAPY.String(), - } - - moneyMarketInterestRates = append(moneyMarketInterestRates, moneyMarketInterestRate) - } - - return &types.QueryInterestRateResponse{ - InterestRates: moneyMarketInterestRates, - }, nil -} - -func (s queryServer) Reserves(ctx context.Context, req *types.QueryReservesRequest) (*types.QueryReservesResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - reserveCoins, found := s.keeper.GetTotalReserves(sdkCtx) - if !found { - reserveCoins = sdk.Coins{} - } - - // If user specified a denom only return coins of that denom type - if len(req.Denom) > 0 { - reserveCoins = sdk.NewCoins(sdk.NewCoin(req.Denom, reserveCoins.AmountOf(req.Denom))) - } - - return &types.QueryReservesResponse{ - Amount: reserveCoins, - }, nil -} - -func (s queryServer) InterestFactors(ctx context.Context, req *types.QueryInterestFactorsRequest) (*types.QueryInterestFactorsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - var interestFactors types.InterestFactors - if len(req.Denom) > 0 { - // Fetch supply/borrow interest factors for a single denom - interestFactor := types.InterestFactor{} - interestFactor.Denom = req.Denom - supplyInterestFactor, found := s.keeper.GetSupplyInterestFactor(sdkCtx, req.Denom) - if found { - interestFactor.SupplyInterestFactor = supplyInterestFactor.String() - } - borrowInterestFactor, found := s.keeper.GetBorrowInterestFactor(sdkCtx, req.Denom) - if found { - interestFactor.BorrowInterestFactor = borrowInterestFactor.String() - } - interestFactors = append(interestFactors, interestFactor) - } else { - interestFactorMap := make(map[string]types.InterestFactor) - // Populate mapping with supply interest factors - s.keeper.IterateSupplyInterestFactors(sdkCtx, func(denom string, factor sdk.Dec) (stop bool) { - interestFactor := types.InterestFactor{Denom: denom, SupplyInterestFactor: factor.String()} - interestFactorMap[denom] = interestFactor - return false - }) - // Populate mapping with borrow interest factors - s.keeper.IterateBorrowInterestFactors(sdkCtx, func(denom string, factor sdk.Dec) (stop bool) { - interestFactor, ok := interestFactorMap[denom] - if !ok { - newInterestFactor := types.InterestFactor{Denom: denom, BorrowInterestFactor: factor.String()} - interestFactorMap[denom] = newInterestFactor - } else { - interestFactor.BorrowInterestFactor = factor.String() - interestFactorMap[denom] = interestFactor - } - return false - }) - // Translate mapping to slice - for _, val := range interestFactorMap { - interestFactors = append(interestFactors, val) - } - } - - return &types.QueryInterestFactorsResponse{ - InterestFactors: interestFactors, - }, nil -} diff --git a/x/hard/keeper/grpc_query_test.go b/x/hard/keeper/grpc_query_test.go deleted file mode 100644 index 0f3e48ba..00000000 --- a/x/hard/keeper/grpc_query_test.go +++ /dev/null @@ -1,530 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/hard/keeper" - "github.com/kava-labs/kava/x/hard/types" - "github.com/stretchr/testify/suite" -) - -type grpcQueryTestSuite struct { - suite.Suite - - tApp app.TestApp - ctx sdk.Context - keeper keeper.Keeper - queryServer types.QueryServer - addrs []sdk.AccAddress -} - -func (suite *grpcQueryTestSuite) SetupTest() { - suite.tApp = app.NewTestApp() - _, addrs := app.GeneratePrivKeyAddressPairs(2) - - suite.addrs = addrs - - suite.ctx = suite.tApp.NewContext(true, tmprototypes.Header{}). - WithBlockTime(time.Now().UTC()) - suite.keeper = suite.tApp.GetHardKeeper() - suite.queryServer = keeper.NewQueryServerImpl(suite.keeper, suite.tApp.GetAccountKeeper(), suite.tApp.GetBankKeeper()) - - err := suite.tApp.FundModuleAccount( - suite.ctx, - types.ModuleAccountName, - cs( - c("usdx", 10000000000), - c("busd", 10000000000), - ), - ) - suite.Require().NoError(err) - - suite.tApp.InitializeFromGenesisStates( - NewPricefeedGenStateMulti(suite.tApp.AppCodec()), - NewHARDGenState(suite.tApp.AppCodec()), - app.NewFundedGenStateWithSameCoins( - suite.tApp.AppCodec(), - cs( - c("bnb", 10000000000), - c("busd", 20000000000), - ), - addrs, - ), - ) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryParams() { - res, err := suite.queryServer.Params(sdk.WrapSDKContext(suite.ctx), &types.QueryParamsRequest{}) - suite.Require().NoError(err) - - var expected types.GenesisState - defaultHARDState := NewHARDGenState(suite.tApp.AppCodec()) - suite.tApp.AppCodec().MustUnmarshalJSON(defaultHARDState[types.ModuleName], &expected) - - suite.Equal(expected.Params, res.Params, "params should equal test genesis state") -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryAccounts() { - res, err := suite.queryServer.Accounts(sdk.WrapSDKContext(suite.ctx), &types.QueryAccountsRequest{}) - suite.Require().NoError(err) - - ak := suite.tApp.GetAccountKeeper() - acc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - - suite.Len(res.Accounts, 1) - suite.Equal(acc, &res.Accounts[0], "accounts should include module account") -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryDeposits_EmptyResponse() { - res, err := suite.queryServer.Deposits(sdk.WrapSDKContext(suite.ctx), &types.QueryDepositsRequest{}) - suite.Require().NoError(err) - suite.Require().Empty(res) -} - -func (suite *grpcQueryTestSuite) addDeposits() { - deposits := []struct { - Address sdk.AccAddress - Coins sdk.Coins - }{ - { - suite.addrs[0], - cs(c("bnb", 100000000)), - }, - { - suite.addrs[1], - cs(c("bnb", 20000000)), - }, - { - suite.addrs[0], - cs(c("busd", 20000000)), - }, - { - suite.addrs[0], - cs(c("busd", 8000000)), - }, - } - - for _, dep := range deposits { - suite.NotPanics(func() { - err := suite.keeper.Deposit(suite.ctx, dep.Address, dep.Coins) - suite.Require().NoError(err) - }) - } -} - -func (suite *grpcQueryTestSuite) addBorrows() { - borrows := []struct { - Address sdk.AccAddress - Coins sdk.Coins - }{ - { - suite.addrs[0], - cs(c("usdx", 10000000)), - }, - { - suite.addrs[1], - cs(c("usdx", 20000000)), - }, - { - suite.addrs[0], - cs(c("usdx", 40000000)), - }, - { - suite.addrs[0], - cs(c("busd", 80000000)), - }, - } - - for _, dep := range borrows { - suite.NotPanics(func() { - err := suite.keeper.Borrow(suite.ctx, dep.Address, dep.Coins) - suite.Require().NoErrorf(err, "borrow %s should not error", dep.Coins) - }) - } -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryDeposits() { - suite.addDeposits() - - tests := []struct { - giveName string - giveRequest *types.QueryDepositsRequest - wantDepositCounts int - shouldError bool - errorSubstr string - }{ - { - "empty query", - &types.QueryDepositsRequest{}, - 2, - false, - "", - }, - { - "owner", - &types.QueryDepositsRequest{ - Owner: suite.addrs[0].String(), - }, - // Excludes the second address - 1, - false, - "", - }, - { - "invalid owner", - &types.QueryDepositsRequest{ - Owner: "invalid address", - }, - // No deposits - 0, - true, - "decoding bech32 failed", - }, - { - "owner and denom", - &types.QueryDepositsRequest{ - Owner: suite.addrs[0].String(), - Denom: "bnb", - }, - // Only the first one - 1, - false, - "", - }, - { - "owner and invalid denom empty response", - &types.QueryDepositsRequest{ - Owner: suite.addrs[0].String(), - Denom: "invalid denom", - }, - 0, - false, - "", - }, - { - "denom", - &types.QueryDepositsRequest{ - Denom: "bnb", - }, - 2, - false, - "", - }, - } - - for _, tt := range tests { - suite.Run(tt.giveName, func() { - res, err := suite.queryServer.Deposits(sdk.WrapSDKContext(suite.ctx), tt.giveRequest) - - if tt.shouldError { - suite.Error(err) - suite.Contains(err.Error(), tt.errorSubstr) - } else { - suite.NoError(err) - suite.Equal(tt.wantDepositCounts, len(res.Deposits)) - } - }) - - // Unsynced deposits should be the same - suite.Run(tt.giveName+"_unsynced", func() { - res, err := suite.queryServer.UnsyncedDeposits(sdk.WrapSDKContext(suite.ctx), &types.QueryUnsyncedDepositsRequest{ - Denom: tt.giveRequest.Denom, - Owner: tt.giveRequest.Owner, - Pagination: tt.giveRequest.Pagination, - }) - - if tt.shouldError { - suite.Error(err) - suite.Contains(err.Error(), tt.errorSubstr) - } else { - suite.NoError(err) - suite.Equal(tt.wantDepositCounts, len(res.Deposits)) - } - }) - } -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryBorrows() { - suite.addDeposits() - suite.addBorrows() - - tests := []struct { - giveName string - giveRequest *types.QueryBorrowsRequest - wantDepositCounts int - shouldError bool - errorSubstr string - }{ - { - "empty query", - &types.QueryBorrowsRequest{}, - 2, - false, - "", - }, - { - "owner", - &types.QueryBorrowsRequest{ - Owner: suite.addrs[0].String(), - }, - // Excludes the second address - 1, - false, - "", - }, - { - "invalid owner", - &types.QueryBorrowsRequest{ - Owner: "invalid address", - }, - // No deposits - 0, - true, - "decoding bech32 failed", - }, - { - "owner and denom", - &types.QueryBorrowsRequest{ - Owner: suite.addrs[0].String(), - Denom: "usdx", - }, - // Only the first one - 1, - false, - "", - }, - { - "owner and invalid denom empty response", - &types.QueryBorrowsRequest{ - Owner: suite.addrs[0].String(), - Denom: "invalid denom", - }, - 0, - false, - "", - }, - { - "denom", - &types.QueryBorrowsRequest{ - Denom: "usdx", - }, - 2, - false, - "", - }, - } - - for _, tt := range tests { - suite.Run(tt.giveName, func() { - res, err := suite.queryServer.Borrows(sdk.WrapSDKContext(suite.ctx), tt.giveRequest) - - if tt.shouldError { - suite.Error(err) - suite.Contains(err.Error(), tt.errorSubstr) - } else { - suite.NoError(err) - suite.Equal(tt.wantDepositCounts, len(res.Borrows)) - } - }) - - // Unsynced deposits should be the same - suite.Run(tt.giveName+"_unsynced", func() { - res, err := suite.queryServer.UnsyncedBorrows(sdk.WrapSDKContext(suite.ctx), &types.QueryUnsyncedBorrowsRequest{ - Denom: tt.giveRequest.Denom, - Owner: tt.giveRequest.Owner, - Pagination: tt.giveRequest.Pagination, - }) - - if tt.shouldError { - suite.Error(err) - suite.Contains(err.Error(), tt.errorSubstr) - } else { - suite.NoError(err) - suite.Equal(tt.wantDepositCounts, len(res.Borrows)) - } - }) - } -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalDeposited() { - suite.addDeposits() - - totalDeposited, err := suite.queryServer.TotalDeposited(sdk.WrapSDKContext(suite.ctx), &types.QueryTotalDepositedRequest{}) - suite.Require().NoError(err) - - suite.Equal(&types.QueryTotalDepositedResponse{ - SuppliedCoins: cs( - c("bnb", 100000000+20000000), - c("busd", 20000000+8000000), - ), - }, totalDeposited) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalDeposited_Empty() { - totalDeposited, err := suite.queryServer.TotalDeposited(sdk.WrapSDKContext(suite.ctx), &types.QueryTotalDepositedRequest{}) - suite.Require().NoError(err) - - suite.Equal(&types.QueryTotalDepositedResponse{ - SuppliedCoins: cs(), - }, totalDeposited) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalDeposited_Denom_Empty() { - totalDeposited, err := suite.queryServer.TotalDeposited(sdk.WrapSDKContext(suite.ctx), &types.QueryTotalDepositedRequest{ - Denom: "bnb", - }) - suite.Require().NoError(err) - - suite.Equal(&types.QueryTotalDepositedResponse{ - SuppliedCoins: cs(), - }, totalDeposited) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalDeposited_Denom() { - suite.addDeposits() - - totalDeposited, err := suite.queryServer.TotalDeposited(sdk.WrapSDKContext(suite.ctx), &types.QueryTotalDepositedRequest{ - Denom: "bnb", - }) - suite.Require().NoError(err) - - suite.Equal(&types.QueryTotalDepositedResponse{ - SuppliedCoins: cs( - c("bnb", 100000000+20000000), - ), - }, totalDeposited) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalBorrowed() { - suite.addDeposits() - suite.addBorrows() - - totalDeposited, err := suite.queryServer.TotalBorrowed(sdk.WrapSDKContext(suite.ctx), &types.QueryTotalBorrowedRequest{}) - suite.Require().NoError(err) - - suite.Equal(&types.QueryTotalBorrowedResponse{ - BorrowedCoins: cs( - c("usdx", 10000000+20000000+40000000), - c("busd", 80000000), - ), - }, totalDeposited) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalBorrowed_denom() { - suite.addDeposits() - suite.addBorrows() - - totalDeposited, err := suite.queryServer.TotalBorrowed(sdk.WrapSDKContext(suite.ctx), &types.QueryTotalBorrowedRequest{ - Denom: "usdx", - }) - suite.Require().NoError(err) - - suite.Equal(&types.QueryTotalBorrowedResponse{ - BorrowedCoins: cs( - c("usdx", 10000000+20000000+40000000), - ), - }, totalDeposited) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryInterestRate() { - tests := []struct { - giveName string - giveDenom string - wantInterestRates types.MoneyMarketInterestRates - shouldError bool - }{ - { - "no denom", - "", - types.MoneyMarketInterestRates{ - { - Denom: "usdx", - SupplyInterestRate: "0.000000000000000000", - BorrowInterestRate: "0.050000000000000000", - }, - { - Denom: "bnb", - SupplyInterestRate: "0.000000000000000000", - BorrowInterestRate: "0.000000000000000000", - }, - { - Denom: "busd", - SupplyInterestRate: "0.000000000000000000", - BorrowInterestRate: "0.000000000000000000", - }, - }, - false, - }, - { - "denom", - "usdx", - types.MoneyMarketInterestRates{ - { - Denom: "usdx", - SupplyInterestRate: "0.000000000000000000", - BorrowInterestRate: "0.050000000000000000", - }, - }, - false, - }, - { - "invalid denom", - "bun", - types.MoneyMarketInterestRates{}, - true, - }, - } - - for _, tt := range tests { - suite.Run(tt.giveName, func() { - res, err := suite.queryServer.InterestRate(sdk.WrapSDKContext(suite.ctx), &types.QueryInterestRateRequest{ - Denom: tt.giveDenom, - }) - - if tt.shouldError { - suite.Require().Error(err) - } else { - suite.Require().NoError(err) - - suite.ElementsMatch(tt.wantInterestRates, res.InterestRates) - } - }) - } -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryInterestFactors() { - res, err := suite.queryServer.InterestFactors(sdk.WrapSDKContext(suite.ctx), &types.QueryInterestFactorsRequest{ - Denom: "usdx", - }) - suite.Require().NoError(err) - - suite.Equal(&types.QueryInterestFactorsResponse{ - InterestFactors: types.InterestFactors{ - { - Denom: "usdx", - BorrowInterestFactor: "1.000000000000000000", - SupplyInterestFactor: "1.000000000000000000", - }, - }, - }, res) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryReserves() { - suite.addDeposits() - suite.addBorrows() - - res, err := suite.queryServer.Reserves(sdk.WrapSDKContext(suite.ctx), &types.QueryReservesRequest{}) - suite.Require().NoError(err) - - suite.Equal(&types.QueryReservesResponse{ - Amount: sdk.Coins{}, - }, res) -} - -func TestGrpcQueryTestSuite(t *testing.T) { - suite.Run(t, new(grpcQueryTestSuite)) -} diff --git a/x/hard/keeper/hooks.go b/x/hard/keeper/hooks.go deleted file mode 100644 index 829ee2e6..00000000 --- a/x/hard/keeper/hooks.go +++ /dev/null @@ -1,52 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/hard/types" -) - -// Implements StakingHooks interface -var _ types.HARDHooks = Keeper{} - -// AfterDepositCreated - call hook if registered -func (k Keeper) AfterDepositCreated(ctx sdk.Context, deposit types.Deposit) { - if k.hooks != nil { - k.hooks.AfterDepositCreated(ctx, deposit) - } -} - -// BeforeDepositModified - call hook if registered -func (k Keeper) BeforeDepositModified(ctx sdk.Context, deposit types.Deposit) { - if k.hooks != nil { - k.hooks.BeforeDepositModified(ctx, deposit) - } -} - -// AfterDepositModified - call hook if registered -func (k Keeper) AfterDepositModified(ctx sdk.Context, deposit types.Deposit) { - if k.hooks != nil { - k.hooks.AfterDepositModified(ctx, deposit) - } -} - -// AfterBorrowCreated - call hook if registered -func (k Keeper) AfterBorrowCreated(ctx sdk.Context, borrow types.Borrow) { - if k.hooks != nil { - k.hooks.AfterBorrowCreated(ctx, borrow) - } -} - -// BeforeBorrowModified - call hook if registered -func (k Keeper) BeforeBorrowModified(ctx sdk.Context, borrow types.Borrow) { - if k.hooks != nil { - k.hooks.BeforeBorrowModified(ctx, borrow) - } -} - -// AfterBorrowModified - call hook if registered -func (k Keeper) AfterBorrowModified(ctx sdk.Context, borrow types.Borrow) { - if k.hooks != nil { - k.hooks.AfterBorrowModified(ctx, borrow) - } -} diff --git a/x/hard/keeper/integration_test.go b/x/hard/keeper/integration_test.go deleted file mode 100644 index b4fcaef8..00000000 --- a/x/hard/keeper/integration_test.go +++ /dev/null @@ -1,125 +0,0 @@ -package keeper_test - -import ( - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/hard/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -func NewHARDGenState(cdc codec.JSONCodec) app.GenesisState { - hardGenesis := types.GenesisState{ - Params: types.NewParams( - types.MoneyMarkets{ - types.MoneyMarket{ - Denom: "usdx", - BorrowLimit: types.BorrowLimit{ - HasMaxLimit: true, - MaximumLimit: sdk.MustNewDecFromStr("100000000000"), - LoanToValue: sdk.MustNewDecFromStr("1"), - }, - SpotMarketID: "usdx:usd", - ConversionFactor: sdkmath.NewInt(USDX_CF), - InterestRateModel: types.InterestRateModel{ - BaseRateAPY: sdk.MustNewDecFromStr("0.05"), - BaseMultiplier: sdk.MustNewDecFromStr("2"), - Kink: sdk.MustNewDecFromStr("0.8"), - JumpMultiplier: sdk.MustNewDecFromStr("10"), - }, - ReserveFactor: sdk.MustNewDecFromStr("0.05"), - KeeperRewardPercentage: sdk.ZeroDec(), - }, - types.MoneyMarket{ - Denom: "bnb", - BorrowLimit: types.BorrowLimit{ - HasMaxLimit: true, - MaximumLimit: sdk.MustNewDecFromStr("3000000000000"), - LoanToValue: sdk.MustNewDecFromStr("0.5"), - }, - SpotMarketID: "bnb:usd", - ConversionFactor: sdkmath.NewInt(USDX_CF), - InterestRateModel: types.InterestRateModel{ - BaseRateAPY: sdk.MustNewDecFromStr("0"), - BaseMultiplier: sdk.MustNewDecFromStr("0.05"), - Kink: sdk.MustNewDecFromStr("0.8"), - JumpMultiplier: sdk.MustNewDecFromStr("5.0"), - }, - ReserveFactor: sdk.MustNewDecFromStr("0.025"), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.02"), - }, - types.MoneyMarket{ - Denom: "busd", - BorrowLimit: types.BorrowLimit{ - HasMaxLimit: true, - MaximumLimit: sdk.MustNewDecFromStr("1000000000000000"), - LoanToValue: sdk.MustNewDecFromStr("0.5"), - }, - SpotMarketID: "busd:usd", - ConversionFactor: sdkmath.NewInt(100000000), - InterestRateModel: types.InterestRateModel{ - BaseRateAPY: sdk.MustNewDecFromStr("0"), - BaseMultiplier: sdk.MustNewDecFromStr("0.5"), - Kink: sdk.MustNewDecFromStr("0.8"), - JumpMultiplier: sdk.MustNewDecFromStr("5"), - }, - ReserveFactor: sdk.MustNewDecFromStr("0.025"), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.02"), - }, - }, - sdk.MustNewDecFromStr("10"), - ), - PreviousAccumulationTimes: types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime( - "usdx", - time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - sdk.OneDec(), - sdk.OneDec(), - ), - }, - Deposits: types.DefaultDeposits, - Borrows: types.DefaultBorrows, - TotalSupplied: sdk.NewCoins(), - TotalBorrowed: sdk.NewCoins(), - TotalReserves: sdk.NewCoins(), - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&hardGenesis)} -} - -func NewPricefeedGenStateMulti(cdc codec.JSONCodec) app.GenesisState { - pfGenesis := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "xrp:usd", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "busd:usd", BaseAsset: "busd", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.OneDec(), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("618.13"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "busd:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.OneDec(), - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - return app.GenesisState{pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pfGenesis)} -} diff --git a/x/hard/keeper/interest.go b/x/hard/keeper/interest.go deleted file mode 100644 index e07d2862..00000000 --- a/x/hard/keeper/interest.go +++ /dev/null @@ -1,317 +0,0 @@ -package keeper - -import ( - "math" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/hard/types" -) - -var ( - scalingFactor = 1e18 - secondsPerYear = 31536000 -) - -// ApplyInterestRateUpdates translates the current interest rate models from the params to the store, -// with each money market accruing interest. -func (k Keeper) ApplyInterestRateUpdates(ctx sdk.Context) { - denomSet := map[string]bool{} - - params := k.GetParams(ctx) - for _, mm := range params.MoneyMarkets { - // Set any new money markets in the store - moneyMarket, found := k.GetMoneyMarket(ctx, mm.Denom) - if !found { - moneyMarket = mm - k.SetMoneyMarket(ctx, mm.Denom, moneyMarket) - } - - // Accrue interest according to the current money markets in the store - err := k.AccrueInterest(ctx, mm.Denom) - if err != nil { - panic(err) - } - - // Update the interest rate in the store if the params have changed - if !moneyMarket.Equal(mm) { - k.SetMoneyMarket(ctx, mm.Denom, mm) - } - denomSet[mm.Denom] = true - } - - // Edge case: money markets removed from params that still exist in the store - k.IterateMoneyMarkets(ctx, func(denom string, i types.MoneyMarket) bool { - if !denomSet[denom] { - // Accrue interest according to current store money market - err := k.AccrueInterest(ctx, denom) - if err != nil { - panic(err) - } - - // Delete the money market from the store - k.DeleteMoneyMarket(ctx, denom) - } - return false - }) -} - -// AccrueInterest applies accrued interest to total borrows and reserves by calculating -// interest from the last checkpoint time and writing the updated values to the store. -func (k Keeper) AccrueInterest(ctx sdk.Context, denom string) error { - previousAccrualTime, found := k.GetPreviousAccrualTime(ctx, denom) - if !found { - k.SetPreviousAccrualTime(ctx, denom, ctx.BlockTime()) - return nil - } - - timeElapsed := int64(math.RoundToEven( - ctx.BlockTime().Sub(previousAccrualTime).Seconds(), - )) - if timeElapsed == 0 { - return nil - } - - // Get current protocol state and hold in memory as 'prior' - macc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - cashPrior := k.bankKeeper.GetBalance(ctx, macc.GetAddress(), denom).Amount - - borrowedPrior := sdk.NewCoin(denom, sdk.ZeroInt()) - borrowedCoinsPrior, foundBorrowedCoinsPrior := k.GetBorrowedCoins(ctx) - if foundBorrowedCoinsPrior { - borrowedPrior = sdk.NewCoin(denom, borrowedCoinsPrior.AmountOf(denom)) - } - if borrowedPrior.IsZero() { - k.SetPreviousAccrualTime(ctx, denom, ctx.BlockTime()) - return nil - } - - reservesPrior, foundReservesPrior := k.GetTotalReserves(ctx) - if !foundReservesPrior { - newReservesPrior := sdk.NewCoins() - k.SetTotalReserves(ctx, newReservesPrior) - reservesPrior = newReservesPrior - } - - borrowInterestFactorPrior, foundBorrowInterestFactorPrior := k.GetBorrowInterestFactor(ctx, denom) - if !foundBorrowInterestFactorPrior { - newBorrowInterestFactorPrior := sdk.MustNewDecFromStr("1.0") - k.SetBorrowInterestFactor(ctx, denom, newBorrowInterestFactorPrior) - borrowInterestFactorPrior = newBorrowInterestFactorPrior - } - - supplyInterestFactorPrior, foundSupplyInterestFactorPrior := k.GetSupplyInterestFactor(ctx, denom) - if !foundSupplyInterestFactorPrior { - newSupplyInterestFactorPrior := sdk.MustNewDecFromStr("1.0") - k.SetSupplyInterestFactor(ctx, denom, newSupplyInterestFactorPrior) - supplyInterestFactorPrior = newSupplyInterestFactorPrior - } - - // Fetch money market from the store - mm, found := k.GetMoneyMarket(ctx, denom) - if !found { - return errorsmod.Wrapf(types.ErrMoneyMarketNotFound, "%s", denom) - } - - // GetBorrowRate calculates the current interest rate based on utilization (the fraction of supply that has been borrowed) - borrowRateApy, err := CalculateBorrowRate(mm.InterestRateModel, sdk.NewDecFromInt(cashPrior), sdk.NewDecFromInt(borrowedPrior.Amount), sdk.NewDecFromInt(reservesPrior.AmountOf(denom))) - if err != nil { - return err - } - - // Convert from APY to SPY, expressed as (1 + borrow rate) - borrowRateSpy, err := APYToSPY(sdk.OneDec().Add(borrowRateApy)) - if err != nil { - return err - } - - // Calculate borrow interest factor and update - borrowInterestFactor := CalculateBorrowInterestFactor(borrowRateSpy, sdkmath.NewInt(timeElapsed)) - interestBorrowAccumulated := (borrowInterestFactor.Mul(sdk.NewDecFromInt(borrowedPrior.Amount)).TruncateInt()).Sub(borrowedPrior.Amount) - - if interestBorrowAccumulated.IsZero() && borrowRateApy.IsPositive() { - // don't accumulate if borrow interest is rounding to zero - return nil - } - - totalBorrowInterestAccumulated := sdk.NewCoins(sdk.NewCoin(denom, interestBorrowAccumulated)) - reservesNew := sdk.NewDecFromInt(interestBorrowAccumulated).Mul(mm.ReserveFactor).TruncateInt() - borrowInterestFactorNew := borrowInterestFactorPrior.Mul(borrowInterestFactor) - k.SetBorrowInterestFactor(ctx, denom, borrowInterestFactorNew) - - // Calculate supply interest factor and update - supplyInterestNew := interestBorrowAccumulated.Sub(reservesNew) - supplyInterestFactor := CalculateSupplyInterestFactor(sdk.NewDecFromInt(supplyInterestNew), sdk.NewDecFromInt(cashPrior), sdk.NewDecFromInt(borrowedPrior.Amount), sdk.NewDecFromInt(reservesPrior.AmountOf(denom))) - supplyInterestFactorNew := supplyInterestFactorPrior.Mul(supplyInterestFactor) - k.SetSupplyInterestFactor(ctx, denom, supplyInterestFactorNew) - - // Update accural keys in store - k.IncrementBorrowedCoins(ctx, totalBorrowInterestAccumulated) - k.IncrementSuppliedCoins(ctx, sdk.NewCoins(sdk.NewCoin(denom, supplyInterestNew))) - k.SetTotalReserves(ctx, reservesPrior.Add(sdk.NewCoin(denom, reservesNew))) - k.SetPreviousAccrualTime(ctx, denom, ctx.BlockTime()) - - return nil -} - -// CalculateBorrowRate calculates the borrow rate, which is the current APY expressed as a decimal -// based on the current utilization. -func CalculateBorrowRate(model types.InterestRateModel, cash, borrows, reserves sdk.Dec) (sdk.Dec, error) { - utilRatio := CalculateUtilizationRatio(cash, borrows, reserves) - - // Calculate normal borrow rate (under kink) - if utilRatio.LTE(model.Kink) { - return utilRatio.Mul(model.BaseMultiplier).Add(model.BaseRateAPY), nil - } - - // Calculate jump borrow rate (over kink) - normalRate := model.Kink.Mul(model.BaseMultiplier).Add(model.BaseRateAPY) - excessUtil := utilRatio.Sub(model.Kink) - return excessUtil.Mul(model.JumpMultiplier).Add(normalRate), nil -} - -// CalculateUtilizationRatio calculates an asset's current utilization rate -func CalculateUtilizationRatio(cash, borrows, reserves sdk.Dec) sdk.Dec { - // Utilization rate is 0 when there are no borrows - if borrows.Equal(sdk.ZeroDec()) { - return sdk.ZeroDec() - } - - totalSupply := cash.Add(borrows).Sub(reserves) - if totalSupply.IsNegative() { - return sdk.OneDec() - } - - return sdk.MinDec(sdk.OneDec(), borrows.Quo(totalSupply)) -} - -// CalculateBorrowInterestFactor calculates the simple interest scaling factor, -// which is equal to: (per-second interest rate * number of seconds elapsed) -// Will return 1.000x, multiply by principal to get new principal with added interest -func CalculateBorrowInterestFactor(perSecondInterestRate sdk.Dec, secondsElapsed sdkmath.Int) sdk.Dec { - scalingFactorUint := sdk.NewUint(uint64(scalingFactor)) - scalingFactorInt := sdkmath.NewInt(int64(scalingFactor)) - - // Convert per-second interest rate to a uint scaled by 1e18 - interestMantissa := sdkmath.NewUintFromBigInt(perSecondInterestRate.MulInt(scalingFactorInt).RoundInt().BigInt()) - // Convert seconds elapsed to uint (*not scaled*) - secondsElapsedUint := sdkmath.NewUintFromBigInt(secondsElapsed.BigInt()) - // Calculate the interest factor as a uint scaled by 1e18 - interestFactorMantissa := sdkmath.RelativePow(interestMantissa, secondsElapsedUint, scalingFactorUint) - - // Convert interest factor to an unscaled sdk.Dec - return sdk.NewDecFromBigInt(interestFactorMantissa.BigInt()).QuoInt(scalingFactorInt) -} - -// CalculateSupplyInterestFactor calculates the supply interest factor, which is the percentage of borrow interest -// that flows to each unit of supply, i.e. at 50% utilization and 0% reserve factor, a 5% borrow interest will -// correspond to a 2.5% supply interest. -func CalculateSupplyInterestFactor(newInterest, cash, borrows, reserves sdk.Dec) sdk.Dec { - totalSupply := cash.Add(borrows).Sub(reserves) - if totalSupply.IsZero() { - return sdk.OneDec() - } - return (newInterest.Quo(totalSupply)).Add(sdk.OneDec()) -} - -// SyncBorrowInterest updates the user's owed interest on newly borrowed coins to the latest global state -func (k Keeper) SyncBorrowInterest(ctx sdk.Context, addr sdk.AccAddress) { - totalNewInterest := sdk.Coins{} - - // Update user's borrow interest factor list for each asset in the 'coins' array. - // We use a list of BorrowInterestFactors here because Amino doesn't support marshaling maps. - borrow, found := k.GetBorrow(ctx, addr) - if !found { - return - } - for _, coin := range borrow.Amount { - // Locate the borrow interest factor item by coin denom in the user's list of borrow indexes - foundAtIndex := -1 - for i := range borrow.Index { - if borrow.Index[i].Denom == coin.Denom { - foundAtIndex = i - break - } - } - - interestFactorValue, _ := k.GetBorrowInterestFactor(ctx, coin.Denom) - if foundAtIndex == -1 { // First time user has borrowed this denom - borrow.Index = append(borrow.Index, types.NewBorrowInterestFactor(coin.Denom, interestFactorValue)) - } else { // User has an existing borrow index for this denom - // Calculate interest owed by user since asset's last borrow index update - storedAmount := sdk.NewDecFromInt(borrow.Amount.AmountOf(coin.Denom)) - userLastInterestFactor := borrow.Index[foundAtIndex].Value - interest := (storedAmount.Quo(userLastInterestFactor).Mul(interestFactorValue)).Sub(storedAmount) - totalNewInterest = totalNewInterest.Add(sdk.NewCoin(coin.Denom, interest.TruncateInt())) - // We're synced up, so update user's borrow index value to match the current global borrow index value - borrow.Index[foundAtIndex].Value = interestFactorValue - } - } - // Add all pending interest to user's borrow - borrow.Amount = borrow.Amount.Add(totalNewInterest...) - - // Update user's borrow in the store - k.SetBorrow(ctx, borrow) -} - -// SyncSupplyInterest updates the user's earned interest on supplied coins based on the latest global state -func (k Keeper) SyncSupplyInterest(ctx sdk.Context, addr sdk.AccAddress) { - totalNewInterest := sdk.Coins{} - - // Update user's supply index list for each asset in the 'coins' array. - // We use a list of SupplyInterestFactors here because Amino doesn't support marshaling maps. - deposit, found := k.GetDeposit(ctx, addr) - if !found { - return - } - - for _, coin := range deposit.Amount { - // Locate the deposit index item by coin denom in the user's list of deposit indexes - foundAtIndex := -1 - for i := range deposit.Index { - if deposit.Index[i].Denom == coin.Denom { - foundAtIndex = i - break - } - } - - interestFactorValue, _ := k.GetSupplyInterestFactor(ctx, coin.Denom) - if foundAtIndex == -1 { // First time user has supplied this denom - deposit.Index = append(deposit.Index, types.NewSupplyInterestFactor(coin.Denom, interestFactorValue)) - } else { // User has an existing supply index for this denom - // Calculate interest earned by user since asset's last deposit index update - storedAmount := sdk.NewDecFromInt(deposit.Amount.AmountOf(coin.Denom)) - userLastInterestFactor := deposit.Index[foundAtIndex].Value - interest := (storedAmount.Mul(interestFactorValue).Quo(userLastInterestFactor)).Sub(storedAmount) - if interest.TruncateInt().GT(sdk.ZeroInt()) { - totalNewInterest = totalNewInterest.Add(sdk.NewCoin(coin.Denom, interest.TruncateInt())) - } - // We're synced up, so update user's deposit index value to match the current global deposit index value - deposit.Index[foundAtIndex].Value = interestFactorValue - } - } - // Add all pending interest to user's deposit - deposit.Amount = deposit.Amount.Add(totalNewInterest...) - - // Update user's deposit in the store - k.SetDeposit(ctx, deposit) -} - -// APYToSPY converts the input annual interest rate. For example, 10% apy would be passed as 1.10. -// SPY = Per second compounded interest rate is how cosmos mathematically represents APY. -func APYToSPY(apy sdk.Dec) (sdk.Dec, error) { - // Note: any APY 179 or greater will cause an out-of-bounds error - root, err := apy.ApproxRoot(uint64(secondsPerYear)) - if err != nil { - return sdk.ZeroDec(), err - } - return root, nil -} - -// SPYToEstimatedAPY converts the internal per second compounded interest rate into an estimated annual -// interest rate. The returned value is an estimate and should not be used for financial calculations. -func SPYToEstimatedAPY(apy sdk.Dec) sdk.Dec { - return apy.Power(uint64(secondsPerYear)) -} diff --git a/x/hard/keeper/interest_test.go b/x/hard/keeper/interest_test.go deleted file mode 100644 index 753e75db..00000000 --- a/x/hard/keeper/interest_test.go +++ /dev/null @@ -1,1440 +0,0 @@ -package keeper_test - -import ( - "strconv" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/hard" - "github.com/kava-labs/kava/x/hard/keeper" - "github.com/kava-labs/kava/x/hard/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -type InterestTestSuite struct { - suite.Suite -} - -func (suite *InterestTestSuite) TestCalculateUtilizationRatio() { - type args struct { - cash sdk.Dec - borrows sdk.Dec - reserves sdk.Dec - expectedValue sdk.Dec - } - - type test struct { - name string - args args - } - - testCases := []test{ - { - "normal", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("5000"), - reserves: sdk.MustNewDecFromStr("100"), - expectedValue: sdk.MustNewDecFromStr("0.847457627118644068"), - }, - }, - { - "high util ratio", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("250000"), - reserves: sdk.MustNewDecFromStr("100"), - expectedValue: sdk.MustNewDecFromStr("0.996412913511359107"), - }, - }, - { - "very high util ratio", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("250000000000"), - reserves: sdk.MustNewDecFromStr("100"), - expectedValue: sdk.MustNewDecFromStr("0.999999996400000013"), - }, - }, - { - "low util ratio", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("50"), - reserves: sdk.MustNewDecFromStr("100"), - expectedValue: sdk.MustNewDecFromStr("0.052631578947368421"), - }, - }, - { - "very low util ratio", - args{ - cash: sdk.MustNewDecFromStr("10000000"), - borrows: sdk.MustNewDecFromStr("50"), - reserves: sdk.MustNewDecFromStr("100"), - expectedValue: sdk.MustNewDecFromStr("0.000005000025000125"), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - utilRatio := keeper.CalculateUtilizationRatio(tc.args.cash, tc.args.borrows, tc.args.reserves) - suite.Require().Equal(tc.args.expectedValue, utilRatio) - }) - } -} - -func (suite *InterestTestSuite) TestCalculateBorrowRate() { - type args struct { - cash sdk.Dec - borrows sdk.Dec - reserves sdk.Dec - model types.InterestRateModel - expectedValue sdk.Dec - } - - type test struct { - name string - args args - } - - // Normal model has: - // - BaseRateAPY: 0.0 - // - BaseMultiplier: 0.1 - // - Kink: 0.8 - // - JumpMultiplier: 0.5 - normalModel := types.NewInterestRateModel(sdk.MustNewDecFromStr("0"), sdk.MustNewDecFromStr("0.1"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("0.5")) - - testCases := []test{ - { - "normal no jump", - args{ - cash: sdk.MustNewDecFromStr("5000"), - borrows: sdk.MustNewDecFromStr("1000"), - reserves: sdk.MustNewDecFromStr("1000"), - model: normalModel, - expectedValue: sdk.MustNewDecFromStr("0.020000000000000000"), - }, - }, - { - "normal with jump", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("5000"), - reserves: sdk.MustNewDecFromStr("100"), - model: normalModel, - expectedValue: sdk.MustNewDecFromStr("0.103728813559322034"), - }, - }, - { - "high cash", - args{ - cash: sdk.MustNewDecFromStr("10000000"), - borrows: sdk.MustNewDecFromStr("5000"), - reserves: sdk.MustNewDecFromStr("100"), - model: normalModel, - expectedValue: sdk.MustNewDecFromStr("0.000049975511999120"), - }, - }, - { - "high borrows", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("5000000000000"), - reserves: sdk.MustNewDecFromStr("100"), - model: normalModel, - expectedValue: sdk.MustNewDecFromStr("0.179999999910000000"), - }, - }, - { - "high reserves", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("5000"), - reserves: sdk.MustNewDecFromStr("1000000000000"), - model: normalModel, - expectedValue: sdk.MustNewDecFromStr("0.180000000000000000"), - }, - }, - { - "random numbers", - args{ - cash: sdk.MustNewDecFromStr("125"), - borrows: sdk.MustNewDecFromStr("11"), - reserves: sdk.MustNewDecFromStr("82"), - model: normalModel, - expectedValue: sdk.MustNewDecFromStr("0.020370370370370370"), - }, - }, - { - "increased base multiplier", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("5000"), - reserves: sdk.MustNewDecFromStr("100"), - model: types.NewInterestRateModel(sdk.MustNewDecFromStr("0"), sdk.MustNewDecFromStr("0.5"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("1.0")), - expectedValue: sdk.MustNewDecFromStr("0.447457627118644068"), - }, - }, - { - "decreased kink", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("5000"), - reserves: sdk.MustNewDecFromStr("100"), - model: types.NewInterestRateModel(sdk.MustNewDecFromStr("0"), sdk.MustNewDecFromStr("0.5"), sdk.MustNewDecFromStr("0.1"), sdk.MustNewDecFromStr("1.0")), - expectedValue: sdk.MustNewDecFromStr("0.797457627118644068"), - }, - }, - { - "zero model returns zero", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("5000"), - reserves: sdk.MustNewDecFromStr("100"), - model: types.NewInterestRateModel( - sdk.MustNewDecFromStr("0.0"), - sdk.MustNewDecFromStr("0.0"), - sdk.MustNewDecFromStr("0.8"), - sdk.MustNewDecFromStr("0.0"), - ), - expectedValue: sdk.MustNewDecFromStr("0.0"), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - borrowRate, err := keeper.CalculateBorrowRate(tc.args.model, tc.args.cash, tc.args.borrows, tc.args.reserves) - suite.Require().NoError(err) - suite.Require().Equal(tc.args.expectedValue, borrowRate) - }) - } -} - -func (suite *InterestTestSuite) TestCalculateBorrowInterestFactor() { - type args struct { - perSecondInterestRate sdk.Dec - timeElapsed sdkmath.Int - expectedValue sdk.Dec - } - - type test struct { - name string - args args - } - - oneYearInSeconds := int64(31536000) - - testCases := []test{ - { - "1 year", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("1.191463614477847370"), - }, - }, - { - "10 year", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds * 10), - expectedValue: sdk.MustNewDecFromStr("5.765113233897391189"), - }, - }, - { - "1 month", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds / 12), - expectedValue: sdk.MustNewDecFromStr("1.014705619075717373"), - }, - }, - { - "1 day", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds / 365), - expectedValue: sdk.MustNewDecFromStr("1.000480067194057924"), - }, - }, - { - "1 year: low interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000000555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("1.017656545925063632"), - }, - }, - { - "1 year, lower interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000000055"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("1.001735985079841390"), - }, - }, - { - "1 year, lowest interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000000005"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("1.000157692432076670"), - }, - }, - { - "1 year: high interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000055555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("5.766022095987868825"), - }, - }, - { - "1 year: higher interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000555555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("40628388.864535408465693310"), - }, - }, - { - "1 year: highest interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000001555555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("2017093013158200407564.613502861572552603"), - }, - }, - { - "largest per second interest rate with practical elapsed time", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("18.445"), // Begins to panic at ~18.45 (1845%/second interest rate) - timeElapsed: sdkmath.NewInt(30), // Assume a 30 second period, longer than any expected individual block - expectedValue: sdk.MustNewDecFromStr("94702138679846565921082258202543002089.215969366091911769"), - }, - }, - { - "supports calculated values greater than 1.84x10^19", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("18.5"), // Old uint64 conversion would panic at ~18.45 (1845%/second interest rate) - timeElapsed: sdkmath.NewInt(30), // Assume a 30 second period, longer than any expected individual block - expectedValue: sdk.MustNewDecFromStr("103550416986452240450480615551792302106.072205164469778538"), - }, - }, - { - "largest per second interest rate before sdk.Uint overflows 256 bytes", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("23.3"), // 23.4 overflows bit length 256 by 1 byte - timeElapsed: sdkmath.NewInt(30), // Assume a 30 second period, longer than any expected individual block - expectedValue: sdk.MustNewDecFromStr("104876366068119517411103023062013348034546.437155815200037999"), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - interestFactor := keeper.CalculateBorrowInterestFactor(tc.args.perSecondInterestRate, tc.args.timeElapsed) - suite.Require().Equal(tc.args.expectedValue, interestFactor) - }) - } -} - -func (suite *InterestTestSuite) TestCalculateSupplyInterestFactor() { - type args struct { - newInterest sdk.Dec - cash sdk.Dec - borrows sdk.Dec - reserves sdk.Dec - reserveFactor sdk.Dec - expectedValue sdk.Dec - } - - type test struct { - name string - args args - } - - testCases := []test{ - { - "low new interest", - args{ - newInterest: sdk.MustNewDecFromStr("1"), - cash: sdk.MustNewDecFromStr("100.0"), - borrows: sdk.MustNewDecFromStr("1000.0"), - reserves: sdk.MustNewDecFromStr("10.0"), - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedValue: sdk.MustNewDecFromStr("1.000917431192660550"), - }, - }, - { - "medium new interest", - args{ - newInterest: sdk.MustNewDecFromStr("5"), - cash: sdk.MustNewDecFromStr("100.0"), - borrows: sdk.MustNewDecFromStr("1000.0"), - reserves: sdk.MustNewDecFromStr("10.0"), - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedValue: sdk.MustNewDecFromStr("1.004587155963302752"), - }, - }, - { - "high new interest", - args{ - newInterest: sdk.MustNewDecFromStr("10"), - cash: sdk.MustNewDecFromStr("100.0"), - borrows: sdk.MustNewDecFromStr("1000.0"), - reserves: sdk.MustNewDecFromStr("10.0"), - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedValue: sdk.MustNewDecFromStr("1.009174311926605505"), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - interestFactor := keeper.CalculateSupplyInterestFactor(tc.args.newInterest, - tc.args.cash, tc.args.borrows, tc.args.reserves) - suite.Require().Equal(tc.args.expectedValue, interestFactor) - }) - } -} - -func (suite *InterestTestSuite) TestAPYToSPY() { - type args struct { - apy sdk.Dec - expectedValue sdk.Dec - } - - type test struct { - name string - args args - expectError bool - } - - testCases := []test{ - { - "lowest apy", - args{ - apy: sdk.MustNewDecFromStr("0.005"), - expectedValue: sdk.MustNewDecFromStr("0.999999831991472557"), - }, - false, - }, - { - "lower apy", - args{ - apy: sdk.MustNewDecFromStr("0.05"), - expectedValue: sdk.MustNewDecFromStr("0.999999905005957279"), - }, - false, - }, - { - "medium-low apy", - args{ - apy: sdk.MustNewDecFromStr("0.5"), - expectedValue: sdk.MustNewDecFromStr("0.999999978020447332"), - }, - false, - }, - { - "5% apy", - args{ - apy: sdk.MustNewDecFromStr("1.05"), - expectedValue: sdk.MustNewDecFromStr("1.000000001547125958"), - }, - false, - }, - { - "25% apy", - args{ - apy: sdk.MustNewDecFromStr("1.25"), - expectedValue: sdk.MustNewDecFromStr("1.000000007075835620"), - }, - false, - }, - { - "medium-high apy", - args{ - apy: sdk.MustNewDecFromStr("5"), - expectedValue: sdk.MustNewDecFromStr("1.000000051034942717"), - }, - false, - }, - { - "high apy", - args{ - apy: sdk.MustNewDecFromStr("50"), - expectedValue: sdk.MustNewDecFromStr("1.000000124049443433"), - }, - false, - }, - { - "highest apy", - args{ - apy: sdk.MustNewDecFromStr("177"), - expectedValue: sdk.MustNewDecFromStr("1.000000164134644767"), - }, - false, - }, - { - "out of bounds error after 178", - args{ - apy: sdk.MustNewDecFromStr("179"), - expectedValue: sdk.ZeroDec(), - }, - true, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - spy, err := keeper.APYToSPY(tc.args.apy) - if tc.expectError { - suite.Require().Error(err) - } else { - suite.Require().NoError(err) - suite.Require().Equal(tc.args.expectedValue, spy) - } - }) - } -} - -func (suite *InterestTestSuite) TestSPYToEstimatedAPY() { - type args struct { - spy sdk.Dec - expectedAPY float64 - acceptableRange float64 - } - - type test struct { - name string - args args - } - - testCases := []test{ - { - "lowest apy", - args{ - spy: sdk.MustNewDecFromStr("0.999999831991472557"), - expectedAPY: 0.005, // Returned value: 0.004999999888241291 - acceptableRange: 0.00001, // +/- 1/10000th of a precent - }, - }, - { - "lower apy", - args{ - spy: sdk.MustNewDecFromStr("0.999999905005957279"), - expectedAPY: 0.05, // Returned value: 0.05000000074505806 - acceptableRange: 0.00001, // +/- 1/10000th of a precent - }, - }, - { - "medium-low apy", - args{ - spy: sdk.MustNewDecFromStr("0.999999978020447332"), - expectedAPY: 0.5, // Returned value: 0.5 - acceptableRange: 0.00001, // +/- 1/10000th of a precent - }, - }, - { - "medium-high apy", - args{ - spy: sdk.MustNewDecFromStr("1.000000051034942717"), - expectedAPY: 5, // Returned value: 5 - acceptableRange: 0.00001, // +/- 1/10000th of a precent - }, - }, - { - "high apy", - args{ - spy: sdk.MustNewDecFromStr("1.000000124049443433"), - expectedAPY: 50, // Returned value: 50 - acceptableRange: 0.00001, // +/- 1/10000th of a precent - }, - }, - { - "highest apy", - args{ - spy: sdk.MustNewDecFromStr("1.000000146028999310"), - expectedAPY: 100, // 100 - acceptableRange: 0.00001, // +/- 1/10000th of a precent - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // From SPY calculate APY and parse result from sdk.Dec to float64 - calculatedAPY := keeper.SPYToEstimatedAPY(tc.args.spy) - calculatedAPYFloat, err := strconv.ParseFloat(calculatedAPY.String(), 32) - suite.Require().NoError(err) - - // Check that the calculated value is within an acceptable percentage range - suite.Require().InEpsilon(tc.args.expectedAPY, calculatedAPYFloat, tc.args.acceptableRange) - }) - } -} - -type ExpectedBorrowInterest struct { - elapsedTime int64 - shouldBorrow bool - borrowCoin sdk.Coin -} - -func (suite *KeeperTestSuite) TestBorrowInterest() { - type args struct { - user sdk.AccAddress - initialBorrowerCoins sdk.Coins - initialModuleCoins sdk.Coins - borrowCoinDenom string - borrowCoins sdk.Coins - interestRateModel types.InterestRateModel - reserveFactor sdk.Dec - expectedInterestSnaphots []ExpectedBorrowInterest - } - - type errArgs struct { - expectPass bool - contains string - } - - type interestTest struct { - name string - args args - errArgs errArgs - } - - normalModel := types.NewInterestRateModel(sdk.MustNewDecFromStr("0"), sdk.MustNewDecFromStr("0.1"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("0.5")) - - oneDayInSeconds := int64(86400) - oneWeekInSeconds := int64(604800) - oneMonthInSeconds := int64(2592000) - oneYearInSeconds := int64(31536000) - - testCases := []interestTest{ - { - "one day", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - borrowCoinDenom: "ukava", - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedBorrowInterest{ - { - elapsedTime: oneDayInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "one week", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - borrowCoinDenom: "ukava", - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedBorrowInterest{ - { - elapsedTime: oneWeekInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "one month", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - borrowCoinDenom: "ukava", - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedBorrowInterest{ - { - elapsedTime: oneMonthInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "one year", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - borrowCoinDenom: "ukava", - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedBorrowInterest{ - { - elapsedTime: oneYearInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "0 reserve factor", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - borrowCoinDenom: "ukava", - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0"), - expectedInterestSnaphots: []ExpectedBorrowInterest{ - { - elapsedTime: oneYearInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "borrow during snapshot", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - borrowCoinDenom: "ukava", - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedBorrowInterest{ - { - elapsedTime: oneYearInSeconds, - shouldBorrow: true, - borrowCoin: sdk.NewCoin("ukava", sdkmath.NewInt(1*KAVA_CF)), - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "multiple snapshots", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - borrowCoinDenom: "ukava", - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedBorrowInterest{ - { - elapsedTime: oneMonthInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - { - elapsedTime: oneMonthInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "varied snapshots", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - borrowCoinDenom: "ukava", - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedBorrowInterest{ - { - elapsedTime: oneDayInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - { - elapsedTime: oneWeekInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - { - elapsedTime: oneMonthInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - { - elapsedTime: oneYearInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - // Auth module genesis state - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{tc.args.initialBorrowerCoins}, - []sdk.AccAddress{tc.args.user}, - ) - - // Hard module genesis state - hardGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("ukava", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "kava:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - tc.args.interestRateModel, // Interest Rate Model - tc.args.reserveFactor, // Reserve Factor - sdk.ZeroDec()), // Keeper Reward Percentage - }, - sdk.NewDec(10), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - }, - } - - // Initialize test application - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}) - - // Mint coins to Hard module account - bankKeeper := tApp.GetBankKeeper() - err := bankKeeper.MintCoins(ctx, types.ModuleAccountName, tc.args.initialModuleCoins) - suite.Require().NoError(err) - - suite.app = tApp - suite.ctx = ctx - suite.keeper = tApp.GetHardKeeper() - - // Run begin blocker and store initial block time - hard.BeginBlocker(suite.ctx, suite.keeper) - - // Deposit 2x as many coins for each coin we intend to borrow - depositCoins := sdk.NewCoins() - for _, borrowCoin := range tc.args.borrowCoins { - depositCoins = depositCoins.Add(sdk.NewCoin(borrowCoin.Denom, borrowCoin.Amount.Mul(sdkmath.NewInt(2)))) - } - err = suite.keeper.Deposit(suite.ctx, tc.args.user, depositCoins) - suite.Require().NoError(err) - - // Borrow coins - err = suite.keeper.Borrow(suite.ctx, tc.args.user, tc.args.borrowCoins) - suite.Require().NoError(err) - - // Check that the initial module-level borrow balance is correct and store it - initialBorrowedCoins, _ := suite.keeper.GetBorrowedCoins(suite.ctx) - suite.Require().Equal(tc.args.borrowCoins, initialBorrowedCoins) - - // Check interest levels for each snapshot - prevCtx := suite.ctx - for _, snapshot := range tc.args.expectedInterestSnaphots { - // ---------------------------- Calculate expected interest ---------------------------- - // 1. Get cash, borrows, reserves, and borrow index - cashPrior := suite.getAccountCoins(suite.getModuleAccountAtCtx(types.ModuleName, prevCtx)).AmountOf(tc.args.borrowCoinDenom) - - borrowCoinsPrior, borrowCoinsPriorFound := suite.keeper.GetBorrowedCoins(prevCtx) - suite.Require().True(borrowCoinsPriorFound) - borrowCoinPriorAmount := borrowCoinsPrior.AmountOf(tc.args.borrowCoinDenom) - - reservesPrior, foundReservesPrior := suite.keeper.GetTotalReserves(prevCtx) - if !foundReservesPrior { - reservesPrior = sdk.NewCoins(sdk.NewCoin(tc.args.borrowCoinDenom, sdk.ZeroInt())) - } - - interestFactorPrior, foundInterestFactorPrior := suite.keeper.GetBorrowInterestFactor(prevCtx, tc.args.borrowCoinDenom) - suite.Require().True(foundInterestFactorPrior) - - // 2. Calculate expected interest owed - borrowRateApy, err := keeper.CalculateBorrowRate(tc.args.interestRateModel, sdk.NewDecFromInt(cashPrior), sdk.NewDecFromInt(borrowCoinPriorAmount), sdk.NewDecFromInt(reservesPrior.AmountOf(tc.args.borrowCoinDenom))) - suite.Require().NoError(err) - - // Convert from APY to SPY, expressed as (1 + borrow rate) - borrowRateSpy, err := keeper.APYToSPY(sdk.OneDec().Add(borrowRateApy)) - suite.Require().NoError(err) - - interestFactor := keeper.CalculateBorrowInterestFactor(borrowRateSpy, sdkmath.NewInt(snapshot.elapsedTime)) - expectedInterest := (interestFactor.Mul(sdk.NewDecFromInt(borrowCoinPriorAmount)).TruncateInt()).Sub(borrowCoinPriorAmount) - expectedReserves := reservesPrior.Add(sdk.NewCoin(tc.args.borrowCoinDenom, sdk.NewDecFromInt(expectedInterest).Mul(tc.args.reserveFactor).TruncateInt())) - expectedInterestFactor := interestFactorPrior.Mul(interestFactor) - // ------------------------------------------------------------------------------------- - - // Set up snapshot chain context and run begin blocker - runAtTime := prevCtx.BlockTime().Add(time.Duration(int64(time.Second) * snapshot.elapsedTime)) - snapshotCtx := prevCtx.WithBlockTime(runAtTime) - hard.BeginBlocker(snapshotCtx, suite.keeper) - - // Check that the total amount of borrowed coins has increased by expected interest amount - expectedBorrowedCoins := borrowCoinsPrior.AmountOf(tc.args.borrowCoinDenom).Add(expectedInterest) - currBorrowedCoins, _ := suite.keeper.GetBorrowedCoins(snapshotCtx) - suite.Require().Equal(expectedBorrowedCoins, currBorrowedCoins.AmountOf(tc.args.borrowCoinDenom)) - - // Check that the total reserves have changed as expected - currTotalReserves, _ := suite.keeper.GetTotalReserves(snapshotCtx) - suite.Require().True(expectedReserves.IsEqual(currTotalReserves)) - - // Check that the borrow index has increased as expected - currIndexPrior, _ := suite.keeper.GetBorrowInterestFactor(snapshotCtx, tc.args.borrowCoinDenom) - suite.Require().Equal(expectedInterestFactor, currIndexPrior) - - // After borrowing again user's borrow balance should have any outstanding interest applied - if snapshot.shouldBorrow { - borrowCoinsBefore, _ := suite.keeper.GetBorrow(snapshotCtx, tc.args.user) - expectedInterestCoins := sdk.NewCoin(tc.args.borrowCoinDenom, expectedInterest) - expectedBorrowCoinsAfter := borrowCoinsBefore.Amount.Add(snapshot.borrowCoin).Add(expectedInterestCoins) - - err = suite.keeper.Borrow(snapshotCtx, tc.args.user, sdk.NewCoins(snapshot.borrowCoin)) - suite.Require().NoError(err) - - borrowCoinsAfter, _ := suite.keeper.GetBorrow(snapshotCtx, tc.args.user) - suite.Require().Equal(expectedBorrowCoinsAfter, borrowCoinsAfter.Amount) - } - // Update previous context to this snapshot's context, segmenting time periods between snapshots - prevCtx = snapshotCtx - } - }) - } -} - -type ExpectedSupplyInterest struct { - elapsedTime int64 - shouldSupply bool - supplyCoin sdk.Coin -} - -func (suite *KeeperTestSuite) TestSupplyInterest() { - type args struct { - user sdk.AccAddress - initialBorrowerCoins sdk.Coins - initialModuleCoins sdk.Coins - depositCoins sdk.Coins - coinDenoms []string - borrowCoins sdk.Coins - interestRateModel types.InterestRateModel - reserveFactor sdk.Dec - expectedInterestSnaphots []ExpectedSupplyInterest - } - - type errArgs struct { - expectPass bool - contains string - } - - type interestTest struct { - name string - args args - errArgs errArgs - } - - normalModel := types.NewInterestRateModel(sdk.MustNewDecFromStr("0"), sdk.MustNewDecFromStr("0.1"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("0.5")) - - oneDayInSeconds := int64(86400) - oneWeekInSeconds := int64(604800) - oneMonthInSeconds := int64(2592000) - oneYearInSeconds := int64(31536000) - - testCases := []interestTest{ - { - "one day", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - coinDenoms: []string{"ukava"}, - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedSupplyInterest{ - { - elapsedTime: oneDayInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "one week", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - coinDenoms: []string{"ukava"}, - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedSupplyInterest{ - { - elapsedTime: oneWeekInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "one month", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - coinDenoms: []string{"ukava"}, - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedSupplyInterest{ - { - elapsedTime: oneMonthInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "one year", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - coinDenoms: []string{"ukava"}, - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedSupplyInterest{ - { - elapsedTime: oneYearInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "supply/borrow multiple coins", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(100*BNB_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(100*BNB_CF))), - coinDenoms: []string{"ukava"}, - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(20*BNB_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedSupplyInterest{ - { - elapsedTime: oneMonthInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "supply during snapshot", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - coinDenoms: []string{"ukava"}, - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedSupplyInterest{ - { - elapsedTime: oneMonthInSeconds, - shouldSupply: true, - supplyCoin: sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF)), - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "multiple snapshots", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - coinDenoms: []string{"ukava"}, - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(80*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedSupplyInterest{ - { - elapsedTime: oneMonthInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - { - elapsedTime: oneMonthInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - { - elapsedTime: oneMonthInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "varied snapshots", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - coinDenoms: []string{"ukava"}, - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedSupplyInterest{ - { - elapsedTime: oneMonthInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - { - elapsedTime: oneDayInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - { - elapsedTime: oneYearInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - { - elapsedTime: oneWeekInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - // Auth module genesis state - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{tc.args.initialBorrowerCoins}, - []sdk.AccAddress{tc.args.user}, - ) - - // Hard module genesis state - hardGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("ukava", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "kava:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - tc.args.interestRateModel, // Interest Rate Model - tc.args.reserveFactor, // Reserve Factor - sdk.ZeroDec()), // Keeper Reward Percentage - types.NewMoneyMarket("bnb", - types.NewBorrowLimit(false, sdk.NewDec(100000000*BNB_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "bnb:usd", // Market ID - sdkmath.NewInt(BNB_CF), // Conversion Factor - tc.args.interestRateModel, // Interest Rate Model - tc.args.reserveFactor, // Reserve Factor - sdk.ZeroDec()), // Keeper Reward Percentage - }, - sdk.NewDec(10), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("20.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - }, - } - - // Initialize test application - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}) - - // Mint coins to Hard module account - bankKeeper := tApp.GetBankKeeper() - err := bankKeeper.MintCoins(ctx, types.ModuleAccountName, tc.args.initialModuleCoins) - suite.Require().NoError(err) - - suite.app = tApp - suite.ctx = ctx - suite.keeper = tApp.GetHardKeeper() - suite.keeper.SetSuppliedCoins(ctx, tc.args.initialModuleCoins) - - // Run begin blocker - hard.BeginBlocker(suite.ctx, suite.keeper) - - // // Deposit coins - err = suite.keeper.Deposit(suite.ctx, tc.args.user, tc.args.depositCoins) - suite.Require().NoError(err) - - // Borrow coins - err = suite.keeper.Borrow(suite.ctx, tc.args.user, tc.args.borrowCoins) - suite.Require().NoError(err) - - // Check interest levels for each snapshot - prevCtx := suite.ctx - for _, snapshot := range tc.args.expectedInterestSnaphots { - for _, coinDenom := range tc.args.coinDenoms { - // ---------------------------- Calculate expected supply interest ---------------------------- - // 1. Get cash, borrows, reserves, and borrow index - cashPrior := suite.getAccountCoins(suite.getModuleAccountAtCtx(types.ModuleName, prevCtx)).AmountOf(coinDenom) - - var borrowCoinPriorAmount sdkmath.Int - borrowCoinsPrior, borrowCoinsPriorFound := suite.keeper.GetBorrowedCoins(prevCtx) - suite.Require().True(borrowCoinsPriorFound) - borrowCoinPriorAmount = borrowCoinsPrior.AmountOf(coinDenom) - - var supplyCoinPriorAmount sdkmath.Int - supplyCoinsPrior, supplyCoinsPriorFound := suite.keeper.GetSuppliedCoins(prevCtx) - suite.Require().True(supplyCoinsPriorFound) - supplyCoinPriorAmount = supplyCoinsPrior.AmountOf(coinDenom) - - reservesPrior, foundReservesPrior := suite.keeper.GetTotalReserves(prevCtx) - if !foundReservesPrior { - reservesPrior = sdk.NewCoins(sdk.NewCoin(coinDenom, sdk.ZeroInt())) - } - - borrowInterestFactorPrior, foundBorrowInterestFactorPrior := suite.keeper.GetBorrowInterestFactor(prevCtx, coinDenom) - suite.Require().True(foundBorrowInterestFactorPrior) - - supplyInterestFactorPrior, foundSupplyInterestFactorPrior := suite.keeper.GetSupplyInterestFactor(prevCtx, coinDenom) - suite.Require().True(foundSupplyInterestFactorPrior) - - // 2. Calculate expected borrow interest owed - borrowRateApy, err := keeper.CalculateBorrowRate(tc.args.interestRateModel, sdk.NewDecFromInt(cashPrior), sdk.NewDecFromInt(borrowCoinPriorAmount), sdk.NewDecFromInt(reservesPrior.AmountOf(coinDenom))) - suite.Require().NoError(err) - - // Convert from APY to SPY, expressed as (1 + borrow rate) - borrowRateSpy, err := keeper.APYToSPY(sdk.OneDec().Add(borrowRateApy)) - suite.Require().NoError(err) - - newBorrowInterestFactor := keeper.CalculateBorrowInterestFactor(borrowRateSpy, sdkmath.NewInt(snapshot.elapsedTime)) - expectedBorrowInterest := (newBorrowInterestFactor.Mul(sdk.NewDecFromInt(borrowCoinPriorAmount)).TruncateInt()).Sub(borrowCoinPriorAmount) - expectedReserves := reservesPrior.Add(sdk.NewCoin(coinDenom, sdk.NewDecFromInt(expectedBorrowInterest).Mul(tc.args.reserveFactor).TruncateInt())).Sub(reservesPrior...) - expectedTotalReserves := expectedReserves.Add(reservesPrior...) - - expectedBorrowInterestFactor := borrowInterestFactorPrior.Mul(newBorrowInterestFactor) - expectedSupplyInterest := expectedBorrowInterest.Sub(expectedReserves.AmountOf(coinDenom)) - - newSupplyInterestFactor := keeper.CalculateSupplyInterestFactor(sdk.NewDecFromInt(expectedSupplyInterest), sdk.NewDecFromInt(cashPrior), sdk.NewDecFromInt(borrowCoinPriorAmount), sdk.NewDecFromInt(reservesPrior.AmountOf(coinDenom))) - expectedSupplyInterestFactor := supplyInterestFactorPrior.Mul(newSupplyInterestFactor) - // ------------------------------------------------------------------------------------- - - // Set up snapshot chain context and run begin blocker - runAtTime := prevCtx.BlockTime().Add(time.Duration(int64(time.Second) * snapshot.elapsedTime)) - snapshotCtx := prevCtx.WithBlockTime(runAtTime) - hard.BeginBlocker(snapshotCtx, suite.keeper) - - borrowInterestFactor, _ := suite.keeper.GetBorrowInterestFactor(ctx, coinDenom) - suite.Require().Equal(expectedBorrowInterestFactor, borrowInterestFactor) - suite.Require().Equal(expectedBorrowInterest, expectedSupplyInterest.Add(expectedReserves.AmountOf(coinDenom))) - - // Check that the total amount of borrowed coins has increased by expected borrow interest amount - borrowCoinsPost, _ := suite.keeper.GetBorrowedCoins(snapshotCtx) - borrowCoinPostAmount := borrowCoinsPost.AmountOf(coinDenom) - suite.Require().Equal(borrowCoinPostAmount, borrowCoinPriorAmount.Add(expectedBorrowInterest)) - - // Check that the total amount of supplied coins has increased by expected supply interest amount - supplyCoinsPost, _ := suite.keeper.GetSuppliedCoins(prevCtx) - supplyCoinPostAmount := supplyCoinsPost.AmountOf(coinDenom) - suite.Require().Equal(supplyCoinPostAmount, supplyCoinPriorAmount.Add(expectedSupplyInterest)) - - // Check current total reserves - totalReserves, _ := suite.keeper.GetTotalReserves(snapshotCtx) - suite.Require().Equal( - sdk.NewCoin(coinDenom, expectedTotalReserves.AmountOf(coinDenom)), - sdk.NewCoin(coinDenom, totalReserves.AmountOf(coinDenom)), - ) - - // Check that the supply index has increased as expected - currSupplyIndexPrior, _ := suite.keeper.GetSupplyInterestFactor(snapshotCtx, coinDenom) - suite.Require().Equal(expectedSupplyInterestFactor, currSupplyIndexPrior) - - // // Check that the borrow index has increased as expected - currBorrowIndexPrior, _ := suite.keeper.GetBorrowInterestFactor(snapshotCtx, coinDenom) - suite.Require().Equal(expectedBorrowInterestFactor, currBorrowIndexPrior) - - // After supplying again user's supplied balance should have owed supply interest applied - if snapshot.shouldSupply { - // Calculate percentage of supply interest profits owed to user - userSupplyBefore, _ := suite.keeper.GetDeposit(snapshotCtx, tc.args.user) - userSupplyCoinAmount := userSupplyBefore.Amount.AmountOf(coinDenom) - userPercentOfTotalSupplied := sdk.NewDecFromInt(userSupplyCoinAmount).Quo(sdk.NewDecFromInt(supplyCoinPriorAmount)) - userExpectedSupplyInterestCoin := sdk.NewCoin(coinDenom, userPercentOfTotalSupplied.MulInt(expectedSupplyInterest).TruncateInt()) - - // Supplying syncs user's owed supply and borrow interest - err = suite.keeper.Deposit(snapshotCtx, tc.args.user, sdk.NewCoins(snapshot.supplyCoin)) - suite.Require().NoError(err) - - // Fetch user's new borrow and supply balance post-interaction - userSupplyAfter, _ := suite.keeper.GetDeposit(snapshotCtx, tc.args.user) - - // Confirm that user's supply index for the denom has increased as expected - var userSupplyAfterIndexFactor sdk.Dec - for _, indexFactor := range userSupplyAfter.Index { - if indexFactor.Denom == coinDenom { - userSupplyAfterIndexFactor = indexFactor.Value - } - } - suite.Require().Equal(userSupplyAfterIndexFactor, currSupplyIndexPrior) - - // Check user's supplied amount increased by supply interest owed + the newly supplied coins - expectedSupplyCoinsAfter := userSupplyBefore.Amount.Add(snapshot.supplyCoin).Add(userExpectedSupplyInterestCoin) - suite.Require().Equal(expectedSupplyCoinsAfter, userSupplyAfter.Amount) - } - prevCtx = snapshotCtx - } - } - }) - } -} - -func TestInterestTestSuite(t *testing.T) { - suite.Run(t, new(InterestTestSuite)) -} diff --git a/x/hard/keeper/keeper.go b/x/hard/keeper/keeper.go deleted file mode 100644 index 5d4fc3e2..00000000 --- a/x/hard/keeper/keeper.go +++ /dev/null @@ -1,366 +0,0 @@ -package keeper - -import ( - "time" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store/prefix" - 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/kava-labs/kava/x/hard/types" -) - -// Keeper keeper for the hard module -type Keeper struct { - key storetypes.StoreKey - cdc codec.Codec - paramSubspace paramtypes.Subspace - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - pricefeedKeeper types.PricefeedKeeper - auctionKeeper types.AuctionKeeper - hooks types.HARDHooks -} - -// NewKeeper creates a new keeper -func NewKeeper(cdc codec.Codec, key storetypes.StoreKey, paramstore paramtypes.Subspace, - ak types.AccountKeeper, bk types.BankKeeper, - pfk types.PricefeedKeeper, auk types.AuctionKeeper, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - key: key, - cdc: cdc, - paramSubspace: paramstore, - accountKeeper: ak, - bankKeeper: bk, - pricefeedKeeper: pfk, - auctionKeeper: auk, - hooks: nil, - } -} - -// SetHooks adds hooks to the keeper. -func (k *Keeper) SetHooks(hooks types.HARDHooks) *Keeper { - if k.hooks != nil { - panic("cannot set hard hooks twice") - } - k.hooks = hooks - return k -} - -// GetDeposit returns a deposit from the store for a particular depositor address, deposit denom -func (k Keeper) GetDeposit(ctx sdk.Context, depositor sdk.AccAddress) (types.Deposit, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositsKeyPrefix) - bz := store.Get(depositor.Bytes()) - if len(bz) == 0 { - return types.Deposit{}, false - } - var deposit types.Deposit - k.cdc.MustUnmarshal(bz, &deposit) - return deposit, true -} - -// SetDeposit sets the input deposit in the store, prefixed by the deposit type, deposit denom, and depositor address, in that order -func (k Keeper) SetDeposit(ctx sdk.Context, deposit types.Deposit) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositsKeyPrefix) - bz := k.cdc.MustMarshal(&deposit) - store.Set(deposit.Depositor.Bytes(), bz) -} - -// DeleteDeposit deletes a deposit from the store -func (k Keeper) DeleteDeposit(ctx sdk.Context, deposit types.Deposit) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositsKeyPrefix) - store.Delete(deposit.Depositor.Bytes()) -} - -// IterateDeposits iterates over all deposit objects in the store and performs a callback function -func (k Keeper) IterateDeposits(ctx sdk.Context, cb func(deposit types.Deposit) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositsKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var deposit types.Deposit - k.cdc.MustUnmarshal(iterator.Value(), &deposit) - if cb(deposit) { - break - } - } -} - -// GetDepositsByUser gets all deposits for an individual user -func (k Keeper) GetDepositsByUser(ctx sdk.Context, user sdk.AccAddress) []types.Deposit { - var deposits []types.Deposit - k.IterateDeposits(ctx, func(deposit types.Deposit) (stop bool) { - if deposit.Depositor.Equals(user) { - deposits = append(deposits, deposit) - } - return false - }) - return deposits -} - -// GetBorrow returns a Borrow from the store for a particular borrower address and borrow denom -func (k Keeper) GetBorrow(ctx sdk.Context, borrower sdk.AccAddress) (types.Borrow, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowsKeyPrefix) - bz := store.Get(borrower) - if len(bz) == 0 { - return types.Borrow{}, false - } - var borrow types.Borrow - k.cdc.MustUnmarshal(bz, &borrow) - return borrow, true -} - -// SetBorrow sets the input borrow in the store, prefixed by the borrower address and borrow denom -func (k Keeper) SetBorrow(ctx sdk.Context, borrow types.Borrow) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowsKeyPrefix) - bz := k.cdc.MustMarshal(&borrow) - store.Set(borrow.Borrower, bz) -} - -// DeleteBorrow deletes a borrow from the store -func (k Keeper) DeleteBorrow(ctx sdk.Context, borrow types.Borrow) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowsKeyPrefix) - store.Delete(borrow.Borrower) -} - -// IterateBorrows iterates over all borrow objects in the store and performs a callback function -func (k Keeper) IterateBorrows(ctx sdk.Context, cb func(borrow types.Borrow) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowsKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var borrow types.Borrow - k.cdc.MustUnmarshal(iterator.Value(), &borrow) - if cb(borrow) { - break - } - } -} - -// SetBorrowedCoins sets the total amount of coins currently borrowed in the store -func (k Keeper) SetBorrowedCoins(ctx sdk.Context, borrowedCoins sdk.Coins) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowedCoinsPrefix) - if borrowedCoins.Empty() { - store.Set(types.BorrowedCoinsPrefix, []byte{}) - } else { - bz := k.cdc.MustMarshal(&types.CoinsProto{ - Coins: borrowedCoins, - }) - store.Set(types.BorrowedCoinsPrefix, bz) - } -} - -// GetBorrowedCoins returns an sdk.Coins object from the store representing all currently borrowed coins -func (k Keeper) GetBorrowedCoins(ctx sdk.Context) (sdk.Coins, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowedCoinsPrefix) - bz := store.Get(types.BorrowedCoinsPrefix) - if len(bz) == 0 { - return sdk.Coins{}, false - } - var borrowed types.CoinsProto - k.cdc.MustUnmarshal(bz, &borrowed) - return borrowed.Coins, true -} - -// SetSuppliedCoins sets the total amount of coins currently supplied in the store -func (k Keeper) SetSuppliedCoins(ctx sdk.Context, suppliedCoins sdk.Coins) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SuppliedCoinsPrefix) - if suppliedCoins.Empty() { - store.Set(types.SuppliedCoinsPrefix, []byte{}) - } else { - bz := k.cdc.MustMarshal(&types.CoinsProto{ - Coins: suppliedCoins, - }) - store.Set(types.SuppliedCoinsPrefix, bz) - } -} - -// GetSuppliedCoins returns an sdk.Coins object from the store representing all currently supplied coins -func (k Keeper) GetSuppliedCoins(ctx sdk.Context) (sdk.Coins, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SuppliedCoinsPrefix) - bz := store.Get(types.SuppliedCoinsPrefix) - if len(bz) == 0 { - return sdk.Coins{}, false - } - var supplied types.CoinsProto - k.cdc.MustUnmarshal(bz, &supplied) - return supplied.Coins, true -} - -// GetMoneyMarket returns a money market from the store for a denom -func (k Keeper) GetMoneyMarket(ctx sdk.Context, denom string) (types.MoneyMarket, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.MoneyMarketsPrefix) - bz := store.Get([]byte(denom)) - if len(bz) == 0 { - return types.MoneyMarket{}, false - } - var moneyMarket types.MoneyMarket - k.cdc.MustUnmarshal(bz, &moneyMarket) - return moneyMarket, true -} - -// SetMoneyMarket sets a money market in the store for a denom -func (k Keeper) SetMoneyMarket(ctx sdk.Context, denom string, moneyMarket types.MoneyMarket) { - store := prefix.NewStore(ctx.KVStore(k.key), types.MoneyMarketsPrefix) - bz := k.cdc.MustMarshal(&moneyMarket) - store.Set([]byte(denom), bz) -} - -// DeleteMoneyMarket deletes a money market from the store -func (k Keeper) DeleteMoneyMarket(ctx sdk.Context, denom string) { - store := prefix.NewStore(ctx.KVStore(k.key), types.MoneyMarketsPrefix) - store.Delete([]byte(denom)) -} - -// IterateMoneyMarkets iterates over all money markets objects in the store and performs a callback function -// -// that returns both the money market and the key (denom) it's stored under -func (k Keeper) IterateMoneyMarkets(ctx sdk.Context, cb func(denom string, moneyMarket types.MoneyMarket) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.MoneyMarketsPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var moneyMarket types.MoneyMarket - k.cdc.MustUnmarshal(iterator.Value(), &moneyMarket) - if cb(string(iterator.Key()), moneyMarket) { - break - } - } -} - -// GetAllMoneyMarkets returns all money markets from the store -func (k Keeper) GetAllMoneyMarkets(ctx sdk.Context) (moneyMarkets types.MoneyMarkets) { - k.IterateMoneyMarkets(ctx, func(denom string, moneyMarket types.MoneyMarket) bool { - moneyMarkets = append(moneyMarkets, moneyMarket) - return false - }) - return -} - -// GetPreviousAccrualTime returns the last time an individual market accrued interest -func (k Keeper) GetPreviousAccrualTime(ctx sdk.Context, denom string) (time.Time, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousAccrualTimePrefix) - bz := store.Get([]byte(denom)) - if len(bz) == 0 { - return time.Time{}, false - } - - var previousAccrualTime time.Time - if err := previousAccrualTime.UnmarshalBinary(bz); err != nil { - panic(err) - } - return previousAccrualTime, true -} - -// SetPreviousAccrualTime sets the most recent accrual time for a particular market -func (k Keeper) SetPreviousAccrualTime(ctx sdk.Context, denom string, previousAccrualTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousAccrualTimePrefix) - bz, err := previousAccrualTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(denom), bz) -} - -// SetTotalReserves sets the total reserves for an individual market -func (k Keeper) SetTotalReserves(ctx sdk.Context, coins sdk.Coins) { - store := prefix.NewStore(ctx.KVStore(k.key), types.TotalReservesPrefix) - if coins.Empty() { - store.Set(types.TotalReservesPrefix, []byte{}) - return - } - - bz := k.cdc.MustMarshal(&types.CoinsProto{ - Coins: coins, - }) - store.Set(types.TotalReservesPrefix, bz) -} - -// GetTotalReserves returns the total reserves for an individual market -func (k Keeper) GetTotalReserves(ctx sdk.Context) (sdk.Coins, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.TotalReservesPrefix) - bz := store.Get(types.TotalReservesPrefix) - if len(bz) == 0 { - return sdk.Coins{}, false - } - - var totalReserves types.CoinsProto - k.cdc.MustUnmarshal(bz, &totalReserves) - return totalReserves.Coins, true -} - -// GetBorrowInterestFactor returns the current borrow interest factor for an individual market -func (k Keeper) GetBorrowInterestFactor(ctx sdk.Context, denom string) (sdk.Dec, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowInterestFactorPrefix) - bz := store.Get([]byte(denom)) - if len(bz) == 0 { - return sdk.ZeroDec(), false - } - var borrowInterestFactor sdk.DecProto - k.cdc.MustUnmarshal(bz, &borrowInterestFactor) - return borrowInterestFactor.Dec, true -} - -// SetBorrowInterestFactor sets the current borrow interest factor for an individual market -func (k Keeper) SetBorrowInterestFactor(ctx sdk.Context, denom string, borrowInterestFactor sdk.Dec) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowInterestFactorPrefix) - bz := k.cdc.MustMarshal(&sdk.DecProto{Dec: borrowInterestFactor}) - store.Set([]byte(denom), bz) -} - -// IterateBorrowInterestFactors iterates over all borrow interest factors in the store and returns -// both the borrow interest factor and the key (denom) it's stored under -func (k Keeper) IterateBorrowInterestFactors(ctx sdk.Context, cb func(denom string, factor sdk.Dec) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowInterestFactorPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var factor sdk.DecProto - k.cdc.MustUnmarshal(iterator.Value(), &factor) - if cb(string(iterator.Key()), factor.Dec) { - break - } - } -} - -// GetSupplyInterestFactor returns the current supply interest factor for an individual market -func (k Keeper) GetSupplyInterestFactor(ctx sdk.Context, denom string) (sdk.Dec, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SupplyInterestFactorPrefix) - bz := store.Get([]byte(denom)) - if len(bz) == 0 { - return sdk.ZeroDec(), false - } - var supplyInterestFactor sdk.DecProto - k.cdc.MustUnmarshal(bz, &supplyInterestFactor) - return supplyInterestFactor.Dec, true -} - -// SetSupplyInterestFactor sets the current supply interest factor for an individual market -func (k Keeper) SetSupplyInterestFactor(ctx sdk.Context, denom string, supplyInterestFactor sdk.Dec) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SupplyInterestFactorPrefix) - bz := k.cdc.MustMarshal(&sdk.DecProto{Dec: supplyInterestFactor}) - store.Set([]byte(denom), bz) -} - -// IterateSupplyInterestFactors iterates over all supply interest factors in the store and returns -// both the supply interest factor and the key (denom) it's stored under -func (k Keeper) IterateSupplyInterestFactors(ctx sdk.Context, cb func(denom string, factor sdk.Dec) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SupplyInterestFactorPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var factor sdk.DecProto - - k.cdc.MustUnmarshal(iterator.Value(), &factor) - if cb(string(iterator.Key()), factor.Dec) { - break - } - } -} diff --git a/x/hard/keeper/keeper_test.go b/x/hard/keeper/keeper_test.go deleted file mode 100644 index 8d2054be..00000000 --- a/x/hard/keeper/keeper_test.go +++ /dev/null @@ -1,235 +0,0 @@ -package keeper_test - -import ( - "fmt" - "strconv" - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - auctionkeeper "github.com/kava-labs/kava/x/auction/keeper" - "github.com/kava-labs/kava/x/hard/keeper" - "github.com/kava-labs/kava/x/hard/types" -) - -// Test suite used for all keeper tests -type KeeperTestSuite struct { - suite.Suite - keeper keeper.Keeper - auctionKeeper auctionkeeper.Keeper - app app.TestApp - ctx sdk.Context - addrs []sdk.AccAddress -} - -// The default state used by each test -func (suite *KeeperTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - tApp.InitializeFromGenesisStates() - _, addrs := app.GeneratePrivKeyAddressPairs(1) - keeper := tApp.GetHardKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - suite.addrs = addrs -} - -func (suite *KeeperTestSuite) TestGetSetDeleteDeposit() { - addr := suite.addrs[0] - dep := types.NewDeposit( - addr, - sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - types.SupplyInterestFactors{types.NewSupplyInterestFactor("bnb", sdk.MustNewDecFromStr("1.12"))}, - ) - - _, f := suite.keeper.GetDeposit(suite.ctx, addr) - suite.Require().False(f) - - suite.keeper.SetDeposit(suite.ctx, dep) - - storedDeposit, f := suite.keeper.GetDeposit(suite.ctx, addr) - suite.Require().True(f) - suite.Require().Equal(dep, storedDeposit) - - suite.Require().NotPanics(func() { suite.keeper.DeleteDeposit(suite.ctx, dep) }) - - _, f = suite.keeper.GetDeposit(suite.ctx, addr) - suite.Require().False(f) -} - -func (suite *KeeperTestSuite) TestIterateDeposits() { - var deposits types.Deposits - for i := 0; i < 5; i++ { - dep := types.NewDeposit( - sdk.AccAddress("test"+fmt.Sprint(i)), - sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - types.SupplyInterestFactors{types.NewSupplyInterestFactor("bnb", sdk.MustNewDecFromStr("1.12"))}, - ) - deposits = append(deposits, dep) - suite.keeper.SetDeposit(suite.ctx, dep) - } - var storedDeposits types.Deposits - suite.keeper.IterateDeposits(suite.ctx, func(d types.Deposit) bool { - storedDeposits = append(storedDeposits, d) - return false - }) - suite.Require().Equal(deposits, storedDeposits) -} - -func (suite *KeeperTestSuite) TestGetSetDeleteBorrow() { - addr := suite.addrs[0] - - borrow := types.NewBorrow( - addr, - sdk.NewCoins(sdk.NewInt64Coin("bnb", 1e9)), - types.BorrowInterestFactors{types.NewBorrowInterestFactor("bnb", sdk.MustNewDecFromStr("1.12"))}, - ) - - _, f := suite.keeper.GetBorrow(suite.ctx, addr) - suite.Require().False(f) - - suite.keeper.SetBorrow(suite.ctx, borrow) - - storedBorrow, f := suite.keeper.GetBorrow(suite.ctx, addr) - suite.Require().True(f) - suite.Require().Equal(borrow, storedBorrow) - - suite.Require().NotPanics(func() { suite.keeper.DeleteBorrow(suite.ctx, borrow) }) - - _, f = suite.keeper.GetBorrow(suite.ctx, addr) - suite.Require().False(f) -} - -func (suite *KeeperTestSuite) TestIterateBorrows() { - var borrows types.Borrows - for i := 0; i < 5; i++ { - borrow := types.NewBorrow( - sdk.AccAddress("test"+fmt.Sprint(i)), - sdk.NewCoins(sdk.NewInt64Coin("bnb", 1e9)), - types.BorrowInterestFactors{types.NewBorrowInterestFactor("bnb", sdk.MustNewDecFromStr("1.12"))}, - ) - borrows = append(borrows, borrow) - suite.keeper.SetBorrow(suite.ctx, borrow) - } - var storedBorrows types.Borrows - suite.keeper.IterateBorrows(suite.ctx, func(b types.Borrow) bool { - storedBorrows = append(storedBorrows, b) - return false - }) - suite.Require().Equal(borrows, storedBorrows) -} - -func (suite *KeeperTestSuite) TestGetSetDeleteInterestRateModel() { - denom := "test" - model := types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")) - borrowLimit := types.NewBorrowLimit(false, sdk.MustNewDecFromStr("0.2"), sdk.MustNewDecFromStr("0.5")) - moneyMarket := types.NewMoneyMarket(denom, borrowLimit, denom+":usd", sdkmath.NewInt(1000000), model, sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()) - - _, f := suite.keeper.GetMoneyMarket(suite.ctx, denom) - suite.Require().False(f) - - suite.keeper.SetMoneyMarket(suite.ctx, denom, moneyMarket) - - testMoneyMarket, f := suite.keeper.GetMoneyMarket(suite.ctx, denom) - suite.Require().True(f) - suite.Require().Equal(moneyMarket, testMoneyMarket) - - suite.Require().NotPanics(func() { suite.keeper.DeleteMoneyMarket(suite.ctx, denom) }) - - _, f = suite.keeper.GetMoneyMarket(suite.ctx, denom) - suite.Require().False(f) -} - -func (suite *KeeperTestSuite) TestIterateInterestRateModels() { - testDenom := "test" - var setMMs types.MoneyMarkets - var setDenoms []string - for i := 0; i < 5; i++ { - // Initialize a new money market - denom := testDenom + strconv.Itoa(i) - model := types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")) - borrowLimit := types.NewBorrowLimit(false, sdk.MustNewDecFromStr("0.2"), sdk.MustNewDecFromStr("0.5")) - moneyMarket := types.NewMoneyMarket(denom, borrowLimit, denom+":usd", sdkmath.NewInt(1000000), model, sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()) - - // Store money market in the module's store - suite.Require().NotPanics(func() { suite.keeper.SetMoneyMarket(suite.ctx, denom, moneyMarket) }) - - // Save the denom and model - setDenoms = append(setDenoms, denom) - setMMs = append(setMMs, moneyMarket) - } - - var seenMMs types.MoneyMarkets - var seenDenoms []string - suite.keeper.IterateMoneyMarkets(suite.ctx, func(denom string, i types.MoneyMarket) bool { - seenDenoms = append(seenDenoms, denom) - seenMMs = append(seenMMs, i) - return false - }) - - suite.Require().Equal(setMMs, seenMMs) - suite.Require().Equal(setDenoms, seenDenoms) -} - -func (suite *KeeperTestSuite) TestGetSetBorrowedCoins() { - suite.keeper.SetBorrowedCoins(suite.ctx, sdk.Coins{c("ukava", 123)}) - - coins, found := suite.keeper.GetBorrowedCoins(suite.ctx) - suite.Require().True(found) - suite.Require().Len(coins, 1) - suite.Require().Equal(coins, cs(c("ukava", 123))) -} - -func (suite *KeeperTestSuite) TestGetSetBorrowedCoins_Empty() { - coins, found := suite.keeper.GetBorrowedCoins(suite.ctx) - suite.Require().False(found) - suite.Require().Empty(coins) - - // None set and setting empty coins should both be the same - suite.keeper.SetBorrowedCoins(suite.ctx, sdk.Coins{}) - - coins, found = suite.keeper.GetBorrowedCoins(suite.ctx) - suite.Require().False(found) - suite.Require().Empty(coins) -} - -func (suite *KeeperTestSuite) getAccountCoins(acc authtypes.AccountI) sdk.Coins { - bk := suite.app.GetBankKeeper() - return bk.GetAllBalances(suite.ctx, acc.GetAddress()) -} - -func (suite *KeeperTestSuite) getAccount(addr sdk.AccAddress) authtypes.AccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetAccount(suite.ctx, addr) -} - -func (suite *KeeperTestSuite) getAccountAtCtx(addr sdk.AccAddress, ctx sdk.Context) authtypes.AccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetAccount(ctx, addr) -} - -func (suite *KeeperTestSuite) getModuleAccount(name string) authtypes.ModuleAccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetModuleAccount(suite.ctx, name) -} - -func (suite *KeeperTestSuite) getModuleAccountAtCtx(name string, ctx sdk.Context) authtypes.ModuleAccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetModuleAccount(ctx, name) -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} diff --git a/x/hard/keeper/liquidation.go b/x/hard/keeper/liquidation.go deleted file mode 100644 index 94fce1a8..00000000 --- a/x/hard/keeper/liquidation.go +++ /dev/null @@ -1,428 +0,0 @@ -package keeper - -import ( - "sort" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/hard/types" -) - -// LiqData holds liquidation-related data -type LiqData struct { - price sdk.Dec - ltv sdk.Dec - conversionFactor sdkmath.Int -} - -// AttemptKeeperLiquidation enables a keeper to liquidate an individual borrower's position -func (k Keeper) AttemptKeeperLiquidation(ctx sdk.Context, keeper sdk.AccAddress, borrower sdk.AccAddress) error { - deposit, found := k.GetDeposit(ctx, borrower) - if !found { - return types.ErrDepositNotFound - } - - borrow, found := k.GetBorrow(ctx, borrower) - if !found { - return types.ErrBorrowNotFound - } - - // Call incentive hooks - k.BeforeDepositModified(ctx, deposit) - k.BeforeBorrowModified(ctx, borrow) - - k.SyncBorrowInterest(ctx, borrower) - k.SyncSupplyInterest(ctx, borrower) - - deposit, found = k.GetDeposit(ctx, borrower) - if !found { - return types.ErrDepositNotFound - } - - borrow, found = k.GetBorrow(ctx, borrower) - if !found { - return types.ErrBorrowNotFound - } - - isWithinRange, err := k.IsWithinValidLtvRange(ctx, deposit, borrow) - if err != nil { - return err - } - if isWithinRange { - return errorsmod.Wrapf(types.ErrBorrowNotLiquidatable, "position is within valid LTV range") - } - - // Sending coins to auction module with keeper address getting % of the profits - borrowDenoms := getDenoms(borrow.Amount) - depositDenoms := getDenoms(deposit.Amount) - err = k.SeizeDeposits(ctx, keeper, deposit, borrow, depositDenoms, borrowDenoms) - if err != nil { - return err - } - - deposit.Amount = sdk.NewCoins() - k.DeleteDeposit(ctx, deposit) - k.AfterDepositModified(ctx, deposit) - - borrow.Amount = sdk.NewCoins() - k.DeleteBorrow(ctx, borrow) - k.AfterBorrowModified(ctx, borrow) - return nil -} - -// SeizeDeposits seizes a list of deposits and sends them to auction -func (k Keeper) SeizeDeposits(ctx sdk.Context, keeper sdk.AccAddress, deposit types.Deposit, - borrow types.Borrow, dDenoms, bDenoms []string, -) error { - liqMap, err := k.LoadLiquidationData(ctx, deposit, borrow) - if err != nil { - return err - } - - // Seize % of every deposit and send to the keeper - keeperRewardCoins := sdk.Coins{} - for _, depCoin := range deposit.Amount { - mm, _ := k.GetMoneyMarket(ctx, depCoin.Denom) - keeperReward := mm.KeeperRewardPercentage.MulInt(depCoin.Amount).TruncateInt() - if keeperReward.GT(sdk.ZeroInt()) { - // Send keeper their reward - keeperCoin := sdk.NewCoin(depCoin.Denom, keeperReward) - keeperRewardCoins = append(keeperRewardCoins, keeperCoin) - } - } - if !keeperRewardCoins.Empty() { - if err := k.DecrementSuppliedCoins(ctx, keeperRewardCoins); err != nil { - return err - } - if err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, keeper, keeperRewardCoins); err != nil { - return err - } - } - - // All deposit amounts not given to keeper as rewards are eligible to be auctioned off - aucDeposits := deposit.Amount.Sub(keeperRewardCoins...) - - // Build valuation map to hold deposit coin USD valuations - depositCoinValues := types.NewValuationMap() - for _, deposit := range aucDeposits { - dData := liqMap[deposit.Denom] - dCoinUsdValue := sdk.NewDecFromInt(deposit.Amount).Quo(sdk.NewDecFromInt(dData.conversionFactor)).Mul(dData.price) - depositCoinValues.Increment(deposit.Denom, dCoinUsdValue) - } - - // Build valuation map to hold borrow coin USD valuations - borrowCoinValues := types.NewValuationMap() - for _, bCoin := range borrow.Amount { - bData := liqMap[bCoin.Denom] - bCoinUsdValue := sdk.NewDecFromInt(bCoin.Amount).Quo(sdk.NewDecFromInt(bData.conversionFactor)).Mul(bData.price) - borrowCoinValues.Increment(bCoin.Denom, bCoinUsdValue) - } - - // Loan-to-Value ratio after sending keeper their reward - depositUsdValue := depositCoinValues.Sum() - if depositUsdValue.IsZero() { - // Deposit value can be zero if params.KeeperRewardPercent is 1.0, or all deposit asset prices are zero. - // In this case the full deposit will be sent to the keeper and no auctions started. - return nil - } - ltv := borrowCoinValues.Sum().Quo(depositUsdValue) - - liquidatedCoins, err := k.StartAuctions(ctx, deposit.Depositor, borrow.Amount, aucDeposits, depositCoinValues, borrowCoinValues, ltv, liqMap) - // If some coins were liquidated and sent to auction prior to error, still need to emit liquidation event - if !liquidatedCoins.Empty() { - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeHardLiquidation, - sdk.NewAttribute(types.AttributeKeyLiquidatedOwner, deposit.Depositor.String()), - sdk.NewAttribute(types.AttributeKeyLiquidatedCoins, liquidatedCoins.String()), - sdk.NewAttribute(types.AttributeKeyKeeper, keeper.String()), - sdk.NewAttribute(types.AttributeKeyKeeperRewardCoins, keeperRewardCoins.String()), - ), - ) - } - // Returns nil if there's no error - return err -} - -// StartAuctions attempts to start auctions for seized assets -func (k Keeper) StartAuctions(ctx sdk.Context, borrower sdk.AccAddress, borrows, deposits sdk.Coins, - depositCoinValues, borrowCoinValues types.ValuationMap, ltv sdk.Dec, liqMap map[string]LiqData, -) (sdk.Coins, error) { - // Sort keys to ensure deterministic behavior - bKeys := borrowCoinValues.GetSortedKeys() - dKeys := depositCoinValues.GetSortedKeys() - - // Set up auction constants - returnAddrs := []sdk.AccAddress{borrower} - weights := []sdkmath.Int{sdkmath.NewInt(100)} - debt := sdk.NewCoin("debt", sdk.ZeroInt()) - - macc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - maccCoins := k.bankKeeper.SpendableCoins(ctx, macc.GetAddress()) - - var liquidatedCoins sdk.Coins - for _, bKey := range bKeys { - bValue := borrowCoinValues.Get(bKey) - maxLotSize := bValue.Quo(ltv) - - for _, dKey := range dKeys { - dValue := depositCoinValues.Get(dKey) - if maxLotSize.Equal(sdk.ZeroDec()) { - break // exit out of the loop if we have cleared the full amount - } - - if dValue.GTE(maxLotSize) { // We can start an auction for the whole borrow amount] - bid := sdk.NewCoin(bKey, borrows.AmountOf(bKey)) - - lotSize := maxLotSize.MulInt(liqMap[dKey].conversionFactor).Quo(liqMap[dKey].price) - if lotSize.TruncateInt().Equal(sdk.ZeroInt()) { - continue - } - lot := sdk.NewCoin(dKey, lotSize.TruncateInt()) - - insufficientLotFunds := false - if lot.Amount.GT(maccCoins.AmountOf(dKey)) { - insufficientLotFunds = true - lot = sdk.NewCoin(lot.Denom, maccCoins.AmountOf(dKey)) - } - - // Sanity check that we can deliver coins to the liquidator account - if deposits.AmountOf(dKey).LT(lot.Amount) { - return liquidatedCoins, types.ErrInsufficientCoins - } - - // Start auction: bid = full borrow amount, lot = maxLotSize - _, err := k.auctionKeeper.StartCollateralAuction(ctx, types.ModuleAccountName, lot, bid, returnAddrs, weights, debt) - if err != nil { - return liquidatedCoins, err - } - // Decrement supplied coins and decrement borrowed coins optimistically - err = k.DecrementSuppliedCoins(ctx, sdk.Coins{lot}) - if err != nil { - return liquidatedCoins, err - } - err = k.DecrementBorrowedCoins(ctx, sdk.Coins{bid}) - if err != nil { - return liquidatedCoins, err - } - - // Add lot to liquidated coins - liquidatedCoins = liquidatedCoins.Add(lot) - - // Update USD valuation maps - borrowCoinValues.SetZero(bKey) - depositCoinValues.Decrement(dKey, maxLotSize) - // Update deposits, borrows - borrows = borrows.Sub(bid) - if insufficientLotFunds { - deposits = deposits.Sub(sdk.NewCoin(dKey, deposits.AmountOf(dKey))) - } else { - deposits = deposits.Sub(lot) - } - // Update max lot size - maxLotSize = sdk.ZeroDec() - } else { // We can only start an auction for the partial borrow amount - maxBid := dValue.Mul(ltv) - bidSize := maxBid.MulInt(liqMap[bKey].conversionFactor).Quo(liqMap[bKey].price) - bid := sdk.NewCoin(bKey, bidSize.TruncateInt()) - lot := sdk.NewCoin(dKey, deposits.AmountOf(dKey)) - - if bid.Amount.Equal(sdk.ZeroInt()) || lot.Amount.Equal(sdk.ZeroInt()) { - continue - } - - insufficientLotFunds := false - if lot.Amount.GT(maccCoins.AmountOf(dKey)) { - insufficientLotFunds = true - lot = sdk.NewCoin(lot.Denom, maccCoins.AmountOf(dKey)) - } - - // Sanity check that we can deliver coins to the liquidator account - if deposits.AmountOf(dKey).LT(lot.Amount) { - return liquidatedCoins, types.ErrInsufficientCoins - } - - // Start auction: bid = maxBid, lot = whole deposit amount - _, err := k.auctionKeeper.StartCollateralAuction(ctx, types.ModuleAccountName, lot, bid, returnAddrs, weights, debt) - if err != nil { - return liquidatedCoins, err - } - // Decrement supplied coins and decrement borrowed coins optimistically - err = k.DecrementSuppliedCoins(ctx, sdk.Coins{lot}) - if err != nil { - return liquidatedCoins, err - } - err = k.DecrementBorrowedCoins(ctx, sdk.Coins{bid}) - if err != nil { - return liquidatedCoins, err - } - - // Add lot to liquidated coins - liquidatedCoins = liquidatedCoins.Add(lot) - - // Update variables to account for partial auction - borrowCoinValues.Decrement(bKey, maxBid) - depositCoinValues.SetZero(dKey) - - borrows = borrows.Sub(bid) - if insufficientLotFunds { - deposits = deposits.Sub(sdk.NewCoin(dKey, deposits.AmountOf(dKey))) - } else { - deposits = deposits.Sub(lot) - } - - // Update max lot size - maxLotSize = borrowCoinValues.Get(bKey).Quo(ltv) - } - } - } - - // Send any remaining deposit back to the original borrower - for _, dKey := range dKeys { - remaining := deposits.AmountOf(dKey) - if remaining.GT(sdk.ZeroInt()) { - returnCoin := sdk.NewCoins(sdk.NewCoin(dKey, remaining)) - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, borrower, returnCoin) - if err != nil { - return liquidatedCoins, err - } - } - } - - return liquidatedCoins, nil -} - -// IsWithinValidLtvRange compares a borrow and deposit to see if it's within a valid LTV range at current prices -func (k Keeper) IsWithinValidLtvRange(ctx sdk.Context, deposit types.Deposit, borrow types.Borrow) (bool, error) { - liqMap, err := k.LoadLiquidationData(ctx, deposit, borrow) - if err != nil { - return false, err - } - - totalBorrowableUSDAmount := sdk.ZeroDec() - for _, depCoin := range deposit.Amount { - lData := liqMap[depCoin.Denom] - usdValue := sdk.NewDecFromInt(depCoin.Amount).Quo(sdk.NewDecFromInt(lData.conversionFactor)).Mul(lData.price) - borrowableUSDAmountForDeposit := usdValue.Mul(lData.ltv) - totalBorrowableUSDAmount = totalBorrowableUSDAmount.Add(borrowableUSDAmountForDeposit) - } - - totalBorrowedUSDAmount := sdk.ZeroDec() - for _, coin := range borrow.Amount { - lData := liqMap[coin.Denom] - usdValue := sdk.NewDecFromInt(coin.Amount).Quo(sdk.NewDecFromInt(lData.conversionFactor)).Mul(lData.price) - totalBorrowedUSDAmount = totalBorrowedUSDAmount.Add(usdValue) - } - - // Check if the user's has borrowed more than they're allowed to - if totalBorrowedUSDAmount.GT(totalBorrowableUSDAmount) { - return false, nil - } - - return true, nil -} - -// GetStoreLTV calculates the user's current LTV based on their deposits/borrows in the store -// and does not include any outsanding interest. -func (k Keeper) GetStoreLTV(ctx sdk.Context, addr sdk.AccAddress) (sdk.Dec, error) { - // Fetch deposits and parse coin denoms - deposit, found := k.GetDeposit(ctx, addr) - if !found { - return sdk.ZeroDec(), nil - } - - // Fetch borrow balances and parse coin denoms - borrow, found := k.GetBorrow(ctx, addr) - if !found { - return sdk.ZeroDec(), nil - } - - return k.CalculateLtv(ctx, deposit, borrow) -} - -// CalculateLtv calculates the potential LTV given a user's deposits and borrows. -// The boolean returned indicates if the LTV should be added to the store's LTV index. -func (k Keeper) CalculateLtv(ctx sdk.Context, deposit types.Deposit, borrow types.Borrow) (sdk.Dec, error) { - // Load required liquidation data for every deposit/borrow denom - liqMap, err := k.LoadLiquidationData(ctx, deposit, borrow) - if err != nil { - return sdk.ZeroDec(), nil - } - - // Build valuation map to hold deposit coin USD valuations - depositCoinValues := types.NewValuationMap() - for _, depCoin := range deposit.Amount { - dData := liqMap[depCoin.Denom] - dCoinUsdValue := sdk.NewDecFromInt(depCoin.Amount).Quo(sdk.NewDecFromInt(dData.conversionFactor)).Mul(dData.price) - depositCoinValues.Increment(depCoin.Denom, dCoinUsdValue) - } - - // Build valuation map to hold borrow coin USD valuations - borrowCoinValues := types.NewValuationMap() - for _, bCoin := range borrow.Amount { - bData := liqMap[bCoin.Denom] - bCoinUsdValue := sdk.NewDecFromInt(bCoin.Amount).Quo(sdk.NewDecFromInt(bData.conversionFactor)).Mul(bData.price) - borrowCoinValues.Increment(bCoin.Denom, bCoinUsdValue) - } - - // User doesn't have any deposits, catch divide by 0 error - sumDeposits := depositCoinValues.Sum() - if sumDeposits.Equal(sdk.ZeroDec()) { - return sdk.ZeroDec(), nil - } - - // Loan-to-Value ratio - return borrowCoinValues.Sum().Quo(sumDeposits), nil -} - -// LoadLiquidationData returns liquidation data, deposit, borrow -func (k Keeper) LoadLiquidationData(ctx sdk.Context, deposit types.Deposit, borrow types.Borrow) (map[string]LiqData, error) { - liqMap := make(map[string]LiqData) - - borrowDenoms := getDenoms(borrow.Amount) - depositDenoms := getDenoms(deposit.Amount) - denoms := removeDuplicates(borrowDenoms, depositDenoms) - - // Load required liquidation data for every deposit/borrow denom - for _, denom := range denoms { - mm, found := k.GetMoneyMarket(ctx, denom) - if !found { - return liqMap, errorsmod.Wrapf(types.ErrMarketNotFound, "no market found for denom %s", denom) - } - - priceData, err := k.pricefeedKeeper.GetCurrentPrice(ctx, mm.SpotMarketID) - if err != nil { - return liqMap, err - } - - liqMap[denom] = LiqData{priceData.Price, mm.BorrowLimit.LoanToValue, mm.ConversionFactor} - } - - return liqMap, nil -} - -func getDenoms(coins sdk.Coins) []string { - denoms := []string{} - for _, coin := range coins { - denoms = append(denoms, coin.Denom) - } - return denoms -} - -func removeDuplicates(one []string, two []string) []string { - check := make(map[string]int) - fullList := append(one, two...) - - res := []string{} - for _, val := range fullList { - check[val] = 1 - } - - for key := range check { - res = append(res, key) - } - sort.Strings(res) - return res -} diff --git a/x/hard/keeper/liquidation_test.go b/x/hard/keeper/liquidation_test.go deleted file mode 100644 index d9c3fe33..00000000 --- a/x/hard/keeper/liquidation_test.go +++ /dev/null @@ -1,765 +0,0 @@ -package keeper_test - -import ( - "strings" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - auctiontypes "github.com/kava-labs/kava/x/auction/types" - "github.com/kava-labs/kava/x/hard" - "github.com/kava-labs/kava/x/hard/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -func (suite *KeeperTestSuite) TestKeeperLiquidation() { - type args struct { - borrower sdk.AccAddress - keeper sdk.AccAddress - keeperRewardPercent sdk.Dec - initialModuleCoins sdk.Coins - initialBorrowerCoins sdk.Coins - initialKeeperCoins sdk.Coins - depositCoins []sdk.Coin - borrowCoins sdk.Coins - liquidateAfter time.Duration - expectedTotalSuppliedCoins sdk.Coins - expectedTotalBorrowedCoins sdk.Coins - expectedKeeperCoins sdk.Coins // coins keeper address should have after successfully liquidating position - expectedBorrowerCoins sdk.Coins // additional coins (if any) the borrower address should have after successfully liquidating position - expectedAuctions []auctiontypes.Auction // the auctions we should expect to find have been started - } - - type errArgs struct { - expectPass bool - contains string - } - - type liqTest struct { - name string - args args - errArgs errArgs - } - - // Set up test constants - model := types.NewInterestRateModel(sdk.MustNewDecFromStr("0"), sdk.MustNewDecFromStr("0.1"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("0.5")) - reserveFactor := sdk.MustNewDecFromStr("0.05") - oneMonthDur := time.Second * 30 * 24 * 3600 - borrower := sdk.AccAddress(crypto.AddressHash([]byte("testborrower"))) - keeper := sdk.AccAddress(crypto.AddressHash([]byte("testkeeper"))) - - // Set up auction constants - layout := "2006-01-02T15:04:05.000Z" - endTimeStr := "9000-01-01T00:00:00.000Z" - endTime, _ := time.Parse(layout, endTimeStr) - - lotReturns, _ := auctiontypes.NewWeightedAddresses([]sdk.AccAddress{borrower}, []sdkmath.Int{sdkmath.NewInt(100)}) - - testCases := []liqTest{ - { - "valid: keeper liquidates borrow", - args{ - borrower: borrower, - keeper: keeper, - keeperRewardPercent: sdk.MustNewDecFromStr("0.05"), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(8*KAVA_CF))), - liquidateAfter: oneMonthDur, - expectedTotalSuppliedCoins: sdk.NewCoins(sdk.NewInt64Coin("ukava", 100004118)), - expectedTotalBorrowedCoins: nil, - expectedKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100500020))), - expectedBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(98000001))), // initial - deposit + borrow + liquidation leftovers - expectedAuctions: []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "hard", - Lot: sdk.NewInt64Coin("ukava", 9500390), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("ukava", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("ukava", 8004766), - LotReturns: lotReturns, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid: 0% keeper rewards", - args{ - borrower: borrower, - keeper: keeper, - keeperRewardPercent: sdk.MustNewDecFromStr("0.0"), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(8*KAVA_CF))), - liquidateAfter: oneMonthDur, - expectedTotalSuppliedCoins: sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_004_117)), - expectedTotalBorrowedCoins: sdk.NewCoins(sdk.NewInt64Coin("ukava", 1)), - expectedKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - expectedBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(98*KAVA_CF))), // initial - deposit + borrow + liquidation leftovers - expectedAuctions: []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "hard", - Lot: sdk.NewInt64Coin("ukava", 10000411), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("ukava", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("ukava", 8004765), - LotReturns: lotReturns, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid: 100% keeper reward", - args{ - borrower: borrower, - keeper: keeper, - keeperRewardPercent: sdk.MustNewDecFromStr("1.0"), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(8*KAVA_CF))), - liquidateAfter: oneMonthDur, - expectedTotalSuppliedCoins: sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_004_117)), - expectedTotalBorrowedCoins: sdk.NewCoins(sdk.NewInt64Coin("ukava", 8_004_766)), - expectedKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(110_000_411))), - expectedBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(98*KAVA_CF))), // initial - deposit + borrow + liquidation leftovers - expectedAuctions: nil, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid: single deposit, multiple borrows", - args{ - borrower: borrower, - keeper: keeper, - keeperRewardPercent: sdk.MustNewDecFromStr("0.05"), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(1000*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(1000*BTCB_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), // $100 * 0.8 = $80 borrowable - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdc", sdkmath.NewInt(20*KAVA_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(2*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(0.2*BTCB_CF))), // $20+$20+$20 = $80 borrowed - liquidateAfter: oneMonthDur, - expectedTotalSuppliedCoins: sdk.NewCoins( - sdk.NewInt64Coin("ukava", 1000000710), - sdk.NewInt64Coin("usdc", 1000003120), - sdk.NewInt64Coin("bnb", 100000003123), - sdk.NewInt64Coin("btc", 100000000031), - ), - expectedTotalBorrowedCoins: nil, - expectedKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(102500001))), - expectedBorrowerCoins: sdk.NewCoins(sdk.NewCoin("usdc", sdkmath.NewInt(20*KAVA_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(60000002)), sdk.NewCoin("bnb", sdkmath.NewInt(2*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(0.2*BTCB_CF))), // initial - deposit + borrow + liquidation leftovers - expectedAuctions: []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "hard", - Lot: sdk.NewInt64Coin("ukava", 11874430), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("bnb", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("bnb", 200003287), - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 2, - Initiator: "hard", - Lot: sdk.NewInt64Coin("ukava", 11874254), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("btc", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("btc", 20000032), - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 3, - Initiator: "hard", - Lot: sdk.NewInt64Coin("ukava", 11875163), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("ukava", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("ukava", 10000782), - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 4, - Initiator: "hard", - Lot: sdk.NewInt64Coin("ukava", 11876185), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("usdc", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("usdc", 20003284), - LotReturns: lotReturns, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid: multiple deposits, single borrow", - args{ - borrower: borrower, - keeper: keeper, - keeperRewardPercent: sdk.MustNewDecFromStr("0.05"), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(100*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(100*BTCB_CF))), - initialKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(10*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(1*BTCB_CF))), // $100 + $100 + $100 = $300 * 0.8 = $240 borrowable // $100 * 0.8 = $80 borrowable - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(120*KAVA_CF))), // $240 borrowed - liquidateAfter: oneMonthDur, - expectedTotalSuppliedCoins: sdk.NewCoins( - sdk.NewInt64Coin("ukava", 1000101456), - ), - expectedTotalBorrowedCoins: nil, - expectedKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(102500253)), sdk.NewCoin("bnb", sdkmath.NewInt(0.5*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(0.05*BTCB_CF))), // 5% of each seized coin + initial balances - expectedBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(170.000001*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(90*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(99*BTCB_CF))), - expectedAuctions: []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "hard", - Lot: sdk.NewInt64Coin("bnb", 950000000), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("ukava", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("ukava", 40036023), - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 2, - Initiator: "hard", - Lot: sdk.NewInt64Coin("btc", 95000000), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("ukava", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("ukava", 40036023), - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 3, - Initiator: "hard", - Lot: sdk.NewInt64Coin("ukava", 47504818), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("ukava", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("ukava", 40040087), - LotReturns: lotReturns, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid: multiple stablecoin deposits, multiple variable coin borrows", - // Auctions: total lot value = $285 ($300 of deposits - $15 keeper reward), total max bid value = $270 - args{ - borrower: borrower, - keeper: keeper, - keeperRewardPercent: sdk.MustNewDecFromStr("0.05"), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(1000*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(1000*BTCB_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("usdt", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(100*KAVA_CF))), - initialKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("usdc", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("usdt", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(100*KAVA_CF))), // $100 + $100 + $100 = $300 * 0.9 = $270 borrowable - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(35*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(10*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(1*BTCB_CF))), // $270 borrowed - liquidateAfter: oneMonthDur, - expectedTotalSuppliedCoins: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100000078047), - sdk.NewInt64Coin("btc", 100000000780), - sdk.NewInt64Coin("ukava", 1000009550), - sdk.NewInt64Coin("usdx", 1), - ), - expectedTotalBorrowedCoins: nil, - expectedKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(5*KAVA_CF)), sdk.NewCoin("usdt", sdkmath.NewInt(5*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(5*KAVA_CF))), // 5% of each seized coin + initial balances - expectedBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(135*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(10*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(1*BTCB_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(0.000001*KAVA_CF))), - expectedAuctions: []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "hard", - Lot: sdk.NewInt64Coin("usdc", 95000000), // $95.00 - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("bnb", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("bnb", 900097134), // $90.00 - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 2, - Initiator: "hard", - Lot: sdk.NewInt64Coin("usdt", 10552835), // $10.55 - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("bnb", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("bnb", 99985020), // $10.00 - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 3, - Initiator: "hard", - Lot: sdk.NewInt64Coin("usdt", 84447165), // $84.45 - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("btc", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("btc", 80011211), // $80.01 - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 4, - Initiator: "hard", - Lot: sdk.NewInt64Coin("usdx", 21097866), // $21.10 - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("btc", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("btc", 19989610), // $19.99 - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 5, - Initiator: "hard", - Lot: sdk.NewInt64Coin("usdx", 73902133), //$73.90 - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("ukava", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("ukava", 35010052), // $70.02 - LotReturns: lotReturns, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid: multiple stablecoin deposits, multiple stablecoin borrows", - args{ - borrower: borrower, - keeper: keeper, - keeperRewardPercent: sdk.MustNewDecFromStr("0.05"), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdt", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("dai", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(1000*KAVA_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdt", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("dai", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(1000*KAVA_CF))), - initialKeeperCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdt", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("dai", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("dai", sdkmath.NewInt(350*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(200*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdt", sdkmath.NewInt(250*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(245*KAVA_CF))), - liquidateAfter: oneMonthDur, - expectedTotalSuppliedCoins: sdk.NewCoins( - sdk.NewInt64Coin("dai", 1000000000), - sdk.NewInt64Coin("usdc", 1000000001), - sdk.NewInt64Coin("usdt", 1000482503), - sdk.NewInt64Coin("usdx", 1000463500), - ), - expectedTotalBorrowedCoins: nil, - expectedKeeperCoins: sdk.NewCoins(sdk.NewCoin("dai", sdkmath.NewInt(1017.50*KAVA_CF)), sdk.NewCoin("usdt", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(1010*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*KAVA_CF))), - expectedBorrowerCoins: sdk.NewCoins(sdk.NewCoin("dai", sdkmath.NewInt(650*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(800000001)), sdk.NewCoin("usdt", sdkmath.NewInt(1250*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1245*KAVA_CF))), - expectedAuctions: []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "hard", - Lot: sdk.NewInt64Coin("dai", 263894126), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("usdt", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("usdt", 250507897), - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 2, - Initiator: "hard", - Lot: sdk.NewInt64Coin("dai", 68605874), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("usdx", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("usdx", 65125788), - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 3, - Initiator: "hard", - Lot: sdk.NewInt64Coin("usdc", 189999999), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("usdx", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("usdx", 180362106), - LotReturns: lotReturns, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid: borrow not liquidatable", - args{ - borrower: borrower, - keeper: keeper, - keeperRewardPercent: sdk.MustNewDecFromStr("0.05"), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), // Deposit 20 KAVA - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(5*KAVA_CF))), // Borrow 5 KAVA - liquidateAfter: oneMonthDur, - expectedTotalSuppliedCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(120001624))), - expectedTotalBorrowedCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(5001709))), - expectedKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100.5*KAVA_CF))), - expectedBorrowerCoins: sdk.NewCoins(), - expectedAuctions: []auctiontypes.Auction{}, - }, - errArgs{ - expectPass: false, - contains: "borrow not liquidatable", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC)}) - - // account which will deposit "initial module account coins" - depositor := sdk.AccAddress(crypto.AddressHash([]byte("testdepositor"))) - - // Auth module genesis state - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{ - tc.args.initialBorrowerCoins, - tc.args.initialKeeperCoins, - tc.args.initialModuleCoins, - }, - []sdk.AccAddress{ - tc.args.borrower, - tc.args.keeper, - depositor, - }, - ) - - // Hard module genesis state - hardGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("usdx", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.9")), // Borrow Limit - "usdx:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - tc.args.keeperRewardPercent), // Keeper Reward Percent - types.NewMoneyMarket("usdt", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.9")), // Borrow Limit - "usdt:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - tc.args.keeperRewardPercent), // Keeper Reward Percent - types.NewMoneyMarket("usdc", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.9")), // Borrow Limit - "usdc:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - tc.args.keeperRewardPercent), // Keeper Reward Percent - types.NewMoneyMarket("dai", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.9")), // Borrow Limit - "dai:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - tc.args.keeperRewardPercent), // Keeper Reward Percent - types.NewMoneyMarket("ukava", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "kava:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - tc.args.keeperRewardPercent), // Keeper Reward Percent - types.NewMoneyMarket("bnb", - types.NewBorrowLimit(false, sdk.NewDec(100000000*BNB_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "bnb:usd", // Market ID - sdkmath.NewInt(BNB_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - tc.args.keeperRewardPercent), // Keeper Reward Percent - types.NewMoneyMarket("btc", - types.NewBorrowLimit(false, sdk.NewDec(100000000*BTCB_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "btc:usd", // Market ID - sdkmath.NewInt(BTCB_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - tc.args.keeperRewardPercent), // Keeper Reward Percent - }, - sdk.NewDec(10), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "usdt:usd", BaseAsset: "usdt", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "usdc:usd", BaseAsset: "usdc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "dai:usd", BaseAsset: "dai", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "btc:usd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "usdt:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "usdc:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "dai:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("10.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "btc:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("100.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - }, - } - - // Initialize test application - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}) - - keeper := tApp.GetHardKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - suite.auctionKeeper = tApp.GetAuctionKeeper() - - var err error - - // Run begin blocker to set up state - hard.BeginBlocker(suite.ctx, suite.keeper) - - // Deposit initial module account coins - err = suite.keeper.Deposit(suite.ctx, depositor, tc.args.initialModuleCoins) - suite.Require().NoError(err) - - // Deposit coins - err = suite.keeper.Deposit(suite.ctx, tc.args.borrower, tc.args.depositCoins) - suite.Require().NoError(err) - - // Borrow coins - err = suite.keeper.Borrow(suite.ctx, tc.args.borrower, tc.args.borrowCoins) - suite.Require().NoError(err) - - // Set up liquidation chain context and run begin blocker - runAtTime := suite.ctx.BlockTime().Add(tc.args.liquidateAfter) - liqCtx := suite.ctx.WithBlockTime(runAtTime) - hard.BeginBlocker(liqCtx, suite.keeper) - - // Check borrow exists before liquidation - _, foundBorrowBefore := suite.keeper.GetBorrow(liqCtx, tc.args.borrower) - suite.Require().True(foundBorrowBefore) - // Check that the user's deposit exists before liquidation - _, foundDepositBefore := suite.keeper.GetDeposit(liqCtx, tc.args.borrower) - suite.Require().True(foundDepositBefore) - - // Fetch supplied and borrowed coins pre-liquidation - suppliedCoinsPre, foundSuppliedCoinsPre := suite.keeper.GetSuppliedCoins(liqCtx) - suite.Require().True(foundSuppliedCoinsPre) - borrowedCoinsPre, foundBorrowedCoinsPre := suite.keeper.GetBorrowedCoins(liqCtx) - suite.Require().True(foundBorrowedCoinsPre) - - // Attempt to liquidate - err = suite.keeper.AttemptKeeperLiquidation(liqCtx, tc.args.keeper, tc.args.borrower) - if tc.errArgs.expectPass { - suite.Require().NoError(err) - - // Check borrow does not exist after liquidation - _, foundBorrowAfter := suite.keeper.GetBorrow(liqCtx, tc.args.borrower) - suite.Require().False(foundBorrowAfter) - // Check deposits do not exist after liquidation - _, foundDepositAfter := suite.keeper.GetDeposit(liqCtx, tc.args.borrower) - suite.Require().False(foundDepositAfter) - - // Check that the keeper's balance increased by reward % of all the borrowed coins - accKeeper := suite.getAccountAtCtx(tc.args.keeper, liqCtx) - suite.Require().Equal(tc.args.expectedKeeperCoins, suite.getAccountCoins(accKeeper)) - - // Check that borrower's balance contains the expected coins - accBorrower := suite.getAccountAtCtx(tc.args.borrower, liqCtx) - suite.Require().Equal(tc.args.expectedBorrowerCoins, suite.getAccountCoins(accBorrower)) - - // Check that the expected auctions have been created - auctions := suite.auctionKeeper.GetAllAuctions(liqCtx) - suite.Require().Equal(tc.args.expectedAuctions, auctions) - - // Check that supplied and borrowed coins have been updated post-liquidation - suppliedCoinsPost, _ := suite.keeper.GetSuppliedCoins(liqCtx) - suite.Require().Equal(tc.args.expectedTotalSuppliedCoins, suppliedCoinsPost) - borrowedCoinsPost, _ := suite.keeper.GetBorrowedCoins(liqCtx) - suite.Require().True(tc.args.expectedTotalBorrowedCoins.IsEqual(borrowedCoinsPost)) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - - // Check that the user's borrow exists - _, foundBorrowAfter := suite.keeper.GetBorrow(liqCtx, tc.args.borrower) - suite.Require().True(foundBorrowAfter) - // Check that the user's deposits exist - _, foundDepositAfter := suite.keeper.GetDeposit(liqCtx, tc.args.borrower) - suite.Require().True(foundDepositAfter) - - // Check that no auctions have been created - auctions := suite.auctionKeeper.GetAllAuctions(liqCtx) - suite.Require().True(len(auctions) == 0) - - // Check that supplied and borrowed coins have not been updated post-liquidation - suite.Require().Equal(tc.args.expectedTotalSuppliedCoins, suppliedCoinsPre) - suite.Require().True(tc.args.expectedTotalBorrowedCoins.IsEqual(borrowedCoinsPre)) - } - }) - } -} diff --git a/x/hard/keeper/msg_server.go b/x/hard/keeper/msg_server.go deleted file mode 100644 index 80c0dd5b..00000000 --- a/x/hard/keeper/msg_server.go +++ /dev/null @@ -1,146 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/hard/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the hard MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -func (k msgServer) Deposit(goCtx context.Context, msg *types.MsgDeposit) (*types.MsgDepositResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - - err = k.keeper.Deposit(ctx, depositor, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Depositor), - ), - ) - return &types.MsgDepositResponse{}, nil -} - -func (k msgServer) Withdraw(goCtx context.Context, msg *types.MsgWithdraw) (*types.MsgWithdrawResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - - err = k.keeper.Withdraw(ctx, depositor, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Depositor), - ), - ) - return &types.MsgWithdrawResponse{}, nil -} - -func (k msgServer) Borrow(goCtx context.Context, msg *types.MsgBorrow) (*types.MsgBorrowResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - borrower, err := sdk.AccAddressFromBech32(msg.Borrower) - if err != nil { - return nil, err - } - - err = k.keeper.Borrow(ctx, borrower, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Borrower), - ), - ) - return &types.MsgBorrowResponse{}, nil -} - -func (k msgServer) Repay(goCtx context.Context, msg *types.MsgRepay) (*types.MsgRepayResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - owner, err := sdk.AccAddressFromBech32(msg.Owner) - if err != nil { - return nil, err - } - - err = k.keeper.Repay(ctx, sender, owner, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - ), - ) - return &types.MsgRepayResponse{}, nil -} - -func (k msgServer) Liquidate(goCtx context.Context, msg *types.MsgLiquidate) (*types.MsgLiquidateResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - keeper, err := sdk.AccAddressFromBech32(msg.Keeper) - if err != nil { - return nil, err - } - - borrower, err := sdk.AccAddressFromBech32(msg.Borrower) - if err != nil { - return nil, err - } - - err = k.keeper.AttemptKeeperLiquidation(ctx, keeper, borrower) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Keeper), - ), - ) - return &types.MsgLiquidateResponse{}, nil -} diff --git a/x/hard/keeper/params.go b/x/hard/keeper/params.go deleted file mode 100644 index 8bcd339c..00000000 --- a/x/hard/keeper/params.go +++ /dev/null @@ -1,25 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/hard/types" -) - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - var p types.Params - k.paramSubspace.GetParamSet(ctx, &p) - return p -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} - -// GetMinimumBorrowUSDValue returns the minimum borrow USD value -func (k Keeper) GetMinimumBorrowUSDValue(ctx sdk.Context) sdk.Dec { - params := k.GetParams(ctx) - return params.MinimumBorrowUSDValue -} diff --git a/x/hard/keeper/repay.go b/x/hard/keeper/repay.go deleted file mode 100644 index 454812fd..00000000 --- a/x/hard/keeper/repay.go +++ /dev/null @@ -1,170 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/hard/types" -) - -// Repay borrowed funds -func (k Keeper) Repay(ctx sdk.Context, sender, owner sdk.AccAddress, coins sdk.Coins) error { - // Check borrow exists here to avoid duplicating store read in ValidateRepay - borrow, found := k.GetBorrow(ctx, owner) - if !found { - return types.ErrBorrowNotFound - } - // Call incentive hook - k.BeforeBorrowModified(ctx, borrow) - - // Sync borrow interest so loan is up-to-date - k.SyncBorrowInterest(ctx, owner) - - // Refresh borrow after syncing interest - borrow, _ = k.GetBorrow(ctx, owner) - - // cap the repayment by what's available to repay (the borrow amount) - payment, err := k.CalculatePaymentAmount(borrow.Amount, coins) - if err != nil { - return err - } - // Validate that sender holds coins for repayment - err = k.ValidateRepay(ctx, sender, owner, payment) - if err != nil { - return err - } - - // Sends coins from user to Hard module account - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleAccountName, payment) - if err != nil { - return err - } - - // If any coin denoms have been completely repaid reset the denom's borrow index factor - for _, coin := range payment { - if coin.Amount.Equal(borrow.Amount.AmountOf(coin.Denom)) { - borrowIndex, removed := borrow.Index.RemoveInterestFactor(coin.Denom) - if !removed { - return errorsmod.Wrapf(types.ErrInvalidIndexFactorDenom, "%s", coin.Denom) - } - borrow.Index = borrowIndex - } - } - - // Update user's borrow in store - borrow.Amount = borrow.Amount.Sub(payment...) - - if borrow.Amount.Empty() { - k.DeleteBorrow(ctx, borrow) - } else { - k.SetBorrow(ctx, borrow) - } - - // Update total borrowed amount - err = k.DecrementBorrowedCoins(ctx, payment) - if err != nil { - return err - } - - // Call incentive hook - k.AfterBorrowModified(ctx, borrow) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeHardRepay, - sdk.NewAttribute(types.AttributeKeySender, sender.String()), - sdk.NewAttribute(types.AttributeKeyOwner, owner.String()), - sdk.NewAttribute(types.AttributeKeyRepayCoins, payment.String()), - ), - ) - - return nil -} - -// ValidateRepay validates a requested loan repay -func (k Keeper) ValidateRepay(ctx sdk.Context, sender, owner sdk.AccAddress, coins sdk.Coins) error { - assetPriceCache := map[string]sdk.Dec{} - - // Get the total USD value of user's existing borrows - existingBorrowUSDValue := sdk.ZeroDec() - existingBorrow, found := k.GetBorrow(ctx, owner) - if found { - for _, coin := range existingBorrow.Amount { - moneyMarket, found := k.GetMoneyMarket(ctx, coin.Denom) - if !found { - return errorsmod.Wrapf(types.ErrMarketNotFound, "no money market found for denom %s", coin.Denom) - } - - assetPrice, ok := assetPriceCache[coin.Denom] - if !ok { // Fetch current asset price and store in local cache - assetPriceInfo, err := k.pricefeedKeeper.GetCurrentPrice(ctx, moneyMarket.SpotMarketID) - if err != nil { - return errorsmod.Wrapf(types.ErrPriceNotFound, "no price found for market %s", moneyMarket.SpotMarketID) - } - assetPriceCache[coin.Denom] = assetPriceInfo.Price - assetPrice = assetPriceInfo.Price - } - - // Calculate this borrow coin's USD value and add it to the total previous borrowed USD value - coinUSDValue := sdk.NewDecFromInt(coin.Amount).Quo(sdk.NewDecFromInt(moneyMarket.ConversionFactor)).Mul(assetPrice) - existingBorrowUSDValue = existingBorrowUSDValue.Add(coinUSDValue) - } - } - - senderCoins := k.bankKeeper.SpendableCoins(ctx, sender) - repayTotalUSDValue := sdk.ZeroDec() - for _, repayCoin := range coins { - // Check that sender holds enough tokens to make the proposed payment - if senderCoins.AmountOf(repayCoin.Denom).LT(repayCoin.Amount) { - return errorsmod.Wrapf(types.ErrInsufficientBalanceForRepay, "account can only repay up to %s%s", senderCoins.AmountOf(repayCoin.Denom), repayCoin.Denom) - } - - moneyMarket, found := k.GetMoneyMarket(ctx, repayCoin.Denom) - if !found { - return errorsmod.Wrapf(types.ErrMarketNotFound, "no money market found for denom %s", repayCoin.Denom) - } - - // Calculate this coin's USD value and add it to the repay's total USD value - assetPrice, ok := assetPriceCache[repayCoin.Denom] - if !ok { // Fetch current asset price and store in local cache - assetPriceInfo, err := k.pricefeedKeeper.GetCurrentPrice(ctx, moneyMarket.SpotMarketID) - if err != nil { - return errorsmod.Wrapf(types.ErrPriceNotFound, "no price found for market %s", moneyMarket.SpotMarketID) - } - assetPriceCache[repayCoin.Denom] = assetPriceInfo.Price - assetPrice = assetPriceInfo.Price - } - coinUSDValue := sdk.NewDecFromInt(repayCoin.Amount).Quo(sdk.NewDecFromInt(moneyMarket.ConversionFactor)).Mul(assetPrice) - repayTotalUSDValue = repayTotalUSDValue.Add(coinUSDValue) - } - - // If the proposed repayment would results in a borrowed USD value below the minimum borrow USD value, reject it. - // User can overpay their loan to close it out, but underpaying by such a margin that the USD value is in an - // invalid range is not allowed - // Unless the user is fully repaying their loan - proposedBorrowNewUSDValue := existingBorrowUSDValue.Sub(repayTotalUSDValue) - isFullRepayment := coins.IsEqual(existingBorrow.Amount) - if proposedBorrowNewUSDValue.LT(k.GetMinimumBorrowUSDValue(ctx)) && !isFullRepayment { - return errorsmod.Wrapf(types.ErrBelowMinimumBorrowValue, "the proposed borrow's USD value $%s is below the minimum borrow limit $%s", proposedBorrowNewUSDValue, k.GetMinimumBorrowUSDValue(ctx)) - } - - return nil -} - -// CalculatePaymentAmount prevents overpayment when repaying borrowed coins -func (k Keeper) CalculatePaymentAmount(owed sdk.Coins, payment sdk.Coins) (sdk.Coins, error) { - repayment := sdk.Coins{} - - if !payment.DenomsSubsetOf(owed) { - return repayment, types.ErrInvalidRepaymentDenom - } - - for _, coin := range payment { - if coin.Amount.GT(owed.AmountOf(coin.Denom)) { - repayment = append(repayment, sdk.NewCoin(coin.Denom, owed.AmountOf(coin.Denom))) - } else { - repayment = append(repayment, coin) - } - } - return repayment, nil -} diff --git a/x/hard/keeper/repay_test.go b/x/hard/keeper/repay_test.go deleted file mode 100644 index 9d9e9e39..00000000 --- a/x/hard/keeper/repay_test.go +++ /dev/null @@ -1,366 +0,0 @@ -package keeper_test - -import ( - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/hard" - "github.com/kava-labs/kava/x/hard/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -func (suite *KeeperTestSuite) TestRepay() { - type args struct { - borrower sdk.AccAddress - repayer sdk.AccAddress - initialBorrowerCoins sdk.Coins - initialRepayerCoins sdk.Coins - initialModuleCoins sdk.Coins - depositCoins []sdk.Coin - borrowCoins sdk.Coins - repayCoins sdk.Coins - } - - type errArgs struct { - expectPass bool - expectDelete bool - contains string - } - - type borrowTest struct { - name string - args args - errArgs errArgs - } - - model := types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")) - - testCases := []borrowTest{ - { - "valid: partial repay", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - repayCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF))), - }, - errArgs{ - expectPass: true, - expectDelete: false, - contains: "", - }, - }, - { - "valid: partial repay by non borrower", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("repayer"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - repayCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF))), - }, - errArgs{ - expectPass: true, - expectDelete: false, - contains: "", - }, - }, - { - "valid: repay in full", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - repayCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - }, - errArgs{ - expectPass: true, - expectDelete: true, - contains: "", - }, - }, - { - "valid: overpayment is adjusted", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(80*KAVA_CF))), // Deposit less so user still has some KAVA - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - repayCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(60*KAVA_CF))), // Exceeds borrowed coins but not user's balance - }, - errArgs{ - expectPass: true, - expectDelete: true, - contains: "", - }, - }, - { - "invalid: attempt to repay non-supplied coin", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - repayCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(10*KAVA_CF))), - }, - errArgs{ - expectPass: false, - expectDelete: false, - contains: "no coins of this type borrowed", - }, - }, - { - "invalid: insufficient balance for repay", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("repayer"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(49*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - repayCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), // Exceeds repayer's balance, but not borrow amount - }, - errArgs{ - expectPass: false, - expectDelete: false, - contains: "account can only repay up to 49000000ukava", - }, - }, - { - "invalid: repaying a single coin type results in borrow position below the minimum USD value", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(50*USDX_CF))), - repayCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(45*USDX_CF))), - }, - errArgs{ - expectPass: false, - expectDelete: false, - contains: "proposed borrow's USD value $5.000000000000000000 is below the minimum borrow limit", - }, - }, - { - "invalid: repaying multiple coin types results in borrow position below the minimum USD value", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(50*USDX_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF))), // (50*$1)+(10*$2) = $70 - repayCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(45*USDX_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(8*KAVA_CF))), // (45*$1)+(8*$2) = $61 - }, - errArgs{ - expectPass: false, - expectDelete: false, - contains: "proposed borrow's USD value $9.000000000000000000 is below the minimum borrow limit", - }, - }, - { - "invalid: overpaying multiple coin types results in borrow position below the minimum USD value", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(50*USDX_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF))), // (50*$1)+(10*$2) = $70 - repayCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(500*USDX_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(8*KAVA_CF))), // (500*$1)+(8*$2) = $516, or capping to borrowed amount, (50*$1)+(8*$2) = $66 - }, - errArgs{ - expectPass: false, - expectDelete: false, - contains: "proposed borrow's USD value $4.000000000000000000 is below the minimum borrow limit", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - // Auth module genesis state - addrs, coinses := uniqueAddressCoins( - []sdk.AccAddress{tc.args.borrower, tc.args.repayer}, - []sdk.Coins{tc.args.initialBorrowerCoins, tc.args.initialRepayerCoins}, - ) - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - coinses, - addrs, - ) - - // Hard module genesis state - hardGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("usdx", - types.NewBorrowLimit(false, sdk.NewDec(100000000*USDX_CF), sdk.MustNewDecFromStr("1")), // Borrow Limit - "usdx:usd", // Market ID - sdkmath.NewInt(USDX_CF), // Conversion Factor - model, // Interest Rate Model - sdk.MustNewDecFromStr("0.05"), // Reserve Factor - sdk.MustNewDecFromStr("0.05")), // Keeper Reward Percent - types.NewMoneyMarket("ukava", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "kava:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - sdk.MustNewDecFromStr("0.05"), // Reserve Factor - sdk.MustNewDecFromStr("0.05")), // Keeper Reward Percent - }, - sdk.NewDec(10), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - - // Initialize test application - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}, - ) - - // Mint coins to Hard module account - bankKeeper := tApp.GetBankKeeper() - err := bankKeeper.MintCoins(ctx, types.ModuleAccountName, tc.args.initialModuleCoins) - suite.Require().NoError(err) - - suite.app = tApp - suite.ctx = ctx - suite.keeper = tApp.GetHardKeeper() - - // Run BeginBlocker once to transition MoneyMarkets - hard.BeginBlocker(suite.ctx, suite.keeper) - - // Deposit coins to hard - err = suite.keeper.Deposit(suite.ctx, tc.args.borrower, tc.args.depositCoins) - suite.Require().NoError(err) - - // Borrow coins from hard - err = suite.keeper.Borrow(suite.ctx, tc.args.borrower, tc.args.borrowCoins) - suite.Require().NoError(err) - - repayerAcc := suite.getAccount(tc.args.repayer) - previousRepayerCoins := bankKeeper.GetAllBalances(suite.ctx, repayerAcc.GetAddress()) - - err = suite.keeper.Repay(suite.ctx, tc.args.repayer, tc.args.borrower, tc.args.repayCoins) - if tc.errArgs.expectPass { - suite.Require().NoError(err) - // If we overpaid expect an adjustment - repaymentCoins, err := suite.keeper.CalculatePaymentAmount(tc.args.borrowCoins, tc.args.repayCoins) - suite.Require().NoError(err) - - // Check repayer balance - expectedRepayerCoins := previousRepayerCoins.Sub(repaymentCoins...) - acc := suite.getAccount(tc.args.repayer) - // use IsEqual for sdk.Coins{nil} vs sdk.Coins{} - suite.Require().True(expectedRepayerCoins.IsEqual(bankKeeper.GetAllBalances(suite.ctx, acc.GetAddress()))) - - // Check module account balance - expectedModuleCoins := tc.args.initialModuleCoins.Add(tc.args.depositCoins...).Sub(tc.args.borrowCoins...).Add(repaymentCoins...) - mAcc := suite.getModuleAccount(types.ModuleAccountName) - suite.Require().Equal(expectedModuleCoins, bankKeeper.GetAllBalances(suite.ctx, mAcc.GetAddress())) - - // Check user's borrow object - borrow, foundBorrow := suite.keeper.GetBorrow(suite.ctx, tc.args.borrower) - expectedBorrowCoins := tc.args.borrowCoins.Sub(repaymentCoins...) - - if tc.errArgs.expectDelete { - suite.Require().False(foundBorrow) - } else { - suite.Require().True(foundBorrow) - suite.Require().Equal(expectedBorrowCoins, borrow.Amount) - } - } else { - suite.Require().Error(err) - suite.Require().Contains(err.Error(), tc.errArgs.contains) - - // Check repayer balance (no repay coins) - acc := suite.getAccount(tc.args.repayer) - suite.Require().Equal(previousRepayerCoins, bankKeeper.GetAllBalances(suite.ctx, acc.GetAddress())) - - // Check module account balance (no repay coins) - expectedModuleCoins := tc.args.initialModuleCoins.Add(tc.args.depositCoins...).Sub(tc.args.borrowCoins...) - mAcc := suite.getModuleAccount(types.ModuleAccountName) - suite.Require().Equal(expectedModuleCoins, bankKeeper.GetAllBalances(suite.ctx, mAcc.GetAddress())) - - // Check user's borrow object (no repay coins) - borrow, foundBorrow := suite.keeper.GetBorrow(suite.ctx, tc.args.borrower) - suite.Require().True(foundBorrow) - suite.Require().Equal(tc.args.borrowCoins, borrow.Amount) - } - }) - } -} - -// uniqueAddressCoins removes duplicate addresses, and the corresponding elements in a list of coins. -func uniqueAddressCoins(addresses []sdk.AccAddress, coinses []sdk.Coins) ([]sdk.AccAddress, []sdk.Coins) { - uniqueAddresses := []sdk.AccAddress{} - filteredCoins := []sdk.Coins{} - - addrMap := map[string]bool{} - for i, a := range addresses { - if !addrMap[a.String()] { - uniqueAddresses = append(uniqueAddresses, a) - filteredCoins = append(filteredCoins, coinses[i]) - } - addrMap[a.String()] = true - } - return uniqueAddresses, filteredCoins -} diff --git a/x/hard/keeper/withdraw.go b/x/hard/keeper/withdraw.go deleted file mode 100644 index c98c5052..00000000 --- a/x/hard/keeper/withdraw.go +++ /dev/null @@ -1,109 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/hard/types" -) - -// Withdraw returns some or all of a deposit back to original depositor -func (k Keeper) Withdraw(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error { - // Call incentive hooks - existingDeposit, found := k.GetDeposit(ctx, depositor) - if !found { - return errorsmod.Wrapf(types.ErrDepositNotFound, "no deposit found for %s", depositor) - } - k.BeforeDepositModified(ctx, existingDeposit) - - existingBorrow, hasExistingBorrow := k.GetBorrow(ctx, depositor) - if hasExistingBorrow { - k.BeforeBorrowModified(ctx, existingBorrow) - } - - // Sync interest - k.SyncBorrowInterest(ctx, depositor) - k.SyncSupplyInterest(ctx, depositor) - - // Refresh Deposit after syncing interest - deposit, _ := k.GetDeposit(ctx, depositor) - - amount, err := k.CalculateWithdrawAmount(deposit.Amount, coins) - if err != nil { - return err - } - - borrow, found := k.GetBorrow(ctx, depositor) - if !found { - borrow = types.Borrow{} - } - - proposedDeposit := types.NewDeposit(deposit.Depositor, deposit.Amount.Sub(amount...), types.SupplyInterestFactors{}) - valid, err := k.IsWithinValidLtvRange(ctx, proposedDeposit, borrow) - if err != nil { - return err - } - if !valid { - return errorsmod.Wrapf(types.ErrInvalidWithdrawAmount, "proposed withdraw outside loan-to-value range") - } - - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, depositor, amount) - if err != nil { - return err - } - - // If any coin denoms have been completely withdrawn reset the denom's supply index factor - for _, coin := range deposit.Amount { - if !sdk.NewCoins(coin).DenomsSubsetOf(proposedDeposit.Amount) { - depositIndex, removed := deposit.Index.RemoveInterestFactor(coin.Denom) - if !removed { - return errorsmod.Wrapf(types.ErrInvalidIndexFactorDenom, "%s", coin.Denom) - } - deposit.Index = depositIndex - } - } - - deposit.Amount = deposit.Amount.Sub(amount...) - if deposit.Amount.Empty() { - k.DeleteDeposit(ctx, deposit) - } else { - k.SetDeposit(ctx, deposit) - } - - // Update total supplied amount - err = k.DecrementSuppliedCoins(ctx, amount) - if err != nil { - return err - } - - // Call incentive hook - k.AfterDepositModified(ctx, deposit) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeHardWithdrawal, - sdk.NewAttribute(sdk.AttributeKeyAmount, amount.String()), - sdk.NewAttribute(types.AttributeKeyDepositor, depositor.String()), - ), - ) - return nil -} - -// CalculateWithdrawAmount enables full withdraw of deposited coins by adjusting withdraw amount -// to equal total deposit amount if the requested withdraw amount > current deposit amount -func (k Keeper) CalculateWithdrawAmount(available sdk.Coins, request sdk.Coins) (sdk.Coins, error) { - result := sdk.Coins{} - - if !request.DenomsSubsetOf(available) { - return result, types.ErrInvalidWithdrawDenom - } - - for _, coin := range request { - if coin.Amount.GT(available.AmountOf(coin.Denom)) { - result = append(result, sdk.NewCoin(coin.Denom, available.AmountOf(coin.Denom))) - } else { - result = append(result, coin) - } - } - return result, nil -} diff --git a/x/hard/keeper/withdraw_test.go b/x/hard/keeper/withdraw_test.go deleted file mode 100644 index 02682831..00000000 --- a/x/hard/keeper/withdraw_test.go +++ /dev/null @@ -1,380 +0,0 @@ -package keeper_test - -import ( - "strings" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/hard" - "github.com/kava-labs/kava/x/hard/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -func (suite *KeeperTestSuite) TestWithdraw() { - type args struct { - depositor sdk.AccAddress - initialModAccountBalance sdk.Coins - depositAmount sdk.Coins - withdrawAmount sdk.Coins - createDeposit bool - expectedAccountBalance sdk.Coins - expectedModAccountBalance sdk.Coins - finalDepositAmount sdk.Coins - } - type errArgs struct { - expectPass bool - expectDelete bool - contains string - } - type withdrawTest struct { - name string - args args - errArgs errArgs - } - testCases := []withdrawTest{ - { - "valid: partial withdraw", - args{ - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialModAccountBalance: sdk.Coins(nil), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - createDeposit: true, - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(900)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - finalDepositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - }, - errArgs{ - expectPass: true, - expectDelete: false, - contains: "", - }, - }, - { - "valid: full withdraw", - args{ - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialModAccountBalance: sdk.Coins(nil), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - createDeposit: true, - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.Coins(nil), - finalDepositAmount: sdk.Coins{}, - }, - errArgs{ - expectPass: true, - expectDelete: true, - contains: "", - }, - }, - { - "valid: withdraw exceeds deposit but is adjusted to match max deposit", - args{ - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(300))), - createDeposit: true, - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000))), - finalDepositAmount: sdk.Coins{}, - }, - errArgs{ - expectPass: true, - expectDelete: true, - contains: "", - }, - }, - { - "invalid: withdraw non-supplied coin type", - args{ - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialModAccountBalance: sdk.Coins(nil), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin("btcb", sdkmath.NewInt(200))), - createDeposit: true, - expectedAccountBalance: sdk.Coins{}, - expectedModAccountBalance: sdk.Coins{}, - finalDepositAmount: sdk.Coins{}, - }, - errArgs{ - expectPass: false, - expectDelete: false, - contains: "no coins of this type deposited", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // create new app with one funded account - - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{sdk.NewCoins( - sdk.NewCoin("bnb", sdkmath.NewInt(1000)), - sdk.NewCoin("btcb", sdkmath.NewInt(1000)), - )}, - []sdk.AccAddress{tc.args.depositor}, - ) - - loanToValue := sdk.MustNewDecFromStr("0.6") - hardGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("usdx", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "usdx:usd", sdkmath.NewInt(1000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("ukava", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "kava:usd", sdkmath.NewInt(1000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("bnb", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "bnb:usd", sdkmath.NewInt(100000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - }, - sdk.NewDec(10), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("10.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - }, - } - - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}) - keeper := tApp.GetHardKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - - // Mint coins to Hard module account - bankKeeper := tApp.GetBankKeeper() - err := bankKeeper.MintCoins(ctx, types.ModuleAccountName, tc.args.initialModAccountBalance) - suite.Require().NoError(err) - - if tc.args.createDeposit { - err := suite.keeper.Deposit(suite.ctx, tc.args.depositor, tc.args.depositAmount) - suite.Require().NoError(err) - } - - err = suite.keeper.Withdraw(suite.ctx, tc.args.depositor, tc.args.withdrawAmount) - - if tc.errArgs.expectPass { - suite.Require().NoError(err) - acc := suite.getAccount(tc.args.depositor) - suite.Require().Equal(tc.args.expectedAccountBalance, bankKeeper.GetAllBalances(ctx, acc.GetAddress())) - mAcc := suite.getModuleAccount(types.ModuleAccountName) - suite.Require().True(tc.args.expectedModAccountBalance.IsEqual(bankKeeper.GetAllBalances(ctx, mAcc.GetAddress()))) - testDeposit, f := suite.keeper.GetDeposit(suite.ctx, tc.args.depositor) - if tc.errArgs.expectDelete { - suite.Require().False(f) - } else { - suite.Require().True(f) - suite.Require().Equal(tc.args.finalDepositAmount, testDeposit.Amount) - } - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *KeeperTestSuite) TestLtvWithdraw() { - type args struct { - borrower sdk.AccAddress - initialModuleCoins sdk.Coins - initialBorrowerCoins sdk.Coins - depositCoins sdk.Coins - borrowCoins sdk.Coins - repayCoins sdk.Coins - futureTime int64 - } - - type errArgs struct { - expectPass bool - contains string - } - - type liqTest struct { - name string - args args - errArgs errArgs - } - - // Set up test constants - model := types.NewInterestRateModel(sdk.MustNewDecFromStr("0"), sdk.MustNewDecFromStr("0.1"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("0.5")) - reserveFactor := sdk.MustNewDecFromStr("0.05") - oneMonthInSeconds := int64(2592000) - borrower := sdk.AccAddress(crypto.AddressHash([]byte("testborrower"))) - - testCases := []liqTest{ - { - "invalid: withdraw is outside loan-to-value range", - args{ - borrower: borrower, - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(100*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), // 100 * 2 = $200 - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(80*KAVA_CF))), // 80 * 2 = $160 - repayCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(60*KAVA_CF))), // 60 * 2 = $120 - futureTime: oneMonthInSeconds, - }, - errArgs{ - expectPass: false, - contains: "proposed withdraw outside loan-to-value range", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - // Auth module genesis state - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{tc.args.initialBorrowerCoins}, - []sdk.AccAddress{tc.args.borrower}, - ) - - // Harvest module genesis state - harvestGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("ukava", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "kava:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - sdk.MustNewDecFromStr("0.05")), // Keeper Reward Percent - types.NewMoneyMarket("usdx", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "usdx:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - sdk.MustNewDecFromStr("0.05")), // Keeper Reward Percent - }, - sdk.NewDec(10), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - }, - } - - // Initialize test application - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&harvestGS)}) - - // Mint coins to Harvest module account - bankKeeper := tApp.GetBankKeeper() - err := bankKeeper.MintCoins(ctx, types.ModuleAccountName, tc.args.initialModuleCoins) - suite.Require().NoError(err) - - auctionKeeper := tApp.GetAuctionKeeper() - - keeper := tApp.GetHardKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - suite.auctionKeeper = auctionKeeper - - // Run begin blocker to set up state - hard.BeginBlocker(suite.ctx, suite.keeper) - - // Borrower deposits coins - err = suite.keeper.Deposit(suite.ctx, tc.args.borrower, tc.args.depositCoins) - suite.Require().NoError(err) - - // Borrower borrows coins - err = suite.keeper.Borrow(suite.ctx, tc.args.borrower, tc.args.borrowCoins) - suite.Require().NoError(err) - - // Attempting to withdraw fails - err = suite.keeper.Withdraw(suite.ctx, tc.args.borrower, sdk.NewCoins(sdk.NewCoin("ukava", sdk.OneInt()))) - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - - // Set up future chain context and run begin blocker, increasing user's owed borrow balance - runAtTime := time.Unix(suite.ctx.BlockTime().Unix()+(tc.args.futureTime), 0) - liqCtx := suite.ctx.WithBlockTime(runAtTime) - hard.BeginBlocker(liqCtx, suite.keeper) - - // Attempted withdraw of 1 coin still fails - err = suite.keeper.Withdraw(suite.ctx, tc.args.borrower, sdk.NewCoins(sdk.NewCoin("ukava", sdk.OneInt()))) - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - - // Repay the initial principal. Over pay the position so the borrow is closed. - err = suite.keeper.Repay(suite.ctx, tc.args.borrower, tc.args.borrower, tc.args.repayCoins) - suite.Require().NoError(err) - - // Attempted withdraw of all deposited coins fails as user hasn't repaid interest debt - err = suite.keeper.Withdraw(suite.ctx, tc.args.borrower, tc.args.depositCoins) - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - - // Withdrawing 10% of the coins should succeed - withdrawCoins := sdk.NewCoins(sdk.NewCoin("ukava", tc.args.depositCoins[0].Amount.Quo(sdkmath.NewInt(10)))) - err = suite.keeper.Withdraw(suite.ctx, tc.args.borrower, withdrawCoins) - suite.Require().NoError(err) - }) - } -} diff --git a/x/hard/legacy/v0_15/types.go b/x/hard/legacy/v0_15/types.go deleted file mode 100644 index bfdfd85d..00000000 --- a/x/hard/legacy/v0_15/types.go +++ /dev/null @@ -1,108 +0,0 @@ -package v0_15 - -import ( - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName name that will be used throughout the module - ModuleName = "hard" -) - -// GenesisState is the state that must be provided at genesis. -type GenesisState struct { - Params Params `json:"params" yaml:"params"` - PreviousAccumulationTimes GenesisAccumulationTimes `json:"previous_accumulation_times" yaml:"previous_accumulation_times"` - Deposits Deposits `json:"deposits" yaml:"deposits"` - Borrows Borrows `json:"borrows" yaml:"borrows"` - TotalSupplied sdk.Coins `json:"total_supplied" yaml:"total_supplied"` - TotalBorrowed sdk.Coins `json:"total_borrowed" yaml:"total_borrowed"` - TotalReserves sdk.Coins `json:"total_reserves" yaml:"total_reserves"` -} - -// Params governance parameters for hard module -type Params struct { - MoneyMarkets MoneyMarkets `json:"money_markets" yaml:"money_markets"` - MinimumBorrowUSDValue sdk.Dec `json:"minimum_borrow_usd_value" yaml:"minimum_borrow_usd_value"` -} - -// MoneyMarkets slice of MoneyMarket -type MoneyMarkets []MoneyMarket - -// MoneyMarket is a money market for an individual asset -type MoneyMarket struct { - Denom string `json:"denom" yaml:"denom"` - BorrowLimit BorrowLimit `json:"borrow_limit" yaml:"borrow_limit"` - SpotMarketID string `json:"spot_market_id" yaml:"spot_market_id"` - ConversionFactor sdkmath.Int `json:"conversion_factor" yaml:"conversion_factor"` - InterestRateModel InterestRateModel `json:"interest_rate_model" yaml:"interest_rate_model"` - ReserveFactor sdk.Dec `json:"reserve_factor" yaml:"reserve_factor"` - KeeperRewardPercentage sdk.Dec `json:"keeper_reward_percentage" yaml:"keeper_reward_percentages"` -} - -// BorrowLimit enforces restrictions on a money market -type BorrowLimit struct { - HasMaxLimit bool `json:"has_max_limit" yaml:"has_max_limit"` - MaximumLimit sdk.Dec `json:"maximum_limit" yaml:"maximum_limit"` - LoanToValue sdk.Dec `json:"loan_to_value" yaml:"loan_to_value"` -} - -// InterestRateModel contains information about an asset's interest rate -type InterestRateModel struct { - BaseRateAPY sdk.Dec `json:"base_rate_apy" yaml:"base_rate_apy"` - BaseMultiplier sdk.Dec `json:"base_multiplier" yaml:"base_multiplier"` - Kink sdk.Dec `json:"kink" yaml:"kink"` - JumpMultiplier sdk.Dec `json:"jump_multiplier" yaml:"jump_multiplier"` -} - -// GenesisAccumulationTimes slice of GenesisAccumulationTime -type GenesisAccumulationTimes []GenesisAccumulationTime - -// GenesisAccumulationTime stores the previous distribution time and its corresponding denom -type GenesisAccumulationTime struct { - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - PreviousAccumulationTime time.Time `json:"previous_accumulation_time" yaml:"previous_accumulation_time"` - SupplyInterestFactor sdk.Dec `json:"supply_interest_factor" yaml:"supply_interest_factor"` - BorrowInterestFactor sdk.Dec `json:"borrow_interest_factor" yaml:"borrow_interest_factor"` -} - -// Deposits is a slice of Deposit -type Deposits []Deposit - -// Deposit defines an amount of coins deposited into a hard module account -type Deposit struct { - Depositor sdk.AccAddress `json:"depositor" yaml:"depositor"` - Amount sdk.Coins `json:"amount" yaml:"amount"` - Index SupplyInterestFactors `json:"index" yaml:"index"` -} - -// SupplyInterestFactors is a slice of SupplyInterestFactor, because Amino won't marshal maps -type SupplyInterestFactors []SupplyInterestFactor - -// SupplyInterestFactor defines an individual borrow interest factor -type SupplyInterestFactor struct { - Denom string `json:"denom" yaml:"denom"` - Value sdk.Dec `json:"value" yaml:"value"` -} - -// Borrows is a slice of Borrow -type Borrows []Borrow - -// Borrow defines an amount of coins borrowed from a hard module account -type Borrow struct { - Borrower sdk.AccAddress `json:"borrower" yaml:"borrower"` - Amount sdk.Coins `json:"amount" yaml:"amount"` - Index BorrowInterestFactors `json:"index" yaml:"index"` -} - -// BorrowInterestFactors is a slice of BorrowInterestFactor, because Amino won't marshal maps -type BorrowInterestFactors []BorrowInterestFactor - -// BorrowInterestFactor defines an individual borrow interest factor -type BorrowInterestFactor struct { - Denom string `json:"denom" yaml:"denom"` - Value sdk.Dec `json:"value" yaml:"value"` -} diff --git a/x/hard/legacy/v0_16/migrate.go b/x/hard/legacy/v0_16/migrate.go deleted file mode 100644 index cc4fbdd7..00000000 --- a/x/hard/legacy/v0_16/migrate.go +++ /dev/null @@ -1,128 +0,0 @@ -package v0_16 - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - v015hard "github.com/kava-labs/kava/x/hard/legacy/v0_15" - v016hard "github.com/kava-labs/kava/x/hard/types" -) - -// Denom generated via: echo -n transfer/channel-0/uatom | shasum -a 256 | awk '{printf "ibc/%s",toupper($1)}' -const UATOM_IBC_DENOM = "ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2" - -func migrateParams(params v015hard.Params) v016hard.Params { - var moneyMarkets []v016hard.MoneyMarket - for _, mm := range params.MoneyMarkets { - moneyMarket := v016hard.MoneyMarket{ - Denom: mm.Denom, - BorrowLimit: v016hard.BorrowLimit{ - HasMaxLimit: mm.BorrowLimit.HasMaxLimit, - MaximumLimit: mm.BorrowLimit.MaximumLimit, - LoanToValue: mm.BorrowLimit.LoanToValue, - }, - SpotMarketID: mm.SpotMarketID, - ConversionFactor: mm.ConversionFactor, - InterestRateModel: v016hard.InterestRateModel{ - BaseRateAPY: mm.InterestRateModel.BaseRateAPY, - BaseMultiplier: mm.InterestRateModel.BaseMultiplier, - Kink: mm.InterestRateModel.Kink, - JumpMultiplier: mm.InterestRateModel.JumpMultiplier, - }, - ReserveFactor: mm.ReserveFactor, - KeeperRewardPercentage: mm.KeeperRewardPercentage, - } - moneyMarkets = append(moneyMarkets, moneyMarket) - } - - atomMoneyMarket := v016hard.MoneyMarket{ - Denom: UATOM_IBC_DENOM, - BorrowLimit: v016hard.BorrowLimit{ - HasMaxLimit: true, - MaximumLimit: sdk.NewDec(25000000000), - LoanToValue: sdk.MustNewDecFromStr("0.5"), - }, - SpotMarketID: "atom:usd:30", - ConversionFactor: sdkmath.NewInt(1000000), - InterestRateModel: v016hard.InterestRateModel{ - BaseRateAPY: sdk.ZeroDec(), - BaseMultiplier: sdk.MustNewDecFromStr("0.05"), - Kink: sdk.MustNewDecFromStr("0.8"), - JumpMultiplier: sdk.NewDec(5), - }, - ReserveFactor: sdk.MustNewDecFromStr("0.025"), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.02"), - } - moneyMarkets = append(moneyMarkets, atomMoneyMarket) - - return v016hard.Params{ - MoneyMarkets: moneyMarkets, - MinimumBorrowUSDValue: params.MinimumBorrowUSDValue, - } -} - -func migrateDeposits(oldDeposits v015hard.Deposits) v016hard.Deposits { - deposits := make(v016hard.Deposits, len(oldDeposits)) - for i, deposit := range oldDeposits { - - interestFactors := make(v016hard.SupplyInterestFactors, len(deposit.Index)) - for j, interestFactor := range deposit.Index { - interestFactors[j] = v016hard.SupplyInterestFactor{ - Denom: interestFactor.Denom, - Value: interestFactor.Value, - } - } - - deposits[i] = v016hard.Deposit{ - Depositor: deposit.Depositor, - Amount: deposit.Amount, - Index: interestFactors, - } - } - return deposits -} - -func migratePrevAccTimes(oldPrevAccTimes v015hard.GenesisAccumulationTimes) v016hard.GenesisAccumulationTimes { - prevAccTimes := make(v016hard.GenesisAccumulationTimes, len(oldPrevAccTimes)) - for i, prevAccTime := range oldPrevAccTimes { - prevAccTimes[i] = v016hard.GenesisAccumulationTime{ - CollateralType: prevAccTime.CollateralType, - PreviousAccumulationTime: prevAccTime.PreviousAccumulationTime, - SupplyInterestFactor: prevAccTime.SupplyInterestFactor, - BorrowInterestFactor: prevAccTime.BorrowInterestFactor, - } - } - return prevAccTimes -} - -func migrateBorrows(oldBorrows v015hard.Borrows) v016hard.Borrows { - borrows := make(v016hard.Borrows, len(oldBorrows)) - for i, borrow := range oldBorrows { - interestFactors := make(v016hard.BorrowInterestFactors, len(borrow.Index)) - for j, interestFactor := range borrow.Index { - interestFactors[j] = v016hard.BorrowInterestFactor{ - Denom: interestFactor.Denom, - Value: interestFactor.Value, - } - } - borrows[i] = v016hard.Borrow{ - Borrower: borrow.Borrower, - Amount: borrow.Amount, - Index: interestFactors, - } - } - return borrows -} - -// Migrate converts v0.15 hard state and returns it in v0.16 format -func Migrate(oldState v015hard.GenesisState) *v016hard.GenesisState { - return &v016hard.GenesisState{ - Params: migrateParams(oldState.Params), - PreviousAccumulationTimes: migratePrevAccTimes(oldState.PreviousAccumulationTimes), - Deposits: migrateDeposits(oldState.Deposits), - Borrows: migrateBorrows(oldState.Borrows), - TotalSupplied: oldState.TotalSupplied, - TotalBorrowed: oldState.TotalBorrowed, - TotalReserves: oldState.TotalReserves, - } -} diff --git a/x/hard/legacy/v0_16/migrate_test.go b/x/hard/legacy/v0_16/migrate_test.go deleted file mode 100644 index b15c1b6e..00000000 --- a/x/hard/legacy/v0_16/migrate_test.go +++ /dev/null @@ -1,198 +0,0 @@ -package v0_16 - -import ( - "io/ioutil" - "path/filepath" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - app "github.com/kava-labs/kava/app" - v015hard "github.com/kava-labs/kava/x/hard/legacy/v0_15" - v016hard "github.com/kava-labs/kava/x/hard/types" -) - -type migrateTestSuite struct { - suite.Suite - - addresses []sdk.AccAddress - cdc codec.Codec - legacyCdc *codec.LegacyAmino -} - -func (s *migrateTestSuite) SetupTest() { - app.SetSDKConfig() - config := app.MakeEncodingConfig() - s.cdc = config.Marshaler - - legacyCodec := codec.NewLegacyAmino() - s.legacyCdc = legacyCodec - - _, accAddresses := app.GeneratePrivKeyAddressPairs(10) - s.addresses = accAddresses -} - -func (s *migrateTestSuite) TestMigrate_JSON() { - file := filepath.Join("testdata", "v15-hard.json") - data, err := ioutil.ReadFile(file) - s.Require().NoError(err) - var v15genstate v015hard.GenesisState - err = s.legacyCdc.UnmarshalJSON(data, &v15genstate) - s.Require().NoError(err) - genstate := Migrate(v15genstate) - actual := s.cdc.MustMarshalJSON(genstate) - - file = filepath.Join("testdata", "v16-hard.json") - expected, err := ioutil.ReadFile(file) - s.Require().NoError(err) - s.Require().JSONEq(string(expected), string(actual)) -} - -func (s *migrateTestSuite) TestMigrate_GenState() { - v15genstate := v015hard.GenesisState{ - Params: v015hard.Params{ - MoneyMarkets: v015hard.MoneyMarkets{ - { - Denom: "kava", - BorrowLimit: v015hard.BorrowLimit{ - HasMaxLimit: true, - MaximumLimit: sdk.MustNewDecFromStr("0.1"), - LoanToValue: sdk.MustNewDecFromStr("0.2"), - }, - SpotMarketID: "spot-market-id", - ConversionFactor: sdkmath.NewInt(110), - InterestRateModel: v015hard.InterestRateModel{ - BaseRateAPY: sdk.MustNewDecFromStr("0.1"), - BaseMultiplier: sdk.MustNewDecFromStr("0.2"), - Kink: sdk.MustNewDecFromStr("0.3"), - JumpMultiplier: sdk.MustNewDecFromStr("0.4"), - }, - ReserveFactor: sdk.MustNewDecFromStr("0.5"), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.6"), - }, - }, - }, - PreviousAccumulationTimes: v015hard.GenesisAccumulationTimes{ - { - CollateralType: "kava", - PreviousAccumulationTime: time.Date(1998, time.January, 1, 12, 0, 0, 1, time.UTC), - SupplyInterestFactor: sdk.MustNewDecFromStr("0.1"), - BorrowInterestFactor: sdk.MustNewDecFromStr("0.2"), - }, - }, - Deposits: v015hard.Deposits{ - { - Depositor: s.addresses[0], - Amount: sdk.NewCoins(sdk.NewCoin("kava", sdkmath.NewInt(100))), - Index: v015hard.SupplyInterestFactors{ - { - Denom: "kava", - Value: sdk.MustNewDecFromStr("1.12"), - }, - }, - }, - }, - Borrows: v015hard.Borrows{ - { - Borrower: s.addresses[1], - Amount: sdk.NewCoins(sdk.NewCoin("kava", sdkmath.NewInt(100))), - Index: v015hard.BorrowInterestFactors{ - { - Denom: "kava", - Value: sdk.MustNewDecFromStr("1.12"), - }, - }, - }, - }, - TotalSupplied: sdk.NewCoins(sdk.NewCoin("kava", sdkmath.NewInt(100))), - TotalBorrowed: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - TotalReserves: sdk.NewCoins(sdk.NewCoin("xrp", sdkmath.NewInt(300))), - } - expected := v016hard.GenesisState{ - Params: v016hard.Params{ - MoneyMarkets: v016hard.MoneyMarkets{ - { - Denom: "kava", - BorrowLimit: v016hard.BorrowLimit{ - HasMaxLimit: true, - MaximumLimit: sdk.MustNewDecFromStr("0.1"), - LoanToValue: sdk.MustNewDecFromStr("0.2"), - }, - SpotMarketID: "spot-market-id", - ConversionFactor: sdkmath.NewInt(110), - InterestRateModel: v016hard.InterestRateModel{ - BaseRateAPY: sdk.MustNewDecFromStr("0.1"), - BaseMultiplier: sdk.MustNewDecFromStr("0.2"), - Kink: sdk.MustNewDecFromStr("0.3"), - JumpMultiplier: sdk.MustNewDecFromStr("0.4"), - }, - ReserveFactor: sdk.MustNewDecFromStr("0.5"), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.6"), - }, - { - Denom: UATOM_IBC_DENOM, - BorrowLimit: v016hard.BorrowLimit{ - HasMaxLimit: true, - MaximumLimit: sdk.NewDec(25000000000), - LoanToValue: sdk.MustNewDecFromStr("0.5"), - }, - SpotMarketID: "atom:usd:30", - ConversionFactor: sdkmath.NewInt(1000000), - InterestRateModel: v016hard.InterestRateModel{ - BaseRateAPY: sdk.ZeroDec(), - BaseMultiplier: sdk.MustNewDecFromStr("0.05"), - Kink: sdk.MustNewDecFromStr("0.8"), - JumpMultiplier: sdk.NewDec(5), - }, - ReserveFactor: sdk.MustNewDecFromStr("0.025"), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.02"), - }, - }, - }, - PreviousAccumulationTimes: v016hard.GenesisAccumulationTimes{ - { - CollateralType: "kava", - PreviousAccumulationTime: time.Date(1998, time.January, 1, 12, 0, 0, 1, time.UTC), - SupplyInterestFactor: sdk.MustNewDecFromStr("0.1"), - BorrowInterestFactor: sdk.MustNewDecFromStr("0.2"), - }, - }, - Deposits: v016hard.Deposits{ - { - Depositor: s.addresses[0], - Amount: sdk.NewCoins(sdk.NewCoin("kava", sdkmath.NewInt(100))), - Index: v016hard.SupplyInterestFactors{ - { - Denom: "kava", - Value: sdk.MustNewDecFromStr("1.12"), - }, - }, - }, - }, - Borrows: v016hard.Borrows{ - { - Borrower: s.addresses[1], - Amount: sdk.NewCoins(sdk.NewCoin("kava", sdkmath.NewInt(100))), - Index: v016hard.BorrowInterestFactors{ - { - Denom: "kava", - Value: sdk.MustNewDecFromStr("1.12"), - }, - }, - }, - }, - TotalSupplied: sdk.NewCoins(sdk.NewCoin("kava", sdkmath.NewInt(100))), - TotalBorrowed: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - TotalReserves: sdk.NewCoins(sdk.NewCoin("xrp", sdkmath.NewInt(300))), - } - genState := Migrate(v15genstate) - s.Require().Equal(expected, *genState) -} - -func TestHardMigrateTestSuite(t *testing.T) { - suite.Run(t, new(migrateTestSuite)) -} diff --git a/x/hard/legacy/v0_16/testdata/v15-hard.json b/x/hard/legacy/v0_16/testdata/v15-hard.json deleted file mode 100644 index c58c35a0..00000000 --- a/x/hard/legacy/v0_16/testdata/v15-hard.json +++ /dev/null @@ -1,115 +0,0 @@ -{ - "params": { - "minimum_borrow_usd_value": "10.0", - "money_markets": [ - { - "denom": "usdx", - "borrow_limit": { - "has_max_limit": false, - "maximum_limit": "20000000", - "loan_to_value": "0.80" - }, - "spot_market_id": "usdx:usd", - "conversion_factor": "1000000", - "interest_rate_model": { - "base_rate_apy": "0.05", - "base_multiplier": "0.1", - "kink": "0.8", - "jump_multiplier": "0.5" - }, - "reserve_factor": "0.0", - "keeper_reward_percentage": "0.05" - }, - { - "denom": "ukava", - "borrow_limit": { - "has_max_limit": false, - "maximum_limit": "100000000000", - "loan_to_value": "0.80" - }, - "spot_market_id": "kava:usd", - "conversion_factor": "1000000", - "interest_rate_model": { - "base_rate_apy": "0.05", - "base_multiplier": "2", - "kink": "0.85", - "jump_multiplier": "10" - }, - "reserve_factor": "0.1", - "keeper_reward_percentage": "0.01" - } - ] - }, - "deposits": [ - { - "amount": [ - { - "amount": "162103943", - "denom": "bnb" - }, - { - "amount": "19428483", - "denom": "btcb" - } - ], - "depositor": "kava1qq9ustlc0nv4aew275w93g4qy5zahqgxf5mwv9", - "index": [ - { - "denom": "bnb", - "value": "1.001740185031830285" - } - ] - } - ], - "borrows": [ - { - "amount": [ - { - "amount": "146724966", - "denom": "usdx" - }, - { - "amount": "541061835659", - "denom": "xrpb" - } - ], - "borrower": "kava1qq9ustlc0nv4aew275w93g4qy5zahqgxf5mwv9", - "index": [ - { - "denom": "usdx", - "value": "1.000156840239586720" - }, - { - "denom": "xrpb", - "value": "1.002063063678030789" - } - ] - } - ], - "total_supplied": [ - { - "amount": "1246173151758", - "denom": "bnb" - } - ], - "total_borrowed": [ - { - "amount": "704609324351367", - "denom": "busd" - } - ], - "total_reserves": [ - { - "amount": "711656301126744", - "denom": "xrpb" - } - ], - "previous_accumulation_times": [ - { - "borrow_interest_factor": "1.002233592784895182", - "collateral_type": "btcb", - "previous_accumulation_time": "2021-11-05T21:13:12.85608847Z", - "supply_interest_factor": "1.000205165357775358" - } - ] -} diff --git a/x/hard/legacy/v0_16/testdata/v16-hard.json b/x/hard/legacy/v0_16/testdata/v16-hard.json deleted file mode 100644 index 027676ed..00000000 --- a/x/hard/legacy/v0_16/testdata/v16-hard.json +++ /dev/null @@ -1,95 +0,0 @@ -{ - "params": { - "money_markets": [ - { - "denom": "usdx", - "borrow_limit": { - "has_max_limit": false, - "maximum_limit": "20000000.000000000000000000", - "loan_to_value": "0.800000000000000000" - }, - "spot_market_id": "usdx:usd", - "conversion_factor": "1000000", - "interest_rate_model": { - "base_rate_apy": "0.050000000000000000", - "base_multiplier": "0.100000000000000000", - "kink": "0.800000000000000000", - "jump_multiplier": "0.500000000000000000" - }, - "reserve_factor": "0.000000000000000000", - "keeper_reward_percentage": "0.050000000000000000" - }, - { - "denom": "ukava", - "borrow_limit": { - "has_max_limit": false, - "maximum_limit": "100000000000.000000000000000000", - "loan_to_value": "0.800000000000000000" - }, - "spot_market_id": "kava:usd", - "conversion_factor": "1000000", - "interest_rate_model": { - "base_rate_apy": "0.050000000000000000", - "base_multiplier": "2.000000000000000000", - "kink": "0.850000000000000000", - "jump_multiplier": "10.000000000000000000" - }, - "reserve_factor": "0.100000000000000000", - "keeper_reward_percentage": "0.010000000000000000" - }, - { - "denom": "ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2", - "borrow_limit": { - "has_max_limit": true, - "maximum_limit": "25000000000.000000000000000000", - "loan_to_value": "0.500000000000000000" - }, - "spot_market_id": "atom:usd:30", - "conversion_factor": "1000000", - "interest_rate_model": { - "base_rate_apy": "0.000000000000000000", - "base_multiplier": "0.050000000000000000", - "kink": "0.800000000000000000", - "jump_multiplier": "5.000000000000000000" - }, - "reserve_factor": "0.025000000000000000", - "keeper_reward_percentage": "0.020000000000000000" - } - ], - "minimum_borrow_usd_value": "10.000000000000000000" - }, - "previous_accumulation_times": [ - { - "collateral_type": "btcb", - "previous_accumulation_time": "2021-11-05T21:13:12.856088470Z", - "supply_interest_factor": "1.000205165357775358", - "borrow_interest_factor": "1.002233592784895182" - } - ], - "deposits": [ - { - "depositor": "kava1qq9ustlc0nv4aew275w93g4qy5zahqgxf5mwv9", - "amount": [ - { "denom": "bnb", "amount": "162103943" }, - { "denom": "btcb", "amount": "19428483" } - ], - "index": [{ "denom": "bnb", "value": "1.001740185031830285" }] - } - ], - "borrows": [ - { - "borrower": "kava1qq9ustlc0nv4aew275w93g4qy5zahqgxf5mwv9", - "amount": [ - { "denom": "usdx", "amount": "146724966" }, - { "denom": "xrpb", "amount": "541061835659" } - ], - "index": [ - { "denom": "usdx", "value": "1.000156840239586720" }, - { "denom": "xrpb", "value": "1.002063063678030789" } - ] - } - ], - "total_supplied": [{ "denom": "bnb", "amount": "1246173151758" }], - "total_borrowed": [{ "denom": "busd", "amount": "704609324351367" }], - "total_reserves": [{ "denom": "xrpb", "amount": "711656301126744" }] -} diff --git a/x/hard/module.go b/x/hard/module.go deleted file mode 100644 index 952ff860..00000000 --- a/x/hard/module.go +++ /dev/null @@ -1,148 +0,0 @@ -package hard - -import ( - "context" - "encoding/json" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/kava-labs/kava/x/hard/client/cli" - "github.com/kava-labs/kava/x/hard/keeper" - "github.com/kava-labs/kava/x/hard/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis returns default genesis state as raw bytes for the hard -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - gs := types.DefaultGenesisState() - return cdc.MustMarshalJSON(&gs) -} - -// ValidateGenesis performs genesis state validation for the hard module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) - if err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the gov module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// GetTxCmd returns the root tx command for the hard module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the hard module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - pricefeedKeeper types.PricefeedKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper types.AccountKeeper, bankKeeper types.BankKeeper, pricefeedKeeper types.PricefeedKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - pricefeedKeeper: pricefeedKeeper, - } -} - -// Name module name -func (AppModule) Name() string { - return types.ModuleName -} - -// RegisterInvariants register module invariants -func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper, am.accountKeeper, am.bankKeeper)) -} - -// InitGenesis performs genesis initialization for the hard module. 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, am.accountKeeper, genState) - return []abci.ValidatorUpdate{} -} - -// ExportGenesis returns the exported genesis state as raw bytes for the hard -// module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(&gs) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { - BeginBlocker(ctx, am.keeper) -} - -// EndBlock module end-block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/hard/spec/01_concepts.md b/x/hard/spec/01_concepts.md deleted file mode 100644 index 1886376f..00000000 --- a/x/hard/spec/01_concepts.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# Concepts - -## Automated, Cross-Chain Money Markets - -The hard module provides for functionality and governance of a two-sided money market protocol with autonomous interest rates. The main state transitions in the hard module are composed of deposit, withdraw, borrow and repay actions. Borrow positions can be liquidated by an external party called a "keeper". Keepers receive a fee in exchange for liquidating risk positions, and the fee rate is determined by governance. Internally, all funds are stored in a module account (the cosmos-sdk equivalent of the `address` portion of a smart contract), and can be accessed via the above actions. Each money market has governance parameters which are controlled by token-holder governance. Of particular note are the interest rate model, which determines (using a static formula) what the prevailing rate of interest will be for each block, and the loan-to-value (LTV), which determines how much borrowing power each unit of deposited collateral will count for. Initial parameterization of the hard module will stipulate that all markets are over-collateralized and that overall borrow limits for each collateral will start small and rise gradually. - -## HARD Token distribution - -[See Incentive Module](../../incentive/spec/01_concepts.md) diff --git a/x/hard/spec/02_state.md b/x/hard/spec/02_state.md deleted file mode 100644 index 0bc73e70..00000000 --- a/x/hard/spec/02_state.md +++ /dev/null @@ -1,67 +0,0 @@ - - -# State - -## Parameters and Genesis State - -`Parameters` define the governance parameters and default behavior of each money market. **Money markets should not be removed from params without careful procedures** as it will disable withdraws and liquidations. Deposits can not be explicitly turned off, but these steps remove the economic incentives to do so. In advance of deprecating a money market, the following steps should be observed: - -1. Borrowing: prevent new borrows by setting param `MoneyMarket.BorrowLimit.MaximumLimit` to 0. `HasMaxLimit` must also be set to true to enable limit checks. -2. Interest: turn off interest accumulation by setting params `MoneyMarket.InterestRateModel.BaseRateAPY`, `MoneyMarket.InterestRateModel.BaseMultiplier`, and `MoneyMarket.InterestRateModel.JumpMultiplier` to 0. -3. Rewards: turn off supply side and/or borrow side rewards by removing any coins in the relevant `RewardsPerSecond` param in the Incentive module. - -Without financial incentives, borrowers and suppliers will withdraw their funds from the money market over time. Once the balances have reached an acceptable level the money market can be deprecated and removed from params, with any additional lingering user funds reimbursed/reallocated as appropriate via a chain upgrade. - -```go -// Params governance parameters for hard module -type Params struct { - MoneyMarkets MoneyMarkets `json:"money_markets" yaml:"money_markets"` - MinimumBorrowUSDValue sdk.Dec `json:"minimum_borrow_usd_value" yaml:"minimum_borrow_usd_value"` -} - -// MoneyMarket is a money market for an individual asset -type MoneyMarket struct { - Denom string `json:"denom" yaml:"denom"` // the denomination of the token for this money market - BorrowLimit BorrowLimit `json:"borrow_limit" yaml:"borrow_limit"` // the borrow limits, if any, applied to this money market - SpotMarketID string `json:"spot_market_id" yaml:"spot_market_id"` // the pricefeed market where price data is fetched - ConversionFactor sdkmath.Int `json:"conversion_factor" yaml:"conversion_factor"` //the internal conversion factor for going from the smallest unit of a token to a whole unit (ie. 8 for BTC, 6 for KAVA, 18 for ETH) - InterestRateModel InterestRateModel `json:"interest_rate_model" yaml:"interest_rate_model"` // the model that determines the prevailing interest rate at each block - ReserveFactor sdk.Dec `json:"reserve_factor" yaml:"reserve_factor"` // the percentage of interest that is accumulated by the protocol as reserves - KeeperRewardPercentage sdk.Dec `json:"keeper_reward_percentage" yaml:"keeper_reward_percentages"` // the percentage of a liquidation that is given to the keeper that liquidated the position -} - -// MoneyMarkets slice of MoneyMarket -type MoneyMarkets []MoneyMarket - -// InterestRateModel contains information about an asset's interest rate -type InterestRateModel struct { - BaseRateAPY sdk.Dec `json:"base_rate_apy" yaml:"base_rate_apy"` // the base rate of APY when borrows are zero. Ex. A value of "0.02" would signify an interest rate of 2% APY as the Y-intercept of the interest rate model for the money market. Note that internally, interest rates are stored as per-second interest. - BaseMultiplier sdk.Dec `json:"base_multiplier" yaml:"base_multiplier"` // the percentage rate at which the interest rate APY increases for each percentage increase in borrow utilization. Ex. A value of "0.01" signifies that the APY interest rate increases by 1% for each additional percentage increase in borrow utilization. - Kink sdk.Dec `json:"kink" yaml:"kink"` // the inflection point at which the BaseMultiplier no longer applies and the JumpMultiplier does apply. For example, a value of "0.8" signifies that at 80% utilization, the JumpMultiplier applies - JumpMultiplier sdk.Dec `json:"jump_multiplier" yaml:"jump_multiplier"` // same as BaseMultiplier, but only applied when utilization is above the Kink -} - -// BorrowLimit enforces restrictions on a money market -type BorrowLimit struct { - HasMaxLimit bool `json:"has_max_limit" yaml:"has_max_limit"` // boolean for if the money market has a max amount that can be borrowed, irrespective of utilization. - MaximumLimit sdk.Dec `json:"maximum_limit" yaml:"maximum_limit"` // the maximum amount that can be borrowed for this money market, irrespective of utilization. Ignored if HasMaxLimit is false - LoanToValue sdk.Dec `json:"loan_to_value" yaml:"loan_to_value"` // the percentage amount of borrow power each unit of deposit accounts for. Ex. A value of "0.5" signifies that for $1 of supply of a particular asset, borrow limits will be increased by $0.5 -} -``` - -`GenesisState` defines the state that must be persisted when the blockchain stops/restarts in order for normal function of the hard module to resume and all outstanding funds + interest to be accounted for. - -```go -// GenesisState is the state that must be provided at genesis. -type GenesisState struct { - Params Params `json:"params" yaml:"params"` // governance parameters - PreviousAccumulationTimes GenesisAccumulationTimes `json:"previous_accumulation_times" yaml:"previous_accumulation_times"` // stores the last time interest was calculated for a particular money market - Deposits Deposits `json:"deposits" yaml:"deposits"` // stores existing deposits when the chain starts, if any - Borrows Borrows `json:"borrows" yaml:"borrows"` // stores existing borrows when the chain starts, if any - TotalSupplied sdk.Coins `json:"total_supplied" yaml:"total_supplied"` // stores the running total of supplied (deposits + interest) coins when the chain starts, if any - TotalBorrowed sdk.Coins `json:"total_borrowed" yaml:"total_borrowed"` // stores the running total of borrowed coins when the chain starts, if any - TotalReserves sdk.Coins `json:"total_reserves" yaml:"total_reserves"` // stores the running total of reserves when the chain starts, if any -} -``` diff --git a/x/hard/spec/03_messages.md b/x/hard/spec/03_messages.md deleted file mode 100644 index 15580606..00000000 --- a/x/hard/spec/03_messages.md +++ /dev/null @@ -1,58 +0,0 @@ - - -# Messages - -There are three messages in the hard module. Deposit allows users to deposit assets to the hard module. In version 2, depositors will be able to use their deposits as collateral to borrow from hard. Withdraw removes assets from the hard module, returning them to the user. Claim allows users to claim earned HARD tokens. - -```go -// MsgDeposit deposit collateral to the hard module. -type MsgDeposit struct { - Depositor sdk.AccAddress `json:"depositor" yaml:"depositor"` - Amount sdk.Coins `json:"amount" yaml:"amount"` -} -``` - -This message creates a `Deposit` object if one does not exist, or updates an existing one, as well as creating/updating the necessary indexes and synchronizing any outstanding interest. The `Amount` of coins is transferred from `Depositor` to the hard module account. The global variable for `TotalSupplied` is updated. - -```go -// MsgWithdraw withdraw from the hard module. -type MsgWithdraw struct { - Depositor sdk.AccAddress `json:"depositor" yaml:"depositor"` - Amount sdk.Coins `json:"amount" yaml:"amount"` -} -``` - -This message decrements a `Deposit` object, or deletes one if the `Amount` specified is greater than or equal to the total deposited amount, as well as creating/updating the necessary indexes and synchronizing any outstanding interest. For example, a message which requests to withdraw 100xyz tokens, if `Depositor` has only deposited 50xyz tokens, will withdraw the full 50xyz tokens. The `Amount` of coins, or the current deposited amount, whichever is lower, is transferred from the hard module account to `Depositor`. The global variable for `TotalSupplied` is updated. - -```go -// MsgBorrow borrows funds from the hard module. -type MsgBorrow struct { - Borrower sdk.AccAddress `json:"borrower" yaml:"borrower"` - Amount sdk.Coins `json:"amount" yaml:"amount"` -} -``` - -This message creates a `Borrow` object is one does not exist, or updates an existing one, as well as creating/updating the necessary indexes and synchronizing any outstanding interest. The `Amount` of coins is transferred from the hard module account to `Depositor`. The global variable for `TotalBorrowed` is updated. - -```go -// MsgRepay repays funds to the hard module. -type MsgRepay struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - Owner sdk.AccAddress `json:"owner" yaml:"owner"` - Amount sdk.Coins `json:"amount" yaml:"amount"` -} -``` - -This message decrements a `Borrow` object, or deletes one if the `Amount` specified is greater than or equal to the total borrowed amount, as well as creating/updating the necessary indexes and synchronizing any outstanding interest. For example, a message which requests to repay 100xyz tokens, if `Owner` has only deposited 50xyz tokens, the `Sender` will repay the full 50xyz tokens. The `Amount` of coins, or the current borrow amount, is transferred from `Sender`. The global variable for `TotalBorrowed` is updated. - -```go -// MsgLiquidate attempts to liquidate a borrower's borrow -type MsgLiquidate struct { - Keeper sdk.AccAddress `json:"keeper" yaml:"keeper"` - Borrower sdk.AccAddress `json:"borrower" yaml:"borrower"` -} -``` - -This message deletes `Borrower's` `Deposit` and `Borrow` objects if they are below the required LTV ratio. The keeper (the sender of the message) is rewarded a portion of the borrow position, according to the `KeeperReward` governance parameter. The coins from the `Deposit` are then sold at auction (see [auction module](../../auction/spec/README.md)), which any remaining tokens returned to `Borrower`. After being liquidated, `Borrower` no longer must repay the borrow amount. The global variables for `TotalSupplied` and `TotalBorrowed` are updated. diff --git a/x/hard/spec/04_events.md b/x/hard/spec/04_events.md deleted file mode 100644 index 44532100..00000000 --- a/x/hard/spec/04_events.md +++ /dev/null @@ -1,46 +0,0 @@ - - -# Events - -The hard module emits the following events: - -## Handlers - -### MsgDeposit - -| Type | Attribute Key | Attribute Value | -| ------------ | ------------- | --------------------- | -| message | module | hard | -| message | sender | `{sender address}` | -| hard_deposit | amount | `{amount}` | -| hard_deposit | depositor | `{depositor address}` | - -### MsgWithdraw - -| Type | Attribute Key | Attribute Value | -| --------------- | ------------- | --------------------- | -| message | module | hard | -| message | sender | `{sender address}` | -| hard_withdrawal | amount | `{amount}` | -| hard_withdrawal | depositor | `{depositor address}` | - -### MsgBorrow - -| Type | Attribute Key | Attribute Value | -| --------------- | ------------- | -------------------- | -| message | module | hard | -| message | sender | `{sender address}` | -| hard_borrow | borrow_coins | `{amount}` | -| hard_withdrawal | borrower | `{borrower address}` | - -### MsgRepay - -| Type | Attribute Key | Attribute Value | -| ---------- | ------------- | -------------------- | -| message | module | hard | -| message | sender | `{sender address}` | -| message | owner | `{owner address}` | -| hard_repay | repay_coins | `{amount}` | -| hard_repay | sender | `{borrower address}` | diff --git a/x/hard/spec/05_params.md b/x/hard/spec/05_params.md deleted file mode 100644 index 6f4ad2c5..00000000 --- a/x/hard/spec/05_params.md +++ /dev/null @@ -1,41 +0,0 @@ - - -# Parameters - -Example parameters for the Hard module: - -| Key | Type | Example | Description | -| --------------------- | ------------------- | ------------- | -------------------------------------------- | -| MoneyMarkets | array (MoneyMarket) | [{see below}] | Array of params for each supported market | -| MinimumBorrowUSDValue | sdk.Dec | 10.0 | Minimum amount an individual user can borrow | - -Example parameters for `MoneyMarket`: - -| Key | Type | Example | Description | -| ---------------------- | ----------------- | ------------- | --------------------------------------------------------------------- | -| Denom | string | "bnb" | Coin denom of the asset which can be deposited and borrowed | -| BorrowLimit | BorrowLimit | [{see below}] | Borrow limits applied to this money market | -| SpotMarketID | string | "bnb:usd" | The market id which determines the price of the asset | -| ConversionFactor | Int | "6" | Conversion factor for one unit (ie BNB) to the smallest internal unit | -| InterestRateModel | InterestRateModel | [{see below}] | Model which determines the prevailing interest rate per block | -| ReserveFactor | Dec | "0.01" | Percentage of interest that is kept as protocol reserves | -| KeeperRewardPercentage | Dec | "0.02" | Percentage of deposit rewarded to keeper who liquidates a position | - -Example parameters for `BorrowLimit`: - -| Key | Type | Example | Description | -| ------------ | ---- | ------------ | ----------------------------------------------------------------------- | -| HasMaxLimit | bool | "true" | Boolean for if a maximum limit is in effect | -| MaximumLimit | Dec | "10000000.0" | Global maximum amount of coins that can be borrowed | -| LoanToValue | Dec | "0.5" | The percentage amount of borrow power each unit of deposit accounts for | - -Example parameters for `InterestRateModel`: - -| Key | Type | Example | Description | -| -------------- | ---- | ------- | --------------------------------------------------------------------------------------------------------------- | -| BaseRateAPY | Dec | "0.0" | The base rate of APY interest when borrows are zero | -| BaseMultiplier | Dec | "0.01" | The percentage rate at which the interest rate APY increases for each percentage increase in borrow utilization | -| Kink | Dec | "0.5" | The inflection point of utilization at which the BaseMultiplier no longer applies and the JumpMultiplier does | -| JumpMultiplier | Dec | "0.5" | Same as BaseMultiplier, but only applied when utilization is above the Kink | diff --git a/x/hard/spec/06_begin_block.md b/x/hard/spec/06_begin_block.md deleted file mode 100644 index 173fb954..00000000 --- a/x/hard/spec/06_begin_block.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# Begin Block - -At the start of each block interest is accumulated - -```go -// BeginBlocker updates interest rates -func BeginBlocker(ctx sdk.Context, k Keeper) { - k.ApplyInterestRateUpdates(ctx) -} -``` diff --git a/x/hard/spec/README.md b/x/hard/spec/README.md deleted file mode 100644 index a37e6be2..00000000 --- a/x/hard/spec/README.md +++ /dev/null @@ -1,21 +0,0 @@ - - -# `hard` - - - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** -5. **[Params](05_params.md)** -6. **[BeginBlock](06_begin_block.md)** - -## Abstract - -`x/hard` is an implementation of a Cosmos SDK Module that provides for functionality and governance of a two-sided, cross-chain, money market protocol. diff --git a/x/hard/types/borrow.go b/x/hard/types/borrow.go deleted file mode 100644 index 5c395610..00000000 --- a/x/hard/types/borrow.go +++ /dev/null @@ -1,198 +0,0 @@ -package types - -import ( - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewBorrow returns a new Borrow instance -func NewBorrow(borrower sdk.AccAddress, amount sdk.Coins, index BorrowInterestFactors) Borrow { - return Borrow{ - Borrower: borrower, - Amount: amount, - Index: index, - } -} - -// NormalizedBorrow is the borrow amounts divided by the interest factors. -// -// Multiplying the normalized borrow by the current global factors gives the current borrow (ie including all interest, ie a synced borrow). -// The normalized borrow is effectively how big the borrow would have been if it had been borrowed at time 0 and not touched since. -// -// An error is returned if the borrow is in an invalid state. -func (b Borrow) NormalizedBorrow() (sdk.DecCoins, error) { - normalized := sdk.NewDecCoins() - - for _, coin := range b.Amount { - - factor, found := b.Index.GetInterestFactor(coin.Denom) - if !found { - return nil, fmt.Errorf("borrowed amount '%s' missing interest factor", coin.Denom) - } - if factor.LT(sdk.OneDec()) { - return nil, fmt.Errorf("interest factor '%s' < 1", coin.Denom) - } - - normalized = normalized.Add( - sdk.NewDecCoinFromDec( - coin.Denom, - sdk.NewDecFromInt(coin.Amount).Quo(factor), - ), - ) - } - return normalized, nil -} - -// Validate deposit validation -func (b Borrow) Validate() error { - if b.Borrower.Empty() { - return fmt.Errorf("borrower cannot be empty") - } - if !b.Amount.IsValid() { - return fmt.Errorf("invalid borrow coins: %s", b.Amount) - } - - if err := b.Index.Validate(); err != nil { - return err - } - - return nil -} - -// ToResponse converts Borrow to BorrowResponse -func (b Borrow) ToResponse() BorrowResponse { - return NewBorrowResponse(b.Borrower, b.Amount, b.Index) -} - -// Borrows is a slice of Borrow -type Borrows []Borrow - -// Validate validates Borrows -func (bs Borrows) Validate() error { - borrowDupMap := make(map[string]Borrow) - for _, b := range bs { - if err := b.Validate(); err != nil { - return err - } - dup, ok := borrowDupMap[b.Borrower.String()] - if ok { - return fmt.Errorf("duplicate borrower: %s\n%s", b, dup) - } - borrowDupMap[b.Borrower.String()] = b - } - return nil -} - -// ToResponse converts Borrows to BorrowResponses -func (bs Borrows) ToResponse() BorrowResponses { - var bResponses BorrowResponses - - for _, b := range bs { - bResponses = append(bResponses, b.ToResponse()) - } - return bResponses -} - -// NewBorrowResponse returns a new BorrowResponse instance -func NewBorrowResponse(borrower sdk.AccAddress, amount sdk.Coins, index BorrowInterestFactors) BorrowResponse { - return BorrowResponse{ - Borrower: borrower.String(), - Amount: amount, - Index: index.ToResponse(), - } -} - -// BorrowResponses is a slice of BorrowResponse -type BorrowResponses []BorrowResponse - -// NewBorrowInterestFactor returns a new BorrowInterestFactor instance -func NewBorrowInterestFactor(denom string, value sdk.Dec) BorrowInterestFactor { - return BorrowInterestFactor{ - Denom: denom, - Value: value, - } -} - -// Validate validates BorrowInterestFactor values -func (bif BorrowInterestFactor) Validate() error { - if strings.TrimSpace(bif.Denom) == "" { - return fmt.Errorf("borrow interest factor denom cannot be empty") - } - if bif.Value.IsNegative() { - return fmt.Errorf("borrow interest factor value cannot be negative: %s", bif) - } - return nil -} - -// ToResponse converts BorrowInterestFactor to BorrowInterestFactorResponse -func (bif BorrowInterestFactor) ToResponse() BorrowInterestFactorResponse { - return NewBorrowInterestFactorResponse(bif.Denom, bif.Value) -} - -// NewBorrowInterestFactorResponse returns a new BorrowInterestFactorResponse instance -func NewBorrowInterestFactorResponse(denom string, value sdk.Dec) BorrowInterestFactorResponse { - return BorrowInterestFactorResponse{ - Denom: denom, - Value: value.String(), - } -} - -// BorrowInterestFactors is a slice of BorrowInterestFactor, because Amino won't marshal maps -type BorrowInterestFactors []BorrowInterestFactor - -// GetInterestFactor returns a denom's interest factor value -func (bifs BorrowInterestFactors) GetInterestFactor(denom string) (sdk.Dec, bool) { - for _, bif := range bifs { - if bif.Denom == denom { - return bif.Value, true - } - } - return sdk.ZeroDec(), false -} - -// SetInterestFactor sets a denom's interest factor value -func (bifs BorrowInterestFactors) SetInterestFactor(denom string, factor sdk.Dec) BorrowInterestFactors { - for i, bif := range bifs { - if bif.Denom == denom { - bif.Value = factor - bifs[i] = bif - return bifs - } - } - return append(bifs, NewBorrowInterestFactor(denom, factor)) -} - -// RemoveInterestFactor removes a denom's interest factor value -func (bifs BorrowInterestFactors) RemoveInterestFactor(denom string) (BorrowInterestFactors, bool) { - for i, bif := range bifs { - if bif.Denom == denom { - return append(bifs[:i], bifs[i+1:]...), true - } - } - return bifs, false -} - -// Validate validates BorrowInterestFactors -func (bifs BorrowInterestFactors) Validate() error { - for _, bif := range bifs { - if err := bif.Validate(); err != nil { - return err - } - } - return nil -} - -// ToResponse converts BorrowInterestFactors to BorrowInterestFactorResponses -func (bifs BorrowInterestFactors) ToResponse() BorrowInterestFactorResponses { - var bifResponses BorrowInterestFactorResponses - - for _, bif := range bifs { - bifResponses = append(bifResponses, bif.ToResponse()) - } - return bifResponses -} - -// BorrowInterestFactorResponses is a slice of BorrowInterestFactorResponse -type BorrowInterestFactorResponses []BorrowInterestFactorResponse diff --git a/x/hard/types/borrow_test.go b/x/hard/types/borrow_test.go deleted file mode 100644 index 107bf1f2..00000000 --- a/x/hard/types/borrow_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package types_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/kava-labs/kava/x/hard/types" -) - -func TestBorrow_NormalizedBorrow(t *testing.T) { - testCases := []struct { - name string - borrow types.Borrow - expect sdk.DecCoins - expectErr string - }{ - { - name: "multiple denoms are calculated correctly", - borrow: types.Borrow{ - Amount: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100e8), - sdk.NewInt64Coin("xrpb", 1e8), - ), - Index: types.BorrowInterestFactors{ - { - Denom: "xrpb", - Value: sdk.MustNewDecFromStr("1.25"), - }, - { - Denom: "bnb", - Value: sdk.MustNewDecFromStr("2.0"), - }, - }, - }, - expect: sdk.NewDecCoins( - sdk.NewInt64DecCoin("bnb", 50e8), - sdk.NewInt64DecCoin("xrpb", 8e7), - ), - }, - { - name: "empty borrow amount returns empty dec coins", - borrow: types.Borrow{ - Amount: sdk.Coins{}, - Index: types.BorrowInterestFactors{}, - }, - expect: sdk.DecCoins{}, - }, - { - name: "nil borrow amount returns empty dec coins", - borrow: types.Borrow{ - Amount: nil, - Index: types.BorrowInterestFactors{}, - }, - expect: sdk.DecCoins{}, - }, - { - name: "missing indexes return error", - borrow: types.Borrow{ - Amount: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100e8), - ), - Index: types.BorrowInterestFactors{ - { - Denom: "xrpb", - Value: sdk.MustNewDecFromStr("1.25"), - }, - }, - }, - expectErr: "missing interest factor", - }, - { - name: "invalid indexes return error", - borrow: types.Borrow{ - Amount: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100e8), - ), - Index: types.BorrowInterestFactors{ - { - Denom: "bnb", - Value: sdk.MustNewDecFromStr("0.999999999999999999"), - }, - }, - }, - expectErr: "< 1", - }, - { - name: "zero indexes return error rather than panicking", - borrow: types.Borrow{ - Amount: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100e8), - ), - Index: types.BorrowInterestFactors{ - { - Denom: "bnb", - Value: sdk.MustNewDecFromStr("0"), - }, - }, - }, - expectErr: "< 1", - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - nb, err := tc.borrow.NormalizedBorrow() - - require.Equal(t, tc.expect, nb) - - if len(tc.expectErr) > 0 { - require.Error(t, err) - require.Contains(t, err.Error(), tc.expectErr) - } - }) - } -} diff --git a/x/hard/types/codec.go b/x/hard/types/codec.go deleted file mode 100644 index 44c19da4..00000000 --- a/x/hard/types/codec.go +++ /dev/null @@ -1,44 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgDeposit{}, "hard/MsgDeposit", nil) - cdc.RegisterConcrete(&MsgWithdraw{}, "hard/MsgWithdraw", nil) - cdc.RegisterConcrete(&MsgBorrow{}, "hard/MsgBorrow", nil) - cdc.RegisterConcrete(&MsgLiquidate{}, "hard/MsgLiquidate", nil) - cdc.RegisterConcrete(&MsgRepay{}, "hard/MsgRepay", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgDeposit{}, - &MsgWithdraw{}, - &MsgBorrow{}, - &MsgLiquidate{}, - &MsgRepay{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/hard/types/deposit.go b/x/hard/types/deposit.go deleted file mode 100644 index f73c4dd5..00000000 --- a/x/hard/types/deposit.go +++ /dev/null @@ -1,198 +0,0 @@ -package types - -import ( - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewDeposit returns a new deposit -func NewDeposit(depositor sdk.AccAddress, amount sdk.Coins, indexes SupplyInterestFactors) Deposit { - return Deposit{ - Depositor: depositor, - Amount: amount, - Index: indexes, - } -} - -// NormalizedDeposit is the deposit amounts divided by the interest factors. -// -// Multiplying the normalized deposit by the current global factors gives the current deposit (ie including all interest, ie a synced deposit). -// The normalized deposit is effectively how big the deposit would have been if it had been supplied at time 0 and not touched since. -// -// An error is returned if the deposit is in an invalid state. -func (b Deposit) NormalizedDeposit() (sdk.DecCoins, error) { - normalized := sdk.NewDecCoins() - - for _, coin := range b.Amount { - - factor, found := b.Index.GetInterestFactor(coin.Denom) - if !found { - return nil, fmt.Errorf("deposited amount '%s' missing interest factor", coin.Denom) - } - if factor.LT(sdk.OneDec()) { - return nil, fmt.Errorf("interest factor '%s' < 1", coin.Denom) - } - - normalized = normalized.Add( - sdk.NewDecCoinFromDec( - coin.Denom, - sdk.NewDecFromInt(coin.Amount).Quo(factor), - ), - ) - } - return normalized, nil -} - -// Validate deposit validation -func (d Deposit) Validate() error { - if d.Depositor.Empty() { - return fmt.Errorf("depositor cannot be empty") - } - if !d.Amount.IsValid() { - return fmt.Errorf("invalid deposit coins: %s", d.Amount) - } - - if err := d.Index.Validate(); err != nil { - return err - } - - return nil -} - -// ToResponse converts Deposit to DepositResponse -func (d Deposit) ToResponse() DepositResponse { - return NewDepositResponse(d.Depositor, d.Amount, d.Index) -} - -// Deposits is a slice of Deposit -type Deposits []Deposit - -// Validate validates Deposits -func (ds Deposits) Validate() error { - depositDupMap := make(map[string]Deposit) - for _, d := range ds { - if err := d.Validate(); err != nil { - return err - } - dup, ok := depositDupMap[d.Depositor.String()] - if ok { - return fmt.Errorf("duplicate depositor: %s\n%s", d, dup) - } - depositDupMap[d.Depositor.String()] = d - } - return nil -} - -// ToResponse converts Deposits to DepositResponses -func (ds Deposits) ToResponse() DepositResponses { - var dResponses DepositResponses - - for _, d := range ds { - dResponses = append(dResponses, d.ToResponse()) - } - return dResponses -} - -// NewDepositResponse returns a new DepositResponse -func NewDepositResponse(depositor sdk.AccAddress, amount sdk.Coins, indexes SupplyInterestFactors) DepositResponse { - return DepositResponse{ - Depositor: depositor.String(), - Amount: amount, - Index: indexes.ToResponse(), - } -} - -// DepositResponses is a slice of DepositResponse -type DepositResponses []DepositResponse - -// NewSupplyInterestFactor returns a new SupplyInterestFactor instance -func NewSupplyInterestFactor(denom string, value sdk.Dec) SupplyInterestFactor { - return SupplyInterestFactor{ - Denom: denom, - Value: value, - } -} - -// Validate validates SupplyInterestFactor values -func (sif SupplyInterestFactor) Validate() error { - if strings.TrimSpace(sif.Denom) == "" { - return fmt.Errorf("supply interest factor denom cannot be empty") - } - if sif.Value.IsNegative() { - return fmt.Errorf("supply interest factor value cannot be negative: %s", sif) - } - return nil -} - -// ToResponse converts SupplyInterestFactor to SupplyInterestFactorResponse -func (sif SupplyInterestFactor) ToResponse() SupplyInterestFactorResponse { - return NewSupplyInterestFactorResponse(sif.Denom, sif.Value) -} - -// NewSupplyInterestFactorResponse returns a new SupplyInterestFactorResponse instance -func NewSupplyInterestFactorResponse(denom string, value sdk.Dec) SupplyInterestFactorResponse { - return SupplyInterestFactorResponse{ - Denom: denom, - Value: value.String(), - } -} - -// SupplyInterestFactors is a slice of SupplyInterestFactor, because Amino won't marshal maps -type SupplyInterestFactors []SupplyInterestFactor - -// GetInterestFactor returns a denom's interest factor value -func (sifs SupplyInterestFactors) GetInterestFactor(denom string) (sdk.Dec, bool) { - for _, sif := range sifs { - if sif.Denom == denom { - return sif.Value, true - } - } - return sdk.ZeroDec(), false -} - -// SetInterestFactor sets a denom's interest factor value -func (sifs SupplyInterestFactors) SetInterestFactor(denom string, factor sdk.Dec) SupplyInterestFactors { - for i, sif := range sifs { - if sif.Denom == denom { - sif.Value = factor - sifs[i] = sif - return sifs - } - } - return append(sifs, NewSupplyInterestFactor(denom, factor)) -} - -// RemoveInterestFactor removes a denom's interest factor value -func (sifs SupplyInterestFactors) RemoveInterestFactor(denom string) (SupplyInterestFactors, bool) { - for i, sif := range sifs { - if sif.Denom == denom { - return append(sifs[:i], sifs[i+1:]...), true - } - } - return sifs, false -} - -// Validate validates SupplyInterestFactors -func (sifs SupplyInterestFactors) Validate() error { - for _, sif := range sifs { - if err := sif.Validate(); err != nil { - return err - } - } - return nil -} - -// ToResponse converts SupplyInterestFactor to SupplyInterestFactorResponses -func (sifs SupplyInterestFactors) ToResponse() SupplyInterestFactorResponses { - var sifResponses SupplyInterestFactorResponses - - for _, sif := range sifs { - sifResponses = append(sifResponses, sif.ToResponse()) - } - return sifResponses -} - -// SupplyInterestFactorResponses is a slice of SupplyInterestFactorResponse -type SupplyInterestFactorResponses []SupplyInterestFactorResponse diff --git a/x/hard/types/deposit_test.go b/x/hard/types/deposit_test.go deleted file mode 100644 index 7776fb40..00000000 --- a/x/hard/types/deposit_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package types_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/kava-labs/kava/x/hard/types" -) - -func TestDeposit_NormalizedDeposit(t *testing.T) { - testCases := []struct { - name string - deposit types.Deposit - expect sdk.DecCoins - expectErr string - }{ - { - name: "multiple denoms are calculated correctly", - deposit: types.Deposit{ - Amount: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100e8), - sdk.NewInt64Coin("xrpb", 1e8), - ), - Index: types.SupplyInterestFactors{ - { - Denom: "xrpb", - Value: sdk.MustNewDecFromStr("1.25"), - }, - { - Denom: "bnb", - Value: sdk.MustNewDecFromStr("2.0"), - }, - }, - }, - expect: sdk.NewDecCoins( - sdk.NewInt64DecCoin("bnb", 50e8), - sdk.NewInt64DecCoin("xrpb", 8e7), - ), - }, - { - name: "empty deposit amount returns empty dec coins", - deposit: types.Deposit{ - Amount: sdk.Coins{}, - Index: types.SupplyInterestFactors{}, - }, - expect: sdk.DecCoins{}, - }, - { - name: "nil deposit amount returns empty dec coins", - deposit: types.Deposit{ - Amount: nil, - Index: types.SupplyInterestFactors{}, - }, - expect: sdk.DecCoins{}, - }, - { - name: "missing indexes return error", - deposit: types.Deposit{ - Amount: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100e8), - ), - Index: types.SupplyInterestFactors{ - { - Denom: "xrpb", - Value: sdk.MustNewDecFromStr("1.25"), - }, - }, - }, - expectErr: "missing interest factor", - }, - { - name: "invalid indexes return error", - deposit: types.Deposit{ - Amount: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100e8), - ), - Index: types.SupplyInterestFactors{ - { - Denom: "bnb", - Value: sdk.MustNewDecFromStr("0.999999999999999999"), - }, - }, - }, - expectErr: "< 1", - }, - { - name: "zero indexes return error rather than panicking", - deposit: types.Deposit{ - Amount: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100e8), - ), - Index: types.SupplyInterestFactors{ - { - Denom: "bnb", - Value: sdk.MustNewDecFromStr("0"), - }, - }, - }, - expectErr: "< 1", - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - nb, err := tc.deposit.NormalizedDeposit() - - require.Equal(t, tc.expect, nb) - - if len(tc.expectErr) > 0 { - require.Error(t, err) - require.Contains(t, err.Error(), tc.expectErr) - } - }) - } -} diff --git a/x/hard/types/errors.go b/x/hard/types/errors.go deleted file mode 100644 index 98cf4c47..00000000 --- a/x/hard/types/errors.go +++ /dev/null @@ -1,70 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// DONTCOVER - -var ( - // ErrInvalidDepositDenom error for invalid deposit denoms - ErrInvalidDepositDenom = errorsmod.Register(ModuleName, 2, "invalid deposit denom") - // ErrDepositNotFound error for deposit not found - ErrDepositNotFound = errorsmod.Register(ModuleName, 3, "deposit not found") - // ErrInvalidWithdrawAmount error for invalid withdrawal amount - ErrInvalidWithdrawAmount = errorsmod.Register(ModuleName, 4, "invalid withdrawal amount") - // ErrInsufficientModAccountBalance error for module account with innsufficient balance - ErrInsufficientModAccountBalance = errorsmod.Register(ModuleName, 5, "module account has insufficient balance to pay reward") - // ErrInvalidAccountType error for unsupported accounts - ErrInvalidAccountType = errorsmod.Register(ModuleName, 6, "receiver account type not supported") - // ErrAccountNotFound error for accounts that are not found in state - ErrAccountNotFound = errorsmod.Register(ModuleName, 7, "account not found") - // ErrInvalidReceiver error for when sending and receiving accounts don't match - ErrInvalidReceiver = errorsmod.Register(ModuleName, 8, "receiver account must match sender account") - // ErrMoneyMarketNotFound error for money market param not found - ErrMoneyMarketNotFound = errorsmod.Register(ModuleName, 9, "no money market found") - // ErrDepositsNotFound error for no deposits found - ErrDepositsNotFound = errorsmod.Register(ModuleName, 10, "no deposits found") - // ErrInsufficientLoanToValue error for when an attempted borrow exceeds maximum loan-to-value - ErrInsufficientLoanToValue = errorsmod.Register(ModuleName, 11, "not enough collateral supplied by account") - // ErrMarketNotFound error for when a market for the input denom is not found - ErrMarketNotFound = errorsmod.Register(ModuleName, 12, "no market found for denom") - // ErrPriceNotFound error for when a price for the input market is not found - ErrPriceNotFound = errorsmod.Register(ModuleName, 13, "no price found for market") - // ErrBorrowExceedsAvailableBalance for when a requested borrow exceeds available module acc balances - ErrBorrowExceedsAvailableBalance = errorsmod.Register(ModuleName, 14, "exceeds module account balance") - // ErrBorrowedCoinsNotFound error for when the total amount of borrowed coins cannot be found - ErrBorrowedCoinsNotFound = errorsmod.Register(ModuleName, 15, "no borrowed coins found") - // ErrNegativeBorrowedCoins error for when substracting coins from the total borrowed balance results in a negative amount - ErrNegativeBorrowedCoins = errorsmod.Register(ModuleName, 16, "subtraction results in negative borrow amount") - // ErrGreaterThanAssetBorrowLimit error for when a proposed borrow would increase borrowed amount over the asset's global borrow limit - ErrGreaterThanAssetBorrowLimit = errorsmod.Register(ModuleName, 17, "fails global asset borrow limit validation") - // ErrBorrowEmptyCoins error for when you cannot borrow empty coins - ErrBorrowEmptyCoins = errorsmod.Register(ModuleName, 18, "cannot borrow zero coins") - // ErrBorrowNotFound error for when a user's borrow is not found in the store - ErrBorrowNotFound = errorsmod.Register(ModuleName, 19, "borrow not found") - // ErrPreviousAccrualTimeNotFound error for no previous accrual time found in store - ErrPreviousAccrualTimeNotFound = errorsmod.Register(ModuleName, 20, "no previous accrual time found") - // ErrInsufficientBalanceForRepay error for when requested repay exceeds user's balance - ErrInsufficientBalanceForRepay = errorsmod.Register(ModuleName, 21, "insufficient balance") - // ErrBorrowNotLiquidatable error for when a borrow is within valid LTV and cannot be liquidated - ErrBorrowNotLiquidatable = errorsmod.Register(ModuleName, 22, "borrow not liquidatable") - // ErrInsufficientCoins error for when there are not enough coins for the operation - ErrInsufficientCoins = errorsmod.Register(ModuleName, 23, "unrecoverable state - insufficient coins") - // ErrInsufficientBalanceForBorrow error for when the requested borrow exceeds user's balance - ErrInsufficientBalanceForBorrow = errorsmod.Register(ModuleName, 24, "insufficient balance") - // ErrSuppliedCoinsNotFound error for when the total amount of supplied coins cannot be found - ErrSuppliedCoinsNotFound = errorsmod.Register(ModuleName, 25, "no supplied coins found") - // ErrNegativeSuppliedCoins error for when substracting coins from the total supplied balance results in a negative amount - ErrNegativeSuppliedCoins = errorsmod.Register(ModuleName, 26, "subtraction results in negative supplied amount") - // ErrInvalidWithdrawDenom error for when user attempts to withdraw a non-supplied coin type - ErrInvalidWithdrawDenom = errorsmod.Register(ModuleName, 27, "no coins of this type deposited") - // ErrInvalidRepaymentDenom error for when user attempts to repay a non-borrowed coin type - ErrInvalidRepaymentDenom = errorsmod.Register(ModuleName, 28, "no coins of this type borrowed") - // ErrInvalidIndexFactorDenom error for when index factor denom cannot be found - ErrInvalidIndexFactorDenom = errorsmod.Register(ModuleName, 29, "no index factor found for denom") - // ErrBelowMinimumBorrowValue error for when a proposed borrow position is less than the minimum USD value - ErrBelowMinimumBorrowValue = errorsmod.Register(ModuleName, 30, "invalid proposed borrow value") - // ErrExceedsProtocolBorrowableBalance for when a requested borrow exceeds the module account's borrowable balance - ErrExceedsProtocolBorrowableBalance = errorsmod.Register(ModuleName, 31, "exceeds borrowable module account balance") - // ErrReservesExceedCash for when the protocol is insolvent because available reserves exceeds available cash - ErrReservesExceedCash = errorsmod.Register(ModuleName, 32, "insolvency - protocol reserves exceed available cash") -) diff --git a/x/hard/types/events.go b/x/hard/types/events.go deleted file mode 100644 index d0b1386e..00000000 --- a/x/hard/types/events.go +++ /dev/null @@ -1,25 +0,0 @@ -package types - -// Event types for hard module -const ( - EventTypeHardDeposit = "hard_deposit" - EventTypeHardWithdrawal = "hard_withdrawal" - EventTypeHardBorrow = "hard_borrow" - EventTypeHardLiquidation = "hard_liquidation" - EventTypeHardRepay = "hard_repay" - AttributeValueCategory = ModuleName - AttributeKeyDeposit = "deposit" - AttributeKeyDepositDenom = "deposit_denom" - AttributeKeyDepositCoins = "deposit_coins" - AttributeKeyDepositor = "depositor" - AttributeKeyBorrow = "borrow" - AttributeKeyBorrower = "borrower" - AttributeKeyBorrowCoins = "borrow_coins" - AttributeKeySender = "sender" - AttributeKeyRepayCoins = "repay_coins" - AttributeKeyLiquidatedOwner = "liquidated_owner" - AttributeKeyLiquidatedCoins = "liquidated_coins" - AttributeKeyKeeper = "keeper" - AttributeKeyKeeperRewardCoins = "keeper_reward_coins" - AttributeKeyOwner = "owner" -) diff --git a/x/hard/types/expected_keepers.go b/x/hard/types/expected_keepers.go deleted file mode 100644 index 61d7740c..00000000 --- a/x/hard/types/expected_keepers.go +++ /dev/null @@ -1,60 +0,0 @@ -package types // noalias - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - pftypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -// BankKeeper defines the expected bank keeper -type BankKeeper interface { - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - - GetSupply(ctx sdk.Context, denom string) sdk.Coin - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins -} - -// AccountKeeper defines the expected keeper interface for interacting with account -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI - SetAccount(ctx sdk.Context, acc authtypes.AccountI) - - GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, name string) authtypes.ModuleAccountI -} - -// StakingKeeper defines the expected keeper interface for the staking keeper -type StakingKeeper interface { - IterateLastValidators(ctx sdk.Context, fn func(index int64, validator stakingtypes.ValidatorI) (stop bool)) - IterateValidators(sdk.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) - IterateAllDelegations(ctx sdk.Context, cb func(delegation stakingtypes.Delegation) (stop bool)) - GetBondedPool(ctx sdk.Context) (bondedPool authtypes.ModuleAccountI) - BondDenom(ctx sdk.Context) (res string) -} - -// PricefeedKeeper defines the expected interface for the pricefeed -type PricefeedKeeper interface { - GetCurrentPrice(sdk.Context, string) (pftypes.CurrentPrice, error) -} - -// AuctionKeeper expected interface for the auction keeper (noalias) -type AuctionKeeper interface { - StartCollateralAuction(ctx sdk.Context, seller string, lot sdk.Coin, maxBid sdk.Coin, lotReturnAddrs []sdk.AccAddress, lotReturnWeights []sdkmath.Int, debt sdk.Coin) (uint64, error) -} - -// HARDHooks event hooks for other keepers to run code in response to HARD modifications -type HARDHooks interface { - AfterDepositCreated(ctx sdk.Context, deposit Deposit) - BeforeDepositModified(ctx sdk.Context, deposit Deposit) - AfterDepositModified(ctx sdk.Context, deposit Deposit) - AfterBorrowCreated(ctx sdk.Context, borrow Borrow) - BeforeBorrowModified(ctx sdk.Context, borrow Borrow) - AfterBorrowModified(ctx sdk.Context, borrow Borrow) -} diff --git a/x/hard/types/genesis.go b/x/hard/types/genesis.go deleted file mode 100644 index e138b16a..00000000 --- a/x/hard/types/genesis.go +++ /dev/null @@ -1,99 +0,0 @@ -package types - -import ( - "fmt" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewGenesisState returns a new genesis state -func NewGenesisState( - params Params, prevAccumulationTimes GenesisAccumulationTimes, deposits Deposits, - borrows Borrows, totalSupplied, totalBorrowed, totalReserves sdk.Coins, -) GenesisState { - return GenesisState{ - Params: params, - PreviousAccumulationTimes: prevAccumulationTimes, - Deposits: deposits, - Borrows: borrows, - TotalSupplied: totalSupplied, - TotalBorrowed: totalBorrowed, - TotalReserves: totalReserves, - } -} - -// DefaultGenesisState returns a default genesis state -func DefaultGenesisState() GenesisState { - return GenesisState{ - Params: DefaultParams(), - PreviousAccumulationTimes: DefaultAccumulationTimes, - Deposits: DefaultDeposits, - Borrows: DefaultBorrows, - TotalSupplied: DefaultTotalSupplied, - TotalBorrowed: DefaultTotalBorrowed, - TotalReserves: DefaultTotalReserves, - } -} - -// Validate performs basic validation of genesis data returning an -// error for any failed validation criteria. -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - if err := gs.PreviousAccumulationTimes.Validate(); err != nil { - return err - } - if err := gs.Deposits.Validate(); err != nil { - return err - } - if err := gs.Borrows.Validate(); err != nil { - return err - } - - if !gs.TotalSupplied.IsValid() { - return fmt.Errorf("invalid total supplied coins: %s", gs.TotalSupplied) - } - if !gs.TotalBorrowed.IsValid() { - return fmt.Errorf("invalid total borrowed coins: %s", gs.TotalBorrowed) - } - if !gs.TotalReserves.IsValid() { - return fmt.Errorf("invalid total reserves coins: %s", gs.TotalReserves) - } - return nil -} - -// NewGenesisAccumulationTime returns a new GenesisAccumulationTime -func NewGenesisAccumulationTime(ctype string, prevTime time.Time, supplyFactor, borrowFactor sdk.Dec) GenesisAccumulationTime { - return GenesisAccumulationTime{ - CollateralType: ctype, - PreviousAccumulationTime: prevTime, - SupplyInterestFactor: supplyFactor, - BorrowInterestFactor: borrowFactor, - } -} - -// GenesisAccumulationTimes slice of GenesisAccumulationTime -type GenesisAccumulationTimes []GenesisAccumulationTime - -// Validate performs validation of GenesisAccumulationTimes -func (gats GenesisAccumulationTimes) Validate() error { - for _, gat := range gats { - if err := gat.Validate(); err != nil { - return err - } - } - return nil -} - -// Validate performs validation of GenesisAccumulationTime -func (gat GenesisAccumulationTime) Validate() error { - if gat.SupplyInterestFactor.LT(sdk.OneDec()) { - return fmt.Errorf("supply interest factor should be ≥ 1.0, is %s for %s", gat.SupplyInterestFactor, gat.CollateralType) - } - if gat.BorrowInterestFactor.LT(sdk.OneDec()) { - return fmt.Errorf("borrow interest factor should be ≥ 1.0, is %s for %s", gat.BorrowInterestFactor, gat.CollateralType) - } - return nil -} diff --git a/x/hard/types/genesis.pb.go b/x/hard/types/genesis.pb.go deleted file mode 100644 index 45dcb84d..00000000 --- a/x/hard/types/genesis.pb.go +++ /dev/null @@ -1,1040 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/hard/v1beta1/genesis.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" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 hard module's genesis state. -type GenesisState struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - PreviousAccumulationTimes GenesisAccumulationTimes `protobuf:"bytes,2,rep,name=previous_accumulation_times,json=previousAccumulationTimes,proto3,castrepeated=GenesisAccumulationTimes" json:"previous_accumulation_times"` - Deposits Deposits `protobuf:"bytes,3,rep,name=deposits,proto3,castrepeated=Deposits" json:"deposits"` - Borrows Borrows `protobuf:"bytes,4,rep,name=borrows,proto3,castrepeated=Borrows" json:"borrows"` - TotalSupplied github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,5,rep,name=total_supplied,json=totalSupplied,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"total_supplied"` - TotalBorrowed github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,6,rep,name=total_borrowed,json=totalBorrowed,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"total_borrowed"` - TotalReserves github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,7,rep,name=total_reserves,json=totalReserves,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"total_reserves"` -} - -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_20a1f6c2cf728e74, []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) GetPreviousAccumulationTimes() GenesisAccumulationTimes { - if m != nil { - return m.PreviousAccumulationTimes - } - return nil -} - -func (m *GenesisState) GetDeposits() Deposits { - if m != nil { - return m.Deposits - } - return nil -} - -func (m *GenesisState) GetBorrows() Borrows { - if m != nil { - return m.Borrows - } - return nil -} - -func (m *GenesisState) GetTotalSupplied() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.TotalSupplied - } - return nil -} - -func (m *GenesisState) GetTotalBorrowed() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.TotalBorrowed - } - return nil -} - -func (m *GenesisState) GetTotalReserves() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.TotalReserves - } - return nil -} - -// GenesisAccumulationTime stores the previous distribution time and its corresponding denom. -type GenesisAccumulationTime struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - PreviousAccumulationTime time.Time `protobuf:"bytes,2,opt,name=previous_accumulation_time,json=previousAccumulationTime,proto3,stdtime" json:"previous_accumulation_time"` - SupplyInterestFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=supply_interest_factor,json=supplyInterestFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"supply_interest_factor"` - BorrowInterestFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=borrow_interest_factor,json=borrowInterestFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"borrow_interest_factor"` -} - -func (m *GenesisAccumulationTime) Reset() { *m = GenesisAccumulationTime{} } -func (m *GenesisAccumulationTime) String() string { return proto.CompactTextString(m) } -func (*GenesisAccumulationTime) ProtoMessage() {} -func (*GenesisAccumulationTime) Descriptor() ([]byte, []int) { - return fileDescriptor_20a1f6c2cf728e74, []int{1} -} -func (m *GenesisAccumulationTime) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisAccumulationTime) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisAccumulationTime.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 *GenesisAccumulationTime) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisAccumulationTime.Merge(m, src) -} -func (m *GenesisAccumulationTime) XXX_Size() int { - return m.Size() -} -func (m *GenesisAccumulationTime) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisAccumulationTime.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisAccumulationTime proto.InternalMessageInfo - -func (m *GenesisAccumulationTime) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func (m *GenesisAccumulationTime) GetPreviousAccumulationTime() time.Time { - if m != nil { - return m.PreviousAccumulationTime - } - return time.Time{} -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.hard.v1beta1.GenesisState") - proto.RegisterType((*GenesisAccumulationTime)(nil), "kava.hard.v1beta1.GenesisAccumulationTime") -} - -func init() { proto.RegisterFile("kava/hard/v1beta1/genesis.proto", fileDescriptor_20a1f6c2cf728e74) } - -var fileDescriptor_20a1f6c2cf728e74 = []byte{ - // 590 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x94, 0xcd, 0x6e, 0xd3, 0x40, - 0x10, 0xc7, 0xe3, 0xa6, 0x6d, 0xc2, 0x16, 0x5a, 0xb0, 0x2a, 0x70, 0x02, 0xb2, 0xa3, 0x1e, 0x20, - 0x42, 0x8a, 0x4d, 0xcb, 0x81, 0x0b, 0x07, 0x30, 0x11, 0x1f, 0x37, 0xe4, 0xe6, 0xc4, 0xc5, 0x5a, - 0x3b, 0x5b, 0xd7, 0xaa, 0x9d, 0xb5, 0x76, 0xd6, 0x81, 0xbc, 0x03, 0x42, 0x7d, 0x0e, 0xce, 0x3c, - 0x01, 0xa7, 0x1e, 0x2b, 0x4e, 0x88, 0x43, 0x8b, 0x92, 0x17, 0x41, 0xfb, 0x91, 0xa4, 0x28, 0x89, - 0xc4, 0x81, 0x9e, 0xe2, 0xdd, 0xfd, 0xcf, 0xff, 0x37, 0x3b, 0x3b, 0x13, 0xe4, 0x9c, 0xe0, 0x21, - 0xf6, 0x8e, 0x31, 0xeb, 0x7b, 0xc3, 0xfd, 0x88, 0x70, 0xbc, 0xef, 0x25, 0x64, 0x40, 0x20, 0x05, - 0xb7, 0x60, 0x94, 0x53, 0xf3, 0x8e, 0x10, 0xb8, 0x42, 0xe0, 0x6a, 0x41, 0xd3, 0x8e, 0x29, 0xe4, - 0x14, 0xbc, 0x08, 0x03, 0x99, 0x45, 0xc5, 0x34, 0x1d, 0xa8, 0x90, 0x66, 0x43, 0x9d, 0x87, 0x72, - 0xe5, 0xa9, 0x85, 0x3e, 0xda, 0x4d, 0x68, 0x42, 0xd5, 0xbe, 0xf8, 0xd2, 0xbb, 0x4e, 0x42, 0x69, - 0x92, 0x11, 0x4f, 0xae, 0xa2, 0xf2, 0xc8, 0xe3, 0x69, 0x4e, 0x80, 0xe3, 0xbc, 0xd0, 0x82, 0x07, - 0x8b, 0x59, 0xca, 0x8c, 0xe4, 0xe9, 0xde, 0xf7, 0x0d, 0x74, 0xf3, 0x8d, 0x4a, 0xfa, 0x90, 0x63, - 0x4e, 0xcc, 0x67, 0x68, 0xb3, 0xc0, 0x0c, 0xe7, 0x60, 0x19, 0x2d, 0xa3, 0xbd, 0x75, 0xd0, 0x70, - 0x17, 0x2e, 0xe1, 0xbe, 0x97, 0x02, 0x7f, 0xfd, 0xec, 0xc2, 0xa9, 0x04, 0x5a, 0x6e, 0x7e, 0x36, - 0xd0, 0xfd, 0x82, 0x91, 0x61, 0x4a, 0x4b, 0x08, 0x71, 0x1c, 0x97, 0x79, 0x99, 0x61, 0x9e, 0xd2, - 0x41, 0x28, 0x33, 0xb2, 0xd6, 0x5a, 0xd5, 0xf6, 0xd6, 0xc1, 0xe3, 0x25, 0x76, 0x9a, 0xff, 0xf2, - 0x4a, 0x4c, 0x2f, 0xcd, 0x89, 0xdf, 0x12, 0xfe, 0x5f, 0x2f, 0x1d, 0x6b, 0x85, 0x00, 0x82, 0xc6, - 0x14, 0xb8, 0x70, 0x64, 0xbe, 0x45, 0xf5, 0x3e, 0x29, 0x28, 0xa4, 0x1c, 0xac, 0xaa, 0x44, 0x37, - 0x97, 0xa0, 0xbb, 0x4a, 0xe2, 0xdf, 0xd6, 0xa8, 0xba, 0xde, 0x80, 0x60, 0x16, 0x6d, 0x76, 0x51, - 0x2d, 0xa2, 0x8c, 0xd1, 0x8f, 0x60, 0xad, 0x4b, 0xa3, 0x65, 0x25, 0xf1, 0xa5, 0xc2, 0xdf, 0xd1, - 0x3e, 0x35, 0xb5, 0x86, 0x60, 0x1a, 0x6a, 0x32, 0xb4, 0xcd, 0x29, 0xc7, 0x59, 0x08, 0x65, 0x51, - 0x64, 0x29, 0xe9, 0x5b, 0x1b, 0xda, 0x4c, 0x3f, 0xb2, 0xe8, 0x88, 0x99, 0xdd, 0x2b, 0x9a, 0x0e, - 0xfc, 0x27, 0xda, 0xac, 0x9d, 0xa4, 0xfc, 0xb8, 0x8c, 0xdc, 0x98, 0xe6, 0xba, 0x23, 0xf4, 0x4f, - 0x07, 0xfa, 0x27, 0x1e, 0x1f, 0x15, 0x04, 0x64, 0x00, 0x04, 0xb7, 0x24, 0xe2, 0x50, 0x13, 0xe6, - 0x4c, 0x95, 0x04, 0xe9, 0x5b, 0x9b, 0xd7, 0xc5, 0xf4, 0x35, 0x61, 0xce, 0x64, 0x04, 0x08, 0x1b, - 0x12, 0xb0, 0x6a, 0xd7, 0xc5, 0x0c, 0x34, 0x61, 0xef, 0x4b, 0x15, 0xdd, 0x5b, 0xd1, 0x23, 0xe6, - 0x23, 0xb4, 0x13, 0xd3, 0x2c, 0xc3, 0x9c, 0x30, 0x9c, 0x85, 0xc2, 0x44, 0x36, 0xf6, 0x8d, 0x60, - 0x7b, 0xbe, 0xdd, 0x1b, 0x15, 0xc4, 0x8c, 0x50, 0x73, 0x75, 0xfb, 0x5a, 0x6b, 0x72, 0x18, 0x9a, - 0xae, 0x9a, 0x36, 0x77, 0x3a, 0x6d, 0x6e, 0x6f, 0x3a, 0x6d, 0x7e, 0x5d, 0xdc, 0xe2, 0xf4, 0xd2, - 0x31, 0x02, 0x6b, 0x55, 0x57, 0x9a, 0x0c, 0xdd, 0x95, 0xcf, 0x3f, 0x0a, 0xd3, 0x01, 0x27, 0x8c, - 0x00, 0x0f, 0x8f, 0x70, 0xcc, 0x29, 0xb3, 0xaa, 0x22, 0x27, 0xff, 0xb9, 0xf0, 0xf8, 0x75, 0xe1, - 0x3c, 0xfc, 0x87, 0x4a, 0x74, 0x49, 0xfc, 0xe3, 0x5b, 0x07, 0xe9, 0xaa, 0x76, 0x49, 0x1c, 0xec, - 0x2a, 0xef, 0x77, 0xda, 0xfa, 0xb5, 0x74, 0x16, 0x4c, 0xf5, 0xfc, 0x0b, 0xcc, 0xf5, 0xff, 0xc1, - 0x54, 0xde, 0x7f, 0x33, 0xfd, 0x17, 0x67, 0x63, 0xdb, 0x38, 0x1f, 0xdb, 0xc6, 0xef, 0xb1, 0x6d, - 0x9c, 0x4e, 0xec, 0xca, 0xf9, 0xc4, 0xae, 0xfc, 0x9c, 0xd8, 0x95, 0x0f, 0x57, 0x29, 0x62, 0x8a, - 0x3a, 0x19, 0x8e, 0x40, 0x7e, 0x79, 0x9f, 0xd4, 0x9f, 0x94, 0x24, 0x45, 0x9b, 0xb2, 0xc2, 0x4f, - 0xff, 0x04, 0x00, 0x00, 0xff, 0xff, 0x16, 0xde, 0x3f, 0x0d, 0x64, 0x05, 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.TotalReserves) > 0 { - for iNdEx := len(m.TotalReserves) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TotalReserves[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - } - if len(m.TotalBorrowed) > 0 { - for iNdEx := len(m.TotalBorrowed) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TotalBorrowed[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - } - if len(m.TotalSupplied) > 0 { - for iNdEx := len(m.TotalSupplied) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TotalSupplied[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - } - if len(m.Borrows) > 0 { - for iNdEx := len(m.Borrows) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Borrows[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.PreviousAccumulationTimes) > 0 { - for iNdEx := len(m.PreviousAccumulationTimes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.PreviousAccumulationTimes[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 (m *GenesisAccumulationTime) 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 *GenesisAccumulationTime) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisAccumulationTime) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.BorrowInterestFactor.Size() - i -= size - if _, err := m.BorrowInterestFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.SupplyInterestFactor.Size() - i -= size - if _, err := m.SupplyInterestFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - n2, err2 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.PreviousAccumulationTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousAccumulationTime):]) - if err2 != nil { - return 0, err2 - } - i -= n2 - i = encodeVarintGenesis(dAtA, i, uint64(n2)) - i-- - dAtA[i] = 0x12 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.CollateralType))) - 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.PreviousAccumulationTimes) > 0 { - for _, e := range m.PreviousAccumulationTimes { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.Deposits) > 0 { - for _, e := range m.Deposits { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.Borrows) > 0 { - for _, e := range m.Borrows { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.TotalSupplied) > 0 { - for _, e := range m.TotalSupplied { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.TotalBorrowed) > 0 { - for _, e := range m.TotalBorrowed { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.TotalReserves) > 0 { - for _, e := range m.TotalReserves { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func (m *GenesisAccumulationTime) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousAccumulationTime) - n += 1 + l + sovGenesis(uint64(l)) - l = m.SupplyInterestFactor.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.BorrowInterestFactor.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 PreviousAccumulationTimes", 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.PreviousAccumulationTimes = append(m.PreviousAccumulationTimes, GenesisAccumulationTime{}) - if err := m.PreviousAccumulationTimes[len(m.PreviousAccumulationTimes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposits", 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.Deposits = append(m.Deposits, Deposit{}) - if err := m.Deposits[len(m.Deposits)-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 Borrows", 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.Borrows = append(m.Borrows, Borrow{}) - if err := m.Borrows[len(m.Borrows)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalSupplied", 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.TotalSupplied = append(m.TotalSupplied, types.Coin{}) - if err := m.TotalSupplied[len(m.TotalSupplied)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalBorrowed", 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.TotalBorrowed = append(m.TotalBorrowed, types.Coin{}) - if err := m.TotalBorrowed[len(m.TotalBorrowed)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalReserves", 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.TotalReserves = append(m.TotalReserves, types.Coin{}) - if err := m.TotalReserves[len(m.TotalReserves)-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 (m *GenesisAccumulationTime) 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: GenesisAccumulationTime: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisAccumulationTime: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PreviousAccumulationTime", 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 := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.PreviousAccumulationTime, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SupplyInterestFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SupplyInterestFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BorrowInterestFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BorrowInterestFactor.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/hard/types/genesis_test.go b/x/hard/types/genesis_test.go deleted file mode 100644 index 2769040c..00000000 --- a/x/hard/types/genesis_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package types_test - -import ( - "strings" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/hard/types" -) - -const ( - USDX_CF = 1000000 - KAVA_CF = 1000000 - BTCB_CF = 100000000 - BNB_CF = 100000000 - BUSD_CF = 100000000 -) - -type GenesisTestSuite struct { - suite.Suite -} - -func (suite *GenesisTestSuite) TestGenesisValidation() { - type args struct { - params types.Params - gats types.GenesisAccumulationTimes - deps types.Deposits - brws types.Borrows - ts sdk.Coins - tb sdk.Coins - tr sdk.Coins - } - testCases := []struct { - name string - args args - expectPass bool - expectedErr string - }{ - { - name: "default", - args: args{ - params: types.DefaultParams(), - gats: types.DefaultAccumulationTimes, - deps: types.DefaultDeposits, - brws: types.DefaultBorrows, - ts: types.DefaultTotalSupplied, - tb: types.DefaultTotalBorrowed, - tr: types.DefaultTotalReserves, - }, - expectPass: true, - expectedErr: "", - }, - { - name: "valid", - args: args{ - params: types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("usdx", types.NewBorrowLimit(true, sdk.MustNewDecFromStr("100000000000"), sdk.MustNewDecFromStr("1")), "usdx:usd", sdkmath.NewInt(USDX_CF), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - }, - sdk.MustNewDecFromStr("10"), - ), - gats: types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime("usdx", time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), sdk.OneDec(), sdk.OneDec()), - }, - deps: types.DefaultDeposits, - brws: types.DefaultBorrows, - ts: sdk.Coins{}, - tb: sdk.Coins{}, - tr: sdk.Coins{}, - }, - expectPass: true, - expectedErr: "", - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - gs := types.NewGenesisState(tc.args.params, tc.args.gats, tc.args.deps, tc.args.brws, tc.args.ts, tc.args.tb, tc.args.tr) - err := gs.Validate() - if tc.expectPass { - suite.NoError(err) - } else { - suite.Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.expectedErr)) - } - }) - } -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(GenesisTestSuite)) -} diff --git a/x/hard/types/hard.pb.go b/x/hard/types/hard.pb.go deleted file mode 100644 index e7de080b..00000000 --- a/x/hard/types/hard.pb.go +++ /dev/null @@ -1,2559 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/hard/v1beta1/hard.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" - 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 hard module. -type Params struct { - MoneyMarkets MoneyMarkets `protobuf:"bytes,1,rep,name=money_markets,json=moneyMarkets,proto3,castrepeated=MoneyMarkets" json:"money_markets"` - MinimumBorrowUSDValue github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=minimum_borrow_usd_value,json=minimumBorrowUsdValue,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"minimum_borrow_usd_value"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []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 - -// MoneyMarket is a money market for an individual asset. -type MoneyMarket struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - BorrowLimit BorrowLimit `protobuf:"bytes,2,opt,name=borrow_limit,json=borrowLimit,proto3" json:"borrow_limit"` - SpotMarketID string `protobuf:"bytes,3,opt,name=spot_market_id,json=spotMarketId,proto3" json:"spot_market_id,omitempty"` - ConversionFactor github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,4,opt,name=conversion_factor,json=conversionFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"conversion_factor"` - InterestRateModel InterestRateModel `protobuf:"bytes,5,opt,name=interest_rate_model,json=interestRateModel,proto3" json:"interest_rate_model"` - ReserveFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,6,opt,name=reserve_factor,json=reserveFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"reserve_factor"` - KeeperRewardPercentage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,7,opt,name=keeper_reward_percentage,json=keeperRewardPercentage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"keeper_reward_percentage"` -} - -func (m *MoneyMarket) Reset() { *m = MoneyMarket{} } -func (m *MoneyMarket) String() string { return proto.CompactTextString(m) } -func (*MoneyMarket) ProtoMessage() {} -func (*MoneyMarket) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []int{1} -} -func (m *MoneyMarket) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MoneyMarket) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MoneyMarket.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 *MoneyMarket) XXX_Merge(src proto.Message) { - xxx_messageInfo_MoneyMarket.Merge(m, src) -} -func (m *MoneyMarket) XXX_Size() int { - return m.Size() -} -func (m *MoneyMarket) XXX_DiscardUnknown() { - xxx_messageInfo_MoneyMarket.DiscardUnknown(m) -} - -var xxx_messageInfo_MoneyMarket proto.InternalMessageInfo - -// BorrowLimit enforces restrictions on a money market. -type BorrowLimit struct { - HasMaxLimit bool `protobuf:"varint,1,opt,name=has_max_limit,json=hasMaxLimit,proto3" json:"has_max_limit"` - MaximumLimit github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=maximum_limit,json=maximumLimit,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"maximum_limit"` - LoanToValue github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=loan_to_value,json=loanToValue,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"loan_to_value"` -} - -func (m *BorrowLimit) Reset() { *m = BorrowLimit{} } -func (m *BorrowLimit) String() string { return proto.CompactTextString(m) } -func (*BorrowLimit) ProtoMessage() {} -func (*BorrowLimit) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []int{2} -} -func (m *BorrowLimit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BorrowLimit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BorrowLimit.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 *BorrowLimit) XXX_Merge(src proto.Message) { - xxx_messageInfo_BorrowLimit.Merge(m, src) -} -func (m *BorrowLimit) XXX_Size() int { - return m.Size() -} -func (m *BorrowLimit) XXX_DiscardUnknown() { - xxx_messageInfo_BorrowLimit.DiscardUnknown(m) -} - -var xxx_messageInfo_BorrowLimit proto.InternalMessageInfo - -// InterestRateModel contains information about an asset's interest rate. -type InterestRateModel struct { - BaseRateAPY github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=base_rate_apy,json=baseRateApy,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"base_rate_apy"` - BaseMultiplier github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=base_multiplier,json=baseMultiplier,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"base_multiplier"` - Kink github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=kink,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"kink"` - JumpMultiplier github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=jump_multiplier,json=jumpMultiplier,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"jump_multiplier"` -} - -func (m *InterestRateModel) Reset() { *m = InterestRateModel{} } -func (m *InterestRateModel) String() string { return proto.CompactTextString(m) } -func (*InterestRateModel) ProtoMessage() {} -func (*InterestRateModel) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []int{3} -} -func (m *InterestRateModel) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *InterestRateModel) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_InterestRateModel.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 *InterestRateModel) XXX_Merge(src proto.Message) { - xxx_messageInfo_InterestRateModel.Merge(m, src) -} -func (m *InterestRateModel) XXX_Size() int { - return m.Size() -} -func (m *InterestRateModel) XXX_DiscardUnknown() { - xxx_messageInfo_InterestRateModel.DiscardUnknown(m) -} - -var xxx_messageInfo_InterestRateModel proto.InternalMessageInfo - -// Deposit defines an amount of coins deposited into a hard module account. -type Deposit struct { - Depositor github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=depositor,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"depositor,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` - Index SupplyInterestFactors `protobuf:"bytes,3,rep,name=index,proto3,castrepeated=SupplyInterestFactors" json:"index"` -} - -func (m *Deposit) Reset() { *m = Deposit{} } -func (m *Deposit) String() string { return proto.CompactTextString(m) } -func (*Deposit) ProtoMessage() {} -func (*Deposit) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []int{4} -} -func (m *Deposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Deposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Deposit.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 *Deposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_Deposit.Merge(m, src) -} -func (m *Deposit) XXX_Size() int { - return m.Size() -} -func (m *Deposit) XXX_DiscardUnknown() { - xxx_messageInfo_Deposit.DiscardUnknown(m) -} - -var xxx_messageInfo_Deposit proto.InternalMessageInfo - -// Borrow defines an amount of coins borrowed from a hard module account. -type Borrow struct { - Borrower github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=borrower,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"borrower,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` - Index BorrowInterestFactors `protobuf:"bytes,3,rep,name=index,proto3,castrepeated=BorrowInterestFactors" json:"index"` -} - -func (m *Borrow) Reset() { *m = Borrow{} } -func (m *Borrow) String() string { return proto.CompactTextString(m) } -func (*Borrow) ProtoMessage() {} -func (*Borrow) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []int{5} -} -func (m *Borrow) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Borrow) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Borrow.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 *Borrow) XXX_Merge(src proto.Message) { - xxx_messageInfo_Borrow.Merge(m, src) -} -func (m *Borrow) XXX_Size() int { - return m.Size() -} -func (m *Borrow) XXX_DiscardUnknown() { - xxx_messageInfo_Borrow.DiscardUnknown(m) -} - -var xxx_messageInfo_Borrow proto.InternalMessageInfo - -// SupplyInterestFactor defines an individual borrow interest factor. -type SupplyInterestFactor struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Value github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=value,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"value"` -} - -func (m *SupplyInterestFactor) Reset() { *m = SupplyInterestFactor{} } -func (m *SupplyInterestFactor) String() string { return proto.CompactTextString(m) } -func (*SupplyInterestFactor) ProtoMessage() {} -func (*SupplyInterestFactor) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []int{6} -} -func (m *SupplyInterestFactor) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SupplyInterestFactor) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SupplyInterestFactor.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 *SupplyInterestFactor) XXX_Merge(src proto.Message) { - xxx_messageInfo_SupplyInterestFactor.Merge(m, src) -} -func (m *SupplyInterestFactor) XXX_Size() int { - return m.Size() -} -func (m *SupplyInterestFactor) XXX_DiscardUnknown() { - xxx_messageInfo_SupplyInterestFactor.DiscardUnknown(m) -} - -var xxx_messageInfo_SupplyInterestFactor proto.InternalMessageInfo - -// BorrowInterestFactor defines an individual borrow interest factor. -type BorrowInterestFactor struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Value github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=value,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"value"` -} - -func (m *BorrowInterestFactor) Reset() { *m = BorrowInterestFactor{} } -func (m *BorrowInterestFactor) String() string { return proto.CompactTextString(m) } -func (*BorrowInterestFactor) ProtoMessage() {} -func (*BorrowInterestFactor) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []int{7} -} -func (m *BorrowInterestFactor) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BorrowInterestFactor) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BorrowInterestFactor.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 *BorrowInterestFactor) XXX_Merge(src proto.Message) { - xxx_messageInfo_BorrowInterestFactor.Merge(m, src) -} -func (m *BorrowInterestFactor) XXX_Size() int { - return m.Size() -} -func (m *BorrowInterestFactor) XXX_DiscardUnknown() { - xxx_messageInfo_BorrowInterestFactor.DiscardUnknown(m) -} - -var xxx_messageInfo_BorrowInterestFactor proto.InternalMessageInfo - -// CoinsProto defines a Protobuf wrapper around a Coins slice -type CoinsProto struct { - Coins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=coins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"coins"` -} - -func (m *CoinsProto) Reset() { *m = CoinsProto{} } -func (m *CoinsProto) String() string { return proto.CompactTextString(m) } -func (*CoinsProto) ProtoMessage() {} -func (*CoinsProto) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []int{8} -} -func (m *CoinsProto) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CoinsProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CoinsProto.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 *CoinsProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_CoinsProto.Merge(m, src) -} -func (m *CoinsProto) XXX_Size() int { - return m.Size() -} -func (m *CoinsProto) XXX_DiscardUnknown() { - xxx_messageInfo_CoinsProto.DiscardUnknown(m) -} - -var xxx_messageInfo_CoinsProto proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Params)(nil), "kava.hard.v1beta1.Params") - proto.RegisterType((*MoneyMarket)(nil), "kava.hard.v1beta1.MoneyMarket") - proto.RegisterType((*BorrowLimit)(nil), "kava.hard.v1beta1.BorrowLimit") - proto.RegisterType((*InterestRateModel)(nil), "kava.hard.v1beta1.InterestRateModel") - proto.RegisterType((*Deposit)(nil), "kava.hard.v1beta1.Deposit") - proto.RegisterType((*Borrow)(nil), "kava.hard.v1beta1.Borrow") - proto.RegisterType((*SupplyInterestFactor)(nil), "kava.hard.v1beta1.SupplyInterestFactor") - proto.RegisterType((*BorrowInterestFactor)(nil), "kava.hard.v1beta1.BorrowInterestFactor") - proto.RegisterType((*CoinsProto)(nil), "kava.hard.v1beta1.CoinsProto") -} - -func init() { proto.RegisterFile("kava/hard/v1beta1/hard.proto", fileDescriptor_23a5de800263a2ff) } - -var fileDescriptor_23a5de800263a2ff = []byte{ - // 911 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x56, 0xbd, 0x8f, 0x1b, 0x45, - 0x14, 0xf7, 0x9e, 0x3f, 0x92, 0x8c, 0xed, 0x23, 0xde, 0xdc, 0xa1, 0x4d, 0x04, 0xeb, 0xc8, 0x42, - 0x70, 0x8d, 0x6d, 0x02, 0x82, 0x8a, 0xe6, 0x16, 0x0b, 0x38, 0x81, 0x25, 0x6b, 0x8f, 0x20, 0x25, - 0x42, 0x5a, 0xc6, 0xbb, 0x2f, 0x77, 0x83, 0x3d, 0x3b, 0xab, 0x99, 0xb1, 0x63, 0x77, 0xb4, 0x34, - 0x88, 0x3f, 0x82, 0x8a, 0x0e, 0xe9, 0xfe, 0x88, 0x2b, 0xa3, 0x54, 0x88, 0xc2, 0x80, 0xaf, 0xa3, - 0xa6, 0xa2, 0x42, 0xf3, 0xe1, 0x8f, 0x5c, 0x1c, 0x29, 0xa7, 0x58, 0x88, 0x6a, 0x77, 0xe6, 0xbd, - 0xf9, 0xbd, 0xdf, 0xfb, 0xcd, 0x9b, 0x99, 0x87, 0xde, 0x18, 0xe0, 0x31, 0x6e, 0x9f, 0x62, 0x9e, - 0xb4, 0xc7, 0xf7, 0xfa, 0x20, 0xf1, 0x3d, 0x3d, 0x68, 0x65, 0x9c, 0x49, 0xe6, 0xd6, 0x94, 0xb5, - 0xa5, 0x27, 0xac, 0xf5, 0x8e, 0x1f, 0x33, 0x41, 0x99, 0x68, 0xf7, 0xb1, 0x80, 0xe5, 0x92, 0x98, - 0x91, 0xd4, 0x2c, 0xb9, 0x73, 0xdb, 0xd8, 0x23, 0x3d, 0x6a, 0x9b, 0x81, 0x35, 0xed, 0x9d, 0xb0, - 0x13, 0x66, 0xe6, 0xd5, 0x9f, 0x99, 0x6d, 0xfc, 0xed, 0xa0, 0x52, 0x0f, 0x73, 0x4c, 0x85, 0xfb, - 0x00, 0x55, 0x29, 0x4b, 0x61, 0x1a, 0x51, 0xcc, 0x07, 0x20, 0x85, 0xe7, 0xdc, 0xcd, 0x1f, 0x94, - 0xdf, 0xf3, 0x5b, 0xcf, 0xd1, 0x68, 0x75, 0x95, 0x5f, 0x57, 0xbb, 0x05, 0x7b, 0xe7, 0xb3, 0x7a, - 0xee, 0xe7, 0xdf, 0xeb, 0x95, 0xb5, 0x49, 0x11, 0x56, 0xe8, 0xda, 0xc8, 0xfd, 0xc1, 0x41, 0x1e, - 0x25, 0x29, 0xa1, 0x23, 0x1a, 0xf5, 0x19, 0xe7, 0xec, 0x71, 0x34, 0x12, 0x49, 0x34, 0xc6, 0xc3, - 0x11, 0x78, 0x3b, 0x77, 0x9d, 0x83, 0x1b, 0xc1, 0x7d, 0x05, 0xf3, 0xdb, 0xac, 0xfe, 0xf6, 0x09, - 0x91, 0xa7, 0xa3, 0x7e, 0x2b, 0x66, 0xd4, 0xf2, 0xb7, 0x9f, 0xa6, 0x48, 0x06, 0x6d, 0x39, 0xcd, - 0x40, 0xb4, 0x3a, 0x10, 0xcf, 0x67, 0xf5, 0xfd, 0xae, 0x41, 0x0c, 0x34, 0xe0, 0xfd, 0xe3, 0xce, - 0x57, 0x0a, 0xee, 0xe9, 0x59, 0x13, 0xd9, 0xbc, 0x3b, 0x10, 0x87, 0xfb, 0xf4, 0x19, 0x27, 0x91, - 0x68, 0xa7, 0xc6, 0x79, 0x01, 0x95, 0xd7, 0xf8, 0xba, 0x7b, 0xa8, 0x98, 0x40, 0xca, 0xa8, 0xe7, - 0x28, 0x32, 0xa1, 0x19, 0xb8, 0x9f, 0xa2, 0x8a, 0x65, 0x3b, 0x24, 0x94, 0x48, 0xcd, 0x74, 0xb3, - 0x20, 0x06, 0xfe, 0x0b, 0xe5, 0x15, 0x14, 0x54, 0x26, 0x61, 0xb9, 0xbf, 0x9a, 0x72, 0x3f, 0x44, - 0xbb, 0x22, 0x63, 0xd2, 0x2a, 0x1b, 0x91, 0xc4, 0xcb, 0xeb, 0xa4, 0x6f, 0xce, 0x67, 0xf5, 0xca, - 0x71, 0xc6, 0xa4, 0xa1, 0x71, 0xd4, 0x09, 0x2b, 0x62, 0x35, 0x4a, 0x5c, 0x82, 0x6a, 0x31, 0x4b, - 0xc7, 0xc0, 0x05, 0x61, 0x69, 0xf4, 0x08, 0xc7, 0x92, 0x71, 0xaf, 0xa0, 0x97, 0x7e, 0x74, 0x05, - 0xbd, 0x8e, 0x52, 0xb9, 0x26, 0xcb, 0x51, 0x2a, 0xc3, 0x9b, 0x2b, 0xd8, 0x4f, 0x34, 0xaa, 0xfb, - 0x10, 0xdd, 0x22, 0xa9, 0x04, 0x0e, 0x42, 0x46, 0x1c, 0x4b, 0x88, 0x28, 0x4b, 0x60, 0xe8, 0x15, - 0x75, 0xca, 0x6f, 0x6d, 0x48, 0xf9, 0xc8, 0x7a, 0x87, 0x58, 0x42, 0x57, 0xf9, 0xda, 0xc4, 0x6b, - 0xe4, 0xb2, 0xc1, 0x8d, 0xd1, 0x2e, 0x07, 0x01, 0x7c, 0x0c, 0x8b, 0x1c, 0x4a, 0x57, 0xce, 0xa1, - 0x03, 0xf1, 0xa5, 0xad, 0xad, 0x5a, 0x4c, 0x9b, 0xc0, 0x18, 0x79, 0x03, 0x80, 0x0c, 0x78, 0xc4, - 0xe1, 0x31, 0xe6, 0x49, 0x94, 0x01, 0x8f, 0x21, 0x95, 0xf8, 0x04, 0xbc, 0x6b, 0x5b, 0x08, 0xf7, - 0xba, 0x41, 0x0f, 0x35, 0x78, 0x6f, 0x89, 0xdd, 0xf8, 0x7e, 0x07, 0x95, 0xd7, 0xb6, 0xdf, 0xfd, - 0x00, 0x55, 0x4f, 0xb1, 0x88, 0x28, 0x9e, 0xd8, 0xaa, 0x51, 0x25, 0x75, 0x3d, 0xa8, 0xfd, 0x35, - 0xab, 0x3f, 0x6b, 0x08, 0xcb, 0xa7, 0x58, 0x74, 0xf1, 0xc4, 0x2c, 0xc3, 0xa8, 0x4a, 0xf1, 0x44, - 0x9f, 0x90, 0x55, 0xb1, 0xbd, 0x2a, 0xe7, 0x8a, 0x85, 0x34, 0x21, 0xbe, 0x41, 0xd5, 0x21, 0xc3, - 0x69, 0x24, 0x99, 0x3d, 0x79, 0xf9, 0x2d, 0x84, 0x28, 0x2b, 0xc8, 0x2f, 0x99, 0x39, 0x56, 0x3f, - 0xe5, 0x51, 0xed, 0xb9, 0xba, 0x70, 0x19, 0xaa, 0xaa, 0xfb, 0xca, 0x94, 0x15, 0xce, 0xa6, 0xe6, - 0x90, 0x05, 0x9f, 0x5f, 0xf9, 0xc4, 0x97, 0x03, 0x2c, 0x40, 0xe1, 0x1e, 0xf6, 0x1e, 0x5c, 0xa6, - 0xd1, 0x5f, 0x98, 0xb2, 0xa9, 0x0b, 0xe8, 0x35, 0x1d, 0x90, 0x8e, 0x86, 0x92, 0x64, 0x43, 0x02, - 0x7c, 0x2b, 0x6a, 0xee, 0x2a, 0xd0, 0xee, 0x12, 0xd3, 0xed, 0xa1, 0xc2, 0x80, 0xa4, 0x83, 0xad, - 0xc8, 0xa8, 0x91, 0x14, 0xf1, 0x6f, 0x47, 0x34, 0x5b, 0x27, 0x5e, 0xd8, 0x06, 0x71, 0x05, 0xba, - 0x22, 0xde, 0x38, 0xdb, 0x41, 0xd7, 0x3a, 0x90, 0x31, 0x41, 0xa4, 0xfb, 0x08, 0xdd, 0x48, 0xcc, - 0x2f, 0xe3, 0x76, 0x63, 0x3e, 0xfb, 0x67, 0x56, 0x6f, 0xbe, 0x44, 0xa0, 0xc3, 0x38, 0x3e, 0x4c, - 0x12, 0x0e, 0x42, 0x3c, 0x3d, 0x6b, 0xde, 0xb2, 0xf1, 0xec, 0x4c, 0x30, 0x95, 0x20, 0xc2, 0x15, - 0xb4, 0x1b, 0xa3, 0x12, 0xa6, 0x6c, 0x94, 0xaa, 0xc2, 0x56, 0xcf, 0xca, 0xed, 0x96, 0x5d, 0xa0, - 0x44, 0x5d, 0x5e, 0x2a, 0x1f, 0x33, 0x92, 0x06, 0xef, 0xda, 0x17, 0xe5, 0xe0, 0x25, 0x38, 0xa8, - 0x05, 0x22, 0xb4, 0xd0, 0xee, 0xd7, 0xa8, 0x48, 0xd2, 0x04, 0x26, 0x5e, 0x5e, 0xc7, 0x78, 0x67, - 0xc3, 0xb5, 0x75, 0x3c, 0xca, 0xb2, 0xe1, 0x74, 0x51, 0xa4, 0xe6, 0xee, 0x08, 0xde, 0xb4, 0x11, - 0xf7, 0x37, 0x59, 0x45, 0x68, 0x40, 0x1b, 0xbf, 0xec, 0xa0, 0x92, 0x39, 0xe9, 0x6e, 0x82, 0xae, - 0x9b, 0xfb, 0x1d, 0xb6, 0x2f, 0xda, 0x12, 0xf9, 0x7f, 0xa3, 0x99, 0x49, 0xfa, 0x45, 0x9a, 0x6d, - 0xb2, 0x2e, 0x35, 0xfb, 0xce, 0x41, 0x7b, 0x9b, 0x44, 0x7d, 0xc1, 0x8b, 0x1b, 0xa2, 0xe2, 0x7a, - 0x53, 0xf0, 0x6a, 0x65, 0x6f, 0xa0, 0x34, 0x85, 0x4d, 0x1c, 0xff, 0x43, 0x0a, 0x0c, 0x21, 0x2d, - 0x7a, 0x4f, 0xf7, 0x75, 0x18, 0x15, 0x55, 0xcb, 0xb6, 0x68, 0xb0, 0xb6, 0xba, 0xab, 0x06, 0x39, - 0xe8, 0x9c, 0xff, 0xe9, 0xe7, 0xce, 0xe7, 0xbe, 0xf3, 0x64, 0xee, 0x3b, 0x7f, 0xcc, 0x7d, 0xe7, - 0xc7, 0x0b, 0x3f, 0xf7, 0xe4, 0xc2, 0xcf, 0xfd, 0x7a, 0xe1, 0xe7, 0x1e, 0xae, 0xe7, 0xa2, 0x76, - 0xbb, 0x39, 0xc4, 0x7d, 0xa1, 0xff, 0xda, 0x13, 0xd3, 0x8d, 0x6a, 0xc8, 0x7e, 0x49, 0xf7, 0x88, - 0xef, 0xff, 0x1b, 0x00, 0x00, 0xff, 0xff, 0x40, 0xda, 0xa7, 0xd8, 0xa7, 0x0a, 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 - { - size := m.MinimumBorrowUSDValue.Size() - i -= size - if _, err := m.MinimumBorrowUSDValue.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.MoneyMarkets) > 0 { - for iNdEx := len(m.MoneyMarkets) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.MoneyMarkets[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *MoneyMarket) 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 *MoneyMarket) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MoneyMarket) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.KeeperRewardPercentage.Size() - i -= size - if _, err := m.KeeperRewardPercentage.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - { - size := m.ReserveFactor.Size() - i -= size - if _, err := m.ReserveFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.InterestRateModel.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.ConversionFactor.Size() - i -= size - if _, err := m.ConversionFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - if len(m.SpotMarketID) > 0 { - i -= len(m.SpotMarketID) - copy(dAtA[i:], m.SpotMarketID) - i = encodeVarintHard(dAtA, i, uint64(len(m.SpotMarketID))) - i-- - dAtA[i] = 0x1a - } - { - size, err := m.BorrowLimit.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintHard(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *BorrowLimit) 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 *BorrowLimit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *BorrowLimit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.LoanToValue.Size() - i -= size - if _, err := m.LoanToValue.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.MaximumLimit.Size() - i -= size - if _, err := m.MaximumLimit.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.HasMaxLimit { - i-- - if m.HasMaxLimit { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *InterestRateModel) 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 *InterestRateModel) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *InterestRateModel) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.JumpMultiplier.Size() - i -= size - if _, err := m.JumpMultiplier.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.Kink.Size() - i -= size - if _, err := m.Kink.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.BaseMultiplier.Size() - i -= size - if _, err := m.BaseMultiplier.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.BaseRateAPY.Size() - i -= size - if _, err := m.BaseRateAPY.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *Deposit) 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 *Deposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Deposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Index) > 0 { - for iNdEx := len(m.Index) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Index[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintHard(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *Borrow) 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 *Borrow) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Borrow) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Index) > 0 { - for iNdEx := len(m.Index) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Index[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Borrower) > 0 { - i -= len(m.Borrower) - copy(dAtA[i:], m.Borrower) - i = encodeVarintHard(dAtA, i, uint64(len(m.Borrower))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *SupplyInterestFactor) 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 *SupplyInterestFactor) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SupplyInterestFactor) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Value.Size() - i -= size - if _, err := m.Value.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintHard(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *BorrowInterestFactor) 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 *BorrowInterestFactor) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *BorrowInterestFactor) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Value.Size() - i -= size - if _, err := m.Value.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintHard(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CoinsProto) 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 *CoinsProto) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CoinsProto) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Coins) > 0 { - for iNdEx := len(m.Coins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Coins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintHard(dAtA []byte, offset int, v uint64) int { - offset -= sovHard(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 - if len(m.MoneyMarkets) > 0 { - for _, e := range m.MoneyMarkets { - l = e.Size() - n += 1 + l + sovHard(uint64(l)) - } - } - l = m.MinimumBorrowUSDValue.Size() - n += 1 + l + sovHard(uint64(l)) - return n -} - -func (m *MoneyMarket) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovHard(uint64(l)) - } - l = m.BorrowLimit.Size() - n += 1 + l + sovHard(uint64(l)) - l = len(m.SpotMarketID) - if l > 0 { - n += 1 + l + sovHard(uint64(l)) - } - l = m.ConversionFactor.Size() - n += 1 + l + sovHard(uint64(l)) - l = m.InterestRateModel.Size() - n += 1 + l + sovHard(uint64(l)) - l = m.ReserveFactor.Size() - n += 1 + l + sovHard(uint64(l)) - l = m.KeeperRewardPercentage.Size() - n += 1 + l + sovHard(uint64(l)) - return n -} - -func (m *BorrowLimit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.HasMaxLimit { - n += 2 - } - l = m.MaximumLimit.Size() - n += 1 + l + sovHard(uint64(l)) - l = m.LoanToValue.Size() - n += 1 + l + sovHard(uint64(l)) - return n -} - -func (m *InterestRateModel) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseRateAPY.Size() - n += 1 + l + sovHard(uint64(l)) - l = m.BaseMultiplier.Size() - n += 1 + l + sovHard(uint64(l)) - l = m.Kink.Size() - n += 1 + l + sovHard(uint64(l)) - l = m.JumpMultiplier.Size() - n += 1 + l + sovHard(uint64(l)) - return n -} - -func (m *Deposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovHard(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovHard(uint64(l)) - } - } - if len(m.Index) > 0 { - for _, e := range m.Index { - l = e.Size() - n += 1 + l + sovHard(uint64(l)) - } - } - return n -} - -func (m *Borrow) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Borrower) - if l > 0 { - n += 1 + l + sovHard(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovHard(uint64(l)) - } - } - if len(m.Index) > 0 { - for _, e := range m.Index { - l = e.Size() - n += 1 + l + sovHard(uint64(l)) - } - } - return n -} - -func (m *SupplyInterestFactor) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovHard(uint64(l)) - } - l = m.Value.Size() - n += 1 + l + sovHard(uint64(l)) - return n -} - -func (m *BorrowInterestFactor) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovHard(uint64(l)) - } - l = m.Value.Size() - n += 1 + l + sovHard(uint64(l)) - return n -} - -func (m *CoinsProto) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Coins) > 0 { - for _, e := range m.Coins { - l = e.Size() - n += 1 + l + sovHard(uint64(l)) - } - } - return n -} - -func sovHard(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozHard(x uint64) (n int) { - return sovHard(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 ErrIntOverflowHard - } - 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 { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MoneyMarkets", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MoneyMarkets = append(m.MoneyMarkets, MoneyMarket{}) - if err := m.MoneyMarkets[len(m.MoneyMarkets)-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 MinimumBorrowUSDValue", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MinimumBorrowUSDValue.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MoneyMarket) 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 ErrIntOverflowHard - } - 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: MoneyMarket: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MoneyMarket: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BorrowLimit", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BorrowLimit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SpotMarketID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SpotMarketID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ConversionFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ConversionFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InterestRateModel", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.InterestRateModel.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ReserveFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ReserveFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field KeeperRewardPercentage", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.KeeperRewardPercentage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *BorrowLimit) 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 ErrIntOverflowHard - } - 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: BorrowLimit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BorrowLimit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field HasMaxLimit", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.HasMaxLimit = bool(v != 0) - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaximumLimit", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MaximumLimit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LoanToValue", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.LoanToValue.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *InterestRateModel) 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 ErrIntOverflowHard - } - 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: InterestRateModel: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: InterestRateModel: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseRateAPY", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseRateAPY.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseMultiplier", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseMultiplier.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Kink", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Kink.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field JumpMultiplier", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.JumpMultiplier.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Deposit) 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 ErrIntOverflowHard - } - 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: Deposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Deposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = github_com_cosmos_cosmos_sdk_types.AccAddress(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Index = append(m.Index, SupplyInterestFactor{}) - if err := m.Index[len(m.Index)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Borrow) 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 ErrIntOverflowHard - } - 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: Borrow: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Borrow: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Borrower", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Borrower = github_com_cosmos_cosmos_sdk_types.AccAddress(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Index = append(m.Index, BorrowInterestFactor{}) - if err := m.Index[len(m.Index)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *SupplyInterestFactor) 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 ErrIntOverflowHard - } - 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: SupplyInterestFactor: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SupplyInterestFactor: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *BorrowInterestFactor) 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 ErrIntOverflowHard - } - 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: BorrowInterestFactor: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BorrowInterestFactor: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - 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 ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CoinsProto) 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 ErrIntOverflowHard - } - 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: CoinsProto: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CoinsProto: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Coins", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Coins = append(m.Coins, types.Coin{}) - if err := m.Coins[len(m.Coins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipHard(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, ErrIntOverflowHard - } - 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, ErrIntOverflowHard - } - 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, ErrIntOverflowHard - } - 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, ErrInvalidLengthHard - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupHard - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthHard - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthHard = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowHard = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupHard = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/hard/types/hooks.go b/x/hard/types/hooks.go deleted file mode 100644 index 80260d87..00000000 --- a/x/hard/types/hooks.go +++ /dev/null @@ -1,53 +0,0 @@ -package types - -import sdk "github.com/cosmos/cosmos-sdk/types" - -// MultiHARDHooks combine multiple HARD hooks, all hook functions are run in array sequence -type MultiHARDHooks []HARDHooks - -// NewMultiHARDHooks returns a new MultiHARDHooks -func NewMultiHARDHooks(hooks ...HARDHooks) MultiHARDHooks { - return hooks -} - -// AfterDepositCreated runs after a deposit is created -func (h MultiHARDHooks) AfterDepositCreated(ctx sdk.Context, deposit Deposit) { - for i := range h { - h[i].AfterDepositCreated(ctx, deposit) - } -} - -// BeforeDepositModified runs before a deposit is modified -func (h MultiHARDHooks) BeforeDepositModified(ctx sdk.Context, deposit Deposit) { - for i := range h { - h[i].BeforeDepositModified(ctx, deposit) - } -} - -// AfterDepositModified runs after a deposit is modified -func (h MultiHARDHooks) AfterDepositModified(ctx sdk.Context, deposit Deposit) { - for i := range h { - h[i].AfterDepositModified(ctx, deposit) - } -} - -// AfterBorrowCreated runs after a borrow is created -func (h MultiHARDHooks) AfterBorrowCreated(ctx sdk.Context, borrow Borrow) { - for i := range h { - h[i].AfterBorrowCreated(ctx, borrow) - } -} - -// BeforeBorrowModified runs before a borrow is modified -func (h MultiHARDHooks) BeforeBorrowModified(ctx sdk.Context, borrow Borrow) { - for i := range h { - h[i].BeforeBorrowModified(ctx, borrow) - } -} - -// AfterBorrowModified runs after a borrow is modified -func (h MultiHARDHooks) AfterBorrowModified(ctx sdk.Context, borrow Borrow) { - for i := range h { - h[i].AfterBorrowModified(ctx, borrow) - } -} diff --git a/x/hard/types/keys.go b/x/hard/types/keys.go deleted file mode 100644 index cc42bec0..00000000 --- a/x/hard/types/keys.go +++ /dev/null @@ -1,43 +0,0 @@ -package types - -const ( - // ModuleName name that will be used throughout the module - ModuleName = "hard" - - // ModuleAccountName name of module account used to hold deposits - ModuleAccountName = "hard" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default name for parameter store - DefaultParamspace = ModuleName -) - -var ( - DepositsKeyPrefix = []byte{0x01} - BorrowsKeyPrefix = []byte{0x02} - BorrowedCoinsPrefix = []byte{0x03} - SuppliedCoinsPrefix = []byte{0x04} - MoneyMarketsPrefix = []byte{0x05} - PreviousAccrualTimePrefix = []byte{0x06} // denom -> time - TotalReservesPrefix = []byte{0x07} // denom -> sdk.Coin - BorrowInterestFactorPrefix = []byte{0x08} // denom -> sdk.Dec - SupplyInterestFactorPrefix = []byte{0x09} // denom -> sdk.Dec - DelegatorInterestFactorPrefix = []byte{0x10} // denom -> sdk.Dec -) - -// DepositTypeIteratorKey returns an interator prefix for interating over deposits by deposit denom -func DepositTypeIteratorKey(denom string) []byte { - return createKey([]byte(denom)) -} - -func createKey(bytes ...[]byte) (r []byte) { - for _, b := range bytes { - r = append(r, b...) - } - return -} diff --git a/x/hard/types/liquidation.go b/x/hard/types/liquidation.go deleted file mode 100644 index 81398eb9..00000000 --- a/x/hard/types/liquidation.go +++ /dev/null @@ -1,70 +0,0 @@ -package types - -import ( - "sort" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// ValuationMap holds the USD value of various coin types -type ValuationMap struct { - Usd map[string]sdk.Dec -} - -// NewValuationMap returns a new instance of ValuationMap -func NewValuationMap() ValuationMap { - return ValuationMap{ - Usd: make(map[string]sdk.Dec), - } -} - -// Get returns the USD value for a specific denom -func (m ValuationMap) Get(denom string) sdk.Dec { - return m.Usd[denom] -} - -// SetZero sets the USD value for a specific denom to 0 -func (m ValuationMap) SetZero(denom string) { - m.Usd[denom] = sdk.ZeroDec() -} - -// Increment increments the USD value of a denom -func (m ValuationMap) Increment(denom string, amount sdk.Dec) { - _, ok := m.Usd[denom] - if !ok { - m.Usd[denom] = amount - return - } - m.Usd[denom] = m.Usd[denom].Add(amount) -} - -// Decrement decrements the USD value of a denom -func (m ValuationMap) Decrement(denom string, amount sdk.Dec) { - _, ok := m.Usd[denom] - if !ok { - m.Usd[denom] = amount - return - } - m.Usd[denom] = m.Usd[denom].Sub(amount) -} - -// Sum returns the total USD value of all coins in the map -func (m ValuationMap) Sum() sdk.Dec { - sum := sdk.ZeroDec() - for _, v := range m.Usd { - sum = sum.Add(v) - } - return sum -} - -// GetSortedKeys returns an array of the map's keys in alphabetical order -func (m ValuationMap) GetSortedKeys() []string { - keys := make([]string, len(m.Usd)) - i := 0 - for k := range m.Usd { - keys[i] = k - i++ - } - sort.Strings(keys) - return keys -} diff --git a/x/hard/types/msg.go b/x/hard/types/msg.go deleted file mode 100644 index c62ce328..00000000 --- a/x/hard/types/msg.go +++ /dev/null @@ -1,228 +0,0 @@ -package types - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// ensure Msg interface compliance at compile time -var ( - _ sdk.Msg = &MsgDeposit{} - _ sdk.Msg = &MsgWithdraw{} - _ sdk.Msg = &MsgBorrow{} - _ sdk.Msg = &MsgRepay{} - _ sdk.Msg = &MsgLiquidate{} -) - -// NewMsgDeposit returns a new MsgDeposit -func NewMsgDeposit(depositor sdk.AccAddress, amount sdk.Coins) MsgDeposit { - return MsgDeposit{ - Depositor: depositor.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgDeposit) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgDeposit) Type() string { return "hard_deposit" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgDeposit) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "deposit amount %s", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgDeposit) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgDeposit) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - panic(err) - } - return []sdk.AccAddress{depositor} -} - -// NewMsgWithdraw returns a new MsgWithdraw -func NewMsgWithdraw(depositor sdk.AccAddress, amount sdk.Coins) MsgWithdraw { - return MsgWithdraw{ - Depositor: depositor.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgWithdraw) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgWithdraw) Type() string { return "hard_withdraw" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgWithdraw) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - if !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "deposit amount %s", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgWithdraw) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgWithdraw) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - panic(err) - } - return []sdk.AccAddress{depositor} -} - -// NewMsgBorrow returns a new MsgBorrow -func NewMsgBorrow(borrower sdk.AccAddress, amount sdk.Coins) MsgBorrow { - return MsgBorrow{ - Borrower: borrower.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgBorrow) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgBorrow) Type() string { return "hard_borrow" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgBorrow) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Borrower) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - if !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "borrow amount %s", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgBorrow) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgBorrow) GetSigners() []sdk.AccAddress { - borrower, err := sdk.AccAddressFromBech32(msg.Borrower) - if err != nil { - panic(err) - } - return []sdk.AccAddress{borrower} -} - -// NewMsgRepay returns a new MsgRepay -func NewMsgRepay(sender, owner sdk.AccAddress, amount sdk.Coins) MsgRepay { - return MsgRepay{ - Sender: sender.String(), - Owner: owner.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgRepay) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgRepay) Type() string { return "hard_repay" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgRepay) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - _, err = sdk.AccAddressFromBech32(msg.Owner) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - if !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "repay amount %s", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgRepay) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgRepay) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgLiquidate returns a new MsgLiquidate -func NewMsgLiquidate(keeper, borrower sdk.AccAddress) MsgLiquidate { - return MsgLiquidate{ - Keeper: keeper.String(), - Borrower: borrower.String(), - } -} - -// Route return the message type used for routing the message. -func (msg MsgLiquidate) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgLiquidate) Type() string { return "liquidate" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgLiquidate) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Keeper) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - _, err = sdk.AccAddressFromBech32(msg.Borrower) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgLiquidate) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgLiquidate) GetSigners() []sdk.AccAddress { - keeper, err := sdk.AccAddressFromBech32(msg.Keeper) - if err != nil { - panic(err) - } - return []sdk.AccAddress{keeper} -} diff --git a/x/hard/types/msg_test.go b/x/hard/types/msg_test.go deleted file mode 100644 index 9b75ab44..00000000 --- a/x/hard/types/msg_test.go +++ /dev/null @@ -1,195 +0,0 @@ -package types_test - -import ( - "strings" - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/hard/types" -) - -type MsgTestSuite struct { - suite.Suite -} - -func (suite *MsgTestSuite) TestMsgDeposit() { - type args struct { - depositor sdk.AccAddress - amount sdk.Coins - } - addrs := []sdk.AccAddress{ - sdk.AccAddress("test1"), - sdk.AccAddress("test2"), - } - testCases := []struct { - name string - args args - expectPass bool - expectedErr string - }{ - { - name: "valid", - args: args{ - depositor: addrs[0], - amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10000000))), - }, - expectPass: true, - expectedErr: "", - }, - { - name: "valid2", - args: args{ - depositor: addrs[0], - amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10000000))), - }, - expectPass: true, - expectedErr: "", - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - msg := types.NewMsgDeposit(tc.args.depositor, tc.args.amount) - err := msg.ValidateBasic() - if tc.expectPass { - suite.NoError(err) - } else { - suite.Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.expectedErr)) - } - }) - } -} - -func (suite *MsgTestSuite) TestMsgWithdraw() { - type args struct { - depositor sdk.AccAddress - amount sdk.Coins - } - addrs := []sdk.AccAddress{ - sdk.AccAddress("test1"), - sdk.AccAddress("test2"), - } - testCases := []struct { - name string - args args - expectPass bool - expectedErr string - }{ - { - name: "valid", - args: args{ - depositor: addrs[0], - amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10000000))), - }, - expectPass: true, - expectedErr: "", - }, - { - name: "valid2", - args: args{ - depositor: addrs[0], - amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10000000))), - }, - expectPass: true, - expectedErr: "", - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - msg := types.NewMsgWithdraw(tc.args.depositor, tc.args.amount) - err := msg.ValidateBasic() - if tc.expectPass { - suite.NoError(err) - } else { - suite.Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.expectedErr)) - } - }) - } -} - -func (suite *MsgTestSuite) TestMsgBorrow() { - type args struct { - borrower sdk.AccAddress - amount sdk.Coins - } - addrs := []sdk.AccAddress{ - sdk.AccAddress("test1"), - } - testCases := []struct { - name string - args args - expectPass bool - expectedErr string - }{ - { - name: "valid", - args: args{ - borrower: addrs[0], - amount: sdk.NewCoins(sdk.NewCoin("test", sdkmath.NewInt(1000000))), - }, - expectPass: true, - expectedErr: "", - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - msg := types.NewMsgBorrow(tc.args.borrower, tc.args.amount) - err := msg.ValidateBasic() - if tc.expectPass { - suite.NoError(err) - } else { - suite.Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.expectedErr)) - } - }) - } -} - -func (suite *MsgTestSuite) TestMsgRepay() { - type args struct { - sender sdk.AccAddress - owner sdk.AccAddress - amount sdk.Coins - } - addrs := []sdk.AccAddress{ - sdk.AccAddress("test1"), - } - testCases := []struct { - name string - args args - expectPass bool - expectedErr string - }{ - { - name: "valid", - args: args{ - sender: addrs[0], - owner: addrs[0], - amount: sdk.NewCoins(sdk.NewCoin("test", sdkmath.NewInt(1000000))), - }, - expectPass: true, - expectedErr: "", - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - msg := types.NewMsgRepay(tc.args.sender, tc.args.owner, tc.args.amount) - err := msg.ValidateBasic() - if tc.expectPass { - suite.NoError(err) - } else { - suite.Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.expectedErr)) - } - }) - } -} - -func TestMsgTestSuite(t *testing.T) { - suite.Run(t, new(MsgTestSuite)) -} diff --git a/x/hard/types/params.go b/x/hard/types/params.go deleted file mode 100644 index f3422a8e..00000000 --- a/x/hard/types/params.go +++ /dev/null @@ -1,252 +0,0 @@ -package types - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// Parameter keys and default values -var ( - KeyMoneyMarkets = []byte("MoneyMarkets") - KeyMinimumBorrowUSDValue = []byte("MinimumBorrowUSDValue") - DefaultMoneyMarkets = MoneyMarkets{} - DefaultMinimumBorrowUSDValue = sdk.NewDec(10) // $10 USD minimum borrow value - DefaultAccumulationTimes = GenesisAccumulationTimes{} - DefaultTotalSupplied = sdk.Coins{} - DefaultTotalBorrowed = sdk.Coins{} - DefaultTotalReserves = sdk.Coins{} - DefaultDeposits = Deposits{} - DefaultBorrows = Borrows{} -) - -// NewBorrowLimit returns a new BorrowLimit -func NewBorrowLimit(hasMaxLimit bool, maximumLimit, loanToValue sdk.Dec) BorrowLimit { - return BorrowLimit{ - HasMaxLimit: hasMaxLimit, - MaximumLimit: maximumLimit, - LoanToValue: loanToValue, - } -} - -// Validate BorrowLimit -func (bl BorrowLimit) Validate() error { - if bl.MaximumLimit.IsNegative() { - return fmt.Errorf("maximum limit USD cannot be negative: %s", bl.MaximumLimit) - } - if bl.LoanToValue.IsNegative() { - return fmt.Errorf("loan-to-value must be a non-negative decimal: %s", bl.LoanToValue) - } - if bl.LoanToValue.GT(sdk.OneDec()) { - return fmt.Errorf("loan-to-value cannot be greater than 1.0: %s", bl.LoanToValue) - } - return nil -} - -// Equal returns a boolean indicating if an BorrowLimit is equal to another BorrowLimit -func (bl BorrowLimit) Equal(blCompareTo BorrowLimit) bool { - if bl.HasMaxLimit != blCompareTo.HasMaxLimit { - return false - } - if !bl.MaximumLimit.Equal(blCompareTo.MaximumLimit) { - return false - } - if !bl.LoanToValue.Equal(blCompareTo.LoanToValue) { - return false - } - return true -} - -// NewMoneyMarket returns a new MoneyMarket -func NewMoneyMarket(denom string, borrowLimit BorrowLimit, spotMarketID string, conversionFactor sdkmath.Int, - interestRateModel InterestRateModel, reserveFactor, keeperRewardPercentage sdk.Dec, -) MoneyMarket { - return MoneyMarket{ - Denom: denom, - BorrowLimit: borrowLimit, - SpotMarketID: spotMarketID, - ConversionFactor: conversionFactor, - InterestRateModel: interestRateModel, - ReserveFactor: reserveFactor, - KeeperRewardPercentage: keeperRewardPercentage, - } -} - -// Validate MoneyMarket param -func (mm MoneyMarket) Validate() error { - if err := sdk.ValidateDenom(mm.Denom); err != nil { - return err - } - - if err := mm.BorrowLimit.Validate(); err != nil { - return err - } - - if mm.ConversionFactor.IsNil() || mm.ConversionFactor.LT(sdk.OneInt()) { - return fmt.Errorf("conversion '%s' factor must be ≥ one", mm.ConversionFactor) - } - - if err := mm.InterestRateModel.Validate(); err != nil { - return err - } - - if mm.ReserveFactor.IsNegative() || mm.ReserveFactor.GT(sdk.OneDec()) { - return fmt.Errorf("reserve factor must be between 0.0-1.0") - } - - if mm.KeeperRewardPercentage.IsNegative() || mm.KeeperRewardPercentage.GT(sdk.OneDec()) { - return fmt.Errorf("keeper reward percentage must be between 0.0-1.0") - } - - return nil -} - -// Equal returns a boolean indicating if a MoneyMarket is equal to another MoneyMarket -func (mm MoneyMarket) Equal(mmCompareTo MoneyMarket) bool { - if mm.Denom != mmCompareTo.Denom { - return false - } - if !mm.BorrowLimit.Equal(mmCompareTo.BorrowLimit) { - return false - } - if mm.SpotMarketID != mmCompareTo.SpotMarketID { - return false - } - if !mm.ConversionFactor.Equal(mmCompareTo.ConversionFactor) { - return false - } - if !mm.InterestRateModel.Equal(mmCompareTo.InterestRateModel) { - return false - } - if !mm.ReserveFactor.Equal(mmCompareTo.ReserveFactor) { - return false - } - if !mm.KeeperRewardPercentage.Equal(mmCompareTo.KeeperRewardPercentage) { - return false - } - return true -} - -// MoneyMarkets slice of MoneyMarket -type MoneyMarkets []MoneyMarket - -// Validate borrow limits -func (mms MoneyMarkets) Validate() error { - for _, moneyMarket := range mms { - if err := moneyMarket.Validate(); err != nil { - return err - } - } - return nil -} - -// NewInterestRateModel returns a new InterestRateModel -func NewInterestRateModel(baseRateAPY, baseMultiplier, kink, jumpMultiplier sdk.Dec) InterestRateModel { - return InterestRateModel{ - BaseRateAPY: baseRateAPY, - BaseMultiplier: baseMultiplier, - Kink: kink, - JumpMultiplier: jumpMultiplier, - } -} - -// Validate InterestRateModel param -func (irm InterestRateModel) Validate() error { - if irm.BaseRateAPY.IsNegative() || irm.BaseRateAPY.GT(sdk.OneDec()) { - return fmt.Errorf("base rate APY must be in the inclusive range 0.0-1.0") - } - - if irm.BaseMultiplier.IsNegative() { - return fmt.Errorf("base multiplier must not be negative") - } - - if irm.Kink.IsNegative() || irm.Kink.GT(sdk.OneDec()) { - return fmt.Errorf("kink must be in the inclusive range 0.0-1.0") - } - - if irm.JumpMultiplier.IsNegative() { - return fmt.Errorf("jump multiplier must not be negative") - } - - return nil -} - -// Equal returns a boolean indicating if an InterestRateModel is equal to another InterestRateModel -func (irm InterestRateModel) Equal(irmCompareTo InterestRateModel) bool { - if !irm.BaseRateAPY.Equal(irmCompareTo.BaseRateAPY) { - return false - } - if !irm.BaseMultiplier.Equal(irmCompareTo.BaseMultiplier) { - return false - } - if !irm.Kink.Equal(irmCompareTo.Kink) { - return false - } - if !irm.JumpMultiplier.Equal(irmCompareTo.JumpMultiplier) { - return false - } - return true -} - -// InterestRateModels slice of InterestRateModel -type InterestRateModels []InterestRateModel - -// NewParams returns a new params object -func NewParams(moneyMarkets MoneyMarkets, minimumBorrowUSDValue sdk.Dec) Params { - return Params{ - MoneyMarkets: moneyMarkets, - MinimumBorrowUSDValue: minimumBorrowUSDValue, - } -} - -// DefaultParams returns default params for hard module -func DefaultParams() Params { - return NewParams(DefaultMoneyMarkets, DefaultMinimumBorrowUSDValue) -} - -// ParamKeyTable Key declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements the ParamSet interface and returns all the key/value pairs -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyMoneyMarkets, &p.MoneyMarkets, validateMoneyMarketParams), - paramtypes.NewParamSetPair(KeyMinimumBorrowUSDValue, &p.MinimumBorrowUSDValue, validateMinimumBorrowUSDValue), - } -} - -// Validate checks that the parameters have valid values. -func (p Params) Validate() error { - if err := validateMinimumBorrowUSDValue(p.MinimumBorrowUSDValue); err != nil { - return err - } - - return validateMoneyMarketParams(p.MoneyMarkets) -} - -func validateMinimumBorrowUSDValue(i interface{}) error { - minBorrowVal, ok := i.(sdk.Dec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if minBorrowVal.IsNegative() { - return fmt.Errorf("minimum borrow USD value cannot be negative") - } - - return nil -} - -func validateMoneyMarketParams(i interface{}) error { - mm, ok := i.(MoneyMarkets) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return mm.Validate() -} diff --git a/x/hard/types/params_test.go b/x/hard/types/params_test.go deleted file mode 100644 index 7134e4e4..00000000 --- a/x/hard/types/params_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package types_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/hard/types" -) - -type ParamTestSuite struct { - suite.Suite -} - -func (suite *ParamTestSuite) TestParamValidation() { - type args struct { - minBorrowVal sdk.Dec - mms types.MoneyMarkets - } - testCases := []struct { - name string - args args - expectPass bool - expectedErr string - }{ - { - name: "default", - args: args{ - minBorrowVal: types.DefaultMinimumBorrowUSDValue, - mms: types.DefaultMoneyMarkets, - }, - expectPass: true, - expectedErr: "", - }, - { - name: "invalid: conversion factor < one", - args: args{ - minBorrowVal: types.DefaultMinimumBorrowUSDValue, - mms: types.MoneyMarkets{ - { - Denom: "btcb", - BorrowLimit: types.NewBorrowLimit( - false, - sdk.MustNewDecFromStr("100000000000"), - sdk.MustNewDecFromStr("0.5"), - ), - SpotMarketID: "btc:usd", - ConversionFactor: sdkmath.NewInt(0), - InterestRateModel: types.InterestRateModel{}, - ReserveFactor: sdk.MustNewDecFromStr("0.05"), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.05"), - }, - }, - }, - expectPass: false, - expectedErr: "conversion '0' factor must be ≥ one", - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - params := types.NewParams(tc.args.mms, tc.args.minBorrowVal) - err := params.Validate() - if tc.expectPass { - suite.NoError(err) - } else { - suite.Error(err) - suite.Require().Contains(err.Error(), tc.expectedErr) - } - }) - } -} - -func TestParamTestSuite(t *testing.T) { - suite.Run(t, new(ParamTestSuite)) -} diff --git a/x/hard/types/period.go b/x/hard/types/period.go deleted file mode 100644 index 10787a99..00000000 --- a/x/hard/types/period.go +++ /dev/null @@ -1,20 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" -) - -// NewPeriod returns a new vesting period -func NewPeriod(amount sdk.Coins, length int64) vestingtypes.Period { - return vestingtypes.Period{Amount: amount, Length: length} -} - -// GetTotalVestingPeriodLength returns the summed length of all vesting periods -func GetTotalVestingPeriodLength(periods vestingtypes.Periods) int64 { - length := int64(0) - for _, period := range periods { - length += period.Length - } - return length -} diff --git a/x/hard/types/query.go b/x/hard/types/query.go deleted file mode 100644 index ef91d134..00000000 --- a/x/hard/types/query.go +++ /dev/null @@ -1,7 +0,0 @@ -package types - -// MoneyMarketInterestRates is a slice of MoneyMarketInterestRate -type MoneyMarketInterestRates []MoneyMarketInterestRate - -// InterestFactors is a slice of InterestFactor -type InterestFactors []InterestFactor diff --git a/x/hard/types/query.pb.go b/x/hard/types/query.pb.go deleted file mode 100644 index 35d2b877..00000000 --- a/x/hard/types/query.pb.go +++ /dev/null @@ -1,6733 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/hard/v1beta1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types1 "github.com/cosmos/cosmos-sdk/types" - query "github.com/cosmos/cosmos-sdk/types/query" - types "github.com/cosmos/cosmos-sdk/x/auth/types" - _ "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 the 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_1eedf429c9bff7da, []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 the response type for the Query/Params RPC method. -type QueryParamsResponse struct { - 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_1eedf429c9bff7da, []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{} -} - -// QueryAccountsRequest is the request type for the Query/Accounts RPC method. -type QueryAccountsRequest struct { -} - -func (m *QueryAccountsRequest) Reset() { *m = QueryAccountsRequest{} } -func (m *QueryAccountsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAccountsRequest) ProtoMessage() {} -func (*QueryAccountsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{2} -} -func (m *QueryAccountsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAccountsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAccountsRequest.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 *QueryAccountsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAccountsRequest.Merge(m, src) -} -func (m *QueryAccountsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryAccountsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAccountsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAccountsRequest proto.InternalMessageInfo - -// QueryAccountsResponse is the response type for the Query/Accounts RPC method. -type QueryAccountsResponse struct { - Accounts []types.ModuleAccount `protobuf:"bytes,1,rep,name=accounts,proto3" json:"accounts"` -} - -func (m *QueryAccountsResponse) Reset() { *m = QueryAccountsResponse{} } -func (m *QueryAccountsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAccountsResponse) ProtoMessage() {} -func (*QueryAccountsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{3} -} -func (m *QueryAccountsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAccountsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAccountsResponse.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 *QueryAccountsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAccountsResponse.Merge(m, src) -} -func (m *QueryAccountsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryAccountsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAccountsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAccountsResponse proto.InternalMessageInfo - -func (m *QueryAccountsResponse) GetAccounts() []types.ModuleAccount { - if m != nil { - return m.Accounts - } - return nil -} - -// QueryDepositsRequest is the request type for the Query/Deposits RPC method. -type QueryDepositsRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Pagination *query.PageRequest `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDepositsRequest) Reset() { *m = QueryDepositsRequest{} } -func (m *QueryDepositsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsRequest) ProtoMessage() {} -func (*QueryDepositsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{4} -} -func (m *QueryDepositsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsRequest.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 *QueryDepositsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsRequest.Merge(m, src) -} -func (m *QueryDepositsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsRequest proto.InternalMessageInfo - -func (m *QueryDepositsRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *QueryDepositsRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *QueryDepositsRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryDepositsResponse is the response type for the Query/Deposits RPC method. -type QueryDepositsResponse struct { - Deposits DepositResponses `protobuf:"bytes,1,rep,name=deposits,proto3,castrepeated=DepositResponses" json:"deposits"` - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDepositsResponse) Reset() { *m = QueryDepositsResponse{} } -func (m *QueryDepositsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsResponse) ProtoMessage() {} -func (*QueryDepositsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{5} -} -func (m *QueryDepositsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsResponse.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 *QueryDepositsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsResponse.Merge(m, src) -} -func (m *QueryDepositsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsResponse proto.InternalMessageInfo - -func (m *QueryDepositsResponse) GetDeposits() DepositResponses { - if m != nil { - return m.Deposits - } - return nil -} - -func (m *QueryDepositsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryUnsyncedDepositsRequest is the request type for the Query/UnsyncedDeposits RPC method. -type QueryUnsyncedDepositsRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Pagination *query.PageRequest `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryUnsyncedDepositsRequest) Reset() { *m = QueryUnsyncedDepositsRequest{} } -func (m *QueryUnsyncedDepositsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryUnsyncedDepositsRequest) ProtoMessage() {} -func (*QueryUnsyncedDepositsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{6} -} -func (m *QueryUnsyncedDepositsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryUnsyncedDepositsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryUnsyncedDepositsRequest.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 *QueryUnsyncedDepositsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryUnsyncedDepositsRequest.Merge(m, src) -} -func (m *QueryUnsyncedDepositsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryUnsyncedDepositsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryUnsyncedDepositsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryUnsyncedDepositsRequest proto.InternalMessageInfo - -func (m *QueryUnsyncedDepositsRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *QueryUnsyncedDepositsRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *QueryUnsyncedDepositsRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryUnsyncedDepositsResponse is the response type for the Query/UnsyncedDeposits RPC method. -type QueryUnsyncedDepositsResponse struct { - Deposits DepositResponses `protobuf:"bytes,1,rep,name=deposits,proto3,castrepeated=DepositResponses" json:"deposits"` - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryUnsyncedDepositsResponse) Reset() { *m = QueryUnsyncedDepositsResponse{} } -func (m *QueryUnsyncedDepositsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryUnsyncedDepositsResponse) ProtoMessage() {} -func (*QueryUnsyncedDepositsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{7} -} -func (m *QueryUnsyncedDepositsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryUnsyncedDepositsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryUnsyncedDepositsResponse.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 *QueryUnsyncedDepositsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryUnsyncedDepositsResponse.Merge(m, src) -} -func (m *QueryUnsyncedDepositsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryUnsyncedDepositsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryUnsyncedDepositsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryUnsyncedDepositsResponse proto.InternalMessageInfo - -func (m *QueryUnsyncedDepositsResponse) GetDeposits() DepositResponses { - if m != nil { - return m.Deposits - } - return nil -} - -func (m *QueryUnsyncedDepositsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryTotalDepositedRequest is the request type for the Query/TotalDeposited RPC method. -type QueryTotalDepositedRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` -} - -func (m *QueryTotalDepositedRequest) Reset() { *m = QueryTotalDepositedRequest{} } -func (m *QueryTotalDepositedRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalDepositedRequest) ProtoMessage() {} -func (*QueryTotalDepositedRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{8} -} -func (m *QueryTotalDepositedRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalDepositedRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalDepositedRequest.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 *QueryTotalDepositedRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalDepositedRequest.Merge(m, src) -} -func (m *QueryTotalDepositedRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalDepositedRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalDepositedRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalDepositedRequest proto.InternalMessageInfo - -func (m *QueryTotalDepositedRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -// QueryTotalDepositedResponse is the response type for the Query/TotalDeposited RPC method. -type QueryTotalDepositedResponse struct { - SuppliedCoins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=supplied_coins,json=suppliedCoins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"supplied_coins"` -} - -func (m *QueryTotalDepositedResponse) Reset() { *m = QueryTotalDepositedResponse{} } -func (m *QueryTotalDepositedResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalDepositedResponse) ProtoMessage() {} -func (*QueryTotalDepositedResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{9} -} -func (m *QueryTotalDepositedResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalDepositedResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalDepositedResponse.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 *QueryTotalDepositedResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalDepositedResponse.Merge(m, src) -} -func (m *QueryTotalDepositedResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalDepositedResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalDepositedResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalDepositedResponse proto.InternalMessageInfo - -func (m *QueryTotalDepositedResponse) GetSuppliedCoins() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.SuppliedCoins - } - return nil -} - -// QueryBorrowsRequest is the request type for the Query/Borrows RPC method. -type QueryBorrowsRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Pagination *query.PageRequest `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryBorrowsRequest) Reset() { *m = QueryBorrowsRequest{} } -func (m *QueryBorrowsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryBorrowsRequest) ProtoMessage() {} -func (*QueryBorrowsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{10} -} -func (m *QueryBorrowsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryBorrowsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryBorrowsRequest.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 *QueryBorrowsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryBorrowsRequest.Merge(m, src) -} -func (m *QueryBorrowsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryBorrowsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryBorrowsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryBorrowsRequest proto.InternalMessageInfo - -func (m *QueryBorrowsRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *QueryBorrowsRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *QueryBorrowsRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryBorrowsResponse is the response type for the Query/Borrows RPC method. -type QueryBorrowsResponse struct { - Borrows BorrowResponses `protobuf:"bytes,1,rep,name=borrows,proto3,castrepeated=BorrowResponses" json:"borrows"` - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryBorrowsResponse) Reset() { *m = QueryBorrowsResponse{} } -func (m *QueryBorrowsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryBorrowsResponse) ProtoMessage() {} -func (*QueryBorrowsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{11} -} -func (m *QueryBorrowsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryBorrowsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryBorrowsResponse.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 *QueryBorrowsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryBorrowsResponse.Merge(m, src) -} -func (m *QueryBorrowsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryBorrowsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryBorrowsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryBorrowsResponse proto.InternalMessageInfo - -func (m *QueryBorrowsResponse) GetBorrows() BorrowResponses { - if m != nil { - return m.Borrows - } - return nil -} - -func (m *QueryBorrowsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryUnsyncedBorrowsRequest is the request type for the Query/UnsyncedBorrows RPC method. -type QueryUnsyncedBorrowsRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Pagination *query.PageRequest `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryUnsyncedBorrowsRequest) Reset() { *m = QueryUnsyncedBorrowsRequest{} } -func (m *QueryUnsyncedBorrowsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryUnsyncedBorrowsRequest) ProtoMessage() {} -func (*QueryUnsyncedBorrowsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{12} -} -func (m *QueryUnsyncedBorrowsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryUnsyncedBorrowsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryUnsyncedBorrowsRequest.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 *QueryUnsyncedBorrowsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryUnsyncedBorrowsRequest.Merge(m, src) -} -func (m *QueryUnsyncedBorrowsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryUnsyncedBorrowsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryUnsyncedBorrowsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryUnsyncedBorrowsRequest proto.InternalMessageInfo - -func (m *QueryUnsyncedBorrowsRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *QueryUnsyncedBorrowsRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *QueryUnsyncedBorrowsRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryUnsyncedBorrowsResponse is the response type for the Query/UnsyncedBorrows RPC method. -type QueryUnsyncedBorrowsResponse struct { - Borrows BorrowResponses `protobuf:"bytes,1,rep,name=borrows,proto3,castrepeated=BorrowResponses" json:"borrows"` - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryUnsyncedBorrowsResponse) Reset() { *m = QueryUnsyncedBorrowsResponse{} } -func (m *QueryUnsyncedBorrowsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryUnsyncedBorrowsResponse) ProtoMessage() {} -func (*QueryUnsyncedBorrowsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{13} -} -func (m *QueryUnsyncedBorrowsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryUnsyncedBorrowsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryUnsyncedBorrowsResponse.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 *QueryUnsyncedBorrowsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryUnsyncedBorrowsResponse.Merge(m, src) -} -func (m *QueryUnsyncedBorrowsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryUnsyncedBorrowsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryUnsyncedBorrowsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryUnsyncedBorrowsResponse proto.InternalMessageInfo - -func (m *QueryUnsyncedBorrowsResponse) GetBorrows() BorrowResponses { - if m != nil { - return m.Borrows - } - return nil -} - -func (m *QueryUnsyncedBorrowsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryTotalBorrowedRequest is the request type for the Query/TotalBorrowed RPC method. -type QueryTotalBorrowedRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` -} - -func (m *QueryTotalBorrowedRequest) Reset() { *m = QueryTotalBorrowedRequest{} } -func (m *QueryTotalBorrowedRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalBorrowedRequest) ProtoMessage() {} -func (*QueryTotalBorrowedRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{14} -} -func (m *QueryTotalBorrowedRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalBorrowedRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalBorrowedRequest.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 *QueryTotalBorrowedRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalBorrowedRequest.Merge(m, src) -} -func (m *QueryTotalBorrowedRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalBorrowedRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalBorrowedRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalBorrowedRequest proto.InternalMessageInfo - -func (m *QueryTotalBorrowedRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -// QueryTotalBorrowedResponse is the response type for the Query/TotalBorrowed RPC method. -type QueryTotalBorrowedResponse struct { - BorrowedCoins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=borrowed_coins,json=borrowedCoins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"borrowed_coins"` -} - -func (m *QueryTotalBorrowedResponse) Reset() { *m = QueryTotalBorrowedResponse{} } -func (m *QueryTotalBorrowedResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalBorrowedResponse) ProtoMessage() {} -func (*QueryTotalBorrowedResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{15} -} -func (m *QueryTotalBorrowedResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalBorrowedResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalBorrowedResponse.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 *QueryTotalBorrowedResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalBorrowedResponse.Merge(m, src) -} -func (m *QueryTotalBorrowedResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalBorrowedResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalBorrowedResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalBorrowedResponse proto.InternalMessageInfo - -func (m *QueryTotalBorrowedResponse) GetBorrowedCoins() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.BorrowedCoins - } - return nil -} - -// QueryInterestRateRequest is the request type for the Query/InterestRate RPC method. -type QueryInterestRateRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` -} - -func (m *QueryInterestRateRequest) Reset() { *m = QueryInterestRateRequest{} } -func (m *QueryInterestRateRequest) String() string { return proto.CompactTextString(m) } -func (*QueryInterestRateRequest) ProtoMessage() {} -func (*QueryInterestRateRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{16} -} -func (m *QueryInterestRateRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryInterestRateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryInterestRateRequest.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 *QueryInterestRateRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryInterestRateRequest.Merge(m, src) -} -func (m *QueryInterestRateRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryInterestRateRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryInterestRateRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryInterestRateRequest proto.InternalMessageInfo - -func (m *QueryInterestRateRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -// QueryInterestRateResponse is the response type for the Query/InterestRate RPC method. -type QueryInterestRateResponse struct { - InterestRates MoneyMarketInterestRates `protobuf:"bytes,1,rep,name=interest_rates,json=interestRates,proto3,castrepeated=MoneyMarketInterestRates" json:"interest_rates"` -} - -func (m *QueryInterestRateResponse) Reset() { *m = QueryInterestRateResponse{} } -func (m *QueryInterestRateResponse) String() string { return proto.CompactTextString(m) } -func (*QueryInterestRateResponse) ProtoMessage() {} -func (*QueryInterestRateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{17} -} -func (m *QueryInterestRateResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryInterestRateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryInterestRateResponse.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 *QueryInterestRateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryInterestRateResponse.Merge(m, src) -} -func (m *QueryInterestRateResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryInterestRateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryInterestRateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryInterestRateResponse proto.InternalMessageInfo - -func (m *QueryInterestRateResponse) GetInterestRates() MoneyMarketInterestRates { - if m != nil { - return m.InterestRates - } - return nil -} - -// QueryReservesRequest is the request type for the Query/Reserves RPC method. -type QueryReservesRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` -} - -func (m *QueryReservesRequest) Reset() { *m = QueryReservesRequest{} } -func (m *QueryReservesRequest) String() string { return proto.CompactTextString(m) } -func (*QueryReservesRequest) ProtoMessage() {} -func (*QueryReservesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{18} -} -func (m *QueryReservesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryReservesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryReservesRequest.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 *QueryReservesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryReservesRequest.Merge(m, src) -} -func (m *QueryReservesRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryReservesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryReservesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryReservesRequest proto.InternalMessageInfo - -func (m *QueryReservesRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -// QueryReservesResponse is the response type for the Query/Reserves RPC method. -type QueryReservesResponse struct { - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *QueryReservesResponse) Reset() { *m = QueryReservesResponse{} } -func (m *QueryReservesResponse) String() string { return proto.CompactTextString(m) } -func (*QueryReservesResponse) ProtoMessage() {} -func (*QueryReservesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{19} -} -func (m *QueryReservesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryReservesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryReservesResponse.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 *QueryReservesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryReservesResponse.Merge(m, src) -} -func (m *QueryReservesResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryReservesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryReservesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryReservesResponse proto.InternalMessageInfo - -func (m *QueryReservesResponse) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -// QueryInterestFactorsRequest is the request type for the Query/InterestFactors RPC method. -type QueryInterestFactorsRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` -} - -func (m *QueryInterestFactorsRequest) Reset() { *m = QueryInterestFactorsRequest{} } -func (m *QueryInterestFactorsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryInterestFactorsRequest) ProtoMessage() {} -func (*QueryInterestFactorsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{20} -} -func (m *QueryInterestFactorsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryInterestFactorsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryInterestFactorsRequest.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 *QueryInterestFactorsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryInterestFactorsRequest.Merge(m, src) -} -func (m *QueryInterestFactorsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryInterestFactorsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryInterestFactorsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryInterestFactorsRequest proto.InternalMessageInfo - -func (m *QueryInterestFactorsRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -// QueryInterestFactorsResponse is the response type for the Query/InterestFactors RPC method. -type QueryInterestFactorsResponse struct { - InterestFactors InterestFactors `protobuf:"bytes,1,rep,name=interest_factors,json=interestFactors,proto3,castrepeated=InterestFactors" json:"interest_factors"` -} - -func (m *QueryInterestFactorsResponse) Reset() { *m = QueryInterestFactorsResponse{} } -func (m *QueryInterestFactorsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryInterestFactorsResponse) ProtoMessage() {} -func (*QueryInterestFactorsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{21} -} -func (m *QueryInterestFactorsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryInterestFactorsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryInterestFactorsResponse.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 *QueryInterestFactorsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryInterestFactorsResponse.Merge(m, src) -} -func (m *QueryInterestFactorsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryInterestFactorsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryInterestFactorsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryInterestFactorsResponse proto.InternalMessageInfo - -func (m *QueryInterestFactorsResponse) GetInterestFactors() InterestFactors { - if m != nil { - return m.InterestFactors - } - return nil -} - -// DepositResponse defines an amount of coins deposited into a hard module account. -type DepositResponse struct { - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` - Index SupplyInterestFactorResponses `protobuf:"bytes,3,rep,name=index,proto3,castrepeated=SupplyInterestFactorResponses" json:"index"` -} - -func (m *DepositResponse) Reset() { *m = DepositResponse{} } -func (m *DepositResponse) String() string { return proto.CompactTextString(m) } -func (*DepositResponse) ProtoMessage() {} -func (*DepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{22} -} -func (m *DepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DepositResponse.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 *DepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_DepositResponse.Merge(m, src) -} -func (m *DepositResponse) XXX_Size() int { - return m.Size() -} -func (m *DepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_DepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_DepositResponse proto.InternalMessageInfo - -func (m *DepositResponse) GetDepositor() string { - if m != nil { - return m.Depositor - } - return "" -} - -func (m *DepositResponse) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -func (m *DepositResponse) GetIndex() SupplyInterestFactorResponses { - if m != nil { - return m.Index - } - return nil -} - -// SupplyInterestFactorResponse defines an individual borrow interest factor. -type SupplyInterestFactorResponse struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - // sdk.Dec as string - Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` -} - -func (m *SupplyInterestFactorResponse) Reset() { *m = SupplyInterestFactorResponse{} } -func (m *SupplyInterestFactorResponse) String() string { return proto.CompactTextString(m) } -func (*SupplyInterestFactorResponse) ProtoMessage() {} -func (*SupplyInterestFactorResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{23} -} -func (m *SupplyInterestFactorResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SupplyInterestFactorResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SupplyInterestFactorResponse.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 *SupplyInterestFactorResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_SupplyInterestFactorResponse.Merge(m, src) -} -func (m *SupplyInterestFactorResponse) XXX_Size() int { - return m.Size() -} -func (m *SupplyInterestFactorResponse) XXX_DiscardUnknown() { - xxx_messageInfo_SupplyInterestFactorResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_SupplyInterestFactorResponse proto.InternalMessageInfo - -func (m *SupplyInterestFactorResponse) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *SupplyInterestFactorResponse) GetValue() string { - if m != nil { - return m.Value - } - return "" -} - -// BorrowResponse defines an amount of coins borrowed from a hard module account. -type BorrowResponse struct { - Borrower string `protobuf:"bytes,1,opt,name=borrower,proto3" json:"borrower,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` - Index BorrowInterestFactorResponses `protobuf:"bytes,3,rep,name=index,proto3,castrepeated=BorrowInterestFactorResponses" json:"index"` -} - -func (m *BorrowResponse) Reset() { *m = BorrowResponse{} } -func (m *BorrowResponse) String() string { return proto.CompactTextString(m) } -func (*BorrowResponse) ProtoMessage() {} -func (*BorrowResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{24} -} -func (m *BorrowResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BorrowResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BorrowResponse.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 *BorrowResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_BorrowResponse.Merge(m, src) -} -func (m *BorrowResponse) XXX_Size() int { - return m.Size() -} -func (m *BorrowResponse) XXX_DiscardUnknown() { - xxx_messageInfo_BorrowResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_BorrowResponse proto.InternalMessageInfo - -func (m *BorrowResponse) GetBorrower() string { - if m != nil { - return m.Borrower - } - return "" -} - -func (m *BorrowResponse) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -func (m *BorrowResponse) GetIndex() BorrowInterestFactorResponses { - if m != nil { - return m.Index - } - return nil -} - -// BorrowInterestFactorResponse defines an individual borrow interest factor. -type BorrowInterestFactorResponse struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - // sdk.Dec as string - Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` -} - -func (m *BorrowInterestFactorResponse) Reset() { *m = BorrowInterestFactorResponse{} } -func (m *BorrowInterestFactorResponse) String() string { return proto.CompactTextString(m) } -func (*BorrowInterestFactorResponse) ProtoMessage() {} -func (*BorrowInterestFactorResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{25} -} -func (m *BorrowInterestFactorResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BorrowInterestFactorResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BorrowInterestFactorResponse.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 *BorrowInterestFactorResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_BorrowInterestFactorResponse.Merge(m, src) -} -func (m *BorrowInterestFactorResponse) XXX_Size() int { - return m.Size() -} -func (m *BorrowInterestFactorResponse) XXX_DiscardUnknown() { - xxx_messageInfo_BorrowInterestFactorResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_BorrowInterestFactorResponse proto.InternalMessageInfo - -func (m *BorrowInterestFactorResponse) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *BorrowInterestFactorResponse) GetValue() string { - if m != nil { - return m.Value - } - return "" -} - -// MoneyMarketInterestRate is a unique type returned by interest rate queries -type MoneyMarketInterestRate struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - // sdk.Dec as String - SupplyInterestRate string `protobuf:"bytes,2,opt,name=supply_interest_rate,json=supplyInterestRate,proto3" json:"supply_interest_rate,omitempty"` - // sdk.Dec as String - BorrowInterestRate string `protobuf:"bytes,3,opt,name=borrow_interest_rate,json=borrowInterestRate,proto3" json:"borrow_interest_rate,omitempty"` -} - -func (m *MoneyMarketInterestRate) Reset() { *m = MoneyMarketInterestRate{} } -func (m *MoneyMarketInterestRate) String() string { return proto.CompactTextString(m) } -func (*MoneyMarketInterestRate) ProtoMessage() {} -func (*MoneyMarketInterestRate) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{26} -} -func (m *MoneyMarketInterestRate) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MoneyMarketInterestRate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MoneyMarketInterestRate.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 *MoneyMarketInterestRate) XXX_Merge(src proto.Message) { - xxx_messageInfo_MoneyMarketInterestRate.Merge(m, src) -} -func (m *MoneyMarketInterestRate) XXX_Size() int { - return m.Size() -} -func (m *MoneyMarketInterestRate) XXX_DiscardUnknown() { - xxx_messageInfo_MoneyMarketInterestRate.DiscardUnknown(m) -} - -var xxx_messageInfo_MoneyMarketInterestRate proto.InternalMessageInfo - -func (m *MoneyMarketInterestRate) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *MoneyMarketInterestRate) GetSupplyInterestRate() string { - if m != nil { - return m.SupplyInterestRate - } - return "" -} - -func (m *MoneyMarketInterestRate) GetBorrowInterestRate() string { - if m != nil { - return m.BorrowInterestRate - } - return "" -} - -// InterestFactor is a unique type returned by interest factor queries -type InterestFactor struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - // sdk.Dec as String - BorrowInterestFactor string `protobuf:"bytes,2,opt,name=borrow_interest_factor,json=borrowInterestFactor,proto3" json:"borrow_interest_factor,omitempty"` - // sdk.Dec as String - SupplyInterestFactor string `protobuf:"bytes,3,opt,name=supply_interest_factor,json=supplyInterestFactor,proto3" json:"supply_interest_factor,omitempty"` -} - -func (m *InterestFactor) Reset() { *m = InterestFactor{} } -func (m *InterestFactor) String() string { return proto.CompactTextString(m) } -func (*InterestFactor) ProtoMessage() {} -func (*InterestFactor) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{27} -} -func (m *InterestFactor) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *InterestFactor) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_InterestFactor.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 *InterestFactor) XXX_Merge(src proto.Message) { - xxx_messageInfo_InterestFactor.Merge(m, src) -} -func (m *InterestFactor) XXX_Size() int { - return m.Size() -} -func (m *InterestFactor) XXX_DiscardUnknown() { - xxx_messageInfo_InterestFactor.DiscardUnknown(m) -} - -var xxx_messageInfo_InterestFactor proto.InternalMessageInfo - -func (m *InterestFactor) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *InterestFactor) GetBorrowInterestFactor() string { - if m != nil { - return m.BorrowInterestFactor - } - return "" -} - -func (m *InterestFactor) GetSupplyInterestFactor() string { - if m != nil { - return m.SupplyInterestFactor - } - return "" -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.hard.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.hard.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryAccountsRequest)(nil), "kava.hard.v1beta1.QueryAccountsRequest") - proto.RegisterType((*QueryAccountsResponse)(nil), "kava.hard.v1beta1.QueryAccountsResponse") - proto.RegisterType((*QueryDepositsRequest)(nil), "kava.hard.v1beta1.QueryDepositsRequest") - proto.RegisterType((*QueryDepositsResponse)(nil), "kava.hard.v1beta1.QueryDepositsResponse") - proto.RegisterType((*QueryUnsyncedDepositsRequest)(nil), "kava.hard.v1beta1.QueryUnsyncedDepositsRequest") - proto.RegisterType((*QueryUnsyncedDepositsResponse)(nil), "kava.hard.v1beta1.QueryUnsyncedDepositsResponse") - proto.RegisterType((*QueryTotalDepositedRequest)(nil), "kava.hard.v1beta1.QueryTotalDepositedRequest") - proto.RegisterType((*QueryTotalDepositedResponse)(nil), "kava.hard.v1beta1.QueryTotalDepositedResponse") - proto.RegisterType((*QueryBorrowsRequest)(nil), "kava.hard.v1beta1.QueryBorrowsRequest") - proto.RegisterType((*QueryBorrowsResponse)(nil), "kava.hard.v1beta1.QueryBorrowsResponse") - proto.RegisterType((*QueryUnsyncedBorrowsRequest)(nil), "kava.hard.v1beta1.QueryUnsyncedBorrowsRequest") - proto.RegisterType((*QueryUnsyncedBorrowsResponse)(nil), "kava.hard.v1beta1.QueryUnsyncedBorrowsResponse") - proto.RegisterType((*QueryTotalBorrowedRequest)(nil), "kava.hard.v1beta1.QueryTotalBorrowedRequest") - proto.RegisterType((*QueryTotalBorrowedResponse)(nil), "kava.hard.v1beta1.QueryTotalBorrowedResponse") - proto.RegisterType((*QueryInterestRateRequest)(nil), "kava.hard.v1beta1.QueryInterestRateRequest") - proto.RegisterType((*QueryInterestRateResponse)(nil), "kava.hard.v1beta1.QueryInterestRateResponse") - proto.RegisterType((*QueryReservesRequest)(nil), "kava.hard.v1beta1.QueryReservesRequest") - proto.RegisterType((*QueryReservesResponse)(nil), "kava.hard.v1beta1.QueryReservesResponse") - proto.RegisterType((*QueryInterestFactorsRequest)(nil), "kava.hard.v1beta1.QueryInterestFactorsRequest") - proto.RegisterType((*QueryInterestFactorsResponse)(nil), "kava.hard.v1beta1.QueryInterestFactorsResponse") - proto.RegisterType((*DepositResponse)(nil), "kava.hard.v1beta1.DepositResponse") - proto.RegisterType((*SupplyInterestFactorResponse)(nil), "kava.hard.v1beta1.SupplyInterestFactorResponse") - proto.RegisterType((*BorrowResponse)(nil), "kava.hard.v1beta1.BorrowResponse") - proto.RegisterType((*BorrowInterestFactorResponse)(nil), "kava.hard.v1beta1.BorrowInterestFactorResponse") - proto.RegisterType((*MoneyMarketInterestRate)(nil), "kava.hard.v1beta1.MoneyMarketInterestRate") - proto.RegisterType((*InterestFactor)(nil), "kava.hard.v1beta1.InterestFactor") -} - -func init() { proto.RegisterFile("kava/hard/v1beta1/query.proto", fileDescriptor_1eedf429c9bff7da) } - -var fileDescriptor_1eedf429c9bff7da = []byte{ - // 1318 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x58, 0xcd, 0x6f, 0x1b, 0x45, - 0x14, 0xcf, 0x3a, 0x24, 0x4d, 0x5f, 0x9b, 0x0f, 0x06, 0xd3, 0xda, 0x4e, 0xe2, 0x26, 0x9b, 0xe6, - 0x83, 0x34, 0xf6, 0x26, 0x69, 0x05, 0x57, 0x6a, 0xaa, 0x22, 0x90, 0x82, 0x60, 0x5b, 0x24, 0x84, - 0x84, 0xa2, 0xb5, 0x77, 0x70, 0x56, 0x71, 0x76, 0xdc, 0x9d, 0x75, 0xda, 0x20, 0xc4, 0xa1, 0x12, - 0xf7, 0x42, 0x0e, 0x08, 0x81, 0xc4, 0xa1, 0x9c, 0x80, 0x23, 0x5c, 0x90, 0xb8, 0x70, 0xaa, 0x38, - 0x55, 0x70, 0xe1, 0x04, 0x28, 0xe1, 0x0f, 0x41, 0x3b, 0xf3, 0x66, 0xed, 0x5d, 0xef, 0xae, 0x83, - 0x44, 0x51, 0x7a, 0x4a, 0x66, 0xe6, 0x7d, 0xfc, 0xde, 0x6f, 0xde, 0xbc, 0x7d, 0xcf, 0x30, 0xbb, - 0x6b, 0xed, 0x5b, 0xc6, 0x8e, 0xe5, 0xd9, 0xc6, 0xfe, 0x46, 0x9d, 0xfa, 0xd6, 0x86, 0x71, 0xa7, - 0x43, 0xbd, 0x83, 0x6a, 0xdb, 0x63, 0x3e, 0x23, 0xcf, 0x06, 0xc7, 0xd5, 0xe0, 0xb8, 0x8a, 0xc7, - 0xa5, 0x72, 0x83, 0xf1, 0x3d, 0xc6, 0x0d, 0xab, 0xe3, 0xef, 0x84, 0x3a, 0xc1, 0x42, 0xaa, 0x94, - 0x56, 0xf1, 0xbc, 0x6e, 0x71, 0x2a, 0x6d, 0x85, 0x52, 0x6d, 0xab, 0xe9, 0xb8, 0x96, 0xef, 0x30, - 0x17, 0x65, 0xcb, 0xbd, 0xb2, 0x4a, 0xaa, 0xc1, 0x1c, 0x75, 0x5e, 0x94, 0xe7, 0xdb, 0x62, 0x65, - 0xc8, 0x05, 0x1e, 0xe5, 0x9b, 0xac, 0xc9, 0xe4, 0x7e, 0xf0, 0x1f, 0xee, 0xce, 0x34, 0x19, 0x6b, - 0xb6, 0xa8, 0x61, 0xb5, 0x1d, 0xc3, 0x72, 0x5d, 0xe6, 0x0b, 0x6f, 0x4a, 0x67, 0xa6, 0x3f, 0x58, - 0x11, 0x9a, 0x38, 0xd5, 0xf3, 0x40, 0xde, 0x0a, 0xe0, 0xbe, 0x69, 0x79, 0xd6, 0x1e, 0x37, 0xe9, - 0x9d, 0x0e, 0xe5, 0xbe, 0xfe, 0x06, 0x3c, 0x17, 0xd9, 0xe5, 0x6d, 0xe6, 0x72, 0x4a, 0x5e, 0x82, - 0xd1, 0xb6, 0xd8, 0x29, 0x68, 0x73, 0xda, 0xca, 0xb9, 0xcd, 0x62, 0xb5, 0x8f, 0xa9, 0xaa, 0x54, - 0xa9, 0x3d, 0xf3, 0xe8, 0x8f, 0x4b, 0x43, 0x26, 0x8a, 0xeb, 0x17, 0x20, 0x2f, 0xec, 0x5d, 0x6f, - 0x34, 0x58, 0xc7, 0xf5, 0x43, 0x3f, 0xef, 0xc1, 0xf3, 0xb1, 0x7d, 0xf4, 0x74, 0x03, 0xc6, 0x2c, - 0xdc, 0x2b, 0x68, 0x73, 0xc3, 0x2b, 0xe7, 0x36, 0xf5, 0x2a, 0x32, 0x21, 0x58, 0x57, 0xde, 0xb6, - 0x98, 0xdd, 0x69, 0x51, 0x54, 0x47, 0xa7, 0xa1, 0xa6, 0xfe, 0xb5, 0x86, 0x7e, 0x6f, 0xd0, 0x36, - 0xe3, 0x4e, 0xe8, 0x97, 0xe4, 0x61, 0xc4, 0xa6, 0x2e, 0xdb, 0x13, 0x71, 0x9c, 0x35, 0xe5, 0x82, - 0x54, 0x61, 0x84, 0xdd, 0x75, 0xa9, 0x57, 0xc8, 0x05, 0xbb, 0xb5, 0xc2, 0xaf, 0xdf, 0x57, 0xf2, - 0xe8, 0xf4, 0xba, 0x6d, 0x7b, 0x94, 0xf3, 0x5b, 0xbe, 0xe7, 0xb8, 0x4d, 0x53, 0x8a, 0x91, 0x9b, - 0x00, 0xdd, 0xcb, 0x2d, 0x0c, 0x0b, 0x4a, 0x96, 0x14, 0xcc, 0xe0, 0x76, 0xab, 0x32, 0xab, 0xba, - 0xd4, 0x34, 0x29, 0x22, 0x30, 0x7b, 0x34, 0xf5, 0x1f, 0x35, 0xa4, 0xa1, 0x0b, 0x13, 0x69, 0x78, - 0x07, 0xc6, 0x6c, 0xdc, 0x0b, 0x69, 0xe8, 0xa7, 0x1c, 0xd5, 0x94, 0x56, 0xad, 0x10, 0xd0, 0xf0, - 0xcd, 0x9f, 0x97, 0xa6, 0x62, 0x07, 0xdc, 0x0c, 0xad, 0x91, 0x57, 0x23, 0xd8, 0x73, 0x02, 0xfb, - 0xf2, 0x40, 0xec, 0xd2, 0x4e, 0x04, 0xfc, 0x77, 0x1a, 0xcc, 0x08, 0xf0, 0x6f, 0xbb, 0xfc, 0xc0, - 0x6d, 0x50, 0xfb, 0x74, 0x73, 0xfd, 0xb3, 0x06, 0xb3, 0x29, 0x70, 0x9f, 0x1e, 0xce, 0x37, 0xa1, - 0x24, 0x62, 0xb8, 0xcd, 0x7c, 0xab, 0x85, 0x0e, 0xa9, 0x9d, 0x49, 0xb8, 0xfe, 0x89, 0x06, 0xd3, - 0x89, 0x4a, 0x18, 0xb6, 0x07, 0x13, 0xbc, 0xd3, 0x6e, 0xb7, 0x1c, 0x6a, 0x6f, 0x07, 0xc5, 0x88, - 0x17, 0x72, 0x22, 0xf8, 0x62, 0x04, 0xa0, 0x82, 0xf6, 0x0a, 0x73, 0xdc, 0xda, 0x3a, 0xc6, 0xbc, - 0xd2, 0x74, 0xfc, 0x9d, 0x4e, 0xbd, 0xda, 0x60, 0x7b, 0x58, 0xae, 0xf0, 0x4f, 0x85, 0xdb, 0xbb, - 0x86, 0x7f, 0xd0, 0xa6, 0x5c, 0x28, 0x70, 0x73, 0x5c, 0xb9, 0x10, 0x4b, 0xfd, 0xa1, 0x86, 0x75, - 0xa6, 0xc6, 0x3c, 0x8f, 0xdd, 0x3d, 0xa5, 0x29, 0xf3, 0x83, 0xaa, 0x22, 0x21, 0x4a, 0xa4, 0xec, - 0x36, 0x9c, 0xa9, 0xcb, 0x2d, 0x4c, 0x94, 0xf9, 0x84, 0x44, 0x91, 0x4a, 0x61, 0x9e, 0x5c, 0x44, - 0xce, 0x26, 0xa3, 0xfb, 0xdc, 0x54, 0xa6, 0xfe, 0xbb, 0x2c, 0xf9, 0x56, 0xdd, 0xb8, 0x4a, 0xf5, - 0x53, 0xcd, 0xf2, 0x4f, 0xf1, 0x3a, 0xf2, 0x94, 0xb1, 0xbd, 0x01, 0xc5, 0xee, 0xf3, 0x92, 0xee, - 0x06, 0x3d, 0xc9, 0x07, 0x5a, 0xef, 0x3b, 0xee, 0xea, 0x74, 0x5f, 0x64, 0x1d, 0xf7, 0x9e, 0xe0, - 0x8b, 0x54, 0x2e, 0xe4, 0x8b, 0x5c, 0x87, 0x82, 0x40, 0xf4, 0x9a, 0xeb, 0x53, 0x2f, 0xb8, 0x22, - 0xcb, 0xa7, 0x03, 0x83, 0x28, 0x26, 0xa8, 0x60, 0x0c, 0x1c, 0x26, 0x1c, 0xdc, 0xdf, 0xf6, 0x2c, - 0x9f, 0xaa, 0xbb, 0x5b, 0x4d, 0xb8, 0xbb, 0x2d, 0xe6, 0xd2, 0x83, 0x2d, 0xcb, 0xdb, 0xa5, 0x7e, - 0xaf, 0xad, 0xda, 0x1c, 0x06, 0x55, 0x48, 0x11, 0xe0, 0xe6, 0xb8, 0xd3, 0xbb, 0xd4, 0xd7, 0xf0, - 0xbd, 0x9a, 0x94, 0x53, 0x6f, 0x9f, 0x66, 0x27, 0xbc, 0xfe, 0x21, 0x7e, 0x7c, 0xbb, 0xd2, 0x88, - 0xbd, 0x01, 0xa3, 0xd6, 0x5e, 0xd0, 0x48, 0x3c, 0x09, 0xde, 0xd1, 0xb4, 0x7e, 0x15, 0xdf, 0xa8, - 0x0a, 0xe8, 0xa6, 0xd5, 0xf0, 0x99, 0x37, 0x00, 0xf2, 0xc7, 0xea, 0xad, 0xf4, 0x69, 0x21, 0x74, - 0x0a, 0x53, 0x21, 0xed, 0xef, 0xcb, 0xb3, 0x8c, 0x47, 0x13, 0xb5, 0xd2, 0x7d, 0x34, 0x71, 0xeb, - 0x93, 0x4e, 0x74, 0x43, 0xff, 0x32, 0x07, 0x93, 0xb1, 0xef, 0x1d, 0x79, 0x11, 0xce, 0xe2, 0x07, - 0x8f, 0x79, 0x12, 0x75, 0x46, 0x0d, 0xe9, 0x8a, 0xfe, 0x2f, 0x6c, 0x93, 0x16, 0x8c, 0x38, 0xae, - 0x4d, 0xef, 0x15, 0x86, 0x85, 0x0f, 0x23, 0x81, 0x8c, 0x5b, 0xc1, 0x17, 0x2a, 0x46, 0x6c, 0x58, - 0x4f, 0x16, 0xd1, 0xf3, 0x6c, 0x96, 0x14, 0x37, 0xa5, 0x13, 0xfd, 0x75, 0x98, 0xc9, 0x92, 0x4b, - 0x29, 0xc0, 0x79, 0x18, 0xd9, 0xb7, 0x5a, 0x1d, 0x2a, 0x0b, 0xb0, 0x29, 0x17, 0xfa, 0xe7, 0x39, - 0x98, 0x88, 0x16, 0x31, 0x72, 0x0d, 0xc6, 0xf0, 0xf1, 0x0e, 0x26, 0x3a, 0x94, 0x3c, 0x35, 0x3c, - 0xcb, 0x60, 0x06, 0xf1, 0x9c, 0x25, 0xd5, 0xcb, 0x73, 0x96, 0xdc, 0xbf, 0xe2, 0xf9, 0x50, 0x83, - 0x8b, 0x29, 0x75, 0x26, 0xc5, 0xce, 0x3a, 0xe4, 0x45, 0x57, 0x73, 0xb0, 0x1d, 0xa9, 0x74, 0x68, - 0x96, 0xf0, 0x48, 0x06, 0x08, 0x3b, 0xeb, 0x90, 0x97, 0xd7, 0x11, 0xd3, 0x18, 0x96, 0x1a, 0xf5, - 0x48, 0x2c, 0x81, 0x86, 0xfe, 0xa9, 0x06, 0x13, 0xd1, 0xe0, 0x52, 0xc0, 0x5c, 0x83, 0x0b, 0x71, - 0xd3, 0xf2, 0xfd, 0x23, 0x9c, 0x7c, 0x3d, 0x81, 0xa8, 0x40, 0x2b, 0x1e, 0x02, 0x6a, 0x49, 0x48, - 0x79, 0x9e, 0x90, 0xc6, 0x9b, 0xbf, 0x9c, 0x87, 0x11, 0x51, 0x85, 0xc8, 0x07, 0x30, 0x2a, 0xc7, - 0x3e, 0xb2, 0x98, 0x70, 0xd3, 0xfd, 0xf3, 0x65, 0x69, 0x69, 0x90, 0x98, 0xbc, 0x39, 0x7d, 0xfe, - 0xfe, 0x6f, 0x7f, 0x1f, 0xe6, 0xa6, 0x49, 0xd1, 0xe8, 0x1f, 0x62, 0xe5, 0x68, 0x49, 0xee, 0x6b, - 0x30, 0xa6, 0xc6, 0x47, 0xb2, 0x9c, 0x66, 0x37, 0x36, 0x78, 0x96, 0x56, 0x06, 0x0b, 0x22, 0x84, - 0x05, 0x01, 0x61, 0x96, 0x4c, 0x27, 0x40, 0x50, 0x83, 0xa6, 0x00, 0xa1, 0x06, 0x89, 0x74, 0x10, - 0xb1, 0xc9, 0x28, 0x1d, 0x44, 0x7c, 0x26, 0xc9, 0x04, 0x11, 0x8e, 0x17, 0x0f, 0x35, 0x98, 0x8a, - 0x4f, 0x35, 0xc4, 0x48, 0xf3, 0x91, 0x32, 0xae, 0x95, 0xd6, 0x4f, 0xae, 0x80, 0xe0, 0xd6, 0x04, - 0xb8, 0x25, 0x72, 0x39, 0x01, 0x5c, 0x07, 0x95, 0x2a, 0x21, 0xca, 0x2f, 0x34, 0x98, 0x88, 0x8e, - 0x20, 0xa4, 0x92, 0xe6, 0x32, 0x71, 0xbe, 0x29, 0x55, 0x4f, 0x2a, 0x8e, 0xf8, 0x56, 0x05, 0xbe, - 0xcb, 0x44, 0x4f, 0xc0, 0xe7, 0x07, 0x2a, 0x0a, 0x1c, 0xb5, 0xc9, 0x47, 0x70, 0x06, 0xfb, 0x4e, - 0x92, 0x9a, 0xa3, 0xd1, 0x36, 0xba, 0xb4, 0x3c, 0x50, 0x0e, 0x71, 0xe8, 0x02, 0xc7, 0x0c, 0x29, - 0x25, 0xe0, 0x50, 0xed, 0xe8, 0x57, 0x1a, 0x4c, 0xc6, 0x1a, 0x60, 0x52, 0x1d, 0x74, 0x23, 0x31, - 0x40, 0xc6, 0x89, 0xe5, 0x11, 0xd8, 0x15, 0x01, 0x6c, 0x91, 0x2c, 0x64, 0x5d, 0xa0, 0x42, 0xf8, - 0x99, 0x06, 0xe3, 0x91, 0x7e, 0x95, 0xac, 0x65, 0xde, 0x47, 0xac, 0x15, 0x2e, 0x55, 0x4e, 0x28, - 0x8d, 0xd8, 0x5e, 0x10, 0xd8, 0x16, 0xc8, 0x7c, 0xea, 0xe5, 0xa9, 0x06, 0x96, 0x1c, 0x6a, 0x70, - 0x3e, 0x52, 0x67, 0xaf, 0xa4, 0xb9, 0x4a, 0xe8, 0x6e, 0x4b, 0x6b, 0x27, 0x13, 0x46, 0x58, 0x2b, - 0x02, 0x96, 0x4e, 0xe6, 0x12, 0x60, 0xa9, 0x1a, 0x5a, 0x09, 0x8a, 0xba, 0x28, 0x0d, 0xaa, 0xb5, - 0x4c, 0x2f, 0x0d, 0xb1, 0x56, 0x35, 0xbd, 0x34, 0xc4, 0xbb, 0xd4, 0xcc, 0xd2, 0xe0, 0x29, 0xbf, - 0x41, 0x5a, 0xc5, 0xba, 0xb9, 0xf4, 0xb4, 0x4a, 0x6e, 0x45, 0xd3, 0xd3, 0x2a, 0xa5, 0x09, 0xcd, - 0x4c, 0xab, 0x90, 0x23, 0xec, 0x4e, 0x6b, 0x2f, 0x3f, 0x3a, 0x2a, 0x6b, 0x8f, 0x8f, 0xca, 0xda, - 0x5f, 0x47, 0x65, 0xed, 0xc1, 0x71, 0x79, 0xe8, 0xf1, 0x71, 0x79, 0xe8, 0xf7, 0xe3, 0xf2, 0xd0, - 0xbb, 0x4b, 0x3d, 0xdd, 0x47, 0x60, 0xa8, 0xd2, 0xb2, 0xea, 0x5c, 0x9a, 0xbc, 0x27, 0x8d, 0x8a, - 0x0e, 0xa4, 0x3e, 0x2a, 0x7e, 0xd0, 0xbc, 0xfa, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x50, 0x6b, - 0x16, 0xfb, 0xdd, 0x15, 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 { - // Params queries module params. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Accounts queries module accounts. - Accounts(ctx context.Context, in *QueryAccountsRequest, opts ...grpc.CallOption) (*QueryAccountsResponse, error) - // Deposits queries hard deposits. - Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) - // UnsyncedDeposits queries unsynced deposits. - UnsyncedDeposits(ctx context.Context, in *QueryUnsyncedDepositsRequest, opts ...grpc.CallOption) (*QueryUnsyncedDepositsResponse, error) - // TotalDeposited queries total coins deposited to hard liquidity pools. - TotalDeposited(ctx context.Context, in *QueryTotalDepositedRequest, opts ...grpc.CallOption) (*QueryTotalDepositedResponse, error) - // Borrows queries hard borrows. - Borrows(ctx context.Context, in *QueryBorrowsRequest, opts ...grpc.CallOption) (*QueryBorrowsResponse, error) - // UnsyncedBorrows queries unsynced borrows. - UnsyncedBorrows(ctx context.Context, in *QueryUnsyncedBorrowsRequest, opts ...grpc.CallOption) (*QueryUnsyncedBorrowsResponse, error) - // TotalBorrowed queries total coins borrowed from hard liquidity pools. - TotalBorrowed(ctx context.Context, in *QueryTotalBorrowedRequest, opts ...grpc.CallOption) (*QueryTotalBorrowedResponse, error) - // InterestRate queries the hard module interest rates. - InterestRate(ctx context.Context, in *QueryInterestRateRequest, opts ...grpc.CallOption) (*QueryInterestRateResponse, error) - // Reserves queries total hard reserve coins. - Reserves(ctx context.Context, in *QueryReservesRequest, opts ...grpc.CallOption) (*QueryReservesResponse, error) - // InterestFactors queries hard module interest factors. - InterestFactors(ctx context.Context, in *QueryInterestFactorsRequest, opts ...grpc.CallOption) (*QueryInterestFactorsResponse, 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, "/kava.hard.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Accounts(ctx context.Context, in *QueryAccountsRequest, opts ...grpc.CallOption) (*QueryAccountsResponse, error) { - out := new(QueryAccountsResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/Accounts", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) { - out := new(QueryDepositsResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/Deposits", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) UnsyncedDeposits(ctx context.Context, in *QueryUnsyncedDepositsRequest, opts ...grpc.CallOption) (*QueryUnsyncedDepositsResponse, error) { - out := new(QueryUnsyncedDepositsResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/UnsyncedDeposits", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalDeposited(ctx context.Context, in *QueryTotalDepositedRequest, opts ...grpc.CallOption) (*QueryTotalDepositedResponse, error) { - out := new(QueryTotalDepositedResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/TotalDeposited", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Borrows(ctx context.Context, in *QueryBorrowsRequest, opts ...grpc.CallOption) (*QueryBorrowsResponse, error) { - out := new(QueryBorrowsResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/Borrows", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) UnsyncedBorrows(ctx context.Context, in *QueryUnsyncedBorrowsRequest, opts ...grpc.CallOption) (*QueryUnsyncedBorrowsResponse, error) { - out := new(QueryUnsyncedBorrowsResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/UnsyncedBorrows", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalBorrowed(ctx context.Context, in *QueryTotalBorrowedRequest, opts ...grpc.CallOption) (*QueryTotalBorrowedResponse, error) { - out := new(QueryTotalBorrowedResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/TotalBorrowed", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) InterestRate(ctx context.Context, in *QueryInterestRateRequest, opts ...grpc.CallOption) (*QueryInterestRateResponse, error) { - out := new(QueryInterestRateResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/InterestRate", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Reserves(ctx context.Context, in *QueryReservesRequest, opts ...grpc.CallOption) (*QueryReservesResponse, error) { - out := new(QueryReservesResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/Reserves", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) InterestFactors(ctx context.Context, in *QueryInterestFactorsRequest, opts ...grpc.CallOption) (*QueryInterestFactorsResponse, error) { - out := new(QueryInterestFactorsResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/InterestFactors", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries module params. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Accounts queries module accounts. - Accounts(context.Context, *QueryAccountsRequest) (*QueryAccountsResponse, error) - // Deposits queries hard deposits. - Deposits(context.Context, *QueryDepositsRequest) (*QueryDepositsResponse, error) - // UnsyncedDeposits queries unsynced deposits. - UnsyncedDeposits(context.Context, *QueryUnsyncedDepositsRequest) (*QueryUnsyncedDepositsResponse, error) - // TotalDeposited queries total coins deposited to hard liquidity pools. - TotalDeposited(context.Context, *QueryTotalDepositedRequest) (*QueryTotalDepositedResponse, error) - // Borrows queries hard borrows. - Borrows(context.Context, *QueryBorrowsRequest) (*QueryBorrowsResponse, error) - // UnsyncedBorrows queries unsynced borrows. - UnsyncedBorrows(context.Context, *QueryUnsyncedBorrowsRequest) (*QueryUnsyncedBorrowsResponse, error) - // TotalBorrowed queries total coins borrowed from hard liquidity pools. - TotalBorrowed(context.Context, *QueryTotalBorrowedRequest) (*QueryTotalBorrowedResponse, error) - // InterestRate queries the hard module interest rates. - InterestRate(context.Context, *QueryInterestRateRequest) (*QueryInterestRateResponse, error) - // Reserves queries total hard reserve coins. - Reserves(context.Context, *QueryReservesRequest) (*QueryReservesResponse, error) - // InterestFactors queries hard module interest factors. - InterestFactors(context.Context, *QueryInterestFactorsRequest) (*QueryInterestFactorsResponse, 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) Accounts(ctx context.Context, req *QueryAccountsRequest) (*QueryAccountsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Accounts not implemented") -} -func (*UnimplementedQueryServer) Deposits(ctx context.Context, req *QueryDepositsRequest) (*QueryDepositsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposits not implemented") -} -func (*UnimplementedQueryServer) UnsyncedDeposits(ctx context.Context, req *QueryUnsyncedDepositsRequest) (*QueryUnsyncedDepositsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UnsyncedDeposits not implemented") -} -func (*UnimplementedQueryServer) TotalDeposited(ctx context.Context, req *QueryTotalDepositedRequest) (*QueryTotalDepositedResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalDeposited not implemented") -} -func (*UnimplementedQueryServer) Borrows(ctx context.Context, req *QueryBorrowsRequest) (*QueryBorrowsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Borrows not implemented") -} -func (*UnimplementedQueryServer) UnsyncedBorrows(ctx context.Context, req *QueryUnsyncedBorrowsRequest) (*QueryUnsyncedBorrowsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UnsyncedBorrows not implemented") -} -func (*UnimplementedQueryServer) TotalBorrowed(ctx context.Context, req *QueryTotalBorrowedRequest) (*QueryTotalBorrowedResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalBorrowed not implemented") -} -func (*UnimplementedQueryServer) InterestRate(ctx context.Context, req *QueryInterestRateRequest) (*QueryInterestRateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method InterestRate not implemented") -} -func (*UnimplementedQueryServer) Reserves(ctx context.Context, req *QueryReservesRequest) (*QueryReservesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Reserves not implemented") -} -func (*UnimplementedQueryServer) InterestFactors(ctx context.Context, req *QueryInterestFactorsRequest) (*QueryInterestFactorsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method InterestFactors 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: "/kava.hard.v1beta1.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_Accounts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAccountsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Accounts(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/Accounts", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Accounts(ctx, req.(*QueryAccountsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Deposits_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDepositsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Deposits(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/Deposits", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Deposits(ctx, req.(*QueryDepositsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_UnsyncedDeposits_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryUnsyncedDepositsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).UnsyncedDeposits(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/UnsyncedDeposits", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).UnsyncedDeposits(ctx, req.(*QueryUnsyncedDepositsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalDeposited_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalDepositedRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalDeposited(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/TotalDeposited", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalDeposited(ctx, req.(*QueryTotalDepositedRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Borrows_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryBorrowsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Borrows(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/Borrows", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Borrows(ctx, req.(*QueryBorrowsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_UnsyncedBorrows_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryUnsyncedBorrowsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).UnsyncedBorrows(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/UnsyncedBorrows", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).UnsyncedBorrows(ctx, req.(*QueryUnsyncedBorrowsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalBorrowed_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalBorrowedRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalBorrowed(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/TotalBorrowed", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalBorrowed(ctx, req.(*QueryTotalBorrowedRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_InterestRate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryInterestRateRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).InterestRate(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/InterestRate", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).InterestRate(ctx, req.(*QueryInterestRateRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Reserves_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryReservesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Reserves(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/Reserves", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Reserves(ctx, req.(*QueryReservesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_InterestFactors_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryInterestFactorsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).InterestFactors(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/InterestFactors", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).InterestFactors(ctx, req.(*QueryInterestFactorsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.hard.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Accounts", - Handler: _Query_Accounts_Handler, - }, - { - MethodName: "Deposits", - Handler: _Query_Deposits_Handler, - }, - { - MethodName: "UnsyncedDeposits", - Handler: _Query_UnsyncedDeposits_Handler, - }, - { - MethodName: "TotalDeposited", - Handler: _Query_TotalDeposited_Handler, - }, - { - MethodName: "Borrows", - Handler: _Query_Borrows_Handler, - }, - { - MethodName: "UnsyncedBorrows", - Handler: _Query_UnsyncedBorrows_Handler, - }, - { - MethodName: "TotalBorrowed", - Handler: _Query_TotalBorrowed_Handler, - }, - { - MethodName: "InterestRate", - Handler: _Query_InterestRate_Handler, - }, - { - MethodName: "Reserves", - Handler: _Query_Reserves_Handler, - }, - { - MethodName: "InterestFactors", - Handler: _Query_InterestFactors_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/hard/v1beta1/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 *QueryAccountsRequest) 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 *QueryAccountsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAccountsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryAccountsResponse) 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 *QueryAccountsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAccountsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Accounts) > 0 { - for iNdEx := len(m.Accounts) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Accounts[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 (m *QueryDepositsRequest) 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 *QueryDepositsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsRequest) 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] = 0x1a - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDepositsResponse) 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 *QueryDepositsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsResponse) 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.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[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 (m *QueryUnsyncedDepositsRequest) 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 *QueryUnsyncedDepositsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryUnsyncedDepositsRequest) 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] = 0x1a - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryUnsyncedDepositsResponse) 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 *QueryUnsyncedDepositsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryUnsyncedDepositsResponse) 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.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[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 (m *QueryTotalDepositedRequest) 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 *QueryTotalDepositedRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalDepositedRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalDepositedResponse) 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 *QueryTotalDepositedResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalDepositedResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.SuppliedCoins) > 0 { - for iNdEx := len(m.SuppliedCoins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SuppliedCoins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - return len(dAtA) - i, nil -} - -func (m *QueryBorrowsRequest) 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 *QueryBorrowsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryBorrowsRequest) 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] = 0x1a - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryBorrowsResponse) 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 *QueryBorrowsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryBorrowsResponse) 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.Borrows) > 0 { - for iNdEx := len(m.Borrows) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Borrows[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 (m *QueryUnsyncedBorrowsRequest) 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 *QueryUnsyncedBorrowsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryUnsyncedBorrowsRequest) 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] = 0x1a - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryUnsyncedBorrowsResponse) 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 *QueryUnsyncedBorrowsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryUnsyncedBorrowsResponse) 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.Borrows) > 0 { - for iNdEx := len(m.Borrows) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Borrows[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 (m *QueryTotalBorrowedRequest) 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 *QueryTotalBorrowedRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalBorrowedRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalBorrowedResponse) 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 *QueryTotalBorrowedResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalBorrowedResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.BorrowedCoins) > 0 { - for iNdEx := len(m.BorrowedCoins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.BorrowedCoins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - return len(dAtA) - i, nil -} - -func (m *QueryInterestRateRequest) 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 *QueryInterestRateRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryInterestRateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryInterestRateResponse) 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 *QueryInterestRateResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryInterestRateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.InterestRates) > 0 { - for iNdEx := len(m.InterestRates) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.InterestRates[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 (m *QueryReservesRequest) 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 *QueryReservesRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryReservesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryReservesResponse) 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 *QueryReservesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryReservesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - return len(dAtA) - i, nil -} - -func (m *QueryInterestFactorsRequest) 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 *QueryInterestFactorsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryInterestFactorsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryInterestFactorsResponse) 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 *QueryInterestFactorsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryInterestFactorsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.InterestFactors) > 0 { - for iNdEx := len(m.InterestFactors) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.InterestFactors[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 (m *DepositResponse) 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 *DepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Index) > 0 { - for iNdEx := len(m.Index) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Index[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *SupplyInterestFactorResponse) 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 *SupplyInterestFactorResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SupplyInterestFactorResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Value) > 0 { - i -= len(m.Value) - copy(dAtA[i:], m.Value) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Value))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *BorrowResponse) 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 *BorrowResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *BorrowResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Index) > 0 { - for iNdEx := len(m.Index) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Index[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Borrower) > 0 { - i -= len(m.Borrower) - copy(dAtA[i:], m.Borrower) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Borrower))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *BorrowInterestFactorResponse) 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 *BorrowInterestFactorResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *BorrowInterestFactorResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Value) > 0 { - i -= len(m.Value) - copy(dAtA[i:], m.Value) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Value))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MoneyMarketInterestRate) 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 *MoneyMarketInterestRate) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MoneyMarketInterestRate) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.BorrowInterestRate) > 0 { - i -= len(m.BorrowInterestRate) - copy(dAtA[i:], m.BorrowInterestRate) - i = encodeVarintQuery(dAtA, i, uint64(len(m.BorrowInterestRate))) - i-- - dAtA[i] = 0x1a - } - if len(m.SupplyInterestRate) > 0 { - i -= len(m.SupplyInterestRate) - copy(dAtA[i:], m.SupplyInterestRate) - i = encodeVarintQuery(dAtA, i, uint64(len(m.SupplyInterestRate))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *InterestFactor) 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 *InterestFactor) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *InterestFactor) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.SupplyInterestFactor) > 0 { - i -= len(m.SupplyInterestFactor) - copy(dAtA[i:], m.SupplyInterestFactor) - i = encodeVarintQuery(dAtA, i, uint64(len(m.SupplyInterestFactor))) - i-- - dAtA[i] = 0x1a - } - if len(m.BorrowInterestFactor) > 0 { - i -= len(m.BorrowInterestFactor) - copy(dAtA[i:], m.BorrowInterestFactor) - i = encodeVarintQuery(dAtA, i, uint64(len(m.BorrowInterestFactor))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - 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 *QueryAccountsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryAccountsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Accounts) > 0 { - for _, e := range m.Accounts { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryDepositsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDepositsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Deposits) > 0 { - for _, e := range m.Deposits { - 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 (m *QueryUnsyncedDepositsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryUnsyncedDepositsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Deposits) > 0 { - for _, e := range m.Deposits { - 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 (m *QueryTotalDepositedRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryTotalDepositedResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.SuppliedCoins) > 0 { - for _, e := range m.SuppliedCoins { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryBorrowsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryBorrowsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Borrows) > 0 { - for _, e := range m.Borrows { - 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 (m *QueryUnsyncedBorrowsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryUnsyncedBorrowsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Borrows) > 0 { - for _, e := range m.Borrows { - 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 (m *QueryTotalBorrowedRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryTotalBorrowedResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.BorrowedCoins) > 0 { - for _, e := range m.BorrowedCoins { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryInterestRateRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryInterestRateResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.InterestRates) > 0 { - for _, e := range m.InterestRates { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryReservesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryReservesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryInterestFactorsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryInterestFactorsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.InterestFactors) > 0 { - for _, e := range m.InterestFactors { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *DepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.Index) > 0 { - for _, e := range m.Index { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *SupplyInterestFactorResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Value) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *BorrowResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Borrower) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.Index) > 0 { - for _, e := range m.Index { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *BorrowInterestFactorResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Value) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *MoneyMarketInterestRate) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.SupplyInterestRate) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.BorrowInterestRate) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *InterestFactor) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.BorrowInterestFactor) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.SupplyInterestFactor) - if l > 0 { - 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 *QueryAccountsRequest) 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: QueryAccountsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAccountsRequest: 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 *QueryAccountsResponse) 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: QueryAccountsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAccountsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Accounts", 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.Accounts = append(m.Accounts, types.ModuleAccount{}) - if err := m.Accounts[len(m.Accounts)-1].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 *QueryDepositsRequest) 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: QueryDepositsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - 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 *QueryDepositsResponse) 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: QueryDepositsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposits", 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.Deposits = append(m.Deposits, DepositResponse{}) - if err := m.Deposits[len(m.Deposits)-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 (m *QueryUnsyncedDepositsRequest) 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: QueryUnsyncedDepositsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryUnsyncedDepositsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - 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 *QueryUnsyncedDepositsResponse) 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: QueryUnsyncedDepositsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryUnsyncedDepositsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposits", 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.Deposits = append(m.Deposits, DepositResponse{}) - if err := m.Deposits[len(m.Deposits)-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 (m *QueryTotalDepositedRequest) 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: QueryTotalDepositedRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalDepositedRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - 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 *QueryTotalDepositedResponse) 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: QueryTotalDepositedResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalDepositedResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SuppliedCoins", 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.SuppliedCoins = append(m.SuppliedCoins, types1.Coin{}) - if err := m.SuppliedCoins[len(m.SuppliedCoins)-1].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 *QueryBorrowsRequest) 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: QueryBorrowsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryBorrowsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - 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 *QueryBorrowsResponse) 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: QueryBorrowsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryBorrowsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Borrows", 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.Borrows = append(m.Borrows, BorrowResponse{}) - if err := m.Borrows[len(m.Borrows)-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 (m *QueryUnsyncedBorrowsRequest) 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: QueryUnsyncedBorrowsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryUnsyncedBorrowsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - 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 *QueryUnsyncedBorrowsResponse) 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: QueryUnsyncedBorrowsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryUnsyncedBorrowsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Borrows", 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.Borrows = append(m.Borrows, BorrowResponse{}) - if err := m.Borrows[len(m.Borrows)-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 (m *QueryTotalBorrowedRequest) 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: QueryTotalBorrowedRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalBorrowedRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - 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 *QueryTotalBorrowedResponse) 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: QueryTotalBorrowedResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalBorrowedResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BorrowedCoins", 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.BorrowedCoins = append(m.BorrowedCoins, types1.Coin{}) - if err := m.BorrowedCoins[len(m.BorrowedCoins)-1].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 *QueryInterestRateRequest) 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: QueryInterestRateRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryInterestRateRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - 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 *QueryInterestRateResponse) 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: QueryInterestRateResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryInterestRateResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InterestRates", 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.InterestRates = append(m.InterestRates, MoneyMarketInterestRate{}) - if err := m.InterestRates[len(m.InterestRates)-1].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 *QueryReservesRequest) 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: QueryReservesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryReservesRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - 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 *QueryReservesResponse) 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: QueryReservesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryReservesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", 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.Amount = append(m.Amount, types1.Coin{}) - if err := m.Amount[len(m.Amount)-1].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 *QueryInterestFactorsRequest) 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: QueryInterestFactorsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryInterestFactorsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - 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 *QueryInterestFactorsResponse) 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: QueryInterestFactorsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryInterestFactorsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InterestFactors", 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.InterestFactors = append(m.InterestFactors, InterestFactor{}) - if err := m.InterestFactors[len(m.InterestFactors)-1].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 *DepositResponse) 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: DepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", 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.Amount = append(m.Amount, types1.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Index", 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.Index = append(m.Index, SupplyInterestFactorResponse{}) - if err := m.Index[len(m.Index)-1].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 *SupplyInterestFactorResponse) 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: SupplyInterestFactorResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SupplyInterestFactorResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Value = string(dAtA[iNdEx:postIndex]) - 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 *BorrowResponse) 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: BorrowResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BorrowResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Borrower", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Borrower = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", 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.Amount = append(m.Amount, types1.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Index", 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.Index = append(m.Index, BorrowInterestFactorResponse{}) - if err := m.Index[len(m.Index)-1].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 *BorrowInterestFactorResponse) 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: BorrowInterestFactorResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BorrowInterestFactorResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Value = string(dAtA[iNdEx:postIndex]) - 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 *MoneyMarketInterestRate) 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: MoneyMarketInterestRate: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MoneyMarketInterestRate: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SupplyInterestRate", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SupplyInterestRate = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BorrowInterestRate", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.BorrowInterestRate = string(dAtA[iNdEx:postIndex]) - 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 *InterestFactor) 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: InterestFactor: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: InterestFactor: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BorrowInterestFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.BorrowInterestFactor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SupplyInterestFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SupplyInterestFactor = string(dAtA[iNdEx:postIndex]) - 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/hard/types/query.pb.gw.go b/x/hard/types/query.pb.gw.go deleted file mode 100644 index 725144d6..00000000 --- a/x/hard/types/query.pb.gw.go +++ /dev/null @@ -1,965 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/hard/v1beta1/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_Accounts_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAccountsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Accounts(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Accounts_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAccountsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Accounts(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Deposits_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - 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_Deposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Deposits(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - 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_Deposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Deposits(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_UnsyncedDeposits_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_UnsyncedDeposits_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryUnsyncedDepositsRequest - 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_UnsyncedDeposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.UnsyncedDeposits(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_UnsyncedDeposits_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryUnsyncedDepositsRequest - 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_UnsyncedDeposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.UnsyncedDeposits(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_TotalDeposited_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_TotalDeposited_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalDepositedRequest - 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_TotalDeposited_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.TotalDeposited(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalDeposited_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalDepositedRequest - 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_TotalDeposited_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.TotalDeposited(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Borrows_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Borrows_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryBorrowsRequest - 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_Borrows_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Borrows(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Borrows_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryBorrowsRequest - 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_Borrows_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Borrows(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_UnsyncedBorrows_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_UnsyncedBorrows_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryUnsyncedBorrowsRequest - 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_UnsyncedBorrows_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.UnsyncedBorrows(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_UnsyncedBorrows_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryUnsyncedBorrowsRequest - 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_UnsyncedBorrows_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.UnsyncedBorrows(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_TotalBorrowed_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_TotalBorrowed_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalBorrowedRequest - 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_TotalBorrowed_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.TotalBorrowed(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalBorrowed_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalBorrowedRequest - 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_TotalBorrowed_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.TotalBorrowed(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_InterestRate_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_InterestRate_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryInterestRateRequest - 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_InterestRate_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.InterestRate(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_InterestRate_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryInterestRateRequest - 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_InterestRate_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.InterestRate(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Reserves_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Reserves_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryReservesRequest - 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_Reserves_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Reserves(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Reserves_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryReservesRequest - 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_Reserves_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Reserves(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_InterestFactors_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_InterestFactors_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryInterestFactorsRequest - 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_InterestFactors_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.InterestFactors(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_InterestFactors_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryInterestFactorsRequest - 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_InterestFactors_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.InterestFactors(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_Accounts_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_Accounts_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_Accounts_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_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_Deposits_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_Deposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_UnsyncedDeposits_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_UnsyncedDeposits_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_UnsyncedDeposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalDeposited_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_TotalDeposited_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_TotalDeposited_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Borrows_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_Borrows_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_Borrows_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_UnsyncedBorrows_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_UnsyncedBorrows_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_UnsyncedBorrows_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalBorrowed_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_TotalBorrowed_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_TotalBorrowed_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_InterestRate_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_InterestRate_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_InterestRate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Reserves_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_Reserves_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_Reserves_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_InterestFactors_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_InterestFactors_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_InterestFactors_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_Accounts_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_Accounts_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_Accounts_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_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_Deposits_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_Deposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_UnsyncedDeposits_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_UnsyncedDeposits_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_UnsyncedDeposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalDeposited_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_TotalDeposited_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_TotalDeposited_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Borrows_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_Borrows_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_Borrows_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_UnsyncedBorrows_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_UnsyncedBorrows_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_UnsyncedBorrows_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalBorrowed_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_TotalBorrowed_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_TotalBorrowed_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_InterestRate_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_InterestRate_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_InterestRate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Reserves_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_Reserves_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_Reserves_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_InterestFactors_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_InterestFactors_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_InterestFactors_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{"kava", "hard", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Accounts_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "accounts"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Deposits_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "deposits"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_UnsyncedDeposits_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "unsynced-deposits"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalDeposited_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "total-deposited"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Borrows_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "borrows"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_UnsyncedBorrows_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "unsynced-borrows"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalBorrowed_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "total-borrowed"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_InterestRate_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "interest-rate"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Reserves_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "reserves"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_InterestFactors_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "interest-factors"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Accounts_0 = runtime.ForwardResponseMessage - - forward_Query_Deposits_0 = runtime.ForwardResponseMessage - - forward_Query_UnsyncedDeposits_0 = runtime.ForwardResponseMessage - - forward_Query_TotalDeposited_0 = runtime.ForwardResponseMessage - - forward_Query_Borrows_0 = runtime.ForwardResponseMessage - - forward_Query_UnsyncedBorrows_0 = runtime.ForwardResponseMessage - - forward_Query_TotalBorrowed_0 = runtime.ForwardResponseMessage - - forward_Query_InterestRate_0 = runtime.ForwardResponseMessage - - forward_Query_Reserves_0 = runtime.ForwardResponseMessage - - forward_Query_InterestFactors_0 = runtime.ForwardResponseMessage -) diff --git a/x/hard/types/tx.pb.go b/x/hard/types/tx.pb.go deleted file mode 100644 index e14cb5d5..00000000 --- a/x/hard/types/tx.pb.go +++ /dev/null @@ -1,2216 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/hard/v1beta1/tx.proto - -package types - -import ( - context "context" - 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" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - 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 - -// MsgDeposit defines the Msg/Deposit request type. -type MsgDeposit struct { - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MsgDeposit) Reset() { *m = MsgDeposit{} } -func (m *MsgDeposit) String() string { return proto.CompactTextString(m) } -func (*MsgDeposit) ProtoMessage() {} -func (*MsgDeposit) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{0} -} -func (m *MsgDeposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDeposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDeposit.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 *MsgDeposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDeposit.Merge(m, src) -} -func (m *MsgDeposit) XXX_Size() int { - return m.Size() -} -func (m *MsgDeposit) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDeposit.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDeposit proto.InternalMessageInfo - -func (m *MsgDeposit) GetDepositor() string { - if m != nil { - return m.Depositor - } - return "" -} - -func (m *MsgDeposit) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -// MsgDepositResponse defines the Msg/Deposit response type. -type MsgDepositResponse struct { -} - -func (m *MsgDepositResponse) Reset() { *m = MsgDepositResponse{} } -func (m *MsgDepositResponse) String() string { return proto.CompactTextString(m) } -func (*MsgDepositResponse) ProtoMessage() {} -func (*MsgDepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{1} -} -func (m *MsgDepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDepositResponse.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 *MsgDepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDepositResponse.Merge(m, src) -} -func (m *MsgDepositResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgDepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDepositResponse proto.InternalMessageInfo - -// MsgWithdraw defines the Msg/Withdraw request type. -type MsgWithdraw struct { - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MsgWithdraw) Reset() { *m = MsgWithdraw{} } -func (m *MsgWithdraw) String() string { return proto.CompactTextString(m) } -func (*MsgWithdraw) ProtoMessage() {} -func (*MsgWithdraw) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{2} -} -func (m *MsgWithdraw) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdraw) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdraw.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 *MsgWithdraw) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdraw.Merge(m, src) -} -func (m *MsgWithdraw) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdraw) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdraw.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdraw proto.InternalMessageInfo - -func (m *MsgWithdraw) GetDepositor() string { - if m != nil { - return m.Depositor - } - return "" -} - -func (m *MsgWithdraw) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -type MsgWithdrawResponse struct { -} - -func (m *MsgWithdrawResponse) Reset() { *m = MsgWithdrawResponse{} } -func (m *MsgWithdrawResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawResponse) ProtoMessage() {} -func (*MsgWithdrawResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{3} -} -func (m *MsgWithdrawResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawResponse.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 *MsgWithdrawResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawResponse.Merge(m, src) -} -func (m *MsgWithdrawResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawResponse proto.InternalMessageInfo - -// MsgBorrow defines the Msg/Borrow request type. -type MsgBorrow struct { - Borrower string `protobuf:"bytes,1,opt,name=borrower,proto3" json:"borrower,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MsgBorrow) Reset() { *m = MsgBorrow{} } -func (m *MsgBorrow) String() string { return proto.CompactTextString(m) } -func (*MsgBorrow) ProtoMessage() {} -func (*MsgBorrow) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{4} -} -func (m *MsgBorrow) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgBorrow) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgBorrow.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 *MsgBorrow) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgBorrow.Merge(m, src) -} -func (m *MsgBorrow) XXX_Size() int { - return m.Size() -} -func (m *MsgBorrow) XXX_DiscardUnknown() { - xxx_messageInfo_MsgBorrow.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgBorrow proto.InternalMessageInfo - -func (m *MsgBorrow) GetBorrower() string { - if m != nil { - return m.Borrower - } - return "" -} - -func (m *MsgBorrow) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -// MsgBorrowResponse defines the Msg/Borrow response type. -type MsgBorrowResponse struct { -} - -func (m *MsgBorrowResponse) Reset() { *m = MsgBorrowResponse{} } -func (m *MsgBorrowResponse) String() string { return proto.CompactTextString(m) } -func (*MsgBorrowResponse) ProtoMessage() {} -func (*MsgBorrowResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{5} -} -func (m *MsgBorrowResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgBorrowResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgBorrowResponse.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 *MsgBorrowResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgBorrowResponse.Merge(m, src) -} -func (m *MsgBorrowResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgBorrowResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgBorrowResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgBorrowResponse proto.InternalMessageInfo - -// MsgRepay defines the Msg/Repay request type. -type MsgRepay struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MsgRepay) Reset() { *m = MsgRepay{} } -func (m *MsgRepay) String() string { return proto.CompactTextString(m) } -func (*MsgRepay) ProtoMessage() {} -func (*MsgRepay) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{6} -} -func (m *MsgRepay) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgRepay) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgRepay.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 *MsgRepay) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgRepay.Merge(m, src) -} -func (m *MsgRepay) XXX_Size() int { - return m.Size() -} -func (m *MsgRepay) XXX_DiscardUnknown() { - xxx_messageInfo_MsgRepay.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgRepay proto.InternalMessageInfo - -func (m *MsgRepay) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgRepay) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *MsgRepay) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -// MsgRepayResponse defines the Msg/Repay response type. -type MsgRepayResponse struct { -} - -func (m *MsgRepayResponse) Reset() { *m = MsgRepayResponse{} } -func (m *MsgRepayResponse) String() string { return proto.CompactTextString(m) } -func (*MsgRepayResponse) ProtoMessage() {} -func (*MsgRepayResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{7} -} -func (m *MsgRepayResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgRepayResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgRepayResponse.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 *MsgRepayResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgRepayResponse.Merge(m, src) -} -func (m *MsgRepayResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgRepayResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgRepayResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgRepayResponse proto.InternalMessageInfo - -// MsgLiquidate defines the Msg/Liquidate request type. -type MsgLiquidate struct { - Keeper string `protobuf:"bytes,1,opt,name=keeper,proto3" json:"keeper,omitempty"` - Borrower string `protobuf:"bytes,2,opt,name=borrower,proto3" json:"borrower,omitempty"` -} - -func (m *MsgLiquidate) Reset() { *m = MsgLiquidate{} } -func (m *MsgLiquidate) String() string { return proto.CompactTextString(m) } -func (*MsgLiquidate) ProtoMessage() {} -func (*MsgLiquidate) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{8} -} -func (m *MsgLiquidate) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgLiquidate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgLiquidate.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 *MsgLiquidate) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgLiquidate.Merge(m, src) -} -func (m *MsgLiquidate) XXX_Size() int { - return m.Size() -} -func (m *MsgLiquidate) XXX_DiscardUnknown() { - xxx_messageInfo_MsgLiquidate.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgLiquidate proto.InternalMessageInfo - -func (m *MsgLiquidate) GetKeeper() string { - if m != nil { - return m.Keeper - } - return "" -} - -func (m *MsgLiquidate) GetBorrower() string { - if m != nil { - return m.Borrower - } - return "" -} - -// MsgLiquidateResponse defines the Msg/Liquidate response type. -type MsgLiquidateResponse struct { -} - -func (m *MsgLiquidateResponse) Reset() { *m = MsgLiquidateResponse{} } -func (m *MsgLiquidateResponse) String() string { return proto.CompactTextString(m) } -func (*MsgLiquidateResponse) ProtoMessage() {} -func (*MsgLiquidateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{9} -} -func (m *MsgLiquidateResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgLiquidateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgLiquidateResponse.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 *MsgLiquidateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgLiquidateResponse.Merge(m, src) -} -func (m *MsgLiquidateResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgLiquidateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgLiquidateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgLiquidateResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgDeposit)(nil), "kava.hard.v1beta1.MsgDeposit") - proto.RegisterType((*MsgDepositResponse)(nil), "kava.hard.v1beta1.MsgDepositResponse") - proto.RegisterType((*MsgWithdraw)(nil), "kava.hard.v1beta1.MsgWithdraw") - proto.RegisterType((*MsgWithdrawResponse)(nil), "kava.hard.v1beta1.MsgWithdrawResponse") - proto.RegisterType((*MsgBorrow)(nil), "kava.hard.v1beta1.MsgBorrow") - proto.RegisterType((*MsgBorrowResponse)(nil), "kava.hard.v1beta1.MsgBorrowResponse") - proto.RegisterType((*MsgRepay)(nil), "kava.hard.v1beta1.MsgRepay") - proto.RegisterType((*MsgRepayResponse)(nil), "kava.hard.v1beta1.MsgRepayResponse") - proto.RegisterType((*MsgLiquidate)(nil), "kava.hard.v1beta1.MsgLiquidate") - proto.RegisterType((*MsgLiquidateResponse)(nil), "kava.hard.v1beta1.MsgLiquidateResponse") -} - -func init() { proto.RegisterFile("kava/hard/v1beta1/tx.proto", fileDescriptor_72cf8eb667c23b8a) } - -var fileDescriptor_72cf8eb667c23b8a = []byte{ - // 533 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x55, 0x4f, 0x8f, 0xd2, 0x4e, - 0x18, 0xa6, 0x90, 0xe5, 0x07, 0xef, 0xfe, 0x0e, 0xee, 0x2c, 0x1a, 0xb6, 0x6a, 0xd9, 0xa0, 0xae, - 0x5c, 0x68, 0x77, 0x57, 0xe3, 0x59, 0xd1, 0x8b, 0xc9, 0x36, 0x26, 0x18, 0x63, 0xe2, 0xc5, 0x4c, - 0xe9, 0x64, 0x68, 0x90, 0x4e, 0xed, 0x3b, 0xc0, 0xee, 0xb7, 0xf0, 0xec, 0x07, 0x30, 0x71, 0xcf, - 0x7e, 0x88, 0x3d, 0xae, 0x9e, 0x3c, 0xa9, 0x81, 0x2f, 0x62, 0xda, 0x69, 0x07, 0x8c, 0x04, 0xb8, - 0x68, 0x3c, 0x31, 0xed, 0xf3, 0x87, 0xe7, 0xc9, 0xbc, 0x33, 0x05, 0x73, 0x40, 0xc7, 0xd4, 0xe9, - 0xd3, 0xd8, 0x77, 0xc6, 0x47, 0x1e, 0x93, 0xf4, 0xc8, 0x91, 0xa7, 0x76, 0x14, 0x0b, 0x29, 0xc8, - 0x4e, 0x82, 0xd9, 0x09, 0x66, 0x67, 0x98, 0x69, 0xf5, 0x04, 0x0e, 0x05, 0x3a, 0x1e, 0x45, 0xa6, - 0x05, 0x3d, 0x11, 0x84, 0x4a, 0x62, 0xee, 0x29, 0xfc, 0x75, 0xfa, 0xe4, 0xa8, 0x87, 0x0c, 0xaa, - 0x71, 0xc1, 0x85, 0x7a, 0x9f, 0xac, 0xd4, 0xdb, 0xe6, 0x47, 0x03, 0xc0, 0x45, 0xfe, 0x84, 0x45, - 0x02, 0x03, 0x49, 0x1e, 0x40, 0xd5, 0x57, 0x4b, 0x11, 0xd7, 0x8d, 0x7d, 0xa3, 0x55, 0xed, 0xd4, - 0xbf, 0x7c, 0x6a, 0xd7, 0x32, 0xa7, 0x47, 0xbe, 0x1f, 0x33, 0xc4, 0xe7, 0x32, 0x0e, 0x42, 0xde, - 0x9d, 0x53, 0x49, 0x0f, 0xca, 0x74, 0x28, 0x46, 0xa1, 0xac, 0x17, 0xf7, 0x4b, 0xad, 0xed, 0xe3, - 0x3d, 0x3b, 0x53, 0x24, 0x41, 0xf3, 0xf4, 0xf6, 0x63, 0x11, 0x84, 0x9d, 0xc3, 0x8b, 0x6f, 0x8d, - 0xc2, 0xf9, 0xf7, 0x46, 0x8b, 0x07, 0xb2, 0x3f, 0xf2, 0xec, 0x9e, 0x18, 0x66, 0x41, 0xb3, 0x9f, - 0x36, 0xfa, 0x03, 0x47, 0x9e, 0x45, 0x0c, 0x53, 0x01, 0x76, 0x33, 0xeb, 0x66, 0x0d, 0xc8, 0x3c, - 0x6a, 0x97, 0x61, 0x24, 0x42, 0x64, 0xcd, 0x73, 0x03, 0xb6, 0x5d, 0xe4, 0x2f, 0x03, 0xd9, 0xf7, - 0x63, 0x3a, 0xf9, 0xb7, 0x2b, 0x5c, 0x85, 0xdd, 0x85, 0xac, 0xba, 0xc3, 0x07, 0x03, 0xaa, 0x2e, - 0xf2, 0x8e, 0x88, 0x63, 0x31, 0x21, 0xf7, 0xa1, 0xe2, 0xa5, 0x2b, 0xb6, 0xbe, 0x80, 0x66, 0xfe, - 0x9d, 0xfc, 0xbb, 0xb0, 0xa3, 0x73, 0xea, 0xf4, 0x9f, 0x0d, 0xa8, 0xb8, 0xc8, 0xbb, 0x2c, 0xa2, - 0x67, 0xe4, 0x10, 0xca, 0xc8, 0x42, 0x7f, 0x83, 0xe8, 0x19, 0x8f, 0xd8, 0xb0, 0x25, 0x26, 0x21, - 0x8b, 0xeb, 0xc5, 0x35, 0x02, 0x45, 0x5b, 0x28, 0x5a, 0xfa, 0x73, 0x45, 0x09, 0x5c, 0xc9, 0x2b, - 0xe9, 0x9e, 0x63, 0xf8, 0xdf, 0x45, 0x7e, 0x12, 0xbc, 0x1d, 0x05, 0x3e, 0x95, 0x2c, 0xa9, 0x3a, - 0x60, 0x2c, 0xda, 0xa4, 0xaa, 0xe2, 0xfd, 0xb2, 0xb3, 0xc5, 0x4d, 0x77, 0xb6, 0x79, 0x0d, 0x6a, - 0x8b, 0xff, 0x9b, 0xe7, 0x39, 0x7e, 0x5f, 0x82, 0x92, 0x8b, 0x9c, 0x3c, 0x83, 0xff, 0xf2, 0xf3, - 0x7b, 0xd3, 0xfe, 0xed, 0xce, 0xb0, 0xe7, 0x67, 0xc6, 0xbc, 0xb3, 0x12, 0xce, 0x8d, 0x49, 0x17, - 0x2a, 0xfa, 0x38, 0x59, 0xcb, 0x25, 0x39, 0x6e, 0x1e, 0xac, 0xc6, 0xb5, 0xe7, 0x09, 0x94, 0xb3, - 0xf1, 0xbe, 0xb1, 0x5c, 0xa1, 0x50, 0xf3, 0xf6, 0x2a, 0x54, 0xbb, 0x3d, 0x85, 0x2d, 0x35, 0x6e, - 0xd7, 0x97, 0xd3, 0x53, 0xd0, 0xbc, 0xb5, 0x02, 0xd4, 0x56, 0x2f, 0xa0, 0x3a, 0xdf, 0xd2, 0xc6, - 0x72, 0x85, 0x26, 0x98, 0x77, 0xd7, 0x10, 0x72, 0xdb, 0xce, 0xc3, 0x8b, 0xa9, 0x65, 0x5c, 0x4e, - 0x2d, 0xe3, 0xc7, 0xd4, 0x32, 0xde, 0xcd, 0xac, 0xc2, 0xe5, 0xcc, 0x2a, 0x7c, 0x9d, 0x59, 0x85, - 0x57, 0x07, 0x0b, 0xc3, 0x98, 0x98, 0xb5, 0xdf, 0x50, 0x0f, 0xd3, 0x95, 0x73, 0xaa, 0xbe, 0x04, - 0xe9, 0x40, 0x7a, 0xe5, 0xf4, 0x86, 0xbe, 0xf7, 0x33, 0x00, 0x00, 0xff, 0xff, 0x91, 0x63, 0x35, - 0x65, 0x23, 0x06, 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 { - // Deposit defines a method for depositing funds to hard liquidity pool. - Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) - // Withdraw defines a method for withdrawing funds from hard liquidity pool. - Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) - // Borrow defines a method for borrowing funds from hard liquidity pool. - Borrow(ctx context.Context, in *MsgBorrow, opts ...grpc.CallOption) (*MsgBorrowResponse, error) - // Repay defines a method for repaying funds borrowed from hard liquidity pool. - Repay(ctx context.Context, in *MsgRepay, opts ...grpc.CallOption) (*MsgRepayResponse, error) - // Liquidate defines a method for attempting to liquidate a borrower that is over their loan-to-value. - Liquidate(ctx context.Context, in *MsgLiquidate, opts ...grpc.CallOption) (*MsgLiquidateResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) { - out := new(MsgDepositResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Msg/Deposit", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) { - out := new(MsgWithdrawResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Msg/Withdraw", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Borrow(ctx context.Context, in *MsgBorrow, opts ...grpc.CallOption) (*MsgBorrowResponse, error) { - out := new(MsgBorrowResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Msg/Borrow", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Repay(ctx context.Context, in *MsgRepay, opts ...grpc.CallOption) (*MsgRepayResponse, error) { - out := new(MsgRepayResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Msg/Repay", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Liquidate(ctx context.Context, in *MsgLiquidate, opts ...grpc.CallOption) (*MsgLiquidateResponse, error) { - out := new(MsgLiquidateResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Msg/Liquidate", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // Deposit defines a method for depositing funds to hard liquidity pool. - Deposit(context.Context, *MsgDeposit) (*MsgDepositResponse, error) - // Withdraw defines a method for withdrawing funds from hard liquidity pool. - Withdraw(context.Context, *MsgWithdraw) (*MsgWithdrawResponse, error) - // Borrow defines a method for borrowing funds from hard liquidity pool. - Borrow(context.Context, *MsgBorrow) (*MsgBorrowResponse, error) - // Repay defines a method for repaying funds borrowed from hard liquidity pool. - Repay(context.Context, *MsgRepay) (*MsgRepayResponse, error) - // Liquidate defines a method for attempting to liquidate a borrower that is over their loan-to-value. - Liquidate(context.Context, *MsgLiquidate) (*MsgLiquidateResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Deposit(ctx context.Context, req *MsgDeposit) (*MsgDepositResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposit not implemented") -} -func (*UnimplementedMsgServer) Withdraw(ctx context.Context, req *MsgWithdraw) (*MsgWithdrawResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Withdraw not implemented") -} -func (*UnimplementedMsgServer) Borrow(ctx context.Context, req *MsgBorrow) (*MsgBorrowResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Borrow not implemented") -} -func (*UnimplementedMsgServer) Repay(ctx context.Context, req *MsgRepay) (*MsgRepayResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Repay not implemented") -} -func (*UnimplementedMsgServer) Liquidate(ctx context.Context, req *MsgLiquidate) (*MsgLiquidateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Liquidate not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Deposit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgDeposit) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Deposit(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Msg/Deposit", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Deposit(ctx, req.(*MsgDeposit)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Withdraw_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdraw) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Withdraw(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Msg/Withdraw", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Withdraw(ctx, req.(*MsgWithdraw)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Borrow_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgBorrow) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Borrow(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Msg/Borrow", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Borrow(ctx, req.(*MsgBorrow)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Repay_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgRepay) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Repay(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Msg/Repay", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Repay(ctx, req.(*MsgRepay)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Liquidate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgLiquidate) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Liquidate(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Msg/Liquidate", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Liquidate(ctx, req.(*MsgLiquidate)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.hard.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Deposit", - Handler: _Msg_Deposit_Handler, - }, - { - MethodName: "Withdraw", - Handler: _Msg_Withdraw_Handler, - }, - { - MethodName: "Borrow", - Handler: _Msg_Borrow_Handler, - }, - { - MethodName: "Repay", - Handler: _Msg_Repay_Handler, - }, - { - MethodName: "Liquidate", - Handler: _Msg_Liquidate_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/hard/v1beta1/tx.proto", -} - -func (m *MsgDeposit) 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 *MsgDeposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDeposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgDepositResponse) 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 *MsgDepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgWithdraw) 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 *MsgWithdraw) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdraw) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawResponse) 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 *MsgWithdrawResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgBorrow) 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 *MsgBorrow) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgBorrow) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Borrower) > 0 { - i -= len(m.Borrower) - copy(dAtA[i:], m.Borrower) - i = encodeVarintTx(dAtA, i, uint64(len(m.Borrower))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgBorrowResponse) 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 *MsgBorrowResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgBorrowResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgRepay) 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 *MsgRepay) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgRepay) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintTx(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgRepayResponse) 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 *MsgRepayResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgRepayResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgLiquidate) 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 *MsgLiquidate) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgLiquidate) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Borrower) > 0 { - i -= len(m.Borrower) - copy(dAtA[i:], m.Borrower) - i = encodeVarintTx(dAtA, i, uint64(len(m.Borrower))) - i-- - dAtA[i] = 0x12 - } - if len(m.Keeper) > 0 { - i -= len(m.Keeper) - copy(dAtA[i:], m.Keeper) - i = encodeVarintTx(dAtA, i, uint64(len(m.Keeper))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgLiquidateResponse) 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 *MsgLiquidateResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgLiquidateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgDeposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgDepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgWithdraw) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgWithdrawResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgBorrow) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Borrower) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgBorrowResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgRepay) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgRepayResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgLiquidate) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Keeper) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Borrower) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgLiquidateResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgDeposit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDeposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDeposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDepositResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdraw) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdraw: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdraw: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgBorrow) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgBorrow: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgBorrow: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Borrower", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Borrower = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgBorrowResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgBorrowResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgBorrowResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgRepay) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgRepay: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgRepay: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgRepayResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgRepayResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgRepayResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgLiquidate) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgLiquidate: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgLiquidate: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Keeper", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Keeper = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Borrower", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Borrower = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgLiquidateResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgLiquidateResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgLiquidateResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/incentive/abci.go b/x/incentive/abci.go deleted file mode 100644 index 02d8b67c..00000000 --- a/x/incentive/abci.go +++ /dev/null @@ -1,43 +0,0 @@ -package incentive - -import ( - "fmt" - "time" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/types" -) - -// BeginBlocker runs at the start of every block -func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - - params := k.GetParams(ctx) - - for _, rp := range params.USDXMintingRewardPeriods { - k.AccumulateUSDXMintingRewards(ctx, rp) - } - for _, rp := range params.HardSupplyRewardPeriods { - k.AccumulateHardSupplyRewards(ctx, rp) - } - for _, rp := range params.HardBorrowRewardPeriods { - k.AccumulateHardBorrowRewards(ctx, rp) - } - for _, rp := range params.DelegatorRewardPeriods { - k.AccumulateDelegatorRewards(ctx, rp) - } - for _, rp := range params.SwapRewardPeriods { - k.AccumulateSwapRewards(ctx, rp) - } - for _, rp := range params.SavingsRewardPeriods { - k.AccumulateSavingsRewards(ctx, rp) - } - for _, rp := range params.EarnRewardPeriods { - if err := k.AccumulateEarnRewards(ctx, rp); err != nil { - panic(fmt.Sprintf("failed to accumulate earn rewards: %s", err)) - } - } -} diff --git a/x/incentive/client/cli/query.go b/x/incentive/client/cli/query.go deleted file mode 100644 index 7da9c075..00000000 --- a/x/incentive/client/cli/query.go +++ /dev/null @@ -1,185 +0,0 @@ -package cli - -import ( - "context" - "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/cosmos/cosmos-sdk/version" - - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/types" -) - -const ( - flagOwner = "owner" - flagType = "type" - flagUnsynced = "unsynced" - flagDenom = "denom" -) - -var rewardTypes = []string{ - keeper.RewardTypeHard, - keeper.RewardTypeUSDXMinting, - keeper.RewardTypeDelegator, - keeper.RewardTypeSwap, - keeper.RewardTypeSavings, - keeper.RewardTypeEarn, -} - -// GetQueryCmd returns the cli query commands for the incentive module -func GetQueryCmd() *cobra.Command { - incentiveQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the incentive module", - } - - cmds := []*cobra.Command{ - queryParamsCmd(), - queryRewardsCmd(), - queryRewardFactorsCmd(), - queryApyCmd(), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - incentiveQueryCmd.AddCommand(cmds...) - - return incentiveQueryCmd -} - -func queryRewardsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "rewards", - Short: "query claimable rewards", - Long: strings.TrimSpace( - fmt.Sprintf(`Query rewards with optional flags for owner and type - - Example: - $ %[1]s query %[2]s rewards - $ %[1]s query %[2]s rewards --owner kava15qdefkmwswysgg4qxgqpqr35k3m49pkx2jdfnw - $ %[1]s query %[2]s rewards --type hard - $ %[1]s query %[2]s rewards --type usdx-minting - $ %[1]s query %[2]s rewards --type delegator - $ %[1]s query %[2]s rewards --type swap - $ %[1]s query %[2]s rewards --type savings - $ %[1]s query %[2]s rewards --type earn - $ %[1]s query %[2]s rewards --type hard --owner kava15qdefkmwswysgg4qxgqpqr35k3m49pkx2jdfnw - $ %[1]s query %[2]s rewards --type hard --unsynced - `, - version.AppName, types.ModuleName)), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - strOwner, _ := cmd.Flags().GetString(flagOwner) - strType, _ := cmd.Flags().GetString(flagType) - boolUnsynced, _ := cmd.Flags().GetBool(flagUnsynced) - - // Prepare params for querier - var owner sdk.AccAddress - if strOwner != "" { - if owner, err = sdk.AccAddressFromBech32(strOwner); err != nil { - return err - } - } - - rewardType := strings.ToLower(strType) - queryClient := types.NewQueryClient(cliCtx) - request := types.QueryRewardsRequest{ - RewardType: rewardType, - Owner: owner.String(), - Unsynchronized: boolUnsynced, - } - rewards, err := queryClient.Rewards(context.Background(), &request) - if err != nil { - return err - } - return cliCtx.PrintProto(rewards) - }, - } - cmd.Flags().String(flagOwner, "", "(optional) filter by owner address") - cmd.Flags().String(flagType, "", fmt.Sprintf("(optional) filter by a reward type: %s", strings.Join(rewardTypes, "|"))) - cmd.Flags().Bool(flagUnsynced, false, "(optional) get unsynced claims") - cmd.Flags().Int(flags.FlagPage, 1, "pagination page rewards of to query for") - cmd.Flags().Int(flags.FlagLimit, 100, "pagination limit of rewards to query for") - return cmd -} - -func queryParamsCmd() *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: "get the incentive module parameters", - Long: "Get the current global incentive module parameters.", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(cliCtx) - res, err := queryClient.Params(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - return cliCtx.PrintProto(res) - }, - } -} - -func queryRewardFactorsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "reward-factors", - Short: "get current global reward factors", - Long: `Get current global reward factors for all reward types.`, - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(cliCtx) - res, err := queryClient.RewardFactors(context.Background(), &types.QueryRewardFactorsRequest{}) - if err != nil { - return err - } - return cliCtx.PrintProto(res) - }, - } - cmd.Flags().String(flagDenom, "", "(optional) filter reward factors by denom") - return cmd -} - -func queryApyCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "apy", - Short: "queries incentive reward apy for a reward", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(cliCtx) - res, err := queryClient.Apy(context.Background(), &types.QueryApyRequest{}) - if err != nil { - return err - } - return cliCtx.PrintProto(res) - }, - } - return cmd -} diff --git a/x/incentive/client/cli/tx.go b/x/incentive/client/cli/tx.go deleted file mode 100644 index 73067fcf..00000000 --- a/x/incentive/client/cli/tx.go +++ /dev/null @@ -1,244 +0,0 @@ -package cli - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/kava-labs/kava/x/incentive/types" -) - -const ( - multiplierFlag = "multiplier" - multiplierFlagShort = "m" -) - -// GetTxCmd returns the transaction cli commands for the incentive module -func GetTxCmd() *cobra.Command { - incentiveTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "transaction commands for the incentive module", - } - - cmds := []*cobra.Command{ - getCmdClaimCdp(), - getCmdClaimHard(), - getCmdClaimDelegator(), - getCmdClaimSwap(), - getCmdClaimSavings(), - getCmdClaimEarn(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - incentiveTxCmd.AddCommand(cmds...) - - return incentiveTxCmd -} - -func getCmdClaimCdp() *cobra.Command { - cmd := &cobra.Command{ - Use: "claim-cdp [multiplier]", - Short: "claim USDX minting rewards using a given multiplier", - Long: `Claim sender's outstanding USDX minting rewards using a given multiplier.`, - Example: fmt.Sprintf(` $ %s tx %s claim-cdp large`, version.AppName, types.ModuleName), - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - sender := cliCtx.GetFromAddress() - multiplier := args[0] - - msg := types.NewMsgClaimUSDXMintingReward(sender.String(), multiplier) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), &msg) - }, - } - - return cmd -} - -func getCmdClaimHard() *cobra.Command { - var denomsToClaim map[string]string - - cmd := &cobra.Command{ - Use: "claim-hard", - Short: "claim sender's Hard module rewards using given multipliers", - Long: `Claim sender's outstanding Hard rewards for deposit/borrow using given multipliers`, - Example: strings.Join([]string{ - fmt.Sprintf(` $ %s tx %s claim-hard --%s hard=large --%s ukava=small`, version.AppName, types.ModuleName, multiplierFlag, multiplierFlag), - fmt.Sprintf(` $ %s tx %s claim-hard --%s hard=large,ukava=small`, version.AppName, types.ModuleName, multiplierFlag), - }, "\n"), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - sender := cliCtx.GetFromAddress() - selections := types.NewSelectionsFromMap(denomsToClaim) - - msg := types.NewMsgClaimHardReward(sender.String(), selections) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), &msg) - }, - } - cmd.Flags().StringToStringVarP(&denomsToClaim, multiplierFlag, multiplierFlagShort, nil, "specify the denoms to claim, each with a multiplier lockup") - if err := cmd.MarkFlagRequired(multiplierFlag); err != nil { - panic(err) - } - return cmd -} - -func getCmdClaimDelegator() *cobra.Command { - var denomsToClaim map[string]string - - cmd := &cobra.Command{ - Use: "claim-delegator", - Short: "claim sender's non-sdk delegator rewards using given multipliers", - Long: `Claim sender's outstanding delegator rewards using given multipliers`, - Example: strings.Join([]string{ - fmt.Sprintf(` $ %s tx %s claim-delegator --%s hard=large --%s swp=small`, version.AppName, types.ModuleName, multiplierFlag, multiplierFlag), - fmt.Sprintf(` $ %s tx %s claim-delegator --%s hard=large,swp=small`, version.AppName, types.ModuleName, multiplierFlag), - }, "\n"), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - sender := cliCtx.GetFromAddress() - selections := types.NewSelectionsFromMap(denomsToClaim) - - msg := types.NewMsgClaimDelegatorReward(sender.String(), selections) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), &msg) - }, - } - cmd.Flags().StringToStringVarP(&denomsToClaim, multiplierFlag, multiplierFlagShort, nil, "specify the denoms to claim, each with a multiplier lockup") - if err := cmd.MarkFlagRequired(multiplierFlag); err != nil { - panic(err) - } - return cmd -} - -func getCmdClaimSwap() *cobra.Command { - var denomsToClaim map[string]string - - cmd := &cobra.Command{ - Use: "claim-swap", - Short: "claim sender's swap rewards using given multipliers", - Long: `Claim sender's outstanding swap rewards using given multipliers`, - Example: strings.Join([]string{ - fmt.Sprintf(` $ %s tx %s claim-swap --%s swp=large --%s ukava=small`, version.AppName, types.ModuleName, multiplierFlag, multiplierFlag), - fmt.Sprintf(` $ %s tx %s claim-swap --%s swp=large,ukava=small`, version.AppName, types.ModuleName, multiplierFlag), - }, "\n"), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - sender := cliCtx.GetFromAddress() - selections := types.NewSelectionsFromMap(denomsToClaim) - - msg := types.NewMsgClaimSwapReward(sender.String(), selections) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), &msg) - }, - } - cmd.Flags().StringToStringVarP(&denomsToClaim, multiplierFlag, multiplierFlagShort, nil, "specify the denoms to claim, each with a multiplier lockup") - if err := cmd.MarkFlagRequired(multiplierFlag); err != nil { - panic(err) - } - return cmd -} - -func getCmdClaimSavings() *cobra.Command { - var denomsToClaim map[string]string - - cmd := &cobra.Command{ - Use: "claim-savings", - Short: "claim sender's savings rewards using given multipliers", - Long: `Claim sender's outstanding savings rewards using given multipliers`, - Example: strings.Join([]string{ - fmt.Sprintf(` $ %s tx %s claim-savings --%s swp=large --%s ukava=small`, version.AppName, types.ModuleName, multiplierFlag, multiplierFlag), - fmt.Sprintf(` $ %s tx %s claim-savings --%s swp=large,ukava=small`, version.AppName, types.ModuleName, multiplierFlag), - }, "\n"), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - sender := cliCtx.GetFromAddress() - selections := types.NewSelectionsFromMap(denomsToClaim) - - msg := types.NewMsgClaimSavingsReward(sender.String(), selections) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), &msg) - }, - } - cmd.Flags().StringToStringVarP(&denomsToClaim, multiplierFlag, multiplierFlagShort, nil, "specify the denoms to claim, each with a multiplier lockup") - if err := cmd.MarkFlagRequired(multiplierFlag); err != nil { - panic(err) - } - return cmd -} - -func getCmdClaimEarn() *cobra.Command { - var denomsToClaim map[string]string - - cmd := &cobra.Command{ - Use: "claim-earn", - Short: "claim sender's earn rewards using given multipliers", - Long: `Claim sender's outstanding earn rewards using given multipliers`, - Example: fmt.Sprintf(` $ %s tx %s claim-earn --%s ukava=large`, version.AppName, types.ModuleName, multiplierFlag), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - sender := cliCtx.GetFromAddress() - selections := types.NewSelectionsFromMap(denomsToClaim) - - msg := types.NewMsgClaimEarnReward(sender.String(), selections) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), &msg) - }, - } - cmd.Flags().StringToStringVarP(&denomsToClaim, multiplierFlag, multiplierFlagShort, nil, "specify the denoms to claim, each with a multiplier lockup") - if err := cmd.MarkFlagRequired(multiplierFlag); err != nil { - panic(err) - } - return cmd -} diff --git a/x/incentive/genesis.go b/x/incentive/genesis.go deleted file mode 100644 index 246ffa67..00000000 --- a/x/incentive/genesis.go +++ /dev/null @@ -1,294 +0,0 @@ -package incentive - -import ( - "fmt" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/types" -) - -// InitGenesis initializes the store state from a genesis state. -func InitGenesis( - ctx sdk.Context, - k keeper.Keeper, - accountKeeper types.AccountKeeper, - bankKeeper types.BankKeeper, - cdpKeeper types.CdpKeeper, - gs types.GenesisState, -) { - // check if the module account exists - moduleAcc := accountKeeper.GetModuleAccount(ctx, types.IncentiveMacc) - if moduleAcc == nil { - panic(fmt.Sprintf("%s module account has not been set", types.IncentiveMacc)) - } - - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - for _, rp := range gs.Params.USDXMintingRewardPeriods { - if _, found := cdpKeeper.GetCollateral(ctx, rp.CollateralType); !found { - panic(fmt.Sprintf("incentive params contain collateral not found in cdp params: %s", rp.CollateralType)) - } - } - // TODO more param validation? - - k.SetParams(ctx, gs.Params) - - // USDX Minting - for _, claim := range gs.USDXMintingClaims { - k.SetUSDXMintingClaim(ctx, claim) - } - for _, gat := range gs.USDXRewardState.AccumulationTimes { - if err := ValidateAccumulationTime(gat.PreviousAccumulationTime); err != nil { - panic(err.Error()) - } - k.SetPreviousUSDXMintingAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - } - for _, mri := range gs.USDXRewardState.MultiRewardIndexes { - factor, found := mri.RewardIndexes.Get(types.USDXMintingRewardDenom) - if !found || len(mri.RewardIndexes) != 1 { - panic(fmt.Sprintf("USDX Minting reward factors must only have denom %s", types.USDXMintingRewardDenom)) - } - k.SetUSDXMintingRewardFactor(ctx, mri.CollateralType, factor) - } - - // Hard Supply / Borrow - for _, claim := range gs.HardLiquidityProviderClaims { - k.SetHardLiquidityProviderClaim(ctx, claim) - } - for _, gat := range gs.HardSupplyRewardState.AccumulationTimes { - if err := ValidateAccumulationTime(gat.PreviousAccumulationTime); err != nil { - panic(err.Error()) - } - k.SetPreviousHardSupplyRewardAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - } - for _, mri := range gs.HardSupplyRewardState.MultiRewardIndexes { - k.SetHardSupplyRewardIndexes(ctx, mri.CollateralType, mri.RewardIndexes) - } - for _, gat := range gs.HardBorrowRewardState.AccumulationTimes { - if err := ValidateAccumulationTime(gat.PreviousAccumulationTime); err != nil { - panic(err.Error()) - } - k.SetPreviousHardBorrowRewardAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - } - for _, mri := range gs.HardBorrowRewardState.MultiRewardIndexes { - k.SetHardBorrowRewardIndexes(ctx, mri.CollateralType, mri.RewardIndexes) - } - - // Delegator - for _, claim := range gs.DelegatorClaims { - k.SetDelegatorClaim(ctx, claim) - } - for _, gat := range gs.DelegatorRewardState.AccumulationTimes { - if err := ValidateAccumulationTime(gat.PreviousAccumulationTime); err != nil { - panic(err.Error()) - } - k.SetPreviousDelegatorRewardAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - } - for _, mri := range gs.DelegatorRewardState.MultiRewardIndexes { - k.SetDelegatorRewardIndexes(ctx, mri.CollateralType, mri.RewardIndexes) - } - - // Swap - for _, claim := range gs.SwapClaims { - k.SetSwapClaim(ctx, claim) - } - for _, gat := range gs.SwapRewardState.AccumulationTimes { - if err := ValidateAccumulationTime(gat.PreviousAccumulationTime); err != nil { - panic(err.Error()) - } - k.SetSwapRewardAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - } - for _, mri := range gs.SwapRewardState.MultiRewardIndexes { - k.SetSwapRewardIndexes(ctx, mri.CollateralType, mri.RewardIndexes) - } - - // Savings - for _, claim := range gs.SavingsClaims { - k.SetSavingsClaim(ctx, claim) - } - for _, gat := range gs.SavingsRewardState.AccumulationTimes { - if err := ValidateAccumulationTime(gat.PreviousAccumulationTime); err != nil { - panic(err.Error()) - } - k.SetSavingsRewardAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - } - for _, mri := range gs.SavingsRewardState.MultiRewardIndexes { - k.SetSavingsRewardIndexes(ctx, mri.CollateralType, mri.RewardIndexes) - } - - // Earn - for _, claim := range gs.EarnClaims { - k.SetEarnClaim(ctx, claim) - } - for _, gat := range gs.EarnRewardState.AccumulationTimes { - if err := ValidateAccumulationTime(gat.PreviousAccumulationTime); err != nil { - panic(err.Error()) - } - k.SetEarnRewardAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - } - for _, mri := range gs.EarnRewardState.MultiRewardIndexes { - k.SetEarnRewardIndexes(ctx, mri.CollateralType, mri.RewardIndexes) - } -} - -// ExportGenesis export genesis state for incentive module -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { - params := k.GetParams(ctx) - - usdxClaims := k.GetAllUSDXMintingClaims(ctx) - usdxRewardState := getUSDXMintingGenesisRewardState(ctx, k) - - hardClaims := k.GetAllHardLiquidityProviderClaims(ctx) - hardSupplyRewardState := getHardSupplyGenesisRewardState(ctx, k) - hardBorrowRewardState := getHardBorrowGenesisRewardState(ctx, k) - - delegatorClaims := k.GetAllDelegatorClaims(ctx) - delegatorRewardState := getDelegatorGenesisRewardState(ctx, k) - - swapClaims := k.GetAllSwapClaims(ctx) - swapRewardState := getSwapGenesisRewardState(ctx, k) - - savingsClaims := k.GetAllSavingsClaims(ctx) - savingsRewardState := getSavingsGenesisRewardState(ctx, k) - - earnClaims := k.GetAllEarnClaims(ctx) - earnRewardState := getEarnGenesisRewardState(ctx, k) - - return types.NewGenesisState( - params, - // Reward states - usdxRewardState, hardSupplyRewardState, hardBorrowRewardState, delegatorRewardState, swapRewardState, savingsRewardState, earnRewardState, - // Claims - usdxClaims, hardClaims, delegatorClaims, swapClaims, savingsClaims, earnClaims, - ) -} - -func getUSDXMintingGenesisRewardState(ctx sdk.Context, keeper keeper.Keeper) types.GenesisRewardState { - var ats types.AccumulationTimes - keeper.IterateUSDXMintingAccrualTimes(ctx, func(ctype string, accTime time.Time) bool { - ats = append(ats, types.NewAccumulationTime(ctype, accTime)) - return false - }) - - var mris types.MultiRewardIndexes - keeper.IterateUSDXMintingRewardFactors(ctx, func(ctype string, factor sdk.Dec) bool { - mris = append( - mris, - types.NewMultiRewardIndex( - ctype, - types.RewardIndexes{types.NewRewardIndex(types.USDXMintingRewardDenom, factor)}, - ), - ) - return false - }) - - return types.NewGenesisRewardState(ats, mris) -} - -func getHardSupplyGenesisRewardState(ctx sdk.Context, keeper keeper.Keeper) types.GenesisRewardState { - var ats types.AccumulationTimes - keeper.IterateHardSupplyRewardAccrualTimes(ctx, func(ctype string, accTime time.Time) bool { - ats = append(ats, types.NewAccumulationTime(ctype, accTime)) - return false - }) - - var mris types.MultiRewardIndexes - keeper.IterateHardSupplyRewardIndexes(ctx, func(ctype string, indexes types.RewardIndexes) bool { - mris = append(mris, types.NewMultiRewardIndex(ctype, indexes)) - return false - }) - - return types.NewGenesisRewardState(ats, mris) -} - -func getHardBorrowGenesisRewardState(ctx sdk.Context, keeper keeper.Keeper) types.GenesisRewardState { - var ats types.AccumulationTimes - keeper.IterateHardBorrowRewardAccrualTimes(ctx, func(ctype string, accTime time.Time) bool { - ats = append(ats, types.NewAccumulationTime(ctype, accTime)) - return false - }) - - var mris types.MultiRewardIndexes - keeper.IterateHardBorrowRewardIndexes(ctx, func(ctype string, indexes types.RewardIndexes) bool { - mris = append(mris, types.NewMultiRewardIndex(ctype, indexes)) - return false - }) - - return types.NewGenesisRewardState(ats, mris) -} - -func getDelegatorGenesisRewardState(ctx sdk.Context, keeper keeper.Keeper) types.GenesisRewardState { - var ats types.AccumulationTimes - keeper.IterateDelegatorRewardAccrualTimes(ctx, func(ctype string, accTime time.Time) bool { - ats = append(ats, types.NewAccumulationTime(ctype, accTime)) - return false - }) - - var mris types.MultiRewardIndexes - keeper.IterateDelegatorRewardIndexes(ctx, func(ctype string, indexes types.RewardIndexes) bool { - mris = append(mris, types.NewMultiRewardIndex(ctype, indexes)) - return false - }) - - return types.NewGenesisRewardState(ats, mris) -} - -func getSwapGenesisRewardState(ctx sdk.Context, keeper keeper.Keeper) types.GenesisRewardState { - var ats types.AccumulationTimes - keeper.IterateSwapRewardAccrualTimes(ctx, func(ctype string, accTime time.Time) bool { - ats = append(ats, types.NewAccumulationTime(ctype, accTime)) - return false - }) - - var mris types.MultiRewardIndexes - keeper.IterateSwapRewardIndexes(ctx, func(ctype string, indexes types.RewardIndexes) bool { - mris = append(mris, types.NewMultiRewardIndex(ctype, indexes)) - return false - }) - - return types.NewGenesisRewardState(ats, mris) -} - -func getSavingsGenesisRewardState(ctx sdk.Context, keeper keeper.Keeper) types.GenesisRewardState { - var ats types.AccumulationTimes - keeper.IterateSavingsRewardAccrualTimes(ctx, func(ctype string, accTime time.Time) bool { - ats = append(ats, types.NewAccumulationTime(ctype, accTime)) - return false - }) - - var mris types.MultiRewardIndexes - keeper.IterateSavingsRewardIndexes(ctx, func(ctype string, indexes types.RewardIndexes) bool { - mris = append(mris, types.NewMultiRewardIndex(ctype, indexes)) - return false - }) - - return types.NewGenesisRewardState(ats, mris) -} - -func getEarnGenesisRewardState(ctx sdk.Context, keeper keeper.Keeper) types.GenesisRewardState { - var ats types.AccumulationTimes - keeper.IterateEarnRewardAccrualTimes(ctx, func(ctype string, accTime time.Time) bool { - ats = append(ats, types.NewAccumulationTime(ctype, accTime)) - return false - }) - - var mris types.MultiRewardIndexes - keeper.IterateEarnRewardIndexes(ctx, func(ctype string, indexes types.RewardIndexes) bool { - mris = append(mris, types.NewMultiRewardIndex(ctype, indexes)) - return false - }) - - return types.NewGenesisRewardState(ats, mris) -} - -func ValidateAccumulationTime(previousAccumulationTime time.Time) error { - if previousAccumulationTime.Equal(time.Time{}) { - return fmt.Errorf("accumulation time is not set") - } - return nil -} diff --git a/x/incentive/genesis_test.go b/x/incentive/genesis_test.go deleted file mode 100644 index 78b75cc7..00000000 --- a/x/incentive/genesis_test.go +++ /dev/null @@ -1,401 +0,0 @@ -package incentive_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - - "github.com/kava-labs/kava/app" - hardtypes "github.com/kava-labs/kava/x/hard/types" - "github.com/kava-labs/kava/x/incentive" - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/types" - kavadisttypes "github.com/kava-labs/kava/x/kavadist/types" -) - -const ( - oneYear time.Duration = 365 * 24 * time.Hour -) - -type GenesisTestSuite struct { - suite.Suite - - ctx sdk.Context - app app.TestApp - keeper keeper.Keeper - addrs []sdk.AccAddress - - genesisTime time.Time -} - -func (suite *GenesisTestSuite) SetupTest() { - tApp := app.NewTestApp() - suite.app = tApp - keeper := tApp.GetIncentiveKeeper() - suite.genesisTime = time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - - _, addrs := app.GeneratePrivKeyAddressPairs(5) - - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(addrs[0], cs(c("bnb", 1e10), c("ukava", 1e10))). - WithSimpleModuleAccount(kavadisttypes.KavaDistMacc, cs(c("hard", 1e15), c("ukava", 1e15))) - - loanToValue, _ := sdk.NewDecFromStr("0.6") - borrowLimit := sdk.NewDec(1000000000000000) - hardGS := hardtypes.NewGenesisState( - hardtypes.NewParams( - hardtypes.MoneyMarkets{ - hardtypes.NewMoneyMarket("ukava", hardtypes.NewBorrowLimit(false, borrowLimit, loanToValue), "kava:usd", sdkmath.NewInt(1000000), hardtypes.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - hardtypes.NewMoneyMarket("bnb", hardtypes.NewBorrowLimit(false, borrowLimit, loanToValue), "bnb:usd", sdkmath.NewInt(1000000), hardtypes.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - }, - sdk.NewDec(10), - ), - hardtypes.DefaultAccumulationTimes, - hardtypes.DefaultDeposits, - hardtypes.DefaultBorrows, - hardtypes.DefaultTotalSupplied, - hardtypes.DefaultTotalBorrowed, - hardtypes.DefaultTotalReserves, - ) - incentiveGS := types.NewGenesisState( - types.NewParams( - types.RewardPeriods{types.NewRewardPeriod(true, "bnb-a", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), c("ukava", 122354))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "bnb", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "bnb", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "btcb/usdx", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("swp", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultipliersPerDenoms{ - { - Denom: "ukava", - Multipliers: types.Multipliers{ - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - { - Denom: "hard", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.25")), - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - { - Denom: "swp", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.25")), - types.NewMultiplier("medium", 6, d("0.8")), - }, - }, - }, - suite.genesisTime.Add(5*oneYear), - ), - types.DefaultGenesisRewardState, - types.DefaultGenesisRewardState, - types.DefaultGenesisRewardState, - types.DefaultGenesisRewardState, - types.DefaultGenesisRewardState, - types.DefaultGenesisRewardState, - types.DefaultGenesisRewardState, - types.DefaultUSDXClaims, - types.DefaultHardClaims, - types.DefaultDelegatorClaims, - types.DefaultSwapClaims, - types.DefaultSavingsClaims, - types.DefaultEarnClaims, - ) - - cdc := suite.app.AppCodec() - - tApp.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - authBuilder.BuildMarshalled(cdc), - app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&incentiveGS)}, - app.GenesisState{hardtypes.ModuleName: cdc.MustMarshalJSON(&hardGS)}, - NewCDPGenStateMulti(cdc), - NewPricefeedGenStateMultiFromTime(cdc, suite.genesisTime), - ) - - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: suite.genesisTime}) - - suite.addrs = addrs - suite.keeper = keeper - suite.ctx = ctx -} - -func (suite *GenesisTestSuite) TestExportedGenesisMatchesImported() { - genesisTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - genesisState := types.NewGenesisState( - types.NewParams( - types.RewardPeriods{types.NewRewardPeriod(true, "bnb-a", genesisTime.Add(-1*oneYear), genesisTime.Add(oneYear), c("ukava", 122354))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "bnb", genesisTime.Add(-1*oneYear), genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "bnb", genesisTime.Add(-1*oneYear), genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", genesisTime.Add(-1*oneYear), genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "btcb/usdx", genesisTime.Add(-1*oneYear), genesisTime.Add(oneYear), cs(c("swp", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", genesisTime.Add(-1*oneYear), genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", genesisTime.Add(-1*oneYear), genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultipliersPerDenoms{ - { - Denom: "ukava", - Multipliers: types.Multipliers{ - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - { - Denom: "hard", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.25")), - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - { - Denom: "swp", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.25")), - types.NewMultiplier("medium", 6, d("0.8")), - }, - }, - }, - genesisTime.Add(5*oneYear), - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("bnb-a", genesisTime), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("bnb-a", types.RewardIndexes{{CollateralType: "ukava", RewardFactor: d("0.3")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("bnb", genesisTime.Add(-1*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("bnb", types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.1")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("bnb", genesisTime.Add(-2*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("bnb", types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.05")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("ukava", genesisTime.Add(-3*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("ukava", types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.2")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("bctb/usdx", genesisTime.Add(-4*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("btcb/usdx", types.RewardIndexes{{CollateralType: "swap", RewardFactor: d("0.001")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("ukava", genesisTime.Add(-3*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("ukava", types.RewardIndexes{{CollateralType: "ukava", RewardFactor: d("0.2")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("usdx", genesisTime.Add(-3*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("usdx", types.RewardIndexes{{CollateralType: "usdx", RewardFactor: d("0.2")}}), - }, - ), - types.USDXMintingClaims{ - types.NewUSDXMintingClaim( - suite.addrs[0], - c("ukava", 1e9), - types.RewardIndexes{{CollateralType: "bnb-a", RewardFactor: d("0.3")}}, - ), - types.NewUSDXMintingClaim( - suite.addrs[1], - c("ukava", 1), - types.RewardIndexes{{CollateralType: "bnb-a", RewardFactor: d("0.001")}}, - ), - }, - types.HardLiquidityProviderClaims{ - types.NewHardLiquidityProviderClaim( - suite.addrs[0], - cs(c("ukava", 1e9), c("hard", 1e9)), - types.MultiRewardIndexes{{CollateralType: "bnb", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.01")}}}}, - types.MultiRewardIndexes{{CollateralType: "bnb", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.0")}}}}, - ), - types.NewHardLiquidityProviderClaim( - suite.addrs[1], - cs(c("hard", 1)), - types.MultiRewardIndexes{{CollateralType: "bnb", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.1")}}}}, - types.MultiRewardIndexes{{CollateralType: "bnb", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.0")}}}}, - ), - }, - types.DelegatorClaims{ - types.NewDelegatorClaim( - suite.addrs[2], - cs(c("hard", 5)), - types.MultiRewardIndexes{{CollateralType: "ukava", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.2")}}}}, - ), - }, - types.SwapClaims{ - types.NewSwapClaim( - suite.addrs[3], - nil, - types.MultiRewardIndexes{{CollateralType: "btcb/usdx", RewardIndexes: types.RewardIndexes{{CollateralType: "swap", RewardFactor: d("0.0")}}}}, - ), - }, - types.SavingsClaims{ - types.NewSavingsClaim( - suite.addrs[3], - nil, - types.MultiRewardIndexes{{CollateralType: "ukava", RewardIndexes: types.RewardIndexes{{CollateralType: "ukava", RewardFactor: d("0.0")}}}}, - ), - }, - types.EarnClaims{ - types.NewEarnClaim( - suite.addrs[3], - nil, - types.MultiRewardIndexes{{CollateralType: "usdx", RewardIndexes: types.RewardIndexes{{CollateralType: "earn", RewardFactor: d("0.0")}}}}, - ), - }, - ) - - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 0, Time: genesisTime}) - - // Incentive init genesis reads from the cdp keeper to check params are ok. So it needs to be initialized first. - // Then the cdp keeper reads from pricefeed keeper to check its params are ok. So it also need initialization. - tApp = tApp.InitializeFromGenesisStates( - NewCDPGenStateMulti(tApp.AppCodec()), - NewPricefeedGenStateMultiFromTime(tApp.AppCodec(), genesisTime), - ) - - // Clear genesis validator and genesis delegator incentive state to start empty. - ik := tApp.GetIncentiveKeeper() - suite.app.DeleteGenesisValidator(suite.T(), suite.ctx) - ik.DeleteDelegatorClaim(ctx, tApp.GenesisAddrs[0]) - - incentive.InitGenesis( - ctx, - tApp.GetIncentiveKeeper(), - tApp.GetAccountKeeper(), - tApp.GetBankKeeper(), - tApp.GetCDPKeeper(), - genesisState, - ) - - exportedGenesisState := incentive.ExportGenesis(ctx, tApp.GetIncentiveKeeper()) - - suite.Equal(genesisState, exportedGenesisState) -} - -func (suite *GenesisTestSuite) TestInitGenesisPanicsWhenAccumulationTimesTooLongAgo() { - genesisTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - invalidRewardState := types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime( - "bnb", - time.Time{}, - ), - }, - types.MultiRewardIndexes{}, - ) - minimalParams := types.Params{ - ClaimEnd: genesisTime.Add(5 * oneYear), - } - - testCases := []struct { - genesisState types.GenesisState - }{ - { - types.GenesisState{ - Params: minimalParams, - USDXRewardState: invalidRewardState, - }, - }, - { - types.GenesisState{ - Params: minimalParams, - HardSupplyRewardState: invalidRewardState, - }, - }, - { - types.GenesisState{ - Params: minimalParams, - HardBorrowRewardState: invalidRewardState, - }, - }, - { - types.GenesisState{ - Params: minimalParams, - DelegatorRewardState: invalidRewardState, - }, - }, - { - types.GenesisState{ - Params: minimalParams, - SwapRewardState: invalidRewardState, - }, - }, - { - types.GenesisState{ - Params: minimalParams, - SavingsRewardState: invalidRewardState, - }, - }, - } - - for _, tc := range testCases { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 0, Time: genesisTime}) - - // Incentive init genesis reads from the cdp keeper to check params are ok. So it needs to be initialized first. - // Then the cdp keeper reads from pricefeed keeper to check its params are ok. So it also need initialization. - tApp.InitializeFromGenesisStates( - NewCDPGenStateMulti(tApp.AppCodec()), - NewPricefeedGenStateMultiFromTime(tApp.AppCodec(), genesisTime), - ) - - suite.PanicsWithValue( - "accumulation time is not set", - func() { - incentive.InitGenesis( - ctx, tApp.GetIncentiveKeeper(), - tApp.GetAccountKeeper(), - tApp.GetBankKeeper(), - tApp.GetCDPKeeper(), - tc.genesisState, - ) - }, - ) - } -} - -func (suite *GenesisTestSuite) TestValidateAccumulationTime() { - // valid when set - accTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.NoError(incentive.ValidateAccumulationTime(accTime)) - - // invalid when nil value - suite.Error(incentive.ValidateAccumulationTime(time.Time{})) -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(GenesisTestSuite)) -} diff --git a/x/incentive/integration_test.go b/x/incentive/integration_test.go deleted file mode 100644 index f1d5039d..00000000 --- a/x/incentive/integration_test.go +++ /dev/null @@ -1,185 +0,0 @@ -package incentive_test - -import ( - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/kava-labs/kava/app" - cdptypes "github.com/kava-labs/kava/x/cdp/types" - "github.com/kava-labs/kava/x/incentive/testutil" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" -) - -// Avoid cluttering test cases with long function names -func i(in int64) sdkmath.Int { return sdkmath.NewInt(in) } -func d(str string) sdk.Dec { return sdk.MustNewDecFromStr(str) } -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } - -func NewCDPGenStateMulti(cdc codec.JSONCodec) app.GenesisState { - cdpGenesis := cdptypes.GenesisState{ - Params: cdptypes.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - SurplusAuctionThreshold: cdptypes.DefaultSurplusThreshold, - SurplusAuctionLot: cdptypes.DefaultSurplusLot, - DebtAuctionThreshold: cdptypes.DefaultDebtThreshold, - DebtAuctionLot: cdptypes.DefaultDebtLot, - LiquidationBlockInterval: cdptypes.DefaultBeginBlockerExecutionBlockInterval, - CollateralParams: cdptypes.CollateralParams{ - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("2.0"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(7000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd", - ConversionFactor: i(6), - }, - { - Denom: "btc", - Type: "btc-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000000782997609"), // %2.5 apr - LiquidationPenalty: d("0.025"), - AuctionSize: i(10000000), - SpotMarketID: "btc:usd", - LiquidationMarketID: "btc:usd", - ConversionFactor: i(8), - }, - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - ConversionFactor: i(8), - }, - { - Denom: "busd", - Type: "busd-a", - LiquidationRatio: d("1.01"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.OneDec(), // %0 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(10000000000), - SpotMarketID: "busd:usd", - LiquidationMarketID: "busd:usd", - ConversionFactor: i(8), - }, - }, - DebtParam: cdptypes.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: i(6), - DebtFloor: i(10000000), - }, - }, - StartingCdpID: cdptypes.DefaultCdpStartingID, - DebtDenom: cdptypes.DefaultDebtDenom, - GovDenom: cdptypes.DefaultGovDenom, - CDPs: cdptypes.CDPs{}, - PreviousAccumulationTimes: cdptypes.GenesisAccumulationTimes{ - cdptypes.NewGenesisAccumulationTime("btc-a", time.Time{}, sdk.OneDec()), - cdptypes.NewGenesisAccumulationTime("xrp-a", time.Time{}, sdk.OneDec()), - cdptypes.NewGenesisAccumulationTime("busd-a", time.Time{}, sdk.OneDec()), - cdptypes.NewGenesisAccumulationTime("bnb-a", time.Time{}, sdk.OneDec()), - }, - TotalPrincipals: cdptypes.GenesisTotalPrincipals{ - cdptypes.NewGenesisTotalPrincipal("btc-a", sdk.ZeroInt()), - cdptypes.NewGenesisTotalPrincipal("xrp-a", sdk.ZeroInt()), - cdptypes.NewGenesisTotalPrincipal("busd-a", sdk.ZeroInt()), - cdptypes.NewGenesisTotalPrincipal("bnb-a", sdk.ZeroInt()), - }, - } - return app.GenesisState{cdptypes.ModuleName: cdc.MustMarshalJSON(&cdpGenesis)} -} - -func NewPricefeedGenStateMultiFromTime(cdc codec.JSONCodec, t time.Time) app.GenesisState { - pfGenesis := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "btc:usd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "xrp:usd", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "busd:usd", BaseAsset: "busd", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "zzz:usd", BaseAsset: "zzz", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: t.Add(1 * time.Hour), - }, - { - MarketID: "btc:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("8000.00"), - Expiry: t.Add(1 * time.Hour), - }, - { - MarketID: "xrp:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("0.25"), - Expiry: t.Add(1 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("17.25"), - Expiry: t.Add(1 * time.Hour), - }, - { - MarketID: "busd:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.OneDec(), - Expiry: t.Add(1 * time.Hour), - }, - { - MarketID: "zzz:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: t.Add(1 * time.Hour), - }, - }, - } - return app.GenesisState{pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pfGenesis)} -} - -func NewHardGenStateMulti(genTime time.Time) testutil.HardGenesisBuilder { - kavaMM := testutil.NewStandardMoneyMarket("ukava") - kavaMM.SpotMarketID = "kava:usd" - btcMM := testutil.NewStandardMoneyMarket("btcb") - btcMM.SpotMarketID = "btc:usd" - - builder := testutil.NewHardGenesisBuilder().WithGenesisTime(genTime). - WithInitializedMoneyMarket(testutil.NewStandardMoneyMarket("usdx")). - WithInitializedMoneyMarket(kavaMM). - WithInitializedMoneyMarket(testutil.NewStandardMoneyMarket("bnb")). - WithInitializedMoneyMarket(btcMM). - WithInitializedMoneyMarket(testutil.NewStandardMoneyMarket("xrp")). - WithInitializedMoneyMarket(testutil.NewStandardMoneyMarket("zzz")) - return builder -} - -func NewStakingGenesisState(cdc codec.JSONCodec) app.GenesisState { - genState := stakingtypes.DefaultGenesisState() - genState.Params.BondDenom = "ukava" - return app.GenesisState{ - stakingtypes.ModuleName: cdc.MustMarshalJSON(genState), - } -} diff --git a/x/incentive/keeper/claim.go b/x/incentive/keeper/claim.go deleted file mode 100644 index c58ae6e8..00000000 --- a/x/incentive/keeper/claim.go +++ /dev/null @@ -1,306 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/incentive/types" -) - -// ClaimUSDXMintingReward pays out funds from a claim to a receiver account. -// Rewards are removed from a claim and paid out according to the multiplier, which reduces the reward amount in exchange for shorter vesting times. -func (k Keeper) ClaimUSDXMintingReward(ctx sdk.Context, owner, receiver sdk.AccAddress, multiplierName string) error { - claim, found := k.GetUSDXMintingClaim(ctx, owner) - if !found { - return errorsmod.Wrapf(types.ErrClaimNotFound, "address: %s", owner) - } - - multiplier, found := k.GetMultiplierByDenom(ctx, types.USDXMintingRewardDenom, multiplierName) - if !found { - return errorsmod.Wrapf(types.ErrInvalidMultiplier, "denom '%s' has no multiplier '%s'", types.USDXMintingRewardDenom, multiplierName) - } - - claimEnd := k.GetClaimEnd(ctx) - - if ctx.BlockTime().After(claimEnd) { - return errorsmod.Wrapf(types.ErrClaimExpired, "block time %s > claim end time %s", ctx.BlockTime(), claimEnd) - } - - claim, err := k.SynchronizeUSDXMintingClaim(ctx, claim) - if err != nil { - return err - } - - rewardAmount := sdk.NewDecFromInt(claim.Reward.Amount).Mul(multiplier.Factor).RoundInt() - if rewardAmount.IsZero() { - return types.ErrZeroClaim - } - rewardCoin := sdk.NewCoin(claim.Reward.Denom, rewardAmount) - length := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup) - - err = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, sdk.NewCoins(rewardCoin), length) - if err != nil { - return err - } - - k.ZeroUSDXMintingClaim(ctx, claim) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeClaim, - sdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()), - sdk.NewAttribute(types.AttributeKeyClaimAmount, claim.Reward.String()), - sdk.NewAttribute(types.AttributeKeyClaimType, claim.GetType()), - ), - ) - return nil -} - -// ClaimHardReward pays out funds from a claim to a receiver account. -// Rewards are removed from a claim and paid out according to the multiplier, which reduces the reward amount in exchange for shorter vesting times. -func (k Keeper) ClaimHardReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error { - multiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName) - if !found { - return errorsmod.Wrapf(types.ErrInvalidMultiplier, "denom '%s' has no multiplier '%s'", denom, multiplierName) - } - - claimEnd := k.GetClaimEnd(ctx) - - if ctx.BlockTime().After(claimEnd) { - return errorsmod.Wrapf(types.ErrClaimExpired, "block time %s > claim end time %s", ctx.BlockTime(), claimEnd) - } - - k.SynchronizeHardLiquidityProviderClaim(ctx, owner) - - syncedClaim, found := k.GetHardLiquidityProviderClaim(ctx, owner) - if !found { - return errorsmod.Wrapf(types.ErrClaimNotFound, "address: %s", owner) - } - - amt := syncedClaim.Reward.AmountOf(denom) - - claimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt)) - rewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt())) - if rewardCoins.IsZero() { - return types.ErrZeroClaim - } - length := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup) - - err := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length) - if err != nil { - return err - } - - // remove claimed coins (NOT reward coins) - syncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...) - k.SetHardLiquidityProviderClaim(ctx, syncedClaim) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeClaim, - sdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()), - sdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()), - sdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()), - ), - ) - return nil -} - -// ClaimDelegatorReward pays out funds from a claim to a receiver account. -// Rewards are removed from a claim and paid out according to the multiplier, which reduces the reward amount in exchange for shorter vesting times. -func (k Keeper) ClaimDelegatorReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error { - claim, found := k.GetDelegatorClaim(ctx, owner) - if !found { - return errorsmod.Wrapf(types.ErrClaimNotFound, "address: %s", owner) - } - - multiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName) - if !found { - return errorsmod.Wrapf(types.ErrInvalidMultiplier, "denom '%s' has no multiplier '%s'", denom, multiplierName) - } - - claimEnd := k.GetClaimEnd(ctx) - - if ctx.BlockTime().After(claimEnd) { - return errorsmod.Wrapf(types.ErrClaimExpired, "block time %s > claim end time %s", ctx.BlockTime(), claimEnd) - } - - syncedClaim, err := k.SynchronizeDelegatorClaim(ctx, claim) - if err != nil { - return errorsmod.Wrapf(types.ErrClaimNotFound, "address: %s", owner) - } - - amt := syncedClaim.Reward.AmountOf(denom) - - claimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt)) - rewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt())) - if rewardCoins.IsZero() { - return types.ErrZeroClaim - } - - length := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup) - - err = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length) - if err != nil { - return err - } - - // remove claimed coins (NOT reward coins) - syncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...) - k.SetDelegatorClaim(ctx, syncedClaim) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeClaim, - sdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()), - sdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()), - sdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()), - ), - ) - return nil -} - -// ClaimSwapReward pays out funds from a claim to a receiver account. -// Rewards are removed from a claim and paid out according to the multiplier, which reduces the reward amount in exchange for shorter vesting times. -func (k Keeper) ClaimSwapReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error { - multiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName) - if !found { - return errorsmod.Wrapf(types.ErrInvalidMultiplier, "denom '%s' has no multiplier '%s'", denom, multiplierName) - } - - claimEnd := k.GetClaimEnd(ctx) - - if ctx.BlockTime().After(claimEnd) { - return errorsmod.Wrapf(types.ErrClaimExpired, "block time %s > claim end time %s", ctx.BlockTime(), claimEnd) - } - - syncedClaim, found := k.GetSynchronizedSwapClaim(ctx, owner) - if !found { - return errorsmod.Wrapf(types.ErrClaimNotFound, "address: %s", owner) - } - - amt := syncedClaim.Reward.AmountOf(denom) - - claimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt)) - rewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt())) - if rewardCoins.IsZero() { - return types.ErrZeroClaim - } - length := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup) - - err := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length) - if err != nil { - return err - } - - // remove claimed coins (NOT reward coins) - syncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...) - k.SetSwapClaim(ctx, syncedClaim) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeClaim, - sdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()), - sdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()), - sdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()), - ), - ) - return nil -} - -// ClaimSavingsReward is a stub method for MsgServer interface compliance -func (k Keeper) ClaimSavingsReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error { - multiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName) - if !found { - return errorsmod.Wrapf(types.ErrInvalidMultiplier, "denom '%s' has no multiplier '%s'", denom, multiplierName) - } - - claimEnd := k.GetClaimEnd(ctx) - - if ctx.BlockTime().After(claimEnd) { - return errorsmod.Wrapf(types.ErrClaimExpired, "block time %s > claim end time %s", ctx.BlockTime(), claimEnd) - } - - k.SynchronizeSavingsClaim(ctx, owner) - - syncedClaim, found := k.GetSavingsClaim(ctx, owner) - if !found { - return errorsmod.Wrapf(types.ErrClaimNotFound, "address: %s", owner) - } - - amt := syncedClaim.Reward.AmountOf(denom) - - claimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt)) - rewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt())) - if rewardCoins.IsZero() { - return types.ErrZeroClaim - } - length := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup) - - err := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length) - if err != nil { - return err - } - - // remove claimed coins (NOT reward coins) - syncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...) - k.SetSavingsClaim(ctx, syncedClaim) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeClaim, - sdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()), - sdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()), - sdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()), - ), - ) - return nil -} - -// ClaimEarnReward pays out funds from a claim to a receiver account. -// Rewards are removed from a claim and paid out according to the multiplier, which reduces the reward amount in exchange for shorter vesting times. -func (k Keeper) ClaimEarnReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error { - multiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName) - if !found { - return errorsmod.Wrapf(types.ErrInvalidMultiplier, "denom '%s' has no multiplier '%s'", denom, multiplierName) - } - - claimEnd := k.GetClaimEnd(ctx) - - if ctx.BlockTime().After(claimEnd) { - return errorsmod.Wrapf(types.ErrClaimExpired, "block time %s > claim end time %s", ctx.BlockTime(), claimEnd) - } - - syncedClaim, found := k.GetSynchronizedEarnClaim(ctx, owner) - if !found { - return errorsmod.Wrapf(types.ErrClaimNotFound, "address: %s", owner) - } - - amt := syncedClaim.Reward.AmountOf(denom) - - claimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt)) - rewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt())) - if rewardCoins.IsZero() { - return types.ErrZeroClaim - } - length := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup) - - err := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length) - if err != nil { - return err - } - - // remove claimed coins (NOT reward coins) - syncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...) - k.SetEarnClaim(ctx, syncedClaim) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeClaim, - sdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()), - sdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()), - sdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()), - ), - ) - return nil -} diff --git a/x/incentive/keeper/claim_test.go b/x/incentive/keeper/claim_test.go deleted file mode 100644 index 4ca39a96..00000000 --- a/x/incentive/keeper/claim_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package keeper_test - -import ( - "errors" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/incentive/types" -) - -// ClaimTests runs unit tests for the keeper Claim methods -type ClaimTests struct { - unitTester -} - -func TestClaim(t *testing.T) { - suite.Run(t, new(ClaimTests)) -} - -func (suite *ClaimTests) ErrorIs(err, target error) bool { - return suite.Truef(errors.Is(err, target), "err didn't match: %s, it was: %s", target, err) -} - -func (suite *ClaimTests) TestCannotClaimWhenMultiplierNotRecognised() { - subspace := &fakeParamSubspace{ - params: types.Params{ - ClaimMultipliers: types.MultipliersPerDenoms{ - { - Denom: "hard", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.2")), - }, - }, - }, - }, - } - suite.keeper = suite.NewKeeper(subspace, nil, nil, nil, nil, nil, nil, nil, nil, nil) - - claim := types.DelegatorClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - } - suite.storeDelegatorClaim(claim) - - // multiplier not in params - err := suite.keeper.ClaimDelegatorReward(suite.ctx, claim.Owner, claim.Owner, "hard", "large") - suite.ErrorIs(err, types.ErrInvalidMultiplier) - - // invalid multiplier name - err = suite.keeper.ClaimDelegatorReward(suite.ctx, claim.Owner, claim.Owner, "hard", "") - suite.ErrorIs(err, types.ErrInvalidMultiplier) -} - -func (suite *ClaimTests) TestCannotClaimAfterEndTime() { - endTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - - subspace := &fakeParamSubspace{ - params: types.Params{ - ClaimMultipliers: types.MultipliersPerDenoms{ - { - Denom: "hard", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.2")), - }, - }, - }, - ClaimEnd: endTime, - }, - } - suite.keeper = suite.NewKeeper(subspace, nil, nil, nil, nil, nil, nil, nil, nil, nil) - - suite.ctx = suite.ctx.WithBlockTime(endTime.Add(time.Nanosecond)) - - claim := types.DelegatorClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - } - suite.storeDelegatorClaim(claim) - - err := suite.keeper.ClaimDelegatorReward(suite.ctx, claim.Owner, claim.Owner, "hard", "small") - suite.ErrorIs(err, types.ErrClaimExpired) -} diff --git a/x/incentive/keeper/diff_test.go b/x/incentive/keeper/diff_test.go deleted file mode 100644 index a032a06c..00000000 --- a/x/incentive/keeper/diff_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestSetDiff(t *testing.T) { - tests := []struct { - name string - setA []string - setB []string - expected []string - }{ - {"empty", []string{}, []string{}, []string(nil)}, - {"diff equal sets", []string{"busd", "usdx"}, []string{"busd", "usdx"}, []string(nil)}, - {"diff set empty", []string{"bnb", "ukava", "usdx"}, []string{}, []string{"bnb", "ukava", "usdx"}}, - {"input set empty", []string{}, []string{"bnb", "ukava", "usdx"}, []string(nil)}, - {"diff set with common elements", []string{"bnb", "btcb", "usdx", "xrpb"}, []string{"bnb", "usdx"}, []string{"btcb", "xrpb"}}, - {"diff set with all common elements", []string{"bnb", "usdx"}, []string{"bnb", "btcb", "usdx", "xrpb"}, []string(nil)}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - require.Equal(t, tt.expected, setDifference(tt.setA, tt.setB)) - }) - } -} diff --git a/x/incentive/keeper/grpc_query.go b/x/incentive/keeper/grpc_query.go deleted file mode 100644 index 956eaa40..00000000 --- a/x/incentive/keeper/grpc_query.go +++ /dev/null @@ -1,342 +0,0 @@ -package keeper - -import ( - "context" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/kava-labs/kava/x/incentive/types" - liquidtypes "github.com/kava-labs/kava/x/liquid/types" -) - -const ( - RewardTypeHard = "hard" - RewardTypeUSDXMinting = "usdx_minting" - RewardTypeDelegator = "delegator" - RewardTypeSwap = "swap" - RewardTypeSavings = "savings" - RewardTypeEarn = "earn" -) - -type queryServer struct { - keeper Keeper -} - -var _ types.QueryServer = queryServer{} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(keeper Keeper) types.QueryServer { - return &queryServer{ - keeper: keeper, - } -} - -func (s queryServer) Params( - ctx context.Context, - req *types.QueryParamsRequest, -) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - return &types.QueryParamsResponse{ - Params: s.keeper.GetParams(sdkCtx), - }, nil -} - -func (s queryServer) Rewards( - ctx context.Context, - req *types.QueryRewardsRequest, -) (*types.QueryRewardsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - res := types.QueryRewardsResponse{} - - hasOwner := req.Owner != "" - - var owner sdk.AccAddress - if hasOwner { - addr, err := sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid address: %s", err) - } - - owner = addr - } - - if err := s.queryRewards(sdkCtx, &res, owner, hasOwner, req.RewardType); err != nil { - return nil, err - } - - if !req.Unsynchronized { - if err := s.synchronizeRewards(sdkCtx, &res); err != nil { - return nil, err - } - } - - return &res, nil -} - -func (s queryServer) RewardFactors( - ctx context.Context, - req *types.QueryRewardFactorsRequest, -) (*types.QueryRewardFactorsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - var usdxFactors types.RewardIndexes - s.keeper.IterateUSDXMintingRewardFactors(sdkCtx, func(collateralType string, factor sdk.Dec) (stop bool) { - usdxFactors = usdxFactors.With(collateralType, factor) - return false - }) - - var supplyFactors types.MultiRewardIndexes - s.keeper.IterateHardSupplyRewardIndexes(sdkCtx, func(denom string, indexes types.RewardIndexes) (stop bool) { - supplyFactors = supplyFactors.With(denom, indexes) - return false - }) - - var borrowFactors types.MultiRewardIndexes - s.keeper.IterateHardBorrowRewardIndexes(sdkCtx, func(denom string, indexes types.RewardIndexes) (stop bool) { - borrowFactors = borrowFactors.With(denom, indexes) - return false - }) - - var delegatorFactors types.MultiRewardIndexes - s.keeper.IterateDelegatorRewardIndexes(sdkCtx, func(denom string, indexes types.RewardIndexes) (stop bool) { - delegatorFactors = delegatorFactors.With(denom, indexes) - return false - }) - - var swapFactors types.MultiRewardIndexes - s.keeper.IterateSwapRewardIndexes(sdkCtx, func(poolID string, indexes types.RewardIndexes) (stop bool) { - swapFactors = swapFactors.With(poolID, indexes) - return false - }) - - var savingsFactors types.MultiRewardIndexes - s.keeper.IterateSavingsRewardIndexes(sdkCtx, func(denom string, indexes types.RewardIndexes) (stop bool) { - savingsFactors = savingsFactors.With(denom, indexes) - return false - }) - - var earnFactors types.MultiRewardIndexes - s.keeper.IterateEarnRewardIndexes(sdkCtx, func(denom string, indexes types.RewardIndexes) (stop bool) { - earnFactors = earnFactors.With(denom, indexes) - return false - }) - - return &types.QueryRewardFactorsResponse{ - UsdxMintingRewardFactors: usdxFactors, - HardSupplyRewardFactors: supplyFactors, - HardBorrowRewardFactors: borrowFactors, - DelegatorRewardFactors: delegatorFactors, - SwapRewardFactors: swapFactors, - SavingsRewardFactors: savingsFactors, - EarnRewardFactors: earnFactors, - }, nil -} - -func (s queryServer) Apy( - ctx context.Context, - req *types.QueryApyRequest, -) (*types.QueryApyResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - params := s.keeper.GetParams(sdkCtx) - var apys types.APYs - - // bkava APY (staking + incentive rewards) - stakingAPR, err := GetStakingAPR(sdkCtx, s.keeper, params) - if err != nil { - return nil, err - } - - apys = append(apys, types.NewAPY(liquidtypes.DefaultDerivativeDenom, stakingAPR)) - - // Incentive only APYs - for _, param := range params.EarnRewardPeriods { - // Skip bkava as it's calculated earlier with staking rewards - if param.CollateralType == liquidtypes.DefaultDerivativeDenom { - continue - } - - // Value in the vault in the same denom as CollateralType - vaultTotalValue, err := s.keeper.earnKeeper.GetVaultTotalValue(sdkCtx, param.CollateralType) - if err != nil { - return nil, err - } - apy, err := GetAPYFromMultiRewardPeriod(sdkCtx, s.keeper, param.CollateralType, param, vaultTotalValue.Amount) - if err != nil { - return nil, err - } - - apys = append(apys, types.NewAPY(param.CollateralType, apy)) - } - - return &types.QueryApyResponse{ - Earn: apys, - }, nil -} - -// queryRewards queries the rewards for a given owner and reward type, updating -// the response with the results in place. -func (s queryServer) queryRewards( - ctx sdk.Context, - res *types.QueryRewardsResponse, - owner sdk.AccAddress, - hasOwner bool, - rewardType string, -) error { - rewardType = strings.ToLower(rewardType) - isAllRewards := rewardType == "" - - if !rewardTypeIsValid(rewardType) { - return status.Errorf(codes.InvalidArgument, "invalid reward type for owner %s: %s", owner, rewardType) - } - - if isAllRewards || rewardType == RewardTypeUSDXMinting { - if hasOwner { - usdxMintingClaim, foundUsdxMintingClaim := s.keeper.GetUSDXMintingClaim(ctx, owner) - if foundUsdxMintingClaim { - res.USDXMintingClaims = append(res.USDXMintingClaims, usdxMintingClaim) - } - } else { - usdxMintingClaims := s.keeper.GetAllUSDXMintingClaims(ctx) - res.USDXMintingClaims = append(res.USDXMintingClaims, usdxMintingClaims...) - } - } - - if isAllRewards || rewardType == RewardTypeHard { - if hasOwner { - hardClaim, foundHardClaim := s.keeper.GetHardLiquidityProviderClaim(ctx, owner) - if foundHardClaim { - res.HardLiquidityProviderClaims = append(res.HardLiquidityProviderClaims, hardClaim) - } - } else { - hardClaims := s.keeper.GetAllHardLiquidityProviderClaims(ctx) - res.HardLiquidityProviderClaims = append(res.HardLiquidityProviderClaims, hardClaims...) - } - } - - if isAllRewards || rewardType == RewardTypeDelegator { - if hasOwner { - delegatorClaim, foundDelegatorClaim := s.keeper.GetDelegatorClaim(ctx, owner) - if foundDelegatorClaim { - res.DelegatorClaims = append(res.DelegatorClaims, delegatorClaim) - } - } else { - delegatorClaims := s.keeper.GetAllDelegatorClaims(ctx) - res.DelegatorClaims = append(res.DelegatorClaims, delegatorClaims...) - } - } - - if isAllRewards || rewardType == RewardTypeSwap { - if hasOwner { - swapClaim, foundSwapClaim := s.keeper.GetSwapClaim(ctx, owner) - if foundSwapClaim { - res.SwapClaims = append(res.SwapClaims, swapClaim) - } - } else { - swapClaims := s.keeper.GetAllSwapClaims(ctx) - res.SwapClaims = append(res.SwapClaims, swapClaims...) - } - } - - if isAllRewards || rewardType == RewardTypeSavings { - if hasOwner { - savingsClaim, foundSavingsClaim := s.keeper.GetSavingsClaim(ctx, owner) - if foundSavingsClaim { - res.SavingsClaims = append(res.SavingsClaims, savingsClaim) - } - } else { - savingsClaims := s.keeper.GetAllSavingsClaims(ctx) - res.SavingsClaims = append(res.SavingsClaims, savingsClaims...) - } - } - - if isAllRewards || rewardType == RewardTypeEarn { - if hasOwner { - earnClaim, foundEarnClaim := s.keeper.GetEarnClaim(ctx, owner) - if foundEarnClaim { - res.EarnClaims = append(res.EarnClaims, earnClaim) - } - } else { - earnClaims := s.keeper.GetAllEarnClaims(ctx) - res.EarnClaims = append(res.EarnClaims, earnClaims...) - } - } - - return nil -} - -// synchronizeRewards synchronizes all non-empty rewards in place. -func (s queryServer) synchronizeRewards( - ctx sdk.Context, - res *types.QueryRewardsResponse, -) error { - // Synchronize all non-empty rewards - for i, claim := range res.USDXMintingClaims { - res.USDXMintingClaims[i] = s.keeper.SimulateUSDXMintingSynchronization(ctx, claim) - } - - for i, claim := range res.HardLiquidityProviderClaims { - res.HardLiquidityProviderClaims[i] = s.keeper.SimulateHardSynchronization(ctx, claim) - } - - for i, claim := range res.DelegatorClaims { - res.DelegatorClaims[i] = s.keeper.SimulateDelegatorSynchronization(ctx, claim) - } - - for i, claim := range res.SwapClaims { - syncedClaim, found := s.keeper.GetSynchronizedSwapClaim(ctx, claim.Owner) - if !found { - return status.Errorf(codes.Internal, "previously found swap claim for owner %s should still be found", claim.Owner) - } - res.SwapClaims[i] = syncedClaim - } - - for i, claim := range res.SavingsClaims { - syncedClaim, found := s.keeper.GetSynchronizedSavingsClaim(ctx, claim.Owner) - if !found { - return status.Errorf(codes.Internal, "previously found savings claim for owner %s should still be found", claim.Owner) - } - res.SavingsClaims[i] = syncedClaim - } - - for i, claim := range res.EarnClaims { - syncedClaim, found := s.keeper.GetSynchronizedEarnClaim(ctx, claim.Owner) - if !found { - return status.Errorf(codes.Internal, "previously found earn claim for owner %s should still be found", claim.Owner) - } - res.EarnClaims[i] = syncedClaim - } - - return nil -} - -func rewardTypeIsValid(rewardType string) bool { - return rewardType == "" || - rewardType == RewardTypeHard || - rewardType == RewardTypeUSDXMinting || - rewardType == RewardTypeDelegator || - rewardType == RewardTypeSwap || - rewardType == RewardTypeSavings || - rewardType == RewardTypeEarn -} diff --git a/x/incentive/keeper/grpc_query_test.go b/x/incentive/keeper/grpc_query_test.go deleted file mode 100644 index a4ac6c5b..00000000 --- a/x/incentive/keeper/grpc_query_test.go +++ /dev/null @@ -1,328 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/app" - hardtypes "github.com/kava-labs/kava/x/hard/types" - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/types" - "github.com/stretchr/testify/suite" -) - -const ( - oneYear time.Duration = 365 * 24 * time.Hour -) - -type grpcQueryTestSuite struct { - suite.Suite - - tApp app.TestApp - ctx sdk.Context - keeper keeper.Keeper - queryClient types.QueryClient - addrs []sdk.AccAddress - - genesisTime time.Time - genesisState types.GenesisState -} - -func (suite *grpcQueryTestSuite) SetupTest() { - suite.tApp = app.NewTestApp() - cdc := suite.tApp.AppCodec() - - _, addrs := app.GeneratePrivKeyAddressPairs(5) - suite.genesisTime = time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - - suite.addrs = addrs - - suite.ctx = suite.tApp.NewContext(true, tmprototypes.Header{}). - WithBlockTime(time.Now().UTC()) - suite.keeper = suite.tApp.GetIncentiveKeeper() - - queryHelper := baseapp.NewQueryServerTestHelper(suite.ctx, suite.tApp.InterfaceRegistry()) - types.RegisterQueryServer(queryHelper, keeper.NewQueryServerImpl(suite.keeper)) - - suite.queryClient = types.NewQueryClient(queryHelper) - - loanToValue, _ := sdk.NewDecFromStr("0.6") - borrowLimit := sdk.NewDec(1000000000000000) - hardGS := hardtypes.NewGenesisState( - hardtypes.NewParams( - hardtypes.MoneyMarkets{ - hardtypes.NewMoneyMarket("ukava", hardtypes.NewBorrowLimit(false, borrowLimit, loanToValue), "kava:usd", sdkmath.NewInt(1000000), hardtypes.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - hardtypes.NewMoneyMarket("bnb", hardtypes.NewBorrowLimit(false, borrowLimit, loanToValue), "bnb:usd", sdkmath.NewInt(1000000), hardtypes.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - }, - sdk.NewDec(10), - ), - hardtypes.DefaultAccumulationTimes, - hardtypes.DefaultDeposits, - hardtypes.DefaultBorrows, - hardtypes.DefaultTotalSupplied, - hardtypes.DefaultTotalBorrowed, - hardtypes.DefaultTotalReserves, - ) - - suite.genesisState = types.NewGenesisState( - types.NewParams( - types.RewardPeriods{types.NewRewardPeriod(true, "bnb-a", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), c("ukava", 122354))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "bnb", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "bnb", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "btcb/usdx", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("swp", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultipliersPerDenoms{ - { - Denom: "ukava", - Multipliers: types.Multipliers{ - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - { - Denom: "hard", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.25")), - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - { - Denom: "swp", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.25")), - types.NewMultiplier("medium", 6, d("0.8")), - }, - }, - }, - suite.genesisTime.Add(5*oneYear), - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("bnb-a", suite.genesisTime), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("bnb-a", types.RewardIndexes{{CollateralType: "ukava", RewardFactor: d("0.3")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("bnb", suite.genesisTime.Add(-1*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("bnb", types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.1")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("bnb", suite.genesisTime.Add(-2*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("bnb", types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.05")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("ukava", suite.genesisTime.Add(-3*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("ukava", types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.2")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("bctb/usdx", suite.genesisTime.Add(-4*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("btcb/usdx", types.RewardIndexes{{CollateralType: "swap", RewardFactor: d("0.001")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("ukava", suite.genesisTime.Add(-3*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("ukava", types.RewardIndexes{{CollateralType: "ukava", RewardFactor: d("0.2")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("usdx", suite.genesisTime.Add(-3*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("usdx", types.RewardIndexes{{CollateralType: "usdx", RewardFactor: d("0.2")}}), - }, - ), - types.USDXMintingClaims{ - types.NewUSDXMintingClaim( - suite.addrs[0], - c("ukava", 1e9), - types.RewardIndexes{{CollateralType: "bnb-a", RewardFactor: d("0.3")}}, - ), - types.NewUSDXMintingClaim( - suite.addrs[1], - c("ukava", 1), - types.RewardIndexes{{CollateralType: "bnb-a", RewardFactor: d("0.001")}}, - ), - }, - types.HardLiquidityProviderClaims{ - types.NewHardLiquidityProviderClaim( - suite.addrs[0], - cs(c("ukava", 1e9), c("hard", 1e9)), - types.MultiRewardIndexes{{CollateralType: "bnb", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.01")}}}}, - types.MultiRewardIndexes{{CollateralType: "bnb", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.0")}}}}, - ), - types.NewHardLiquidityProviderClaim( - suite.addrs[1], - cs(c("hard", 1)), - types.MultiRewardIndexes{{CollateralType: "bnb", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.1")}}}}, - types.MultiRewardIndexes{{CollateralType: "bnb", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.0")}}}}, - ), - }, - types.DelegatorClaims{ - types.NewDelegatorClaim( - suite.addrs[2], - cs(c("hard", 5)), - types.MultiRewardIndexes{{CollateralType: "ukava", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.2")}}}}, - ), - }, - types.SwapClaims{ - types.NewSwapClaim( - suite.addrs[3], - nil, - types.MultiRewardIndexes{{CollateralType: "btcb/usdx", RewardIndexes: types.RewardIndexes{{CollateralType: "swap", RewardFactor: d("0.0")}}}}, - ), - }, - types.SavingsClaims{ - types.NewSavingsClaim( - suite.addrs[3], - nil, - types.MultiRewardIndexes{{CollateralType: "ukava", RewardIndexes: types.RewardIndexes{{CollateralType: "ukava", RewardFactor: d("0.0")}}}}, - ), - }, - types.EarnClaims{ - types.NewEarnClaim( - suite.addrs[3], - nil, - types.MultiRewardIndexes{{CollateralType: "usdx", RewardIndexes: types.RewardIndexes{{CollateralType: "usdx", RewardFactor: d("0.0")}}}}, - ), - }, - ) - - err := suite.genesisState.Validate() - suite.Require().NoError(err) - - suite.tApp = suite.tApp.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&suite.genesisState)}, - app.GenesisState{hardtypes.ModuleName: cdc.MustMarshalJSON(&hardGS)}, - NewCDPGenStateMulti(cdc), - NewPricefeedGenStateMultiFromTime(cdc, suite.genesisTime), - ) - - suite.tApp.DeleteGenesisValidator(suite.T(), suite.ctx) - claims := suite.keeper.GetAllDelegatorClaims(suite.ctx) - for _, claim := range claims { - // Delete the InitGenesis validator's claim - if !claim.Owner.Equals(suite.addrs[2]) { - suite.keeper.DeleteDelegatorClaim(suite.ctx, claim.Owner) - } - } -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryParams() { - res, err := suite.queryClient.Params(sdk.WrapSDKContext(suite.ctx), &types.QueryParamsRequest{}) - suite.Require().NoError(err) - - expected := suite.keeper.GetParams(suite.ctx) - - suite.Equal(expected, res.Params, "params should equal default params") -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryRewards() { - res, err := suite.queryClient.Rewards(sdk.WrapSDKContext(suite.ctx), &types.QueryRewardsRequest{ - Unsynchronized: true, - }) - suite.Require().NoError(err) - - suite.Equal(suite.genesisState.USDXMintingClaims, res.USDXMintingClaims) - suite.Equal(suite.genesisState.HardLiquidityProviderClaims, res.HardLiquidityProviderClaims) - suite.Equal(suite.genesisState.DelegatorClaims, res.DelegatorClaims) - suite.Equal(suite.genesisState.SwapClaims, res.SwapClaims) - suite.Equal(suite.genesisState.SavingsClaims, res.SavingsClaims) - suite.Equal(suite.genesisState.EarnClaims, res.EarnClaims) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryRewards_Owner() { - res, err := suite.queryClient.Rewards(sdk.WrapSDKContext(suite.ctx), &types.QueryRewardsRequest{ - Owner: suite.addrs[0].String(), - }) - suite.Require().NoError(err) - - suite.Len(res.USDXMintingClaims, 1) - suite.Len(res.HardLiquidityProviderClaims, 1) - - suite.Equal(suite.genesisState.USDXMintingClaims[0], res.USDXMintingClaims[0]) - suite.Equal(suite.genesisState.HardLiquidityProviderClaims[0], res.HardLiquidityProviderClaims[0]) - - // No other claims - owner has none - suite.Empty(res.DelegatorClaims) - suite.Empty(res.SwapClaims) - suite.Empty(res.SavingsClaims) - suite.Empty(res.EarnClaims) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryRewards_RewardType() { - res, err := suite.queryClient.Rewards(sdk.WrapSDKContext(suite.ctx), &types.QueryRewardsRequest{ - RewardType: keeper.RewardTypeHard, - Unsynchronized: true, - }) - suite.Require().NoError(err) - - suite.Equal(suite.genesisState.HardLiquidityProviderClaims, res.HardLiquidityProviderClaims) - - // No other reward types when specifying rewardType - suite.Empty(res.USDXMintingClaims) - suite.Empty(res.DelegatorClaims) - suite.Empty(res.SwapClaims) - suite.Empty(res.SavingsClaims) - suite.Empty(res.EarnClaims) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryRewards_RewardType_and_Owner() { - res, err := suite.queryClient.Rewards(sdk.WrapSDKContext(suite.ctx), &types.QueryRewardsRequest{ - Owner: suite.addrs[0].String(), - RewardType: keeper.RewardTypeHard, - }) - suite.Require().NoError(err) - - suite.Len(res.HardLiquidityProviderClaims, 1) - suite.Equal(suite.genesisState.HardLiquidityProviderClaims[0], res.HardLiquidityProviderClaims[0]) - - suite.Empty(res.USDXMintingClaims) - suite.Empty(res.DelegatorClaims) - suite.Empty(res.SwapClaims) - suite.Empty(res.SavingsClaims) - suite.Empty(res.EarnClaims) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryRewardFactors() { - res, err := suite.queryClient.RewardFactors(sdk.WrapSDKContext(suite.ctx), &types.QueryRewardFactorsRequest{}) - suite.Require().NoError(err) - - suite.NotEmpty(res.UsdxMintingRewardFactors) - suite.NotEmpty(res.HardSupplyRewardFactors) - suite.NotEmpty(res.HardBorrowRewardFactors) - suite.NotEmpty(res.DelegatorRewardFactors) - suite.NotEmpty(res.SwapRewardFactors) - suite.NotEmpty(res.SavingsRewardFactors) - suite.NotEmpty(res.EarnRewardFactors) -} - -func TestGrpcQueryTestSuite(t *testing.T) { - suite.Run(t, new(grpcQueryTestSuite)) -} diff --git a/x/incentive/keeper/hooks.go b/x/incentive/keeper/hooks.go deleted file mode 100644 index 2fa7e6dc..00000000 --- a/x/incentive/keeper/hooks.go +++ /dev/null @@ -1,227 +0,0 @@ -package keeper - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - cdptypes "github.com/kava-labs/kava/x/cdp/types" - earntypes "github.com/kava-labs/kava/x/earn/types" - hardtypes "github.com/kava-labs/kava/x/hard/types" - savingstypes "github.com/kava-labs/kava/x/savings/types" - swaptypes "github.com/kava-labs/kava/x/swap/types" -) - -// Hooks wrapper struct for hooks -type Hooks struct { - k Keeper -} - -var ( - _ cdptypes.CDPHooks = Hooks{} - _ hardtypes.HARDHooks = Hooks{} - _ stakingtypes.StakingHooks = Hooks{} - _ swaptypes.SwapHooks = Hooks{} - _ savingstypes.SavingsHooks = Hooks{} - _ earntypes.EarnHooks = Hooks{} -) - -// Hooks create new incentive hooks -func (k Keeper) Hooks() Hooks { return Hooks{k} } - -// ------------------- Cdp Module Hooks ------------------- - -// AfterCDPCreated function that runs after a cdp is created -func (h Hooks) AfterCDPCreated(ctx sdk.Context, cdp cdptypes.CDP) { - h.k.InitializeUSDXMintingClaim(ctx, cdp) -} - -// BeforeCDPModified function that runs before a cdp is modified -// note that this is called immediately after interest is synchronized, and so could potentially -// be called AfterCDPInterestUpdated or something like that, if we we're to expand the scope of cdp hooks -func (h Hooks) BeforeCDPModified(ctx sdk.Context, cdp cdptypes.CDP) { - h.k.SynchronizeUSDXMintingReward(ctx, cdp) -} - -// ------------------- Hard Module Hooks ------------------- - -// AfterDepositCreated function that runs after a deposit is created -func (h Hooks) AfterDepositCreated(ctx sdk.Context, deposit hardtypes.Deposit) { - h.k.InitializeHardSupplyReward(ctx, deposit) -} - -// BeforeDepositModified function that runs before a deposit is modified -func (h Hooks) BeforeDepositModified(ctx sdk.Context, deposit hardtypes.Deposit) { - h.k.SynchronizeHardSupplyReward(ctx, deposit) -} - -// AfterDepositModified function that runs after a deposit is modified -func (h Hooks) AfterDepositModified(ctx sdk.Context, deposit hardtypes.Deposit) { - h.k.UpdateHardSupplyIndexDenoms(ctx, deposit) -} - -// AfterBorrowCreated function that runs after a borrow is created -func (h Hooks) AfterBorrowCreated(ctx sdk.Context, borrow hardtypes.Borrow) { - h.k.InitializeHardBorrowReward(ctx, borrow) -} - -// BeforeBorrowModified function that runs before a borrow is modified -func (h Hooks) BeforeBorrowModified(ctx sdk.Context, borrow hardtypes.Borrow) { - h.k.SynchronizeHardBorrowReward(ctx, borrow) -} - -// AfterBorrowModified function that runs after a borrow is modified -func (h Hooks) AfterBorrowModified(ctx sdk.Context, borrow hardtypes.Borrow) { - h.k.UpdateHardBorrowIndexDenoms(ctx, borrow) -} - -/* ------------------- Staking Module Hooks ------------------- - -Rewards are calculated based on total delegated tokens to bonded validators (not shares). -We need to sync the claim before the user's delegated tokens are changed. - -When delegated tokens (to bonded validators) are changed: -- user creates new delegation - - total bonded delegation increases -- user delegates or beginUnbonding or beginRedelegate an existing delegation - - total bonded delegation increases or decreases -- validator is slashed and Jailed/Tombstoned (tokens reduce, and validator is unbonded) - - slash: total bonded delegation decreases (less tokens) - - jail: total bonded delegation decreases (tokens no longer bonded (after end blocker runs)) -- validator becomes unbonded (ie when they drop out of the top 100) - - total bonded delegation decreases (tokens no longer bonded) -- validator becomes bonded (ie when they're promoted into the top 100) - - total bonded delegation increases (tokens become bonded) - -*/ - -// BeforeDelegationCreated runs before a delegation is created -func (h Hooks) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { - // Add a claim if one doesn't exist, otherwise sync the existing. - h.k.InitializeDelegatorReward(ctx, delAddr) - - return nil -} - -// BeforeDelegationSharesModified runs before an existing delegation is modified -func (h Hooks) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { - // Sync rewards based on total delegated to bonded validators. - h.k.SynchronizeDelegatorRewards(ctx, delAddr, nil, false) - - return nil -} - -// BeforeValidatorSlashed is called before a validator is slashed -// Validator status is not updated when Slash or Jail is called -func (h Hooks) BeforeValidatorSlashed(ctx sdk.Context, valAddr sdk.ValAddress, fraction sdk.Dec) error { - // Sync all claims for users delegated to this validator. - // For each claim, sync based on the total delegated to bonded validators. - for _, delegation := range h.k.stakingKeeper.GetValidatorDelegations(ctx, valAddr) { - h.k.SynchronizeDelegatorRewards(ctx, delegation.GetDelegatorAddr(), nil, false) - } - - return nil -} - -// AfterValidatorBeginUnbonding is called after a validator begins unbonding -// Validator status is set to Unbonding prior to hook running -func (h Hooks) AfterValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) error { - // Sync all claims for users delegated to this validator. - // For each claim, sync based on the total delegated to bonded validators, and also delegations to valAddr. - // valAddr's status has just been set to Unbonding, but we want to include delegations to it in the sync. - for _, delegation := range h.k.stakingKeeper.GetValidatorDelegations(ctx, valAddr) { - h.k.SynchronizeDelegatorRewards(ctx, delegation.GetDelegatorAddr(), valAddr, true) - } - - return nil -} - -// AfterValidatorBonded is called after a validator is bonded -// Validator status is set to Bonded prior to hook running -func (h Hooks) AfterValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) error { - // Sync all claims for users delegated to this validator. - // For each claim, sync based on the total delegated to bonded validators, except for delegations to valAddr. - // valAddr's status has just been set to Bonded, but we don't want to include delegations to it in the sync - for _, delegation := range h.k.stakingKeeper.GetValidatorDelegations(ctx, valAddr) { - h.k.SynchronizeDelegatorRewards(ctx, delegation.GetDelegatorAddr(), valAddr, false) - } - - return nil -} - -// NOTE: following hooks are just implemented to ensure StakingHooks interface compliance - -// AfterDelegationModified runs after a delegation is modified -func (h Hooks) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { - return nil -} - -// BeforeDelegationRemoved runs directly before a delegation is deleted. BeforeDelegationSharesModified is run prior to this. -func (h Hooks) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { - return nil -} - -// AfterValidatorCreated runs after a validator is created -func (h Hooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) error { - return nil -} - -// BeforeValidatorModified runs before a validator is modified -func (h Hooks) BeforeValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) error { - return nil -} - -// AfterValidatorRemoved runs after a validator is removed -func (h Hooks) AfterValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) error { - return nil -} - -// AfterUnbondingInitiated is called when an unbonding operation -// (validator unbonding, unbonding delegation, redelegation) was initiated -func (h Hooks) AfterUnbondingInitiated(_ sdk.Context, _ uint64) error { - return nil -} - -// ------------------- Swap Module Hooks ------------------- - -func (h Hooks) AfterPoolDepositCreated(ctx sdk.Context, poolID string, depositor sdk.AccAddress, _ sdkmath.Int) { - h.k.InitializeSwapReward(ctx, poolID, depositor) -} - -func (h Hooks) BeforePoolDepositModified(ctx sdk.Context, poolID string, depositor sdk.AccAddress, sharesOwned sdkmath.Int) { - h.k.SynchronizeSwapReward(ctx, poolID, depositor, sharesOwned) -} - -// ------------------- Savings Module Hooks ------------------- - -// AfterSavingsDepositCreated function that runs after a deposit is created -func (h Hooks) AfterSavingsDepositCreated(ctx sdk.Context, deposit savingstypes.Deposit) { - // h.k.InitializeSavingsReward(ctx, deposit) -} - -// BeforeSavingsDepositModified function that runs before a deposit is modified -func (h Hooks) BeforeSavingsDepositModified(ctx sdk.Context, deposit savingstypes.Deposit, incomingDenoms []string) { - // h.k.SynchronizeSavingsReward(ctx, deposit, incomingDenoms) -} - -// ------------------- Earn Module Hooks ------------------- - -// AfterVaultDepositCreated function that runs after a vault deposit is created -func (h Hooks) AfterVaultDepositCreated( - ctx sdk.Context, - vaultDenom string, - depositor sdk.AccAddress, - _ sdk.Dec, -) { - h.k.InitializeEarnReward(ctx, vaultDenom, depositor) -} - -// BeforeVaultDepositModified function that runs before a vault deposit is modified -func (h Hooks) BeforeVaultDepositModified( - ctx sdk.Context, - vaultDenom string, - depositor sdk.AccAddress, - sharesOwned sdk.Dec, -) { - h.k.SynchronizeEarnReward(ctx, vaultDenom, depositor, sharesOwned) -} diff --git a/x/incentive/keeper/integration_test.go b/x/incentive/keeper/integration_test.go deleted file mode 100644 index efc37169..00000000 --- a/x/incentive/keeper/integration_test.go +++ /dev/null @@ -1,239 +0,0 @@ -package keeper_test - -import ( - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/kava-labs/kava/app" - cdptypes "github.com/kava-labs/kava/x/cdp/types" - committeetypes "github.com/kava-labs/kava/x/committee/types" - "github.com/kava-labs/kava/x/incentive/testutil" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" - swaptypes "github.com/kava-labs/kava/x/swap/types" -) - -// Avoid cluttering test cases with long function names -func i(in int64) sdkmath.Int { return sdkmath.NewInt(in) } -func d(str string) sdk.Dec { return sdk.MustNewDecFromStr(str) } -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } -func dc(denom string, amount string) sdk.DecCoin { - return sdk.NewDecCoinFromDec(denom, sdk.MustNewDecFromStr(amount)) -} -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } -func toDcs(coins ...sdk.Coin) sdk.DecCoins { return sdk.NewDecCoinsFromCoins(coins...) } -func dcs(coins ...sdk.DecCoin) sdk.DecCoins { return sdk.NewDecCoins(coins...) } - -func NewCDPGenStateMulti(cdc codec.JSONCodec) app.GenesisState { - cdpGenesis := cdptypes.GenesisState{ - Params: cdptypes.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - SurplusAuctionThreshold: cdptypes.DefaultSurplusThreshold, - SurplusAuctionLot: cdptypes.DefaultSurplusLot, - DebtAuctionThreshold: cdptypes.DefaultDebtThreshold, - DebtAuctionLot: cdptypes.DefaultDebtLot, - LiquidationBlockInterval: cdptypes.DefaultBeginBlockerExecutionBlockInterval, - CollateralParams: cdptypes.CollateralParams{ - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("2.0"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(7000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd", - ConversionFactor: i(6), - }, - { - Denom: "btc", - Type: "btc-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000000782997609"), // %2.5 apr - LiquidationPenalty: d("0.025"), - AuctionSize: i(10000000), - SpotMarketID: "btc:usd", - LiquidationMarketID: "btc:usd", - ConversionFactor: i(8), - }, - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - ConversionFactor: i(8), - }, - { - Denom: "busd", - Type: "busd-a", - LiquidationRatio: d("1.01"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.OneDec(), // %0 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(10000000000), - SpotMarketID: "busd:usd", - LiquidationMarketID: "busd:usd", - ConversionFactor: i(8), - }, - }, - DebtParam: cdptypes.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: i(6), - DebtFloor: i(10000000), - }, - }, - StartingCdpID: cdptypes.DefaultCdpStartingID, - DebtDenom: cdptypes.DefaultDebtDenom, - GovDenom: cdptypes.DefaultGovDenom, - CDPs: cdptypes.CDPs{}, - PreviousAccumulationTimes: cdptypes.GenesisAccumulationTimes{ - cdptypes.NewGenesisAccumulationTime("btc-a", time.Time{}, sdk.OneDec()), - cdptypes.NewGenesisAccumulationTime("xrp-a", time.Time{}, sdk.OneDec()), - cdptypes.NewGenesisAccumulationTime("busd-a", time.Time{}, sdk.OneDec()), - cdptypes.NewGenesisAccumulationTime("bnb-a", time.Time{}, sdk.OneDec()), - }, - TotalPrincipals: cdptypes.GenesisTotalPrincipals{ - cdptypes.NewGenesisTotalPrincipal("btc-a", sdk.ZeroInt()), - cdptypes.NewGenesisTotalPrincipal("xrp-a", sdk.ZeroInt()), - cdptypes.NewGenesisTotalPrincipal("busd-a", sdk.ZeroInt()), - cdptypes.NewGenesisTotalPrincipal("bnb-a", sdk.ZeroInt()), - }, - } - return app.GenesisState{cdptypes.ModuleName: cdc.MustMarshalJSON(&cdpGenesis)} -} - -func NewPricefeedGenStateMultiFromTime(cdc codec.JSONCodec, t time.Time) app.GenesisState { - expiry := 100 * 365 * 24 * time.Hour // 100 years - - pfGenesis := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "btc:usd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "xrp:usd", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "busd:usd", BaseAsset: "busd", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "zzz:usd", BaseAsset: "zzz", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: t.Add(expiry), - }, - { - MarketID: "btc:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("8000.00"), - Expiry: t.Add(expiry), - }, - { - MarketID: "xrp:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("0.25"), - Expiry: t.Add(expiry), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("17.25"), - Expiry: t.Add(expiry), - }, - { - MarketID: "busd:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.OneDec(), - Expiry: t.Add(expiry), - }, - { - MarketID: "zzz:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: t.Add(expiry), - }, - }, - } - return app.GenesisState{pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pfGenesis)} -} - -func NewHardGenStateMulti(genTime time.Time) testutil.HardGenesisBuilder { - kavaMM := testutil.NewStandardMoneyMarket("ukava") - kavaMM.SpotMarketID = "kava:usd" - btcMM := testutil.NewStandardMoneyMarket("btcb") - btcMM.SpotMarketID = "btc:usd" - - builder := testutil.NewHardGenesisBuilder().WithGenesisTime(genTime). - WithInitializedMoneyMarket(testutil.NewStandardMoneyMarket("usdx")). - WithInitializedMoneyMarket(kavaMM). - WithInitializedMoneyMarket(testutil.NewStandardMoneyMarket("bnb")). - WithInitializedMoneyMarket(btcMM). - WithInitializedMoneyMarket(testutil.NewStandardMoneyMarket("xrp")). - WithInitializedMoneyMarket(testutil.NewStandardMoneyMarket("zzz")) - return builder -} - -func NewStakingGenesisState(cdc codec.JSONCodec) app.GenesisState { - genState := stakingtypes.DefaultGenesisState() - genState.Params.BondDenom = "ukava" - return app.GenesisState{ - stakingtypes.ModuleName: cdc.MustMarshalJSON(genState), - } -} - -func NewCommitteeGenesisState(cdc codec.Codec, committeeID uint64, members ...sdk.AccAddress) app.GenesisState { - genState := committeetypes.DefaultGenesisState() - - com := committeetypes.MustNewMemberCommittee( - committeeID, - "This committee is for testing.", - members, - []committeetypes.Permission{&committeetypes.GodPermission{}}, - sdk.MustNewDecFromStr("0.666666667"), - time.Hour*24*7, - committeetypes.TALLY_OPTION_FIRST_PAST_THE_POST, - ) - - genesisComms := committeetypes.Committees{com} - - err := genesisComms.UnpackInterfaces(cdc) - if err != nil { - panic(err) - } - - committeesAny, err := committeetypes.PackCommittees(genesisComms) - if err != nil { - panic(err) - } - - genState.Committees = committeesAny - - return app.GenesisState{ - committeetypes.ModuleName: cdc.MustMarshalJSON(genState), - } -} - -func NewSwapGenesisState(cdc codec.JSONCodec) app.GenesisState { - genesis := swaptypes.NewGenesisState( - swaptypes.NewParams( - swaptypes.NewAllowedPools(swaptypes.NewAllowedPool("busd", "ukava")), - d("0.0"), - ), - swaptypes.DefaultPoolRecords, - swaptypes.DefaultShareRecords, - ) - return app.GenesisState{ - swaptypes.ModuleName: cdc.MustMarshalJSON(&genesis), - } -} diff --git a/x/incentive/keeper/keeper.go b/x/incentive/keeper/keeper.go deleted file mode 100644 index 07707676..00000000 --- a/x/incentive/keeper/keeper.go +++ /dev/null @@ -1,885 +0,0 @@ -package keeper - -import ( - "time" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store/prefix" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/incentive/types" -) - -// Keeper keeper for the incentive module -type Keeper struct { - cdc codec.Codec - key storetypes.StoreKey - paramSubspace types.ParamSubspace - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - cdpKeeper types.CdpKeeper - hardKeeper types.HardKeeper - stakingKeeper types.StakingKeeper - swapKeeper types.SwapKeeper - savingsKeeper types.SavingsKeeper - liquidKeeper types.LiquidKeeper - earnKeeper types.EarnKeeper - - // Keepers used for APY queries - mintKeeper types.MintKeeper - distrKeeper types.DistrKeeper - pricefeedKeeper types.PricefeedKeeper -} - -// NewKeeper creates a new keeper -func NewKeeper( - cdc codec.Codec, key storetypes.StoreKey, paramstore types.ParamSubspace, bk types.BankKeeper, - cdpk types.CdpKeeper, hk types.HardKeeper, ak types.AccountKeeper, stk types.StakingKeeper, - swpk types.SwapKeeper, svk types.SavingsKeeper, lqk types.LiquidKeeper, ek types.EarnKeeper, - mk types.MintKeeper, dk types.DistrKeeper, pfk types.PricefeedKeeper, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - accountKeeper: ak, - cdc: cdc, - key: key, - paramSubspace: paramstore, - bankKeeper: bk, - cdpKeeper: cdpk, - hardKeeper: hk, - stakingKeeper: stk, - swapKeeper: swpk, - savingsKeeper: svk, - liquidKeeper: lqk, - earnKeeper: ek, - - mintKeeper: mk, - distrKeeper: dk, - pricefeedKeeper: pfk, - } -} - -// GetUSDXMintingClaim returns the claim in the store corresponding the input address collateral type and id and a boolean for if the claim was found -func (k Keeper) GetUSDXMintingClaim(ctx sdk.Context, addr sdk.AccAddress) (types.USDXMintingClaim, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.USDXMintingClaimKeyPrefix) - bz := store.Get(addr) - if bz == nil { - return types.USDXMintingClaim{}, false - } - var c types.USDXMintingClaim - k.cdc.MustUnmarshal(bz, &c) - return c, true -} - -// SetUSDXMintingClaim sets the claim in the store corresponding to the input address, collateral type, and id -func (k Keeper) SetUSDXMintingClaim(ctx sdk.Context, c types.USDXMintingClaim) { - store := prefix.NewStore(ctx.KVStore(k.key), types.USDXMintingClaimKeyPrefix) - bz := k.cdc.MustMarshal(&c) - store.Set(c.Owner, bz) -} - -// DeleteUSDXMintingClaim deletes the claim in the store corresponding to the input address, collateral type, and id -func (k Keeper) DeleteUSDXMintingClaim(ctx sdk.Context, owner sdk.AccAddress) { - store := prefix.NewStore(ctx.KVStore(k.key), types.USDXMintingClaimKeyPrefix) - store.Delete(owner) -} - -// IterateUSDXMintingClaims iterates over all claim objects in the store and preforms a callback function -func (k Keeper) IterateUSDXMintingClaims(ctx sdk.Context, cb func(c types.USDXMintingClaim) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.USDXMintingClaimKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var c types.USDXMintingClaim - k.cdc.MustUnmarshal(iterator.Value(), &c) - if cb(c) { - break - } - } -} - -// GetAllUSDXMintingClaims returns all Claim objects in the store -func (k Keeper) GetAllUSDXMintingClaims(ctx sdk.Context) types.USDXMintingClaims { - cs := types.USDXMintingClaims{} - k.IterateUSDXMintingClaims(ctx, func(c types.USDXMintingClaim) (stop bool) { - cs = append(cs, c) - return false - }) - return cs -} - -// GetPreviousUSDXMintingAccrualTime returns the last time a collateral type accrued USDX minting rewards -func (k Keeper) GetPreviousUSDXMintingAccrualTime(ctx sdk.Context, ctype string) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousUSDXMintingRewardAccrualTimeKeyPrefix) - b := store.Get([]byte(ctype)) - if b == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(b); err != nil { - panic(err) - } - return blockTime, true -} - -// SetPreviousUSDXMintingAccrualTime sets the last time a collateral type accrued USDX minting rewards -func (k Keeper) SetPreviousUSDXMintingAccrualTime(ctx sdk.Context, ctype string, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousUSDXMintingRewardAccrualTimeKeyPrefix) - bz, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(ctype), bz) -} - -// IterateUSDXMintingAccrualTimes iterates over all previous USDX minting accrual times and preforms a callback function -func (k Keeper) IterateUSDXMintingAccrualTimes(ctx sdk.Context, cb func(string, time.Time) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousUSDXMintingRewardAccrualTimeKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var accrualTime time.Time - if err := accrualTime.UnmarshalBinary(iterator.Value()); err != nil { - panic(err) - } - denom := string(iterator.Key()) - if cb(denom, accrualTime) { - break - } - } -} - -// GetUSDXMintingRewardFactor returns the current reward factor for an individual collateral type -func (k Keeper) GetUSDXMintingRewardFactor(ctx sdk.Context, ctype string) (factor sdk.Dec, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.USDXMintingRewardFactorKeyPrefix) - bz := store.Get([]byte(ctype)) - if bz == nil { - return sdk.ZeroDec(), false - } - if err := factor.Unmarshal(bz); err != nil { - panic(err) - } - return factor, true -} - -// SetUSDXMintingRewardFactor sets the current reward factor for an individual collateral type -func (k Keeper) SetUSDXMintingRewardFactor(ctx sdk.Context, ctype string, factor sdk.Dec) { - store := prefix.NewStore(ctx.KVStore(k.key), types.USDXMintingRewardFactorKeyPrefix) - bz, err := factor.Marshal() - if err != nil { - panic(err) - } - store.Set([]byte(ctype), bz) -} - -// IterateUSDXMintingRewardFactors iterates over all USDX Minting reward factor objects in the store and preforms a callback function -func (k Keeper) IterateUSDXMintingRewardFactors(ctx sdk.Context, cb func(denom string, factor sdk.Dec) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.USDXMintingRewardFactorKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var factor sdk.Dec - if err := factor.Unmarshal(iterator.Value()); err != nil { - panic(err) - } - if cb(string(iterator.Key()), factor) { - break - } - } -} - -// GetHardLiquidityProviderClaim returns the claim in the store corresponding the input address collateral type and id and a boolean for if the claim was found -func (k Keeper) GetHardLiquidityProviderClaim(ctx sdk.Context, addr sdk.AccAddress) (types.HardLiquidityProviderClaim, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardLiquidityClaimKeyPrefix) - bz := store.Get(addr) - if bz == nil { - return types.HardLiquidityProviderClaim{}, false - } - var c types.HardLiquidityProviderClaim - k.cdc.MustUnmarshal(bz, &c) - return c, true -} - -// SetHardLiquidityProviderClaim sets the claim in the store corresponding to the input address, collateral type, and id -func (k Keeper) SetHardLiquidityProviderClaim(ctx sdk.Context, c types.HardLiquidityProviderClaim) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardLiquidityClaimKeyPrefix) - bz := k.cdc.MustMarshal(&c) - store.Set(c.Owner, bz) -} - -// DeleteHardLiquidityProviderClaim deletes the claim in the store corresponding to the input address, collateral type, and id -func (k Keeper) DeleteHardLiquidityProviderClaim(ctx sdk.Context, owner sdk.AccAddress) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardLiquidityClaimKeyPrefix) - store.Delete(owner) -} - -// IterateHardLiquidityProviderClaims iterates over all claim objects in the store and preforms a callback function -func (k Keeper) IterateHardLiquidityProviderClaims(ctx sdk.Context, cb func(c types.HardLiquidityProviderClaim) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardLiquidityClaimKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var c types.HardLiquidityProviderClaim - k.cdc.MustUnmarshal(iterator.Value(), &c) - if cb(c) { - break - } - } -} - -// GetAllHardLiquidityProviderClaims returns all Claim objects in the store -func (k Keeper) GetAllHardLiquidityProviderClaims(ctx sdk.Context) types.HardLiquidityProviderClaims { - cs := types.HardLiquidityProviderClaims{} - k.IterateHardLiquidityProviderClaims(ctx, func(c types.HardLiquidityProviderClaim) (stop bool) { - cs = append(cs, c) - return false - }) - return cs -} - -// GetDelegatorClaim returns the claim in the store corresponding the input address collateral type and id and a boolean for if the claim was found -func (k Keeper) GetDelegatorClaim(ctx sdk.Context, addr sdk.AccAddress) (types.DelegatorClaim, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DelegatorClaimKeyPrefix) - bz := store.Get(addr) - if bz == nil { - return types.DelegatorClaim{}, false - } - var c types.DelegatorClaim - k.cdc.MustUnmarshal(bz, &c) - return c, true -} - -// SetDelegatorClaim sets the claim in the store corresponding to the input address, collateral type, and id -func (k Keeper) SetDelegatorClaim(ctx sdk.Context, c types.DelegatorClaim) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DelegatorClaimKeyPrefix) - bz := k.cdc.MustMarshal(&c) - store.Set(c.Owner, bz) -} - -// DeleteDelegatorClaim deletes the claim in the store corresponding to the input address, collateral type, and id -func (k Keeper) DeleteDelegatorClaim(ctx sdk.Context, owner sdk.AccAddress) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DelegatorClaimKeyPrefix) - store.Delete(owner) -} - -// IterateDelegatorClaims iterates over all claim objects in the store and preforms a callback function -func (k Keeper) IterateDelegatorClaims(ctx sdk.Context, cb func(c types.DelegatorClaim) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DelegatorClaimKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var c types.DelegatorClaim - k.cdc.MustUnmarshal(iterator.Value(), &c) - if cb(c) { - break - } - } -} - -// GetAllDelegatorClaims returns all DelegatorClaim objects in the store -func (k Keeper) GetAllDelegatorClaims(ctx sdk.Context) types.DelegatorClaims { - cs := types.DelegatorClaims{} - k.IterateDelegatorClaims(ctx, func(c types.DelegatorClaim) (stop bool) { - cs = append(cs, c) - return false - }) - return cs -} - -// GetSwapClaim returns the claim in the store corresponding the input address. -func (k Keeper) GetSwapClaim(ctx sdk.Context, addr sdk.AccAddress) (types.SwapClaim, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SwapClaimKeyPrefix) - bz := store.Get(addr) - if bz == nil { - return types.SwapClaim{}, false - } - var c types.SwapClaim - k.cdc.MustUnmarshal(bz, &c) - return c, true -} - -// SetSwapClaim sets the claim in the store corresponding to the input address. -func (k Keeper) SetSwapClaim(ctx sdk.Context, c types.SwapClaim) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SwapClaimKeyPrefix) - bz := k.cdc.MustMarshal(&c) - store.Set(c.Owner, bz) -} - -// DeleteSwapClaim deletes the claim in the store corresponding to the input address. -func (k Keeper) DeleteSwapClaim(ctx sdk.Context, owner sdk.AccAddress) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SwapClaimKeyPrefix) - store.Delete(owner) -} - -// IterateSwapClaims iterates over all claim objects in the store and preforms a callback function -func (k Keeper) IterateSwapClaims(ctx sdk.Context, cb func(c types.SwapClaim) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SwapClaimKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var c types.SwapClaim - k.cdc.MustUnmarshal(iterator.Value(), &c) - if cb(c) { - break - } - } -} - -// GetAllSwapClaims returns all Claim objects in the store -func (k Keeper) GetAllSwapClaims(ctx sdk.Context) types.SwapClaims { - cs := types.SwapClaims{} - k.IterateSwapClaims(ctx, func(c types.SwapClaim) (stop bool) { - cs = append(cs, c) - return false - }) - return cs -} - -// GetSavingsClaim returns the claim in the store corresponding the input address. -func (k Keeper) GetSavingsClaim(ctx sdk.Context, addr sdk.AccAddress) (types.SavingsClaim, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SavingsClaimKeyPrefix) - bz := store.Get(addr) - if bz == nil { - return types.SavingsClaim{}, false - } - var c types.SavingsClaim - k.cdc.MustUnmarshal(bz, &c) - return c, true -} - -// SetSavingsClaim sets the claim in the store corresponding to the input address. -func (k Keeper) SetSavingsClaim(ctx sdk.Context, c types.SavingsClaim) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SavingsClaimKeyPrefix) - bz := k.cdc.MustMarshal(&c) - store.Set(c.Owner, bz) -} - -// DeleteSavingsClaim deletes the claim in the store corresponding to the input address. -func (k Keeper) DeleteSavingsClaim(ctx sdk.Context, owner sdk.AccAddress) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SavingsClaimKeyPrefix) - store.Delete(owner) -} - -// IterateSavingsClaims iterates over all savings claim objects in the store and preforms a callback function -func (k Keeper) IterateSavingsClaims(ctx sdk.Context, cb func(c types.SavingsClaim) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SavingsClaimKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var c types.SavingsClaim - k.cdc.MustUnmarshal(iterator.Value(), &c) - if cb(c) { - break - } - } -} - -// GetAllSavingsClaims returns all savings claim objects in the store -func (k Keeper) GetAllSavingsClaims(ctx sdk.Context) types.SavingsClaims { - cs := types.SavingsClaims{} - k.IterateSavingsClaims(ctx, func(c types.SavingsClaim) (stop bool) { - cs = append(cs, c) - return false - }) - return cs -} - -// GetEarnClaim returns the claim in the store corresponding the input address. -func (k Keeper) GetEarnClaim(ctx sdk.Context, addr sdk.AccAddress) (types.EarnClaim, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.EarnClaimKeyPrefix) - bz := store.Get(addr) - if bz == nil { - return types.EarnClaim{}, false - } - var c types.EarnClaim - k.cdc.MustUnmarshal(bz, &c) - return c, true -} - -// SetEarnClaim sets the claim in the store corresponding to the input address. -func (k Keeper) SetEarnClaim(ctx sdk.Context, c types.EarnClaim) { - store := prefix.NewStore(ctx.KVStore(k.key), types.EarnClaimKeyPrefix) - bz := k.cdc.MustMarshal(&c) - store.Set(c.Owner, bz) -} - -// DeleteEarnClaim deletes the claim in the store corresponding to the input address. -func (k Keeper) DeleteEarnClaim(ctx sdk.Context, owner sdk.AccAddress) { - store := prefix.NewStore(ctx.KVStore(k.key), types.EarnClaimKeyPrefix) - store.Delete(owner) -} - -// IterateEarnClaims iterates over all claim objects in the store and preforms a callback function -func (k Keeper) IterateEarnClaims(ctx sdk.Context, cb func(c types.EarnClaim) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.EarnClaimKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var c types.EarnClaim - k.cdc.MustUnmarshal(iterator.Value(), &c) - if cb(c) { - break - } - } -} - -// GetAllEarnClaims returns all Claim objects in the store -func (k Keeper) GetAllEarnClaims(ctx sdk.Context) types.EarnClaims { - cs := types.EarnClaims{} - k.IterateEarnClaims(ctx, func(c types.EarnClaim) (stop bool) { - cs = append(cs, c) - return false - }) - return cs -} - -// SetHardSupplyRewardIndexes sets the current reward indexes for an individual denom -func (k Keeper) SetHardSupplyRewardIndexes(ctx sdk.Context, denom string, indexes types.RewardIndexes) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardSupplyRewardIndexesKeyPrefix) - bz := k.cdc.MustMarshal(&types.RewardIndexesProto{ - RewardIndexes: indexes, - }) - store.Set([]byte(denom), bz) -} - -// GetHardSupplyRewardIndexes gets the current reward indexes for an individual denom -func (k Keeper) GetHardSupplyRewardIndexes(ctx sdk.Context, denom string) (types.RewardIndexes, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardSupplyRewardIndexesKeyPrefix) - bz := store.Get([]byte(denom)) - if bz == nil { - return types.RewardIndexes{}, false - } - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(bz, &proto) - - return proto.RewardIndexes, true -} - -// IterateHardSupplyRewardIndexes iterates over all Hard supply reward index objects in the store and preforms a callback function -func (k Keeper) IterateHardSupplyRewardIndexes(ctx sdk.Context, cb func(denom string, indexes types.RewardIndexes) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardSupplyRewardIndexesKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(iterator.Value(), &proto) - if cb(string(iterator.Key()), proto.RewardIndexes) { - break - } - } -} - -func (k Keeper) IterateHardSupplyRewardAccrualTimes(ctx sdk.Context, cb func(string, time.Time) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousHardSupplyRewardAccrualTimeKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var accrualTime time.Time - if err := accrualTime.UnmarshalBinary(iterator.Value()); err != nil { - panic(err) - } - denom := string(iterator.Key()) - if cb(denom, accrualTime) { - break - } - } -} - -// SetHardBorrowRewardIndexes sets the current reward indexes for an individual denom -func (k Keeper) SetHardBorrowRewardIndexes(ctx sdk.Context, denom string, indexes types.RewardIndexes) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardBorrowRewardIndexesKeyPrefix) - bz := k.cdc.MustMarshal(&types.RewardIndexesProto{ - RewardIndexes: indexes, - }) - store.Set([]byte(denom), bz) -} - -// GetHardBorrowRewardIndexes gets the current reward indexes for an individual denom -func (k Keeper) GetHardBorrowRewardIndexes(ctx sdk.Context, denom string) (types.RewardIndexes, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardBorrowRewardIndexesKeyPrefix) - bz := store.Get([]byte(denom)) - if bz == nil { - return types.RewardIndexes{}, false - } - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(bz, &proto) - - return proto.RewardIndexes, true -} - -// IterateHardBorrowRewardIndexes iterates over all Hard borrow reward index objects in the store and preforms a callback function -func (k Keeper) IterateHardBorrowRewardIndexes(ctx sdk.Context, cb func(denom string, indexes types.RewardIndexes) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardBorrowRewardIndexesKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(iterator.Value(), &proto) - if cb(string(iterator.Key()), proto.RewardIndexes) { - break - } - } -} - -func (k Keeper) IterateHardBorrowRewardAccrualTimes(ctx sdk.Context, cb func(string, time.Time) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousHardBorrowRewardAccrualTimeKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - denom := string(iterator.Key()) - var accrualTime time.Time - if err := accrualTime.UnmarshalBinary(iterator.Value()); err != nil { - panic(err) - } - if cb(denom, accrualTime) { - break - } - } -} - -// GetDelegatorRewardIndexes gets the current reward indexes for an individual denom -func (k Keeper) GetDelegatorRewardIndexes(ctx sdk.Context, denom string) (types.RewardIndexes, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DelegatorRewardIndexesKeyPrefix) - bz := store.Get([]byte(denom)) - if bz == nil { - return types.RewardIndexes{}, false - } - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(bz, &proto) - - return proto.RewardIndexes, true -} - -// SetDelegatorRewardIndexes sets the current reward indexes for an individual denom -func (k Keeper) SetDelegatorRewardIndexes(ctx sdk.Context, denom string, indexes types.RewardIndexes) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DelegatorRewardIndexesKeyPrefix) - bz := k.cdc.MustMarshal(&types.RewardIndexesProto{ - RewardIndexes: indexes, - }) - store.Set([]byte(denom), bz) -} - -// IterateDelegatorRewardIndexes iterates over all delegator reward index objects in the store and preforms a callback function -func (k Keeper) IterateDelegatorRewardIndexes(ctx sdk.Context, cb func(denom string, indexes types.RewardIndexes) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DelegatorRewardIndexesKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(iterator.Value(), &proto) - if cb(string(iterator.Key()), proto.RewardIndexes) { - break - } - } -} - -func (k Keeper) IterateDelegatorRewardAccrualTimes(ctx sdk.Context, cb func(string, time.Time) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousDelegatorRewardAccrualTimeKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - denom := string(iterator.Key()) - var accrualTime time.Time - if err := accrualTime.UnmarshalBinary(iterator.Value()); err != nil { - panic(err) - } - if cb(denom, accrualTime) { - break - } - } -} - -// GetPreviousHardSupplyRewardAccrualTime returns the last time a denom accrued Hard protocol supply-side rewards -func (k Keeper) GetPreviousHardSupplyRewardAccrualTime(ctx sdk.Context, denom string) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousHardSupplyRewardAccrualTimeKeyPrefix) - bz := store.Get([]byte(denom)) - if bz == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(bz); err != nil { - panic(err) - } - return blockTime, true -} - -// SetPreviousHardSupplyRewardAccrualTime sets the last time a denom accrued Hard protocol supply-side rewards -func (k Keeper) SetPreviousHardSupplyRewardAccrualTime(ctx sdk.Context, denom string, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousHardSupplyRewardAccrualTimeKeyPrefix) - bz, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(denom), bz) -} - -// GetPreviousHardBorrowRewardAccrualTime returns the last time a denom accrued Hard protocol borrow-side rewards -func (k Keeper) GetPreviousHardBorrowRewardAccrualTime(ctx sdk.Context, denom string) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousHardBorrowRewardAccrualTimeKeyPrefix) - b := store.Get([]byte(denom)) - if b == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(b); err != nil { - panic(err) - } - return blockTime, true -} - -// SetPreviousHardBorrowRewardAccrualTime sets the last time a denom accrued Hard protocol borrow-side rewards -func (k Keeper) SetPreviousHardBorrowRewardAccrualTime(ctx sdk.Context, denom string, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousHardBorrowRewardAccrualTimeKeyPrefix) - bz, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(denom), bz) -} - -// GetPreviousDelegatorRewardAccrualTime returns the last time a denom accrued protocol delegator rewards -func (k Keeper) GetPreviousDelegatorRewardAccrualTime(ctx sdk.Context, denom string) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousDelegatorRewardAccrualTimeKeyPrefix) - bz := store.Get([]byte(denom)) - if bz == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(bz); err != nil { - panic(err) - } - return blockTime, true -} - -// SetPreviousDelegatorRewardAccrualTime sets the last time a denom accrued protocol delegator rewards -func (k Keeper) SetPreviousDelegatorRewardAccrualTime(ctx sdk.Context, denom string, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousDelegatorRewardAccrualTimeKeyPrefix) - bz, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(denom), bz) -} - -// SetSwapRewardIndexes stores the global reward indexes that track total rewards to a swap pool. -func (k Keeper) SetSwapRewardIndexes(ctx sdk.Context, poolID string, indexes types.RewardIndexes) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SwapRewardIndexesKeyPrefix) - bz := k.cdc.MustMarshal(&types.RewardIndexesProto{ - RewardIndexes: indexes, - }) - store.Set([]byte(poolID), bz) -} - -// GetSwapRewardIndexes fetches the global reward indexes that track total rewards to a swap pool. -func (k Keeper) GetSwapRewardIndexes(ctx sdk.Context, poolID string) (types.RewardIndexes, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SwapRewardIndexesKeyPrefix) - bz := store.Get([]byte(poolID)) - if bz == nil { - return types.RewardIndexes{}, false - } - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(bz, &proto) - return proto.RewardIndexes, true -} - -// IterateSwapRewardIndexes iterates over all swap reward index objects in the store and preforms a callback function -func (k Keeper) IterateSwapRewardIndexes(ctx sdk.Context, cb func(poolID string, indexes types.RewardIndexes) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SwapRewardIndexesKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(iterator.Value(), &proto) - if cb(string(iterator.Key()), proto.RewardIndexes) { - break - } - } -} - -// GetSwapRewardAccrualTime fetches the last time rewards were accrued for a swap pool. -func (k Keeper) GetSwapRewardAccrualTime(ctx sdk.Context, poolID string) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousSwapRewardAccrualTimeKeyPrefix) - b := store.Get([]byte(poolID)) - if b == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(b); err != nil { - panic(err) - } - return blockTime, true -} - -// SetSwapRewardAccrualTime stores the last time rewards were accrued for a swap pool. -func (k Keeper) SetSwapRewardAccrualTime(ctx sdk.Context, poolID string, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousSwapRewardAccrualTimeKeyPrefix) - bz, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(poolID), bz) -} - -func (k Keeper) IterateSwapRewardAccrualTimes(ctx sdk.Context, cb func(string, time.Time) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousSwapRewardAccrualTimeKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - poolID := string(iterator.Key()) - var accrualTime time.Time - if err := accrualTime.UnmarshalBinary(iterator.Value()); err != nil { - panic(err) - } - if cb(poolID, accrualTime) { - break - } - } -} - -// SetSavingsRewardIndexes stores the global reward indexes that rewards for an individual denom type -func (k Keeper) SetSavingsRewardIndexes(ctx sdk.Context, denom string, indexes types.RewardIndexes) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SavingsRewardIndexesKeyPrefix) - bz := k.cdc.MustMarshal(&types.RewardIndexesProto{ - RewardIndexes: indexes, - }) - store.Set([]byte(denom), bz) -} - -// GetSavingsRewardIndexes fetches the global reward indexes that track rewards for an individual denom type -func (k Keeper) GetSavingsRewardIndexes(ctx sdk.Context, denom string) (types.RewardIndexes, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SavingsRewardIndexesKeyPrefix) - bz := store.Get([]byte(denom)) - if bz == nil { - return types.RewardIndexes{}, false - } - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(bz, &proto) - return proto.RewardIndexes, true -} - -// IterateSavingsRewardIndexes iterates over all savings reward index objects in the store and preforms a callback function -func (k Keeper) IterateSavingsRewardIndexes(ctx sdk.Context, cb func(poolID string, indexes types.RewardIndexes) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SavingsRewardIndexesKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(iterator.Value(), &proto) - if cb(string(iterator.Key()), proto.RewardIndexes) { - break - } - } -} - -// GetSavingsRewardAccrualTime fetches the last time rewards were accrued for an individual denom type -func (k Keeper) GetSavingsRewardAccrualTime(ctx sdk.Context, poolID string) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousSavingsRewardAccrualTimeKeyPrefix) - b := store.Get([]byte(poolID)) - if b == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(b); err != nil { - panic(err) - } - return blockTime, true -} - -// SetSavingsRewardAccrualTime stores the last time rewards were accrued for a savings deposit denom type -func (k Keeper) SetSavingsRewardAccrualTime(ctx sdk.Context, poolID string, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousSavingsRewardAccrualTimeKeyPrefix) - bz, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(poolID), bz) -} - -// IterateSavingsRewardAccrualTimesiterates over all the previous savings reward accrual times in the store -func (k Keeper) IterateSavingsRewardAccrualTimes(ctx sdk.Context, cb func(string, time.Time) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousSavingsRewardAccrualTimeKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - poolID := string(iterator.Key()) - var accrualTime time.Time - if err := accrualTime.UnmarshalBinary(iterator.Value()); err != nil { - panic(err) - } - if cb(poolID, accrualTime) { - break - } - } -} - -// SetEarnRewardIndexes stores the global reward indexes that track total rewards to a earn vault. -func (k Keeper) SetEarnRewardIndexes(ctx sdk.Context, vaultDenom string, indexes types.RewardIndexes) { - store := prefix.NewStore(ctx.KVStore(k.key), types.EarnRewardIndexesKeyPrefix) - bz := k.cdc.MustMarshal(&types.RewardIndexesProto{ - RewardIndexes: indexes, - }) - store.Set([]byte(vaultDenom), bz) -} - -// GetEarnRewardIndexes fetches the global reward indexes that track total rewards to a earn vault. -func (k Keeper) GetEarnRewardIndexes(ctx sdk.Context, vaultDenom string) (types.RewardIndexes, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.EarnRewardIndexesKeyPrefix) - bz := store.Get([]byte(vaultDenom)) - if bz == nil { - return types.RewardIndexes{}, false - } - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(bz, &proto) - return proto.RewardIndexes, true -} - -// IterateEarnRewardIndexes iterates over all earn reward index objects in the store and preforms a callback function -func (k Keeper) IterateEarnRewardIndexes(ctx sdk.Context, cb func(vaultDenom string, indexes types.RewardIndexes) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.EarnRewardIndexesKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(iterator.Value(), &proto) - if cb(string(iterator.Key()), proto.RewardIndexes) { - break - } - } -} - -// GetEarnRewardAccrualTime fetches the last time rewards were accrued for an earn vault. -func (k Keeper) GetEarnRewardAccrualTime(ctx sdk.Context, vaultDenom string) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousEarnRewardAccrualTimeKeyPrefix) - b := store.Get([]byte(vaultDenom)) - if b == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(b); err != nil { - panic(err) - } - return blockTime, true -} - -// SetEarnRewardAccrualTime stores the last time rewards were accrued for a earn vault. -func (k Keeper) SetEarnRewardAccrualTime(ctx sdk.Context, vaultDenom string, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousEarnRewardAccrualTimeKeyPrefix) - bz, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(vaultDenom), bz) -} - -func (k Keeper) IterateEarnRewardAccrualTimes(ctx sdk.Context, cb func(string, time.Time) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousEarnRewardAccrualTimeKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - poolID := string(iterator.Key()) - var accrualTime time.Time - if err := accrualTime.UnmarshalBinary(iterator.Value()); err != nil { - panic(err) - } - if cb(poolID, accrualTime) { - break - } - } -} diff --git a/x/incentive/keeper/keeper_test.go b/x/incentive/keeper/keeper_test.go deleted file mode 100644 index 3ab619aa..00000000 --- a/x/incentive/keeper/keeper_test.go +++ /dev/null @@ -1,629 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/types" -) - -// Test suite used for all keeper tests -type KeeperTestSuite struct { - suite.Suite - - keeper keeper.Keeper - - app app.TestApp - ctx sdk.Context - - genesisTime time.Time - addrs []sdk.AccAddress -} - -// SetupTest is run automatically before each suite test -func (suite *KeeperTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *KeeperTestSuite) SetupApp() { - suite.app = app.NewTestApp() - - suite.keeper = suite.app.GetIncentiveKeeper() - - suite.ctx = suite.app.NewContext(true, tmprototypes.Header{Time: suite.genesisTime}) -} - -func (suite *KeeperTestSuite) TestGetSetDeleteUSDXMintingClaim() { - suite.SetupApp() - c := types.NewUSDXMintingClaim(suite.addrs[0], c("ukava", 1000000), types.RewardIndexes{types.NewRewardIndex("bnb-a", sdk.ZeroDec())}) - _, found := suite.keeper.GetUSDXMintingClaim(suite.ctx, suite.addrs[0]) - suite.Require().False(found) - suite.Require().NotPanics(func() { - suite.keeper.SetUSDXMintingClaim(suite.ctx, c) - }) - testC, found := suite.keeper.GetUSDXMintingClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().Equal(c, testC) - suite.Require().NotPanics(func() { - suite.keeper.DeleteUSDXMintingClaim(suite.ctx, suite.addrs[0]) - }) - _, found = suite.keeper.GetUSDXMintingClaim(suite.ctx, suite.addrs[0]) - suite.Require().False(found) -} - -func (suite *KeeperTestSuite) TestIterateUSDXMintingClaims() { - suite.SetupApp() - for i := 0; i < len(suite.addrs); i++ { - c := types.NewUSDXMintingClaim(suite.addrs[i], c("ukava", 100000), types.RewardIndexes{types.NewRewardIndex("bnb-a", sdk.ZeroDec())}) - suite.Require().NotPanics(func() { - suite.keeper.SetUSDXMintingClaim(suite.ctx, c) - }) - } - claims := types.USDXMintingClaims{} - suite.keeper.IterateUSDXMintingClaims(suite.ctx, func(c types.USDXMintingClaim) bool { - claims = append(claims, c) - return false - }) - suite.Require().Equal(len(suite.addrs), len(claims)) - - claims = suite.keeper.GetAllUSDXMintingClaims(suite.ctx) - suite.Require().Equal(len(suite.addrs), len(claims)) -} - -func (suite *KeeperTestSuite) TestGetSetDeleteSwapClaims() { - suite.SetupApp() - c := types.NewSwapClaim(suite.addrs[0], arbitraryCoins(), nonEmptyMultiRewardIndexes) - - _, found := suite.keeper.GetSwapClaim(suite.ctx, suite.addrs[0]) - suite.Require().False(found) - - suite.Require().NotPanics(func() { - suite.keeper.SetSwapClaim(suite.ctx, c) - }) - testC, found := suite.keeper.GetSwapClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().Equal(c, testC) - - suite.Require().NotPanics(func() { - suite.keeper.DeleteSwapClaim(suite.ctx, suite.addrs[0]) - }) - _, found = suite.keeper.GetSwapClaim(suite.ctx, suite.addrs[0]) - suite.Require().False(found) -} - -func (suite *KeeperTestSuite) TestIterateSwapClaims() { - suite.SetupApp() - claims := types.SwapClaims{ - types.NewSwapClaim(suite.addrs[0], arbitraryCoins(), nonEmptyMultiRewardIndexes), - types.NewSwapClaim(suite.addrs[1], nil, nil), // different claim to the first - } - for _, claim := range claims { - suite.keeper.SetSwapClaim(suite.ctx, claim) - } - - var actualClaims types.SwapClaims - suite.keeper.IterateSwapClaims(suite.ctx, func(c types.SwapClaim) bool { - actualClaims = append(actualClaims, c) - return false - }) - - suite.Require().Equal(claims, actualClaims) -} - -func (suite *KeeperTestSuite) TestGetSetSwapRewardIndexes() { - testCases := []struct { - name string - poolName string - indexes types.RewardIndexes - wantIndex types.RewardIndexes - panics bool - }{ - { - name: "two factors can be written and read", - poolName: "btc/usdx", - indexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - wantIndex: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - name: "indexes with empty pool name panics", - poolName: "", - indexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - panics: true, - }, - { - // this test is to detect any changes in behavior - name: "setting empty indexes does not panic", - poolName: "btc/usdx", - // Marshalling empty slice results in [] bytes, unmarshalling the [] - // empty bytes results in a nil slice instead of an empty slice - indexes: types.RewardIndexes{}, - wantIndex: nil, - panics: false, - }, - { - // this test is to detect any changes in behavior - name: "setting nil indexes does not panic", - poolName: "btc/usdx", - indexes: nil, - wantIndex: nil, - panics: false, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupApp() - - _, found := suite.keeper.GetSwapRewardIndexes(suite.ctx, tc.poolName) - suite.False(found) - - setFunc := func() { suite.keeper.SetSwapRewardIndexes(suite.ctx, tc.poolName, tc.indexes) } - if tc.panics { - suite.Panics(setFunc) - return - } else { - suite.NotPanics(setFunc) - } - - storedIndexes, found := suite.keeper.GetSwapRewardIndexes(suite.ctx, tc.poolName) - suite.True(found) - suite.Equal(tc.wantIndex, storedIndexes) - }) - } -} - -func (suite *KeeperTestSuite) TestIterateSwapRewardIndexes() { - suite.SetupApp() - multiIndexes := types.MultiRewardIndexes{ - { - CollateralType: "bnb/usdx", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "swap", - RewardFactor: d("0.0000002"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: "btcb/usdx", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - }, - }, - } - for _, mi := range multiIndexes { - suite.keeper.SetSwapRewardIndexes(suite.ctx, mi.CollateralType, mi.RewardIndexes) - } - - var actualMultiIndexes types.MultiRewardIndexes - suite.keeper.IterateSwapRewardIndexes(suite.ctx, func(poolID string, i types.RewardIndexes) bool { - actualMultiIndexes = actualMultiIndexes.With(poolID, i) - return false - }) - - suite.Require().Equal(multiIndexes, actualMultiIndexes) -} - -func (suite *KeeperTestSuite) TestGetSetSwapRewardAccrualTimes() { - testCases := []struct { - name string - poolName string - accrualTime time.Time - panics bool - }{ - { - name: "normal time can be written and read", - poolName: "btc/usdx", - accrualTime: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - { - name: "zero time can be written and read", - poolName: "btc/usdx", - accrualTime: time.Time{}, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupApp() - - _, found := suite.keeper.GetSwapRewardAccrualTime(suite.ctx, tc.poolName) - suite.False(found) - - setFunc := func() { suite.keeper.SetSwapRewardAccrualTime(suite.ctx, tc.poolName, tc.accrualTime) } - if tc.panics { - suite.Panics(setFunc) - return - } else { - suite.NotPanics(setFunc) - } - - storedTime, found := suite.keeper.GetSwapRewardAccrualTime(suite.ctx, tc.poolName) - suite.True(found) - suite.Equal(tc.accrualTime, storedTime) - }) - } -} - -func (suite *KeeperTestSuite) TestGetSetDeleteEarnClaims() { - suite.SetupApp() - c := types.NewEarnClaim(suite.addrs[0], arbitraryCoins(), nonEmptyMultiRewardIndexes) - - _, found := suite.keeper.GetEarnClaim(suite.ctx, suite.addrs[0]) - suite.Require().False(found) - - suite.Require().NotPanics(func() { - suite.keeper.SetEarnClaim(suite.ctx, c) - }) - testC, found := suite.keeper.GetEarnClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().Equal(c, testC) - - suite.Require().NotPanics(func() { - suite.keeper.DeleteEarnClaim(suite.ctx, suite.addrs[0]) - }) - _, found = suite.keeper.GetEarnClaim(suite.ctx, suite.addrs[0]) - suite.Require().False(found) -} - -func (suite *KeeperTestSuite) TestIterateEarnClaims() { - suite.SetupApp() - claims := types.EarnClaims{ - types.NewEarnClaim(suite.addrs[0], arbitraryCoins(), nonEmptyMultiRewardIndexes), - types.NewEarnClaim(suite.addrs[1], nil, nil), // different claim to the first - } - for _, claim := range claims { - suite.keeper.SetEarnClaim(suite.ctx, claim) - } - - var actualClaims types.EarnClaims - suite.keeper.IterateEarnClaims(suite.ctx, func(c types.EarnClaim) bool { - actualClaims = append(actualClaims, c) - return false - }) - - suite.Require().Equal(claims, actualClaims) -} - -func (suite *KeeperTestSuite) TestGetSetEarnRewardIndexes() { - testCases := []struct { - name string - vaultDenom string - indexes types.RewardIndexes - wantIndex types.RewardIndexes - panics bool - }{ - { - name: "two factors can be written and read", - vaultDenom: "usdx", - indexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - wantIndex: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - name: "indexes with empty vault name panics", - vaultDenom: "", - indexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - panics: true, - }, - { - // this test is to detect any changes in behavior - name: "setting empty indexes does not panic", - vaultDenom: "usdx", - // Marshalling empty slice results in [] bytes, unmarshalling the [] - // empty bytes results in a nil slice instead of an empty slice - indexes: types.RewardIndexes{}, - wantIndex: nil, - panics: false, - }, - { - // this test is to detect any changes in behavior - name: "setting nil indexes does not panic", - vaultDenom: "usdx", - indexes: nil, - wantIndex: nil, - panics: false, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupApp() - - _, found := suite.keeper.GetEarnRewardIndexes(suite.ctx, tc.vaultDenom) - suite.False(found) - - setFunc := func() { suite.keeper.SetEarnRewardIndexes(suite.ctx, tc.vaultDenom, tc.indexes) } - if tc.panics { - suite.Panics(setFunc) - return - } else { - suite.NotPanics(setFunc) - } - - storedIndexes, found := suite.keeper.GetEarnRewardIndexes(suite.ctx, tc.vaultDenom) - suite.True(found) - suite.Equal(tc.wantIndex, storedIndexes) - }) - } -} - -func (suite *KeeperTestSuite) TestIterateEarnRewardIndexes() { - suite.SetupApp() - multiIndexes := types.MultiRewardIndexes{ - { - CollateralType: "ukava", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.0000002"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: "usdx", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - }, - }, - } - for _, mi := range multiIndexes { - suite.keeper.SetEarnRewardIndexes(suite.ctx, mi.CollateralType, mi.RewardIndexes) - } - - var actualMultiIndexes types.MultiRewardIndexes - suite.keeper.IterateEarnRewardIndexes(suite.ctx, func(vaultDenom string, i types.RewardIndexes) bool { - actualMultiIndexes = actualMultiIndexes.With(vaultDenom, i) - return false - }) - - suite.Require().Equal(multiIndexes, actualMultiIndexes) -} - -func (suite *KeeperTestSuite) TestGetSetEarnRewardAccrualTimes() { - testCases := []struct { - name string - vaultDenom string - accrualTime time.Time - panics bool - }{ - { - name: "normal time can be written and read", - vaultDenom: "usdx", - accrualTime: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - { - name: "zero time can be written and read", - vaultDenom: "usdx", - accrualTime: time.Time{}, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupApp() - - _, found := suite.keeper.GetEarnRewardAccrualTime(suite.ctx, tc.vaultDenom) - suite.False(found) - - setFunc := func() { suite.keeper.SetEarnRewardAccrualTime(suite.ctx, tc.vaultDenom, tc.accrualTime) } - if tc.panics { - suite.Panics(setFunc) - return - } else { - suite.NotPanics(setFunc) - } - - storedTime, found := suite.keeper.GetEarnRewardAccrualTime(suite.ctx, tc.vaultDenom) - suite.True(found) - suite.Equal(tc.accrualTime, storedTime) - }) - } -} - -type accrualtime struct { - denom string - time time.Time -} - -var nonEmptyAccrualTimes = []accrualtime{ - { - denom: "btcb", - time: time.Date(1998, 1, 1, 0, 0, 0, 1, time.UTC), - }, - { - denom: "ukava", - time: time.Time{}, - }, -} - -func (suite *KeeperTestSuite) TestIterateUSDXMintingAccrualTimes() { - suite.SetupApp() - - expectedAccrualTimes := nonEmptyAccrualTimes - - for _, at := range expectedAccrualTimes { - suite.keeper.SetPreviousUSDXMintingAccrualTime(suite.ctx, at.denom, at.time) - } - - var actualAccrualTimes []accrualtime - suite.keeper.IterateUSDXMintingAccrualTimes(suite.ctx, func(denom string, accrualTime time.Time) bool { - actualAccrualTimes = append(actualAccrualTimes, accrualtime{denom: denom, time: accrualTime}) - return false - }) - - suite.Equal(expectedAccrualTimes, actualAccrualTimes) -} - -func (suite *KeeperTestSuite) TestIterateHardSupplyRewardAccrualTimes() { - suite.SetupApp() - - expectedAccrualTimes := nonEmptyAccrualTimes - - for _, at := range expectedAccrualTimes { - suite.keeper.SetPreviousHardSupplyRewardAccrualTime(suite.ctx, at.denom, at.time) - } - - var actualAccrualTimes []accrualtime - suite.keeper.IterateHardSupplyRewardAccrualTimes(suite.ctx, func(denom string, accrualTime time.Time) bool { - actualAccrualTimes = append(actualAccrualTimes, accrualtime{denom: denom, time: accrualTime}) - return false - }) - - suite.Equal(expectedAccrualTimes, actualAccrualTimes) -} - -func (suite *KeeperTestSuite) TestIterateHardBorrowrRewardAccrualTimes() { - suite.SetupApp() - - expectedAccrualTimes := nonEmptyAccrualTimes - - for _, at := range expectedAccrualTimes { - suite.keeper.SetPreviousHardBorrowRewardAccrualTime(suite.ctx, at.denom, at.time) - } - - var actualAccrualTimes []accrualtime - suite.keeper.IterateHardBorrowRewardAccrualTimes(suite.ctx, func(denom string, accrualTime time.Time) bool { - actualAccrualTimes = append(actualAccrualTimes, accrualtime{denom: denom, time: accrualTime}) - return false - }) - - suite.Equal(expectedAccrualTimes, actualAccrualTimes) -} - -func (suite *KeeperTestSuite) TestIterateDelegatorRewardAccrualTimes() { - suite.SetupApp() - - expectedAccrualTimes := nonEmptyAccrualTimes - - for _, at := range expectedAccrualTimes { - suite.keeper.SetPreviousDelegatorRewardAccrualTime(suite.ctx, at.denom, at.time) - } - - var actualAccrualTimes []accrualtime - suite.keeper.IterateDelegatorRewardAccrualTimes(suite.ctx, func(denom string, accrualTime time.Time) bool { - actualAccrualTimes = append(actualAccrualTimes, accrualtime{denom: denom, time: accrualTime}) - return false - }) - - suite.Equal(expectedAccrualTimes, actualAccrualTimes) -} - -func (suite *KeeperTestSuite) TestIterateSwapRewardAccrualTimes() { - suite.SetupApp() - - expectedAccrualTimes := nonEmptyAccrualTimes - - for _, at := range expectedAccrualTimes { - suite.keeper.SetSwapRewardAccrualTime(suite.ctx, at.denom, at.time) - } - - var actualAccrualTimes []accrualtime - suite.keeper.IterateSwapRewardAccrualTimes(suite.ctx, func(denom string, accrualTime time.Time) bool { - actualAccrualTimes = append(actualAccrualTimes, accrualtime{denom: denom, time: accrualTime}) - return false - }) - - suite.Equal(expectedAccrualTimes, actualAccrualTimes) -} - -func (suite *KeeperTestSuite) TestIterateEarnRewardAccrualTimes() { - suite.SetupApp() - - expectedAccrualTimes := nonEmptyAccrualTimes - - for _, at := range expectedAccrualTimes { - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, at.denom, at.time) - } - - var actualAccrualTimes []accrualtime - suite.keeper.IterateEarnRewardAccrualTimes(suite.ctx, func(denom string, accrualTime time.Time) bool { - actualAccrualTimes = append(actualAccrualTimes, accrualtime{denom: denom, time: accrualTime}) - return false - }) - - suite.Equal(expectedAccrualTimes, actualAccrualTimes) -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} diff --git a/x/incentive/keeper/keeper_utils_test.go b/x/incentive/keeper/keeper_utils_test.go deleted file mode 100644 index 2dac8ae2..00000000 --- a/x/incentive/keeper/keeper_utils_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package keeper_test - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/types" -) - -// TestKeeper is a test wrapper for the keeper which contains useful methods for testing -type TestKeeper struct { - keeper.Keeper -} - -func (keeper TestKeeper) storeGlobalBorrowIndexes(ctx sdk.Context, indexes types.MultiRewardIndexes) { - for _, i := range indexes { - keeper.SetHardBorrowRewardIndexes(ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (keeper TestKeeper) storeGlobalSupplyIndexes(ctx sdk.Context, indexes types.MultiRewardIndexes) { - for _, i := range indexes { - keeper.SetHardSupplyRewardIndexes(ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (keeper TestKeeper) storeGlobalDelegatorIndexes(ctx sdk.Context, multiRewardIndexes types.MultiRewardIndexes) { - // Hardcoded to use bond denom - multiRewardIndex, _ := multiRewardIndexes.GetRewardIndex(types.BondDenom) - keeper.SetDelegatorRewardIndexes(ctx, types.BondDenom, multiRewardIndex.RewardIndexes) -} - -func (keeper TestKeeper) storeGlobalSwapIndexes(ctx sdk.Context, indexes types.MultiRewardIndexes) { - for _, i := range indexes { - keeper.SetSwapRewardIndexes(ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (keeper TestKeeper) storeGlobalSavingsIndexes(ctx sdk.Context, indexes types.MultiRewardIndexes) { - for _, i := range indexes { - keeper.SetSavingsRewardIndexes(ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (keeper TestKeeper) storeGlobalEarnIndexes(ctx sdk.Context, indexes types.MultiRewardIndexes) { - for _, i := range indexes { - keeper.SetEarnRewardIndexes(ctx, i.CollateralType, i.RewardIndexes) - } -} diff --git a/x/incentive/keeper/msg_server.go b/x/incentive/keeper/msg_server.go deleted file mode 100644 index 2b4e2319..00000000 --- a/x/incentive/keeper/msg_server.go +++ /dev/null @@ -1,117 +0,0 @@ -package keeper - -import ( - "context" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/kava-labs/kava/x/incentive/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the incentive MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -func (k msgServer) ClaimUSDXMintingReward(goCtx context.Context, msg *types.MsgClaimUSDXMintingReward) (*types.MsgClaimUSDXMintingRewardResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - err = k.keeper.ClaimUSDXMintingReward(ctx, sender, sender, msg.MultiplierName) - if err != nil { - return nil, err - } - - return &types.MsgClaimUSDXMintingRewardResponse{}, nil -} - -func (k msgServer) ClaimHardReward(goCtx context.Context, msg *types.MsgClaimHardReward) (*types.MsgClaimHardRewardResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - for _, selection := range msg.DenomsToClaim { - err := k.keeper.ClaimHardReward(ctx, sender, sender, selection.Denom, selection.MultiplierName) - if err != nil { - return nil, err - } - - } - - return &types.MsgClaimHardRewardResponse{}, nil -} - -func (k msgServer) ClaimDelegatorReward(goCtx context.Context, msg *types.MsgClaimDelegatorReward) (*types.MsgClaimDelegatorRewardResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - for _, selection := range msg.DenomsToClaim { - err := k.keeper.ClaimDelegatorReward(ctx, sender, sender, selection.Denom, selection.MultiplierName) - if err != nil { - return nil, err - } - } - - return &types.MsgClaimDelegatorRewardResponse{}, nil -} - -func (k msgServer) ClaimSwapReward(goCtx context.Context, msg *types.MsgClaimSwapReward) (*types.MsgClaimSwapRewardResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - for _, selection := range msg.DenomsToClaim { - err := k.keeper.ClaimSwapReward(ctx, sender, sender, selection.Denom, selection.MultiplierName) - if err != nil { - return nil, err - } - } - - return &types.MsgClaimSwapRewardResponse{}, nil -} - -func (k msgServer) ClaimSavingsReward(goCtx context.Context, msg *types.MsgClaimSavingsReward) (*types.MsgClaimSavingsRewardResponse, error) { - err := errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "savings claims disabled") - return nil, err -} - -func (k msgServer) ClaimEarnReward(goCtx context.Context, msg *types.MsgClaimEarnReward) (*types.MsgClaimEarnRewardResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - for _, selection := range msg.DenomsToClaim { - err := k.keeper.ClaimEarnReward(ctx, sender, sender, selection.Denom, selection.MultiplierName) - if err != nil { - return nil, err - } - } - - return &types.MsgClaimEarnRewardResponse{}, nil -} diff --git a/x/incentive/keeper/msg_server_delegator_test.go b/x/incentive/keeper/msg_server_delegator_test.go deleted file mode 100644 index f3d0331f..00000000 --- a/x/incentive/keeper/msg_server_delegator_test.go +++ /dev/null @@ -1,112 +0,0 @@ -package keeper_test - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - - "github.com/kava-labs/kava/x/incentive/types" -) - -func (suite *HandlerTestSuite) TestPayoutDelegatorClaimMultiDenom() { - userAddr := suite.addrs[0] - receiverAddr := suite.addrs[1] - - authBulder := suite.authBuilder(). - WithSimpleAccount(userAddr, cs(c("ukava", 1e12))). - WithSimpleAccount(receiverAddr, nil) - - incentBuilder := suite.incentiveBuilder(). - WithSimpleDelegatorRewardPeriod(types.BondDenom, cs(c("hard", 1e6), c("swap", 1e6))) - - suite.SetupWithGenState(authBulder, incentBuilder) - - // create a delegation (need to create a validator first, which will have a self delegation) - suite.NoError( - suite.DeliverMsgCreateValidator(sdk.ValAddress(userAddr), c("ukava", 1e9)), - ) - - // Delete genesis validator to not influence rewards - suite.App.DeleteGenesisValidator(suite.T(), suite.Ctx) - - // new block required to bond validator - suite.NextBlockAfter(7 * time.Second) - // Now the delegation is bonded, accumulate some delegator rewards - suite.NextBlockAfter(7 * time.Second) - - preClaimBal := suite.GetBalance(userAddr) - - msg := types.NewMsgClaimDelegatorReward( - userAddr.String(), - types.Selections{ - types.NewSelection("hard", "small"), - types.NewSelection("swap", "medium"), - }, - ) - - // Claim denoms - err := suite.DeliverIncentiveMsg(&msg) - suite.Require().NoError(err) - - // Check rewards were paid out - expectedRewardsHard := c("hard", int64(0.2*float64(2*7*1e6))) - expectedRewardsSwap := c("swap", int64(0.5*float64(2*7*1e6))) - suite.BalanceEquals(userAddr, preClaimBal.Add(expectedRewardsHard, expectedRewardsSwap)) - - suite.VestingPeriodsEqual(userAddr, []vestingtypes.Period{ - {Length: (17+31)*secondsPerDay - 2*7, Amount: cs(expectedRewardsHard)}, - {Length: (28 + 31 + 30 + 31 + 30) * secondsPerDay, Amount: cs(expectedRewardsSwap)}, // second length is stacked on top of the first - }) - // Check that claimed coins have been removed from a claim's reward - suite.DelegatorRewardEquals(userAddr, nil) -} - -func (suite *HandlerTestSuite) TestPayoutDelegatorClaimSingleDenom() { - userAddr := suite.addrs[0] - - authBulder := suite.authBuilder(). - WithSimpleAccount(userAddr, cs(c("ukava", 1e12))) - - incentBuilder := suite.incentiveBuilder(). - WithSimpleDelegatorRewardPeriod(types.BondDenom, cs(c("hard", 1e6), c("swap", 1e6))) - - suite.SetupWithGenState(authBulder, incentBuilder) - - // create a delegation (need to create a validator first, which will have a self delegation) - suite.NoError( - suite.DeliverMsgCreateValidator(sdk.ValAddress(userAddr), c("ukava", 1e9)), - ) - - // Delete genesis validator to not influence rewards - suite.App.DeleteGenesisValidator(suite.T(), suite.Ctx) - - // new block required to bond validator - suite.NextBlockAfter(7 * time.Second) - // Now the delegation is bonded, accumulate some delegator rewards - suite.NextBlockAfter(7 * time.Second) - - preClaimBal := suite.GetBalance(userAddr) - - msg := types.NewMsgClaimDelegatorReward( - userAddr.String(), - types.Selections{ - types.NewSelection("swap", "large"), - }, - ) - - // Claim rewards - err := suite.DeliverIncentiveMsg(&msg) - suite.Require().NoError(err) - - // Check rewards were paid out - expectedRewards := c("swap", 2*7*1e6) - suite.BalanceEquals(userAddr, preClaimBal.Add(expectedRewards)) - - suite.VestingPeriodsEqual(userAddr, []vestingtypes.Period{ - {Length: (17+31+28+31+30+31+30+31+31+30+31+30+31)*secondsPerDay - 2*7, Amount: cs(expectedRewards)}, - }) - - // Check that claimed coins have been removed from a claim's reward - suite.DelegatorRewardEquals(userAddr, cs(c("hard", 2*7*1e6))) -} diff --git a/x/incentive/keeper/msg_server_earn_test.go b/x/incentive/keeper/msg_server_earn_test.go deleted file mode 100644 index 98fd3a53..00000000 --- a/x/incentive/keeper/msg_server_earn_test.go +++ /dev/null @@ -1,239 +0,0 @@ -package keeper_test - -import ( - "time" - - abci "github.com/cometbft/cometbft/abci/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/cosmos/cosmos-sdk/x/distribution" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/cosmos/cosmos-sdk/x/mint" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - earntypes "github.com/kava-labs/kava/x/earn/types" - "github.com/kava-labs/kava/x/incentive" - "github.com/kava-labs/kava/x/incentive/testutil" - "github.com/kava-labs/kava/x/incentive/types" - liquidtypes "github.com/kava-labs/kava/x/liquid/types" -) - -func (suite *HandlerTestSuite) TestEarnLiquidClaim() { - userAddr1, userAddr2, validatorAddr1, validatorAddr2 := suite.addrs[0], suite.addrs[1], suite.addrs[2], suite.addrs[3] - - valAddr1 := sdk.ValAddress(validatorAddr1) - valAddr2 := sdk.ValAddress(validatorAddr2) - - authBuilder := suite.authBuilder(). - WithSimpleAccount(userAddr1, cs(c("ukava", 1e12))). - WithSimpleAccount(userAddr2, cs(c("ukava", 1e12))). - WithSimpleAccount(validatorAddr1, cs(c("ukava", 1e12))). - WithSimpleAccount(validatorAddr2, cs(c("ukava", 1e12))) - - incentBuilder := suite.incentiveBuilder(). - WithSimpleEarnRewardPeriod("bkava", cs()) - - savingsBuilder := testutil.NewSavingsGenesisBuilder(). - WithSupportedDenoms("bkava") - - earnBuilder := testutil.NewEarnGenesisBuilder(). - WithAllowedVaults(earntypes.AllowedVault{ - Denom: "bkava", - Strategies: earntypes.StrategyTypes{earntypes.STRATEGY_TYPE_SAVINGS}, - IsPrivateVault: false, - AllowedDepositors: nil, - }) - - suite.SetupWithGenState( - authBuilder, - incentBuilder, - earnBuilder, - savingsBuilder, - ) - - // ak := suite.App.GetAccountKeeper() - // bk := suite.App.GetBankKeeper() - sk := suite.App.GetStakingKeeper() - lq := suite.App.GetLiquidKeeper() - mk := suite.App.GetMintKeeper() - dk := suite.App.GetDistrKeeper() - ik := suite.App.GetIncentiveKeeper() - - iParams := ik.GetParams(suite.Ctx) - period, found := iParams.EarnRewardPeriods.GetMultiRewardPeriod("bkava") - suite.Require().True(found) - suite.Require().Equal("bkava", period.CollateralType) - - // Use ukava for mint denom - mParams := mk.GetParams(suite.Ctx) - mParams.MintDenom = "ukava" - mk.SetParams(suite.Ctx, mParams) - - bkavaDenom1 := lq.GetLiquidStakingTokenDenom(valAddr1) - bkavaDenom2 := lq.GetLiquidStakingTokenDenom(valAddr2) - - err := suite.App.FundModuleAccount(suite.Ctx, distrtypes.ModuleName, cs(c("ukava", 1e12))) - suite.NoError(err) - - // Create validators - err = suite.DeliverMsgCreateValidator(valAddr1, c("ukava", 1e9)) - suite.Require().NoError(err) - - err = suite.DeliverMsgCreateValidator(valAddr2, c("ukava", 1e9)) - suite.Require().NoError(err) - - // new block required to bond validator - suite.NextBlockAfter(7 * time.Second) - // Now the delegation is bonded, accumulate some delegator rewards - suite.NextBlockAfter(7 * time.Second) - - // Create delegations from users - // User 1: 1e9 ukava to validator 1 - // User 2: 99e9 ukava to validator 1 AND 2 - err = suite.DeliverMsgDelegate(userAddr1, valAddr1, c("ukava", 1e9)) - suite.Require().NoError(err) - - err = suite.DeliverMsgDelegate(userAddr2, valAddr1, c("ukava", 99e9)) - suite.Require().NoError(err) - - err = suite.DeliverMsgDelegate(userAddr2, valAddr2, c("ukava", 99e9)) - suite.Require().NoError(err) - - // Mint liquid tokens - _, err = suite.DeliverMsgMintDerivative(userAddr1, valAddr1, c("ukava", 1e9)) - suite.Require().NoError(err) - - _, err = suite.DeliverMsgMintDerivative(userAddr2, valAddr1, c("ukava", 99e9)) - suite.Require().NoError(err) - - _, err = suite.DeliverMsgMintDerivative(userAddr2, valAddr2, c("ukava", 99e9)) - suite.Require().NoError(err) - - // Deposit liquid tokens to earn - err = suite.DeliverEarnMsgDeposit(userAddr1, c(bkavaDenom1, 1e9), earntypes.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - err = suite.DeliverEarnMsgDeposit(userAddr2, c(bkavaDenom1, 99e9), earntypes.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - err = suite.DeliverEarnMsgDeposit(userAddr2, c(bkavaDenom2, 99e9), earntypes.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // BeginBlocker to update minter annual provisions as it starts at 0 which results in no minted coins - _ = suite.App.BeginBlocker(suite.Ctx, abci.RequestBeginBlock{}) - - // DeliverMsgCreateValidator uses a generated pubkey, so we need to fetch - // the validator to get the correct pubkey - validator1, found := sk.GetValidator(suite.Ctx, valAddr1) - suite.Require().True(found) - - pk, err := validator1.ConsPubKey() - suite.Require().NoError(err) - - val := abci.Validator{ - Address: pk.Address(), - Power: 100, - } - - // Query for next block to get staking rewards - suite.Ctx = suite.Ctx. - WithBlockHeight(suite.Ctx.BlockHeight() + 1). - WithBlockTime(suite.Ctx.BlockTime().Add(7 * time.Second)) - - // Mint tokens - mint.BeginBlocker( - suite.Ctx, - suite.App.GetMintKeeper(), - minttypes.DefaultInflationCalculationFn, - ) - // Distribute to validators, block needs votes - distribution.BeginBlocker( - suite.Ctx, - abci.RequestBeginBlock{ - LastCommitInfo: abci.CommitInfo{ - Votes: []abci.VoteInfo{{ - Validator: val, - SignedLastBlock: true, - }}, - }, - }, - dk, - ) - - liquidMacc := suite.App.GetAccountKeeper().GetModuleAccount(suite.Ctx, liquidtypes.ModuleAccountName) - delegation, found := sk.GetDelegation(suite.Ctx, liquidMacc.GetAddress(), valAddr1) - suite.Require().True(found) - - // Get amount of rewards - endingPeriod := dk.IncrementValidatorPeriod(suite.Ctx, validator1) - - // Zero rewards since this block is the same as the block it was last claimed - - // This needs to run **after** staking rewards are minted/distributed in - // x/mint + x/distribution but **before** the x/incentive BeginBlocker. - - // Order of operations: - // 1. x/mint + x/distribution BeginBlocker - // 2. CalculateDelegationRewards - // 3. x/incentive BeginBlocker to claim staking rewards - delegationRewards := dk.CalculateDelegationRewards(suite.Ctx, validator1, delegation, endingPeriod) - suite.Require().False(delegationRewards.IsZero(), "expected non-zero delegation rewards") - - // Claim staking rewards via incentive. - // Block height was updated earlier. - incentive.BeginBlocker( - suite.Ctx, - ik, - ) - - preClaimBal1 := suite.GetBalance(userAddr1) - preClaimBal2 := suite.GetBalance(userAddr2) - - // Claim ukava staking rewards - denomsToClaim := map[string]string{"ukava": "large"} - selections := types.NewSelectionsFromMap(denomsToClaim) - - msg1 := types.NewMsgClaimEarnReward(userAddr1.String(), selections) - msg2 := types.NewMsgClaimEarnReward(userAddr2.String(), selections) - - err = suite.DeliverIncentiveMsg(&msg1) - suite.Require().NoError(err) - - err = suite.DeliverIncentiveMsg(&msg2) - suite.Require().NoError(err) - - // Check rewards were paid out - // User 1 gets 1% of rewards - // User 2 gets 99% of rewards - stakingRewards1 := delegationRewards. - AmountOf("ukava"). - Quo(sdk.NewDec(100)). - RoundInt() - suite.BalanceEquals(userAddr1, preClaimBal1.Add(sdk.NewCoin("ukava", stakingRewards1))) - - // Total * 99 / 100 - stakingRewards2 := delegationRewards. - AmountOf("ukava"). - Mul(sdk.NewDec(99)). - Quo(sdk.NewDec(100)). - RoundInt() - - suite.BalanceInEpsilon( - userAddr2, - preClaimBal2.Add(sdk.NewCoin("ukava", stakingRewards2)), - // Highest precision to allow 1ukava margin of error - // 820778117815 vs 820778117814 - 1e-11, - ) - - suite.InEpsilonf( - delegationRewards.AmountOf("ukava").RoundInt().Int64(), - stakingRewards1.Add(stakingRewards2).Int64(), - 1e-11, - "expected rewards should add up to staking rewards within a margin of error (%v vs %v)", - delegationRewards.AmountOf("ukava").RoundInt().Int64(), - stakingRewards1.Add(stakingRewards2).Int64(), - ) - - // Check that claimed coins have been removed from a claim's reward - suite.EarnRewardEquals(userAddr1, cs()) - suite.EarnRewardEquals(userAddr2, cs()) -} diff --git a/x/incentive/keeper/msg_server_hard_test.go b/x/incentive/keeper/msg_server_hard_test.go deleted file mode 100644 index 44e5ff71..00000000 --- a/x/incentive/keeper/msg_server_hard_test.go +++ /dev/null @@ -1,100 +0,0 @@ -package keeper_test - -import ( - "time" - - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - - "github.com/kava-labs/kava/x/incentive/types" -) - -func (suite *HandlerTestSuite) TestPayoutHardClaimMultiDenom() { - userAddr, receiverAddr := suite.addrs[0], suite.addrs[1] - - authBulder := suite.authBuilder(). - WithSimpleAccount(userAddr, cs(c("bnb", 1e12))). - WithSimpleAccount(receiverAddr, nil) - - incentBuilder := suite.incentiveBuilder(). - WithSimpleSupplyRewardPeriod("bnb", cs(c("hard", 1e6), c("swap", 1e6))). - WithSimpleBorrowRewardPeriod("bnb", cs(c("hard", 1e6), c("swap", 1e6))) - - suite.SetupWithGenState(authBulder, incentBuilder) - - // create a deposit and borrow - suite.NoError(suite.DeliverHardMsgDeposit(userAddr, cs(c("bnb", 1e11)))) - suite.NoError(suite.DeliverHardMsgBorrow(userAddr, cs(c("bnb", 1e10)))) - - // accumulate some rewards - suite.NextBlockAfter(7 * time.Second) - - preClaimBal := suite.GetBalance(userAddr) - - msg := types.NewMsgClaimHardReward( - userAddr.String(), - types.Selections{ - types.NewSelection("hard", "small"), - types.NewSelection("swap", "medium"), - }, - ) - - // Claim denoms - err := suite.DeliverIncentiveMsg(&msg) - suite.Require().NoError(err) - - // Check rewards were paid out - expectedRewardsHard := c("hard", int64(0.2*float64(2*7*1e6))) - expectedRewardsSwap := c("swap", int64(0.5*float64(2*7*1e6))) - suite.BalanceEquals(userAddr, preClaimBal.Add(expectedRewardsHard, expectedRewardsSwap)) - - suite.VestingPeriodsEqual(userAddr, []vestingtypes.Period{ - {Length: (17+31)*secondsPerDay - 7, Amount: cs(expectedRewardsHard)}, - {Length: (28 + 31 + 30 + 31 + 30) * secondsPerDay, Amount: cs(expectedRewardsSwap)}, // second length is stacked on top of the first - }) - // Check that claimed coins have been removed from a claim's reward - suite.HardRewardEquals(userAddr, nil) -} - -func (suite *HandlerTestSuite) TestPayoutHardClaimSingleDenom() { - userAddr := suite.addrs[0] - - authBulder := suite.authBuilder(). - WithSimpleAccount(userAddr, cs(c("bnb", 1e12))) - - incentBuilder := suite.incentiveBuilder(). - WithSimpleSupplyRewardPeriod("bnb", cs(c("hard", 1e6), c("swap", 1e6))). - WithSimpleBorrowRewardPeriod("bnb", cs(c("hard", 1e6), c("swap", 1e6))) - - suite.SetupWithGenState(authBulder, incentBuilder) - - // create a deposit and borrow - suite.NoError(suite.DeliverHardMsgDeposit(userAddr, cs(c("bnb", 1e11)))) - suite.NoError(suite.DeliverHardMsgBorrow(userAddr, cs(c("bnb", 1e10)))) - - // accumulate some rewards - suite.NextBlockAfter(7 * time.Second) - - preClaimBal := suite.GetBalance(userAddr) - - msg := types.NewMsgClaimHardReward( - userAddr.String(), - types.Selections{ - types.NewSelection("swap", "large"), - }, - ) - - // Claim rewards - err := suite.DeliverIncentiveMsg(&msg) - suite.Require().NoError(err) - - // Check rewards were paid out - expectedRewards := c("swap", 2*7*1e6) - suite.BalanceEquals(userAddr, preClaimBal.Add(expectedRewards)) - - suite.VestingPeriodsEqual(userAddr, []vestingtypes.Period{ - {Length: (17+31+28+31+30+31+30+31+31+30+31+30+31)*secondsPerDay - 7, Amount: cs(expectedRewards)}, - }) - - // Check that claimed coins have been removed from a claim's reward - suite.HardRewardEquals(userAddr, cs(c("hard", 2*7*1e6))) -} diff --git a/x/incentive/keeper/msg_server_swap_test.go b/x/incentive/keeper/msg_server_swap_test.go deleted file mode 100644 index 366fccb8..00000000 --- a/x/incentive/keeper/msg_server_swap_test.go +++ /dev/null @@ -1,191 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/incentive/testutil" - "github.com/kava-labs/kava/x/incentive/types" - kavadisttypes "github.com/kava-labs/kava/x/kavadist/types" -) - -const secondsPerDay = 24 * 60 * 60 - -// Test suite used for all keeper tests -type HandlerTestSuite struct { - testutil.IntegrationTester - - genesisTime time.Time - addrs []sdk.AccAddress -} - -func TestHandlerTestSuite(t *testing.T) { - suite.Run(t, new(HandlerTestSuite)) -} - -// SetupTest is run automatically before each suite test -func (suite *HandlerTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *HandlerTestSuite) SetupApp() { - suite.App = app.NewTestApp() - - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: suite.genesisTime}) -} - -func (suite *HandlerTestSuite) SetupWithGenState(builders ...testutil.GenesisBuilder) { - suite.SetupApp() - - builtGenStates := []app.GenesisState{ - NewStakingGenesisState(suite.App.AppCodec()), - NewPricefeedGenStateMultiFromTime(suite.App.AppCodec(), suite.genesisTime), - NewCDPGenStateMulti(suite.App.AppCodec()), - NewHardGenStateMulti(suite.genesisTime).BuildMarshalled(suite.App.AppCodec()), - NewSwapGenesisState(suite.App.AppCodec()), - } - for _, builder := range builders { - builtGenStates = append(builtGenStates, builder.BuildMarshalled(suite.App.AppCodec())) - } - - suite.App.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - builtGenStates..., - ) -} - -// authBuilder returns a new auth genesis builder with a full kavadist module account. -func (suite *HandlerTestSuite) authBuilder() *app.AuthBankGenesisBuilder { - return app.NewAuthBankGenesisBuilder(). - WithSimpleModuleAccount(kavadisttypes.ModuleName, cs(c(types.USDXMintingRewardDenom, 1e18), c("hard", 1e18), c("swap", 1e18))) -} - -// incentiveBuilder returns a new incentive genesis builder with a genesis time and multipliers set -func (suite *HandlerTestSuite) incentiveBuilder() testutil.IncentiveGenesisBuilder { - return testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithMultipliers(types.MultipliersPerDenoms{ - { - Denom: "hard", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.2")), - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - { - Denom: "swap", - Multipliers: types.Multipliers{ - types.NewMultiplier("medium", 6, d("0.5")), - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - { - Denom: "ukava", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.2")), - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - }) -} - -func (suite *HandlerTestSuite) TestPayoutSwapClaimMultiDenom() { - userAddr := suite.addrs[0] - - authBulder := suite.authBuilder(). - WithSimpleAccount(userAddr, cs(c("ukava", 1e12), c("busd", 1e12))) - - incentBuilder := suite.incentiveBuilder(). - WithSimpleSwapRewardPeriod("busd:ukava", cs(c("hard", 1e6), c("swap", 1e6))) - - suite.SetupWithGenState(authBulder, incentBuilder) - - // deposit into a swap pool - suite.NoError( - suite.DeliverSwapMsgDeposit(userAddr, c("ukava", 1e9), c("busd", 1e9), d("1.0")), - ) - // accumulate some swap rewards - suite.NextBlockAfter(7 * time.Second) - - preClaimBal := suite.GetBalance(userAddr) - - msg := types.NewMsgClaimSwapReward( - userAddr.String(), - types.Selections{ - types.NewSelection("hard", "small"), - types.NewSelection("swap", "medium"), - }, - ) - - // Claim rewards - err := suite.DeliverIncentiveMsg(&msg) - suite.Require().NoError(err) - - // Check rewards were paid out - expectedRewardsHard := c("hard", int64(0.2*float64(7*1e6))) - expectedRewardsSwap := c("swap", int64(0.5*float64(7*1e6))) - suite.BalanceEquals(userAddr, preClaimBal.Add(expectedRewardsHard, expectedRewardsSwap)) - - suite.VestingPeriodsEqual(userAddr, []vestingtypes.Period{ - {Length: (17+31)*secondsPerDay - 7, Amount: cs(expectedRewardsHard)}, - {Length: (28 + 31 + 30 + 31 + 30) * secondsPerDay, Amount: cs(expectedRewardsSwap)}, // second length is stacked on top of the first - }) - - // Check that each claim reward coin's amount has been reset to 0 - suite.SwapRewardEquals(userAddr, nil) -} - -func (suite *HandlerTestSuite) TestPayoutSwapClaimSingleDenom() { - userAddr := suite.addrs[0] - - authBulder := suite.authBuilder(). - WithSimpleAccount(userAddr, cs(c("ukava", 1e12), c("busd", 1e12))) - - incentBuilder := suite.incentiveBuilder(). - WithSimpleSwapRewardPeriod("busd:ukava", cs(c("hard", 1e6), c("swap", 1e6))) - - suite.SetupWithGenState(authBulder, incentBuilder) - - // deposit into a swap pool - suite.NoError( - suite.DeliverSwapMsgDeposit(userAddr, c("ukava", 1e9), c("busd", 1e9), d("1.0")), - ) - - // accumulate some swap rewards - suite.NextBlockAfter(7 * time.Second) - - preClaimBal := suite.GetBalance(userAddr) - - msg := types.NewMsgClaimSwapReward( - userAddr.String(), - types.Selections{ - types.NewSelection("swap", "large"), - }, - ) - - // Claim rewards - err := suite.DeliverIncentiveMsg(&msg) - suite.Require().NoError(err) - - // Check rewards were paid out - expectedRewards := c("swap", 7*1e6) - suite.BalanceEquals(userAddr, preClaimBal.Add(expectedRewards)) - - suite.VestingPeriodsEqual(userAddr, vestingtypes.Periods{ - {Length: (17+31+28+31+30+31+30+31+31+30+31+30+31)*secondsPerDay - 7, Amount: cs(expectedRewards)}, - }) - - // Check that claimed coins have been removed from a claim's reward - suite.SwapRewardEquals(userAddr, cs(c("hard", 7*1e6))) -} diff --git a/x/incentive/keeper/msg_server_usdx_test.go b/x/incentive/keeper/msg_server_usdx_test.go deleted file mode 100644 index ae0e5603..00000000 --- a/x/incentive/keeper/msg_server_usdx_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package keeper_test - -import ( - "time" - - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - - "github.com/kava-labs/kava/x/incentive/types" -) - -func (suite *HandlerTestSuite) TestPayoutUSDXClaim() { - userAddr, receiverAddr := suite.addrs[0], suite.addrs[1] - - authBulder := suite.authBuilder(). - WithSimpleAccount(userAddr, cs(c("bnb", 1e12))). - WithSimpleAccount(receiverAddr, nil) - - incentBuilder := suite.incentiveBuilder(). - WithSimpleUSDXRewardPeriod("bnb-a", c(types.USDXMintingRewardDenom, 1e6)) - - suite.SetupWithGenState(authBulder, incentBuilder) - - // mint some usdx - err := suite.DeliverMsgCreateCDP(userAddr, c("bnb", 1e9), c("usdx", 1e7), "bnb-a") - suite.NoError(err) - // accumulate some rewards - suite.NextBlockAfter(7 * time.Second) - - preClaimBal := suite.GetBalance(userAddr) - - msg := types.NewMsgClaimUSDXMintingReward(userAddr.String(), "large") - - // Claim a single denom - err = suite.DeliverIncentiveMsg(&msg) - suite.Require().NoError(err) - - // Check rewards were paid out - expectedRewards := cs(c(types.USDXMintingRewardDenom, 7*1e6)) - suite.BalanceEquals(userAddr, preClaimBal.Add(expectedRewards...)) - - suite.VestingPeriodsEqual(userAddr, []vestingtypes.Period{ - {Length: (17+31+28+31+30+31+30+31+31+30+31+30+31)*secondsPerDay - 7, Amount: expectedRewards}, - }) - // Check that claimed coins have been removed from a claim's reward - suite.USDXRewardEquals(userAddr, c(types.USDXMintingRewardDenom, 0)) -} diff --git a/x/incentive/keeper/params.go b/x/incentive/keeper/params.go deleted file mode 100644 index c98e4bd9..00000000 --- a/x/incentive/keeper/params.go +++ /dev/null @@ -1,95 +0,0 @@ -package keeper - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/incentive/types" -) - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - var p types.Params - k.paramSubspace.GetParamSet(ctx, &p) - return p -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} - -// GetUSDXMintingRewardPeriod returns the reward period with the specified collateral type if it's found in the params -func (k Keeper) GetUSDXMintingRewardPeriod(ctx sdk.Context, collateralType string) (types.RewardPeriod, bool) { - params := k.GetParams(ctx) - for _, rp := range params.USDXMintingRewardPeriods { - if rp.CollateralType == collateralType { - return rp, true - } - } - return types.RewardPeriod{}, false -} - -// GetHardSupplyRewardPeriods returns the reward period with the specified collateral type if it's found in the params -func (k Keeper) GetHardSupplyRewardPeriods(ctx sdk.Context, denom string) (types.MultiRewardPeriod, bool) { - params := k.GetParams(ctx) - for _, rp := range params.HardSupplyRewardPeriods { - if rp.CollateralType == denom { - return rp, true - } - } - return types.MultiRewardPeriod{}, false -} - -// GetHardBorrowRewardPeriods returns the reward period with the specified collateral type if it's found in the params -func (k Keeper) GetHardBorrowRewardPeriods(ctx sdk.Context, denom string) (types.MultiRewardPeriod, bool) { - params := k.GetParams(ctx) - for _, rp := range params.HardBorrowRewardPeriods { - if rp.CollateralType == denom { - return rp, true - } - } - return types.MultiRewardPeriod{}, false -} - -// GetDelegatorRewardPeriods returns the reward period with the specified collateral type if it's found in the params -func (k Keeper) GetDelegatorRewardPeriods(ctx sdk.Context, denom string) (types.MultiRewardPeriod, bool) { - params := k.GetParams(ctx) - for _, rp := range params.DelegatorRewardPeriods { - if rp.CollateralType == denom { - return rp, true - } - } - return types.MultiRewardPeriod{}, false -} - -// GetSavingsRewardPeriods returns the reward period with the specified collateral type if it's found in the params -func (k Keeper) GetSavingsRewardPeriods(ctx sdk.Context, denom string) (types.MultiRewardPeriod, bool) { - params := k.GetParams(ctx) - for _, rp := range params.SavingsRewardPeriods { - if rp.CollateralType == denom { - return rp, true - } - } - return types.MultiRewardPeriod{}, false -} - -// GetMultiplierByDenom fetches a multiplier from the params matching the denom and name. -func (k Keeper) GetMultiplierByDenom(ctx sdk.Context, denom string, name string) (types.Multiplier, bool) { - params := k.GetParams(ctx) - - for _, dm := range params.ClaimMultipliers { - if dm.Denom == denom { - m, found := dm.Multipliers.Get(name) - return m, found - } - } - return types.Multiplier{}, false -} - -// GetClaimEnd returns the claim end time for the params -func (k Keeper) GetClaimEnd(ctx sdk.Context) time.Time { - params := k.GetParams(ctx) - return params.ClaimEnd -} diff --git a/x/incentive/keeper/payout.go b/x/incentive/keeper/payout.go deleted file mode 100644 index a50ef5a7..00000000 --- a/x/incentive/keeper/payout.go +++ /dev/null @@ -1,198 +0,0 @@ -package keeper - -import ( - "time" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - - "github.com/kava-labs/kava/x/incentive/types" - // validatorvesting "github.com/kava-labs/kava/x/validator-vesting" -) - -const ( - // BeginningOfMonth harvest rewards that are claimed after the 15th at 14:00UTC of the month always vest on the first of the month - BeginningOfMonth = 1 - // MidMonth harvest rewards that are claimed before the 15th at 14:00UTC of the month always vest on the 15 of the month - MidMonth = 15 - // PaymentHour harvest rewards always vest at 14:00UTC - PaymentHour = 14 -) - -// SendTimeLockedCoinsToAccount sends time-locked coins from the input module account to the recipient. If the recipients account is not a vesting account and the input length is greater than zero, the recipient account is converted to a periodic vesting account and the coins are added to the vesting balance as a vesting period with the input length. -func (k Keeper) SendTimeLockedCoinsToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins, length int64) error { - macc := k.accountKeeper.GetModuleAccount(ctx, senderModule) - maccCoins := k.bankKeeper.GetAllBalances(ctx, macc.GetAddress()) - if !maccCoins.IsAllGTE(amt) { - return errorsmod.Wrapf(types.ErrInsufficientModAccountBalance, "%s", senderModule) - } - - // 0. Get the account from the account keeper and do a type switch, error if it's a validator vesting account or module account (can make this work for validator vesting later if necessary) - acc := k.accountKeeper.GetAccount(ctx, recipientAddr) - if acc == nil { - return errorsmod.Wrapf(types.ErrAccountNotFound, recipientAddr.String()) - } - if length == 0 { - return k.bankKeeper.SendCoinsFromModuleToAccount(ctx, senderModule, recipientAddr, amt) - } - - switch acc.(type) { - case *vestingtypes.ContinuousVestingAccount, authtypes.ModuleAccountI: - return errorsmod.Wrapf(types.ErrInvalidAccountType, "%T", acc) - case *vestingtypes.PeriodicVestingAccount: - return k.SendTimeLockedCoinsToPeriodicVestingAccount(ctx, senderModule, recipientAddr, amt, length) - case *authtypes.BaseAccount: - return k.SendTimeLockedCoinsToBaseAccount(ctx, senderModule, recipientAddr, amt, length) - default: - return errorsmod.Wrapf(types.ErrInvalidAccountType, "%T", acc) - } -} - -// SendTimeLockedCoinsToPeriodicVestingAccount sends time-locked coins from the input module account to the recipient -func (k Keeper) SendTimeLockedCoinsToPeriodicVestingAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins, length int64) error { - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, senderModule, recipientAddr, amt) - if err != nil { - return err - } - k.addCoinsToVestingSchedule(ctx, recipientAddr, amt, length) - return nil -} - -// SendTimeLockedCoinsToBaseAccount sends time-locked coins from the input module account to the recipient, converting the recipient account to a vesting account -func (k Keeper) SendTimeLockedCoinsToBaseAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins, length int64) error { - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, senderModule, recipientAddr, amt) - if err != nil { - return err - } - acc := k.accountKeeper.GetAccount(ctx, recipientAddr) - // transition the account to a periodic vesting account: - bacc := authtypes.NewBaseAccount(acc.GetAddress(), acc.GetPubKey(), acc.GetAccountNumber(), acc.GetSequence()) - - newPeriods := vestingtypes.Periods{types.NewPeriod(amt, length)} - bva := vestingtypes.NewBaseVestingAccount(bacc, amt, ctx.BlockTime().Unix()+length) - pva := vestingtypes.NewPeriodicVestingAccountRaw(bva, ctx.BlockTime().Unix(), newPeriods) - k.accountKeeper.SetAccount(ctx, pva) - - return nil -} - -// GetPeriodLength returns the length of the lockup period based on the input blocktime and multiplier lockup. -// Note that pay dates are always the 1st or 15th of the month at 14:00UTC. -// Months lockup cannot be negative -func (k Keeper) GetPeriodLength(blockTime time.Time, monthsLockup int64) int64 { - if monthsLockup < 0 { - panic("months lockup must be non negative") - } - if monthsLockup == 0 { - return 0 - } - currentDay := blockTime.Day() - payDay := BeginningOfMonth - monthOffset := int64(1) - if currentDay < MidMonth || (currentDay == MidMonth && blockTime.Hour() < PaymentHour) { - payDay = MidMonth - monthOffset = int64(0) - } - periodEndDate := time.Date(blockTime.Year(), blockTime.Month(), payDay, PaymentHour, 0, 0, 0, time.UTC).AddDate(0, int(monthsLockup+monthOffset), 0) - return periodEndDate.Unix() - blockTime.Unix() -} - -// addCoinsToVestingSchedule adds coins to the input account's vesting schedule where length is the amount of time (from the current block time), in seconds, that the coins will be vesting for -// the input address must be a periodic vesting account -func (k Keeper) addCoinsToVestingSchedule(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins, length int64) { - acc := k.accountKeeper.GetAccount(ctx, addr) - vacc := acc.(*vestingtypes.PeriodicVestingAccount) - // Add the new vesting coins to OriginalVesting - vacc.OriginalVesting = vacc.OriginalVesting.Add(amt...) - // update vesting periods - // EndTime = 100 - // BlockTime = 110 - // length == 6 - if vacc.EndTime < ctx.BlockTime().Unix() { - // edge case one - the vesting account's end time is in the past (ie, all previous vesting periods have completed) - // append a new period to the vesting account, update the end time, update the account in the store and return - newPeriodLength := (ctx.BlockTime().Unix() - vacc.EndTime) + length // 110 - 100 + 6 = 16 - newPeriod := types.NewPeriod(amt, newPeriodLength) - vacc.VestingPeriods = append(vacc.VestingPeriods, newPeriod) - vacc.EndTime = ctx.BlockTime().Unix() + length - k.accountKeeper.SetAccount(ctx, vacc) - return - } - // StartTime = 110 - // BlockTime = 100 - // length = 6 - if vacc.StartTime > ctx.BlockTime().Unix() { - // edge case two - the vesting account's start time is in the future (all periods have not started) - // update the start time to now and adjust the period lengths in place - a new period will be inserted in the next code block - updatedPeriods := vestingtypes.Periods{} - for i, period := range vacc.VestingPeriods { - updatedPeriod := period - if i == 0 { - updatedPeriod = types.NewPeriod(period.Amount, (vacc.StartTime-ctx.BlockTime().Unix())+period.Length) // 110 - 100 + 6 = 16 - } - updatedPeriods = append(updatedPeriods, updatedPeriod) - } - vacc.VestingPeriods = updatedPeriods - vacc.StartTime = ctx.BlockTime().Unix() - } - - // logic for inserting a new vesting period into the existing vesting schedule - remainingLength := vacc.EndTime - ctx.BlockTime().Unix() - elapsedTime := ctx.BlockTime().Unix() - vacc.StartTime - proposedEndTime := ctx.BlockTime().Unix() + length - if remainingLength < length { - // in the case that the proposed length is longer than the remaining length of all vesting periods, create a new period with length equal to the difference between the proposed length and the previous total length - newPeriodLength := length - remainingLength - newPeriod := types.NewPeriod(amt, newPeriodLength) - vacc.VestingPeriods = append(vacc.VestingPeriods, newPeriod) - // update the end time so that the sum of all period lengths equals endTime - startTime - vacc.EndTime = proposedEndTime - } else { - // In the case that the proposed length is less than or equal to the sum of all previous period lengths, insert the period and update other periods as necessary. - // EXAMPLE (l is length, a is amount) - // Original Periods: {[l: 1 a: 1], [l: 2, a: 1], [l:8, a:3], [l: 5, a: 3]} - // Period we want to insert [l: 5, a: x] - // Expected result: - // {[l: 1, a: 1], [l:2, a: 1], [l:2, a:x], [l:6, a:3], [l:5, a:3]} - - // StartTime = 100 - // Periods = [5,5,5,5] - // EndTime = 120 - // BlockTime = 101 - // length = 2 - - // for period in Periods: - // iteration 1: - // lengthCounter = 5 - // if 5 < 101 - 100 + 2 - no - // if 5 = 3 - no - // else - // newperiod = 2 - 0 - newPeriods := vestingtypes.Periods{} - lengthCounter := int64(0) - appendRemaining := false - for _, period := range vacc.VestingPeriods { - if appendRemaining { - newPeriods = append(newPeriods, period) - continue - } - lengthCounter += period.Length - if lengthCounter < elapsedTime+length { // 1 - newPeriods = append(newPeriods, period) - } else if lengthCounter == elapsedTime+length { - newPeriod := types.NewPeriod(period.Amount.Add(amt...), period.Length) - newPeriods = append(newPeriods, newPeriod) - appendRemaining = true - } else { - newPeriod := types.NewPeriod(amt, elapsedTime+length-types.GetTotalVestingPeriodLength(newPeriods)) - previousPeriod := types.NewPeriod(period.Amount, period.Length-newPeriod.Length) - newPeriods = append(newPeriods, newPeriod, previousPeriod) - appendRemaining = true - } - } - vacc.VestingPeriods = newPeriods - } - k.accountKeeper.SetAccount(ctx, vacc) -} diff --git a/x/incentive/keeper/payout_test.go b/x/incentive/keeper/payout_test.go deleted file mode 100644 index 0c20bfce..00000000 --- a/x/incentive/keeper/payout_test.go +++ /dev/null @@ -1,522 +0,0 @@ -package keeper_test - -import ( - "strings" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - - "github.com/kava-labs/kava/app" - cdpkeeper "github.com/kava-labs/kava/x/cdp/keeper" - cdptypes "github.com/kava-labs/kava/x/cdp/types" - hardkeeper "github.com/kava-labs/kava/x/hard/keeper" - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/testutil" - "github.com/kava-labs/kava/x/incentive/types" - kavadisttypes "github.com/kava-labs/kava/x/kavadist/types" -) - -// Test suite used for all keeper tests -type PayoutTestSuite struct { - suite.Suite - - keeper keeper.Keeper - hardKeeper hardkeeper.Keeper - cdpKeeper cdpkeeper.Keeper - - app app.TestApp - ctx sdk.Context - - genesisTime time.Time - addrs []sdk.AccAddress -} - -// SetupTest is run automatically before each suite test -func (suite *PayoutTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *PayoutTestSuite) SetupApp() { - suite.app = app.NewTestApp() - - suite.keeper = suite.app.GetIncentiveKeeper() - suite.hardKeeper = suite.app.GetHardKeeper() - suite.cdpKeeper = suite.app.GetCDPKeeper() - - suite.ctx = suite.app.NewContext(true, tmprototypes.Header{Time: suite.genesisTime}) -} - -func (suite *PayoutTestSuite) SetupWithGenState(authBuilder app.AuthBankGenesisBuilder, incentBuilder testutil.IncentiveGenesisBuilder, hardBuilder testutil.HardGenesisBuilder) { - suite.SetupApp() - - suite.app.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - authBuilder.BuildMarshalled(suite.app.AppCodec()), - NewPricefeedGenStateMultiFromTime(suite.app.AppCodec(), suite.genesisTime), - NewCDPGenStateMulti(suite.app.AppCodec()), - hardBuilder.BuildMarshalled(suite.app.AppCodec()), - incentBuilder.BuildMarshalled(suite.app.AppCodec()), - ) -} - -func (suite *PayoutTestSuite) getAccount(addr sdk.AccAddress) authtypes.AccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetAccount(suite.ctx, addr) -} - -func (suite *PayoutTestSuite) getModuleAccount(name string) authtypes.ModuleAccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetModuleAccount(suite.ctx, name) -} - -func (suite *PayoutTestSuite) TestSendCoinsToPeriodicVestingAccount() { - type accountArgs struct { - periods []vestingtypes.Period - origVestingCoins sdk.Coins - startTime int64 - endTime int64 - } - type args struct { - accArgs accountArgs - period vestingtypes.Period - ctxTime time.Time - mintModAccountCoins bool - expectedPeriods []vestingtypes.Period - expectedStartTime int64 - expectedEndTime int64 - } - type errArgs struct { - expectErr bool - contains string - } - type testCase struct { - name string - args args - errArgs errArgs - } - type testCases []testCase - - tests := testCases{ - { - name: "insert period at beginning schedule", - args: args{ - accArgs: accountArgs{ - periods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - origVestingCoins: cs(c("ukava", 20)), - startTime: 100, - endTime: 120, - }, - period: vestingtypes.Period{Length: 2, Amount: cs(c("ukava", 6))}, - ctxTime: time.Unix(101, 0), - mintModAccountCoins: true, - expectedPeriods: []vestingtypes.Period{ - {Length: 3, Amount: cs(c("ukava", 6))}, - {Length: 2, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - expectedStartTime: 100, - expectedEndTime: 120, - }, - errArgs: errArgs{ - expectErr: false, - contains: "", - }, - }, - { - name: "insert period at beginning with new start time", - args: args{ - accArgs: accountArgs{ - periods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - origVestingCoins: cs(c("ukava", 20)), - startTime: 100, - endTime: 120, - }, - period: vestingtypes.Period{Length: 7, Amount: cs(c("ukava", 6))}, - ctxTime: time.Unix(80, 0), - mintModAccountCoins: true, - expectedPeriods: []vestingtypes.Period{ - {Length: 7, Amount: cs(c("ukava", 6))}, - {Length: 18, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - expectedStartTime: 80, - expectedEndTime: 120, - }, - errArgs: errArgs{ - expectErr: false, - contains: "", - }, - }, - { - name: "insert period in middle of schedule", - args: args{ - accArgs: accountArgs{ - periods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - origVestingCoins: cs(c("ukava", 20)), - startTime: 100, - endTime: 120, - }, - period: vestingtypes.Period{Length: 7, Amount: cs(c("ukava", 6))}, - ctxTime: time.Unix(101, 0), - mintModAccountCoins: true, - expectedPeriods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 3, Amount: cs(c("ukava", 6))}, - {Length: 2, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - expectedStartTime: 100, - expectedEndTime: 120, - }, - errArgs: errArgs{ - expectErr: false, - contains: "", - }, - }, - { - name: "append to end of schedule", - args: args{ - accArgs: accountArgs{ - periods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - origVestingCoins: cs(c("ukava", 20)), - startTime: 100, - endTime: 120, - }, - period: vestingtypes.Period{Length: 7, Amount: cs(c("ukava", 6))}, - ctxTime: time.Unix(125, 0), - mintModAccountCoins: true, - expectedPeriods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 12, Amount: cs(c("ukava", 6))}, - }, - expectedStartTime: 100, - expectedEndTime: 132, - }, - errArgs: errArgs{ - expectErr: false, - contains: "", - }, - }, - { - name: "add coins to existing period", - args: args{ - accArgs: accountArgs{ - periods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - origVestingCoins: cs(c("ukava", 20)), - startTime: 100, - endTime: 120, - }, - period: vestingtypes.Period{Length: 5, Amount: cs(c("ukava", 6))}, - ctxTime: time.Unix(110, 0), - mintModAccountCoins: true, - expectedPeriods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 11))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - expectedStartTime: 100, - expectedEndTime: 120, - }, - errArgs: errArgs{ - expectErr: false, - contains: "", - }, - }, - { - name: "insufficient mod account balance", - args: args{ - accArgs: accountArgs{ - periods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - origVestingCoins: cs(c("ukava", 20)), - startTime: 100, - endTime: 120, - }, - period: vestingtypes.Period{Length: 7, Amount: cs(c("ukava", 6))}, - ctxTime: time.Unix(125, 0), - mintModAccountCoins: false, - expectedPeriods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 12, Amount: cs(c("ukava", 6))}, - }, - expectedStartTime: 100, - expectedEndTime: 132, - }, - errArgs: errArgs{ - expectErr: true, - contains: "insufficient funds", - }, - }, - { - name: "add large period mid schedule", - args: args{ - accArgs: accountArgs{ - periods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - origVestingCoins: cs(c("ukava", 20)), - startTime: 100, - endTime: 120, - }, - period: vestingtypes.Period{Length: 50, Amount: cs(c("ukava", 6))}, - ctxTime: time.Unix(110, 0), - mintModAccountCoins: true, - expectedPeriods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 40, Amount: cs(c("ukava", 6))}, - }, - expectedStartTime: 100, - expectedEndTime: 160, - }, - errArgs: errArgs{ - expectErr: false, - contains: "", - }, - }, - } - for _, tc := range tests { - suite.Run(tc.name, func() { - authBuilder := app.NewAuthBankGenesisBuilder().WithSimplePeriodicVestingAccount( - suite.addrs[0], - tc.args.accArgs.origVestingCoins, - tc.args.accArgs.periods, - tc.args.accArgs.startTime, - ) - if tc.args.mintModAccountCoins { - authBuilder = authBuilder.WithSimpleModuleAccount(kavadisttypes.ModuleName, tc.args.period.Amount) - } - - suite.genesisTime = tc.args.ctxTime - suite.SetupApp() - suite.app.InitializeFromGenesisStates( - authBuilder.BuildMarshalled(suite.app.AppCodec()), - ) - - err := suite.keeper.SendTimeLockedCoinsToPeriodicVestingAccount(suite.ctx, kavadisttypes.ModuleName, suite.addrs[0], tc.args.period.Amount, tc.args.period.Length) - - if tc.errArgs.expectErr { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } else { - suite.Require().NoError(err) - - acc := suite.getAccount(suite.addrs[0]) - vacc, ok := acc.(*vestingtypes.PeriodicVestingAccount) - suite.Require().True(ok) - suite.Require().Equal(tc.args.expectedPeriods, vacc.VestingPeriods) - suite.Require().Equal(tc.args.expectedStartTime, vacc.StartTime) - suite.Require().Equal(tc.args.expectedEndTime, vacc.EndTime) - } - }) - } -} - -func (suite *PayoutTestSuite) TestSendCoinsToBaseAccount() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[1], cs(c("ukava", 400))). - WithSimpleModuleAccount(kavadisttypes.ModuleName, cs(c("ukava", 600))) - - suite.genesisTime = time.Unix(100, 0) - suite.SetupApp() - suite.app.InitializeFromGenesisStates( - authBuilder.BuildMarshalled(suite.app.AppCodec()), - ) - - // send coins to base account - err := suite.keeper.SendTimeLockedCoinsToAccount(suite.ctx, kavadisttypes.ModuleName, suite.addrs[1], cs(c("ukava", 100)), 5) - suite.Require().NoError(err) - acc := suite.getAccount(suite.addrs[1]) - vacc, ok := acc.(*vestingtypes.PeriodicVestingAccount) - suite.True(ok) - expectedPeriods := []vestingtypes.Period{ - {Length: int64(5), Amount: cs(c("ukava", 100))}, - } - - bk := suite.app.GetBankKeeper() - - suite.Equal(expectedPeriods, vacc.VestingPeriods) - suite.Equal(cs(c("ukava", 100)), vacc.OriginalVesting) - suite.Equal(cs(c("ukava", 500)), bk.GetAllBalances(suite.ctx, vacc.GetAddress())) - suite.Equal(int64(105), vacc.EndTime) - suite.Equal(int64(100), vacc.StartTime) -} - -func (suite *PayoutTestSuite) TestSendCoinsToInvalidAccount() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleModuleAccount(kavadisttypes.ModuleName, cs(c("ukava", 600))) - - suite.SetupApp() - suite.app.InitializeFromGenesisStates( - authBuilder.BuildMarshalled(suite.app.AppCodec()), - ) - - // No longer an empty validator vesting account, just a regular addr - err := suite.keeper.SendTimeLockedCoinsToAccount(suite.ctx, kavadisttypes.ModuleName, suite.addrs[2], cs(c("ukava", 100)), 5) - suite.Require().ErrorIs(err, types.ErrAccountNotFound) - - macc := suite.getModuleAccount(cdptypes.ModuleName) - err = suite.keeper.SendTimeLockedCoinsToAccount(suite.ctx, kavadisttypes.ModuleName, macc.GetAddress(), cs(c("ukava", 100)), 5) - suite.Require().ErrorIs(err, types.ErrInvalidAccountType) -} - -func (suite *PayoutTestSuite) TestGetPeriodLength() { - type args struct { - blockTime time.Time - lockup int64 - } - type periodTest struct { - name string - args args - expectedLength int64 - } - testCases := []periodTest{ - { - name: "first half of month", - args: args{ - blockTime: time.Date(2020, 11, 2, 15, 0, 0, 0, time.UTC), - lockup: 6, - }, - expectedLength: time.Date(2021, 5, 15, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 11, 2, 15, 0, 0, 0, time.UTC).Unix(), - }, - { - name: "first half of month long lockup", - args: args{ - blockTime: time.Date(2020, 11, 2, 15, 0, 0, 0, time.UTC), - lockup: 24, - }, - expectedLength: time.Date(2022, 11, 15, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 11, 2, 15, 0, 0, 0, time.UTC).Unix(), - }, - { - name: "second half of month", - args: args{ - blockTime: time.Date(2020, 12, 31, 15, 0, 0, 0, time.UTC), - lockup: 6, - }, - expectedLength: time.Date(2021, 7, 1, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 12, 31, 15, 0, 0, 0, time.UTC).Unix(), - }, - { - name: "second half of month long lockup", - args: args{ - blockTime: time.Date(2020, 12, 31, 15, 0, 0, 0, time.UTC), - lockup: 24, - }, - expectedLength: time.Date(2023, 1, 1, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 12, 31, 15, 0, 0, 0, time.UTC).Unix(), - }, - { - name: "end of feb", - args: args{ - blockTime: time.Date(2021, 2, 28, 15, 0, 0, 0, time.UTC), - lockup: 6, - }, - expectedLength: time.Date(2021, 9, 1, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2021, 2, 28, 15, 0, 0, 0, time.UTC).Unix(), - }, - { - name: "leap year", - args: args{ - blockTime: time.Date(2020, 2, 29, 15, 0, 0, 0, time.UTC), - lockup: 6, - }, - expectedLength: time.Date(2020, 9, 1, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 2, 29, 15, 0, 0, 0, time.UTC).Unix(), - }, - { - name: "leap year long lockup", - args: args{ - blockTime: time.Date(2020, 2, 29, 15, 0, 0, 0, time.UTC), - lockup: 24, - }, - expectedLength: time.Date(2022, 3, 1, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 2, 29, 15, 0, 0, 0, time.UTC).Unix(), - }, - { - name: "exactly half of month, is pushed to start of month + lockup", - args: args{ - blockTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - lockup: 6, - }, - expectedLength: time.Date(2021, 7, 1, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Unix(), - }, - { - name: "just before half of month", - args: args{ - blockTime: time.Date(2020, 12, 15, 13, 59, 59, 0, time.UTC), - lockup: 6, - }, - expectedLength: time.Date(2021, 6, 15, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 12, 15, 13, 59, 59, 0, time.UTC).Unix(), - }, - { - name: "just after start of month payout time, is pushed to mid month + lockup", - args: args{ - blockTime: time.Date(2020, 12, 1, 14, 0, 1, 0, time.UTC), - lockup: 1, - }, - expectedLength: time.Date(2021, 1, 15, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 12, 1, 14, 0, 1, 0, time.UTC).Unix(), - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - length := suite.keeper.GetPeriodLength(tc.args.blockTime, tc.args.lockup) - suite.Require().Equal(tc.expectedLength, length) - }) - } -} - -func TestPayoutTestSuite(t *testing.T) { - suite.Run(t, new(PayoutTestSuite)) -} diff --git a/x/incentive/keeper/querier.go b/x/incentive/keeper/querier.go deleted file mode 100644 index fc5832b3..00000000 --- a/x/incentive/keeper/querier.go +++ /dev/null @@ -1,144 +0,0 @@ -package keeper - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - earntypes "github.com/kava-labs/kava/x/earn/types" - "github.com/kava-labs/kava/x/incentive/types" - liquidtypes "github.com/kava-labs/kava/x/liquid/types" -) - -const ( - SecondsPerYear = 31536000 -) - -// GetStakingAPR returns the total APR for staking and incentive rewards -func GetStakingAPR(ctx sdk.Context, k Keeper, params types.Params) (sdk.Dec, error) { - // Get staking APR + incentive APR - inflationRate := k.mintKeeper.GetMinter(ctx).Inflation - communityTax := k.distrKeeper.GetCommunityTax(ctx) - - bondedTokens := k.stakingKeeper.TotalBondedTokens(ctx) - circulatingSupply := k.bankKeeper.GetSupply(ctx, types.BondDenom) - - // Staking APR = (Inflation Rate * (1 - Community Tax)) / (Bonded Tokens / Circulating Supply) - stakingAPR := inflationRate. - Mul(sdk.OneDec().Sub(communityTax)). - Quo(sdk.NewDecFromInt(bondedTokens). - Quo(sdk.NewDecFromInt(circulatingSupply.Amount))) - - // Get incentive APR - bkavaRewardPeriod, found := params.EarnRewardPeriods.GetMultiRewardPeriod(liquidtypes.DefaultDerivativeDenom) - if !found { - // No incentive rewards for bkava, only staking rewards - return stakingAPR, nil - } - - // Total amount of bkava in earn vaults, this may be lower than total bank - // supply of bkava as some bkava may not be deposited in earn vaults - totalEarnBkavaDeposited := sdk.ZeroInt() - - var iterErr error - k.earnKeeper.IterateVaultRecords(ctx, func(record earntypes.VaultRecord) (stop bool) { - if !k.liquidKeeper.IsDerivativeDenom(ctx, record.TotalShares.Denom) { - return false - } - - vaultValue, err := k.earnKeeper.GetVaultTotalValue(ctx, record.TotalShares.Denom) - if err != nil { - iterErr = err - return false - } - - totalEarnBkavaDeposited = totalEarnBkavaDeposited.Add(vaultValue.Amount) - - return false - }) - - if iterErr != nil { - return sdk.ZeroDec(), iterErr - } - - // Incentive APR = rewards per second * seconds per year / total supplied to earn vaults - // Override collateral type to use "kava" instead of "bkava" when fetching - incentiveAPY, err := GetAPYFromMultiRewardPeriod(ctx, k, types.BondDenom, bkavaRewardPeriod, totalEarnBkavaDeposited) - if err != nil { - return sdk.ZeroDec(), err - } - - totalAPY := stakingAPR.Add(incentiveAPY) - return totalAPY, nil -} - -// GetAPYFromMultiRewardPeriod calculates the APY for a given MultiRewardPeriod -func GetAPYFromMultiRewardPeriod( - ctx sdk.Context, - k Keeper, - collateralType string, - rewardPeriod types.MultiRewardPeriod, - totalSupply sdkmath.Int, -) (sdk.Dec, error) { - if totalSupply.IsZero() { - return sdk.ZeroDec(), nil - } - - // Get USD value of collateral type - collateralUSDValue, err := k.pricefeedKeeper.GetCurrentPrice(ctx, getMarketID(collateralType)) - if err != nil { - return sdk.ZeroDec(), fmt.Errorf( - "failed to get price for incentive collateralType %s with market ID %s: %w", - collateralType, getMarketID(collateralType), err, - ) - } - - // Total USD value of the collateral type total supply - totalSupplyUSDValue := sdk.NewDecFromInt(totalSupply).Mul(collateralUSDValue.Price) - - totalUSDRewardsPerSecond := sdk.ZeroDec() - - // In many cases, RewardsPerSecond are assets that are different from the - // CollateralType, so we need to use the USD value of CollateralType and - // RewardsPerSecond to determine the APY. - for _, reward := range rewardPeriod.RewardsPerSecond { - // Get USD value of 1 unit of reward asset type, using TWAP - rewardDenomUSDValue, err := k.pricefeedKeeper.GetCurrentPrice(ctx, getMarketID(reward.Denom)) - if err != nil { - return sdk.ZeroDec(), fmt.Errorf("failed to get price for RewardsPerSecond asset %s: %w", reward.Denom, err) - } - - rewardPerSecond := sdk.NewDecFromInt(reward.Amount).Mul(rewardDenomUSDValue.Price) - totalUSDRewardsPerSecond = totalUSDRewardsPerSecond.Add(rewardPerSecond) - } - - // APY = USD rewards per second * seconds per year / USD total supplied - apy := totalUSDRewardsPerSecond. - MulInt64(SecondsPerYear). - Quo(totalSupplyUSDValue) - - return apy, nil -} - -func getMarketID(denom string) string { - // Rewrite denoms as pricefeed has different names for some assets, - // e.g. "ukava" -> "kava", "erc20/multichain/usdc" -> "usdc" - // bkava is not included as it is handled separately - - // TODO: Replace hardcoded conversion with possible params set somewhere - // to be more flexible. E.g. a map of denoms to pricefeed market denoms in - // pricefeed params. - switch denom { - case types.BondDenom: - denom = "kava" - case "erc20/multichain/usdc": - denom = "usdc" - case "erc20/multichain/usdt": - denom = "usdt" - case "erc20/multichain/dai": - denom = "dai" - } - - return fmt.Sprintf("%s:usd:30", denom) -} diff --git a/x/incentive/keeper/querier_test.go b/x/incentive/keeper/querier_test.go deleted file mode 100644 index 30bf0cbe..00000000 --- a/x/incentive/keeper/querier_test.go +++ /dev/null @@ -1,135 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" - - earntypes "github.com/kava-labs/kava/x/earn/types" - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/types" - "github.com/stretchr/testify/suite" -) - -type QuerierTestSuite struct { - unitTester -} - -func TestQuerierTestSuite(t *testing.T) { - suite.Run(t, new(QuerierTestSuite)) -} - -func (suite *QuerierTestSuite) TestGetStakingAPR() { - communityTax := sdk.MustNewDecFromStr("0.90") - inflation := sdk.MustNewDecFromStr("0.75") - - bondedTokens := int64(120_000_000_000000) - liquidStakedTokens := int64(60_000_000_000000) - totalSupply := int64(289_138_414_286684) - - usdcDenom := "erc20/multichain/usdc" - usdcSupply := int64(2_500_000_000000) - - earnKeeper := newFakeEarnKeeper(). - addVault("bkava-asdf", earntypes.NewVaultShare("bkava-asdf", sdk.NewDec(liquidStakedTokens))). - addVault(usdcDenom, earntypes.NewVaultShare(usdcDenom, sdk.NewDec(usdcSupply))) - - suite.keeper = suite.NewTestKeeper(&fakeParamSubspace{}). - WithDistrKeeper( - newFakeDistrKeeper().setCommunityTax(communityTax), - ). - WithMintKeeper( - newFakeMintKeeper(). - setMinter(minttypes.NewMinter(inflation, sdk.OneDec())), - ). - WithStakingKeeper( - newFakeStakingKeeper().addBondedTokens(bondedTokens), - ). - WithBankKeeper( - newFakeBankKeeper().setSupply(sdk.NewCoin(types.BondDenom, sdkmath.NewInt(totalSupply))), - ). - WithEarnKeeper(earnKeeper). - WithLiquidKeeper( - newFakeLiquidKeeper().addDerivative(suite.ctx, "bkava-asdf", sdkmath.NewInt(liquidStakedTokens)), - ). - WithPricefeedKeeper( - newFakePricefeedKeeper(). - setPrice(pricefeedtypes.NewCurrentPrice("kava:usd:30", sdk.MustNewDecFromStr("1.5"))). - setPrice(pricefeedtypes.NewCurrentPrice("usdc:usd:30", sdk.OneDec())), - ). - Build() - - // ~18% APR - expectedStakingAPY := inflation. - Mul(sdk.OneDec().Sub(communityTax)). - Quo(sdk.NewDec(bondedTokens).Quo(sdk.NewDec(totalSupply))) - - // Staking APR = (Inflation Rate * (1 - Community Tax)) / (Bonded Tokens / Circulating Supply) - aprWithoutIncentives, err := keeper.GetStakingAPR(suite.ctx, suite.keeper, types.Params{}) - suite.Require().NoError(err) - suite.Require().Equal( - expectedStakingAPY, - aprWithoutIncentives, - ) - - suite.T().Logf("Staking APR without incentives: %s", aprWithoutIncentives) - - params := types.Params{ - EarnRewardPeriods: types.MultiRewardPeriods{ - { - Active: true, - CollateralType: "bkava", - Start: suite.ctx.BlockTime().Add(-time.Hour), - End: suite.ctx.BlockTime().Add(time.Hour), - RewardsPerSecond: sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(190258)), - ), - }, - { - Active: true, - CollateralType: "erc20/multichain/usdc", - Start: suite.ctx.BlockTime().Add(-time.Hour), - End: suite.ctx.BlockTime().Add(time.Hour), - RewardsPerSecond: sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(5284)), - ), - }, - }, - } - - suite.Run("GetStakingAPR", func() { - aprWithIncentives, err := keeper.GetStakingAPR(suite.ctx, suite.keeper, params) - suite.Require().NoError(err) - // Approx 10% increase in APR from incentives - suite.Require().Equal(sdk.MustNewDecFromStr("0.280711113729177500"), aprWithIncentives) - - suite.Require().Truef( - aprWithIncentives.GT(aprWithoutIncentives), - "APR with incentives (%s) should be greater than APR without incentives (%s)", - ) - }) - - suite.Run("GetAPYFromMultiRewardPeriod", func() { - vaultTotalValue, err := earnKeeper.GetVaultTotalValue(suite.ctx, usdcDenom) - suite.Require().NoError(err) - suite.Require().True(vaultTotalValue.Amount.IsPositive()) - - apy, err := keeper.GetAPYFromMultiRewardPeriod( - suite.ctx, - suite.keeper, - usdcDenom, - params.EarnRewardPeriods[1], - vaultTotalValue.Amount, - ) - suite.Require().NoError(err) - suite.Require().Equal( - sdk.MustNewDecFromStr("0.099981734400000000"), - apy, - "usdc apy should be approx 10%", - ) - }) -} diff --git a/x/incentive/keeper/rewards_borrow.go b/x/incentive/keeper/rewards_borrow.go deleted file mode 100644 index 44de0fb1..00000000 --- a/x/incentive/keeper/rewards_borrow.go +++ /dev/null @@ -1,225 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - hardtypes "github.com/kava-labs/kava/x/hard/types" - "github.com/kava-labs/kava/x/incentive/types" -) - -// AccumulateHardBorrowRewards calculates new rewards to distribute this block and updates the global indexes to reflect this. -// The provided rewardPeriod must be valid to avoid panics in calculating time durations. -func (k Keeper) AccumulateHardBorrowRewards(ctx sdk.Context, rewardPeriod types.MultiRewardPeriod) { - previousAccrualTime, found := k.GetPreviousHardBorrowRewardAccrualTime(ctx, rewardPeriod.CollateralType) - if !found { - previousAccrualTime = ctx.BlockTime() - } - - indexes, found := k.GetHardBorrowRewardIndexes(ctx, rewardPeriod.CollateralType) - if !found { - indexes = types.RewardIndexes{} - } - - acc := types.NewAccumulator(previousAccrualTime, indexes) - - totalSource := k.getHardBorrowTotalSourceShares(ctx, rewardPeriod.CollateralType) - - acc.Accumulate(rewardPeriod, totalSource, ctx.BlockTime()) - - k.SetPreviousHardBorrowRewardAccrualTime(ctx, rewardPeriod.CollateralType, acc.PreviousAccumulationTime) - if len(acc.Indexes) > 0 { - // the store panics when setting empty or nil indexes - k.SetHardBorrowRewardIndexes(ctx, rewardPeriod.CollateralType, acc.Indexes) - } -} - -// getHardBorrowTotalSourceShares fetches the sum of all source shares for a borrow reward. -// -// In the case of hard borrow, this is the total borrowed divided by the borrow interest factor (for a particular denom). -// This gives the "pre interest" or "normalized" value of the total borrowed. This is an amount, that if it was borrowed when -// the interest factor was zero (ie at time 0), the current value of it with interest would be equal to the current total borrowed. -// -// The normalized borrow is also used for each individual borrow's source shares amount. Normalized amounts do not change except through -// user input. This is essential as claims must be synced before any change to a source shares amount. The actual borrowed amounts cannot -// be used as they increase every block due to interest. -func (k Keeper) getHardBorrowTotalSourceShares(ctx sdk.Context, denom string) sdk.Dec { - totalBorrowedCoins, found := k.hardKeeper.GetBorrowedCoins(ctx) - if !found { - // assume no coins have been borrowed - totalBorrowedCoins = sdk.NewCoins() - } - totalBorrowed := totalBorrowedCoins.AmountOf(denom) - - interestFactor, found := k.hardKeeper.GetBorrowInterestFactor(ctx, denom) - if !found { - // assume nothing has been borrowed so the factor starts at it's default value - interestFactor = sdk.OneDec() - } - - // return borrowed/factor to get the "pre interest" value of the current total borrowed - return sdk.NewDecFromInt(totalBorrowed).Quo(interestFactor) -} - -// InitializeHardBorrowReward initializes the borrow-side of a hard liquidity provider claim -// by creating the claim and setting the borrow reward factor index -func (k Keeper) InitializeHardBorrowReward(ctx sdk.Context, borrow hardtypes.Borrow) { - claim, found := k.GetHardLiquidityProviderClaim(ctx, borrow.Borrower) - if !found { - claim = types.NewHardLiquidityProviderClaim(borrow.Borrower, sdk.Coins{}, nil, nil) - } - - var borrowRewardIndexes types.MultiRewardIndexes - for _, coin := range borrow.Amount { - globalRewardIndexes, found := k.GetHardBorrowRewardIndexes(ctx, coin.Denom) - if !found { - globalRewardIndexes = types.RewardIndexes{} - } - borrowRewardIndexes = borrowRewardIndexes.With(coin.Denom, globalRewardIndexes) - } - - claim.BorrowRewardIndexes = borrowRewardIndexes - k.SetHardLiquidityProviderClaim(ctx, claim) -} - -// SynchronizeHardBorrowReward updates the claim object by adding any accumulated rewards -// and updating the reward index value -func (k Keeper) SynchronizeHardBorrowReward(ctx sdk.Context, borrow hardtypes.Borrow) { - claim, found := k.GetHardLiquidityProviderClaim(ctx, borrow.Borrower) - if !found { - return - } - - // Source shares for hard borrows is their normalized borrow amount - normalizedBorrows, err := borrow.NormalizedBorrow() - if err != nil { - panic(fmt.Sprintf("during borrow reward sync, could not get normalized borrow for %s: %s", borrow.Borrower, err.Error())) - } - - for _, normedBorrow := range normalizedBorrows { - claim = k.synchronizeSingleHardBorrowReward(ctx, claim, normedBorrow.Denom, normedBorrow.Amount) - } - k.SetHardLiquidityProviderClaim(ctx, claim) -} - -// synchronizeSingleHardBorrowReward synchronizes a single rewarded borrow denom in a hard claim. -// It returns the claim without setting in the store. -// The public methods for accessing and modifying claims are preferred over this one. Direct modification of claims is easy to get wrong. -func (k Keeper) synchronizeSingleHardBorrowReward(ctx sdk.Context, claim types.HardLiquidityProviderClaim, denom string, sourceShares sdk.Dec) types.HardLiquidityProviderClaim { - globalRewardIndexes, found := k.GetHardBorrowRewardIndexes(ctx, denom) - if !found { - // The global factor is only not found if - // - the borrowed denom has not started accumulating rewards yet (either there is no reward specified in params, or the reward start time hasn't been hit) - // - OR it was wrongly deleted from state (factors should never be removed while unsynced claims exist) - // If not found we could either skip this sync, or assume the global factor is zero. - // Skipping will avoid storing unnecessary factors in the claim for non rewarded denoms. - // And in the event a global factor is wrongly deleted, it will avoid this function panicking when calculating rewards. - return claim - } - - userRewardIndexes, found := claim.BorrowRewardIndexes.Get(denom) - if !found { - // Normally the reward indexes should always be found. - // But if a denom was not rewarded then becomes rewarded (ie a reward period is added to params), then the indexes will be missing from claims for that borrowed denom. - // So given the reward period was just added, assume the starting value for any global reward indexes, which is an empty slice. - userRewardIndexes = types.RewardIndexes{} - } - - newRewards, err := k.CalculateRewards(userRewardIndexes, globalRewardIndexes, sourceShares) - if err != nil { - // Global reward factors should never decrease, as it would lead to a negative update to claim.Rewards. - // This panics if a global reward factor decreases or disappears between the old and new indexes. - panic(fmt.Sprintf("corrupted global reward indexes found: %v", err)) - } - - claim.Reward = claim.Reward.Add(newRewards...) - claim.BorrowRewardIndexes = claim.BorrowRewardIndexes.With(denom, globalRewardIndexes) - - return claim -} - -// UpdateHardBorrowIndexDenoms adds or removes reward indexes from a claim to match the denoms in the borrow. -func (k Keeper) UpdateHardBorrowIndexDenoms(ctx sdk.Context, borrow hardtypes.Borrow) { - claim, found := k.GetHardLiquidityProviderClaim(ctx, borrow.Borrower) - if !found { - claim = types.NewHardLiquidityProviderClaim(borrow.Borrower, sdk.Coins{}, nil, nil) - } - - borrowDenoms := getDenoms(borrow.Amount) - borrowRewardIndexDenoms := claim.BorrowRewardIndexes.GetCollateralTypes() - - borrowRewardIndexes := claim.BorrowRewardIndexes - - // Create a new multi-reward index in the claim for every new borrow denom - uniqueBorrowDenoms := setDifference(borrowDenoms, borrowRewardIndexDenoms) - - for _, denom := range uniqueBorrowDenoms { - globalBorrowRewardIndexes, found := k.GetHardBorrowRewardIndexes(ctx, denom) - if !found { - globalBorrowRewardIndexes = types.RewardIndexes{} - } - borrowRewardIndexes = borrowRewardIndexes.With(denom, globalBorrowRewardIndexes) - } - - // Delete multi-reward index from claim if the collateral type is no longer borrowed - uniqueBorrowRewardDenoms := setDifference(borrowRewardIndexDenoms, borrowDenoms) - - for _, denom := range uniqueBorrowRewardDenoms { - borrowRewardIndexes = borrowRewardIndexes.RemoveRewardIndex(denom) - } - - claim.BorrowRewardIndexes = borrowRewardIndexes - k.SetHardLiquidityProviderClaim(ctx, claim) -} - -// CalculateRewards computes how much rewards should have accrued to a reward source (eg a user's hard borrowed btc amount) -// between two index values. -// -// oldIndex is normally the index stored on a claim, newIndex the current global value, and sourceShares a hard borrowed/supplied amount. -// -// It returns an error if newIndexes does not contain all CollateralTypes from oldIndexes, or if any value of oldIndex.RewardFactor > newIndex.RewardFactor. -// This should never happen, as it would mean that a global reward index has decreased in value, or that a global reward index has been deleted from state. -func (k Keeper) CalculateRewards(oldIndexes, newIndexes types.RewardIndexes, sourceShares sdk.Dec) (sdk.Coins, error) { - // check for missing CollateralType's - for _, oldIndex := range oldIndexes { - if newIndex, found := newIndexes.Get(oldIndex.CollateralType); !found { - return nil, errorsmod.Wrapf(types.ErrDecreasingRewardFactor, "old: %v, new: %v", oldIndex, newIndex) - } - } - var reward sdk.Coins - for _, newIndex := range newIndexes { - oldFactor, found := oldIndexes.Get(newIndex.CollateralType) - if !found { - oldFactor = sdk.ZeroDec() - } - - rewardAmount, err := k.CalculateSingleReward(oldFactor, newIndex.RewardFactor, sourceShares) - if err != nil { - return nil, err - } - - reward = reward.Add( - sdk.NewCoin(newIndex.CollateralType, rewardAmount), - ) - } - return reward, nil -} - -// CalculateSingleReward computes how much rewards should have accrued to a reward source (eg a user's btcb-a cdp principal) -// between two index values. -// -// oldIndex is normally the index stored on a claim, newIndex the current global value, and sourceShares a cdp principal amount. -// -// Returns an error if oldIndex > newIndex. This should never happen, as it would mean that a global reward index has decreased in value, -// or that a global reward index has been deleted from state. -func (k Keeper) CalculateSingleReward(oldIndex, newIndex, sourceShares sdk.Dec) (sdkmath.Int, error) { - increase := newIndex.Sub(oldIndex) - if increase.IsNegative() { - return sdkmath.Int{}, errorsmod.Wrapf(types.ErrDecreasingRewardFactor, "old: %v, new: %v", oldIndex, newIndex) - } - reward := increase.Mul(sourceShares).RoundInt() - return reward, nil -} diff --git a/x/incentive/keeper/rewards_borrow_accum_test.go b/x/incentive/keeper/rewards_borrow_accum_test.go deleted file mode 100644 index e4c7fc35..00000000 --- a/x/incentive/keeper/rewards_borrow_accum_test.go +++ /dev/null @@ -1,322 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/incentive/types" -) - -type AccumulateBorrowRewardsTests struct { - unitTester -} - -func (suite *AccumulateBorrowRewardsTests) storedTimeEquals(denom string, expected time.Time) { - storedTime, found := suite.keeper.GetPreviousHardBorrowRewardAccrualTime(suite.ctx, denom) - suite.True(found) - suite.Equal(expected, storedTime) -} - -func (suite *AccumulateBorrowRewardsTests) storedIndexesEqual(denom string, expected types.RewardIndexes) { - storedIndexes, found := suite.keeper.GetHardBorrowRewardIndexes(suite.ctx, denom) - suite.Equal(found, expected != nil) - - if found { - suite.Equal(expected, storedIndexes) - } else { - // Can't compare Equal for types.RewardIndexes(nil) vs types.RewardIndexes{} - suite.Empty(storedIndexes) - } -} - -func TestAccumulateBorrowRewards(t *testing.T) { - suite.Run(t, new(AccumulateBorrowRewardsTests)) -} - -func (suite *AccumulateBorrowRewardsTests) TestStateUpdatedWhenBlockTimeHasIncreased() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalBorrow(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - suite.storeGlobalBorrowIndexes(types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - }) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardBorrowRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(denom, newAccrualTime) - suite.storedIndexesEqual(denom, types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("7.22"), - }, - { - CollateralType: "ukava", - RewardFactor: d("3.64"), - }, - }) -} - -func (suite *AccumulateBorrowRewardsTests) TestStateUnchangedWhenBlockTimeHasNotIncreased() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalBorrow(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalBorrowIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardBorrowRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(denom, previousAccrualTime) - expected, f := previousIndexes.Get(denom) - suite.True(f) - suite.storedIndexesEqual(denom, expected) -} - -func (suite *AccumulateBorrowRewardsTests) TestNoAccumulationWhenSourceSharesAreZero() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper() // zero total borrows - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalBorrowIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardBorrowRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(7 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(denom, firstAccrualTime) - expected, f := previousIndexes.Get(denom) - suite.True(f) - suite.storedIndexesEqual(denom, expected) -} - -func (suite *AccumulateBorrowRewardsTests) TestStateAddedWhenStateDoesNotExist() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalBorrow(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - firstAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, period) - - // After the first accumulation only the current block time should be stored. - // The indexes will be empty as no time has passed since the previous block because it didn't exist. - suite.storedTimeEquals(denom, firstAccrualTime) - suite.storedIndexesEqual(denom, nil) - - secondAccrualTime := firstAccrualTime.Add(10 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(secondAccrualTime) - - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, period) - - // After the second accumulation both current block time and indexes should be stored. - suite.storedTimeEquals(denom, secondAccrualTime) - suite.storedIndexesEqual(denom, types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.01"), - }, - }) -} - -func (suite *AccumulateBorrowRewardsTests) TestNoPanicWhenStateDoesNotExist() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper() - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(), - ) - - accrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(accrualTime) - - // Accumulate with no source shares and no rewards per second will result in no increment to the indexes. - // No increment and no previous indexes stored, results in an updated of nil. Setting this in the state panics. - // Check there is no panic. - suite.NotPanics(func() { - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, period) - }) - - suite.storedTimeEquals(denom, accrualTime) - suite.storedIndexesEqual(denom, nil) -} - -func (suite *AccumulateBorrowRewardsTests) TestNoAccumulationWhenBeforeStartTime() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalBorrow(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalBorrowIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardBorrowRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(10 * time.Second) - - period := types.NewMultiRewardPeriod( - true, - denom, - firstAccrualTime.Add(time.Nanosecond), // start time after accrual time - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, period) - - // The accrual time should be updated, but the indexes unchanged - suite.storedTimeEquals(denom, firstAccrualTime) - expectedIndexes, f := previousIndexes.Get(denom) - suite.True(f) - suite.storedIndexesEqual(denom, expectedIndexes) -} - -func (suite *AccumulateBorrowRewardsTests) TestPanicWhenCurrentTimeLessThanPrevious() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalBorrow(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardBorrowRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - firstAccrualTime := time.Time{} - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Time{}, // start time after accrual time - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.Panics(func() { - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, period) - }) -} diff --git a/x/incentive/keeper/rewards_borrow_init_test.go b/x/incentive/keeper/rewards_borrow_init_test.go deleted file mode 100644 index 4c8f0b58..00000000 --- a/x/incentive/keeper/rewards_borrow_init_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/incentive/types" -) - -// InitializeHardBorrowRewardTests runs unit tests for the keeper.InitializeHardBorrowReward method -type InitializeHardBorrowRewardTests struct { - unitTester -} - -func TestInitializeHardBorrowReward(t *testing.T) { - suite.Run(t, new(InitializeHardBorrowRewardTests)) -} - -func (suite *InitializeHardBorrowRewardTests) TestClaimIndexesAreSetWhenClaimExists() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - // Indexes should always be empty when initialize is called. - // If initialize is called then the user must have repaid their borrow positions, - // which means UpdateHardBorrowIndexDenoms was called and should have remove indexes. - BorrowRewardIndexes: types.MultiRewardIndexes{}, - } - suite.storeHardClaim(claim) - - globalIndexes := nonEmptyMultiRewardIndexes - suite.storeGlobalBorrowIndexes(globalIndexes) - - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.InitializeHardBorrowReward(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *InitializeHardBorrowRewardTests) TestClaimIndexesAreSetWhenClaimDoesNotExist() { - globalIndexes := nonEmptyMultiRewardIndexes - suite.storeGlobalBorrowIndexes(globalIndexes) - - owner := arbitraryAddress() - borrow := NewBorrowBuilder(owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.InitializeHardBorrowReward(suite.ctx, borrow) - - syncedClaim, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, owner) - suite.True(found) - suite.Equal(globalIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *InitializeHardBorrowRewardTests) TestClaimIndexesAreSetEmptyForMissingIndexes() { - globalIndexes := nonEmptyMultiRewardIndexes - suite.storeGlobalBorrowIndexes(globalIndexes) - - owner := arbitraryAddress() - // Borrow a denom that is not in the global indexes. - // This happens when a borrow denom has no rewards associated with it. - expectedIndexes := appendUniqueEmptyMultiRewardIndex(globalIndexes) - borrowedDenoms := extractCollateralTypes(expectedIndexes) - borrow := NewBorrowBuilder(owner). - WithArbitrarySourceShares(borrowedDenoms...). - Build() - - suite.keeper.InitializeHardBorrowReward(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, owner) - suite.Equal(expectedIndexes, syncedClaim.BorrowRewardIndexes) -} diff --git a/x/incentive/keeper/rewards_borrow_sync_test.go b/x/incentive/keeper/rewards_borrow_sync_test.go deleted file mode 100644 index 8f9f9dc3..00000000 --- a/x/incentive/keeper/rewards_borrow_sync_test.go +++ /dev/null @@ -1,568 +0,0 @@ -package keeper_test - -import ( - "errors" - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" - - hardtypes "github.com/kava-labs/kava/x/hard/types" - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/types" -) - -// SynchronizeHardBorrowRewardTests runs unit tests for the keeper.SynchronizeHardBorrowReward method -type SynchronizeHardBorrowRewardTests struct { - unitTester -} - -func TestSynchronizeHardBorrowReward(t *testing.T) { - suite.Run(t, new(SynchronizeHardBorrowRewardTests)) -} - -func (suite *SynchronizeHardBorrowRewardTests) TestClaimIndexesAreUpdatedWhenGlobalIndexesHaveIncreased() { - // This is the normal case - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - BorrowRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - - globalIndexes := increaseAllRewardFactors(nonEmptyMultiRewardIndexes) - suite.storeGlobalBorrowIndexes(globalIndexes) - - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(claim.BorrowRewardIndexes)...). - Build() - - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *SynchronizeHardBorrowRewardTests) TestClaimIndexesAreUnchangedWhenGlobalIndexesUnchanged() { - // It should be safe to call SynchronizeHardBorrowReward multiple times - - unchangingIndexes := nonEmptyMultiRewardIndexes - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - BorrowRewardIndexes: unchangingIndexes, - } - suite.storeHardClaim(claim) - - suite.storeGlobalBorrowIndexes(unchangingIndexes) - - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(unchangingIndexes)...). - Build() - - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(unchangingIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *SynchronizeHardBorrowRewardTests) TestClaimIndexesAreUpdatedWhenNewRewardAdded() { - // When a new reward is added (via gov) for a hard borrow denom the user has already borrowed, and the claim is synced; - // Then the new reward's index should be added to the claim. - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - BorrowRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - - globalIndexes := appendUniqueMultiRewardIndex(nonEmptyMultiRewardIndexes) - suite.storeGlobalBorrowIndexes(globalIndexes) - - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *SynchronizeHardBorrowRewardTests) TestClaimIndexesAreUpdatedWhenNewRewardDenomAdded() { - // When a new reward coin is added (via gov) to an already rewarded borrow denom (that the user has already borrowed), and the claim is synced; - // Then the new reward coin's index should be added to the claim. - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - BorrowRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - - globalIndexes := appendUniqueRewardIndexToFirstItem(nonEmptyMultiRewardIndexes) - suite.storeGlobalBorrowIndexes(globalIndexes) - - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *SynchronizeHardBorrowRewardTests) TestRewardIsIncrementedWhenGlobalIndexesHaveIncreased() { - // This is the normal case - // Given some time has passed (meaning the global indexes have increased) - // When the claim is synced - // The user earns rewards for the time passed - - originalReward := arbitraryCoins() - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - BorrowRewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "borrowdenom", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeHardClaim(claim) - - suite.storeGlobalBorrowIndexes(types.MultiRewardIndexes{ - { - CollateralType: "borrowdenom", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("2000.002"), - }, - }, - }, - }) - - borrow := NewBorrowBuilder(claim.Owner). - WithSourceShares("borrowdenom", 1e9). - Build() - - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - - // new reward is (new index - old index) * borrow amount - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal( - cs(c("rewarddenom", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeHardBorrowRewardTests) TestRewardIsIncrementedWhenNewRewardAdded() { - // When a new reward is added (via gov) for a hard borrow denom the user has already borrowed, and the claim is synced - // Then the user earns rewards for the time since the reward was added - - originalReward := arbitraryCoins() - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - BorrowRewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "rewarded", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeHardClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: "rewarded", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: "newlyrewarded", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalBorrowIndexes(globalIndexes) - - borrow := NewBorrowBuilder(claim.Owner). - WithSourceShares("rewarded", 1e9). - WithSourceShares("newlyrewarded", 1e9). - Build() - - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - - // new reward is (new index - old index) * borrow amount for each borrowed denom - // The old index for `newlyrewarded` isn't in the claim, so it's added starting at 0 for calculating the reward. - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal( - cs(c("otherreward", 1_000_001_000_000), c("reward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeHardBorrowRewardTests) TestRewardIsIncrementedWhenNewRewardDenomAdded() { - // When a new reward coin is added (via gov) to an already rewarded borrow denom (that the user has already borrowed), and the claim is synced; - // Then the user earns rewards for the time since the reward was added - - originalReward := arbitraryCoins() - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - BorrowRewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "borrowed", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeHardClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: "borrowed", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalBorrowIndexes(globalIndexes) - - borrow := NewBorrowBuilder(claim.Owner). - WithSourceShares("borrowed", 1e9). - Build() - - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - - // new reward is (new index - old index) * borrow amount for each borrowed denom - // The old index for `otherreward` isn't in the claim, so it's added starting at 0 for calculating the reward. - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal( - cs(c("reward", 1_000_001_000_000), c("otherreward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -// BorrowBuilder is a tool for creating a hard borrows. -// The builder inherits from hard.Borrow, so fields can be accessed directly if a helper method doesn't exist. -type BorrowBuilder struct { - hardtypes.Borrow -} - -// NewBorrowBuilder creates a BorrowBuilder containing an empty borrow. -func NewBorrowBuilder(borrower sdk.AccAddress) BorrowBuilder { - return BorrowBuilder{ - Borrow: hardtypes.Borrow{ - Borrower: borrower, - }, - } -} - -// Build assembles and returns the final borrow. -func (builder BorrowBuilder) Build() hardtypes.Borrow { return builder.Borrow } - -// WithSourceShares adds a borrow amount and factor such that the source shares for this borrow is equal to specified. -// With a factor of 1, the borrow amount is the source shares. This picks an arbitrary factor to ensure factors are accounted for in production code. -func (builder BorrowBuilder) WithSourceShares(denom string, shares int64) BorrowBuilder { - if !builder.Amount.AmountOf(denom).Equal(sdk.ZeroInt()) { - panic("adding to amount with existing denom not implemented") - } - if _, f := builder.Index.GetInterestFactor(denom); f { - panic("adding to indexes with existing denom not implemented") - } - - // pick arbitrary factor - factor := sdk.MustNewDecFromStr("2") - - // Calculate borrow amount that would equal the requested source shares given the above factor. - amt := sdkmath.NewInt(shares).Mul(factor.RoundInt()) - - builder.Amount = builder.Amount.Add(sdk.NewCoin(denom, amt)) - builder.Index = builder.Index.SetInterestFactor(denom, factor) - return builder -} - -// WithArbitrarySourceShares adds arbitrary borrow amounts and indexes for each specified denom. -func (builder BorrowBuilder) WithArbitrarySourceShares(denoms ...string) BorrowBuilder { - const arbitraryShares = 1e9 - for _, denom := range denoms { - builder = builder.WithSourceShares(denom, arbitraryShares) - } - return builder -} - -func TestCalculateRewards(t *testing.T) { - type expected struct { - err error - coins sdk.Coins - } - type args struct { - oldIndexes, newIndexes types.RewardIndexes - sourceAmount sdk.Dec - } - testcases := []struct { - name string - args args - expected expected - }{ - { - name: "when old and new indexes have same denoms, rewards are calculated correctly", - args: args{ - oldIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.000000001"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.1"), - }, - }, - newIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("1000.0"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.100000001"), - }, - }, - sourceAmount: d("1000000000"), - }, - expected: expected{ - // for each denom: (new - old) * sourceAmount - coins: cs(c("hard", 999999999999), c("ukava", 1)), - }, - }, - { - name: "when new indexes have an extra denom, rewards are calculated as if it was 0 in old indexes", - args: args{ - oldIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.000000001"), - }, - }, - newIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("1000.0"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.100000001"), - }, - }, - sourceAmount: d("1000000000"), - }, - expected: expected{ - // for each denom: (new - old) * sourceAmount - coins: cs(c("hard", 999999999999), c("ukava", 100000001)), - }, - }, - { - name: "when new indexes are smaller than old, an error is returned", - args: args{ - oldIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.2"), - }, - }, - newIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.1"), - }, - }, - sourceAmount: d("1000000000"), - }, - expected: expected{ - err: types.ErrDecreasingRewardFactor, - }, - }, - { - name: "when old indexes have an extra denom, an error is returned", - args: args{ - oldIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.1"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.1"), - }, - }, - newIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.2"), - }, - }, - sourceAmount: d("1000000000"), - }, - expected: expected{ - err: types.ErrDecreasingRewardFactor, - }, - }, - { - name: "when old and new indexes are 0, rewards are 0", - args: args{ - oldIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.0"), - }, - }, - newIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.0"), - }, - }, - sourceAmount: d("1000000000"), - }, - expected: expected{ - coins: sdk.Coins{}, - }, - }, - { - name: "when old and new indexes are empty, rewards are 0", - args: args{ - oldIndexes: types.RewardIndexes{}, - newIndexes: nil, - sourceAmount: d("1000000000"), - }, - expected: expected{ - coins: nil, - }, - }, - } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - coins, err := keeper.Keeper{}.CalculateRewards(tc.args.oldIndexes, tc.args.newIndexes, tc.args.sourceAmount) - if tc.expected.err != nil { - require.True(t, errors.Is(err, tc.expected.err)) - } else { - require.Equal(t, tc.expected.coins, coins) - } - }) - } -} - -func TestCalculateSingleReward(t *testing.T) { - type expected struct { - err error - reward sdkmath.Int - } - type args struct { - oldIndex, newIndex sdk.Dec - sourceAmount sdk.Dec - } - testcases := []struct { - name string - args args - expected expected - }{ - { - name: "when new index is > old, rewards are calculated correctly", - args: args{ - oldIndex: d("0.000000001"), - newIndex: d("1000.0"), - sourceAmount: d("1000000000"), - }, - expected: expected{ - // (new - old) * sourceAmount - reward: i(999999999999), - }, - }, - { - name: "when new index is < old, an error is returned", - args: args{ - oldIndex: d("0.000000001"), - newIndex: d("0.0"), - sourceAmount: d("1000000000"), - }, - expected: expected{ - err: types.ErrDecreasingRewardFactor, - }, - }, - { - name: "when old and new indexes are 0, rewards are 0", - args: args{ - oldIndex: d("0.0"), - newIndex: d("0.0"), - sourceAmount: d("1000000000"), - }, - expected: expected{ - reward: sdk.ZeroInt(), - }, - }, - } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - reward, err := keeper.Keeper{}.CalculateSingleReward(tc.args.oldIndex, tc.args.newIndex, tc.args.sourceAmount) - if tc.expected.err != nil { - require.True(t, errors.Is(err, tc.expected.err)) - } else { - require.Equal(t, tc.expected.reward, reward) - } - }) - } -} diff --git a/x/incentive/keeper/rewards_borrow_test.go b/x/incentive/keeper/rewards_borrow_test.go deleted file mode 100644 index c76dd2ff..00000000 --- a/x/incentive/keeper/rewards_borrow_test.go +++ /dev/null @@ -1,1073 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - proposaltypes "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/committee" - committeekeeper "github.com/kava-labs/kava/x/committee/keeper" - committeetypes "github.com/kava-labs/kava/x/committee/types" - "github.com/kava-labs/kava/x/hard" - hardkeeper "github.com/kava-labs/kava/x/hard/keeper" - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/testutil" - "github.com/kava-labs/kava/x/incentive/types" - kavadisttypes "github.com/kava-labs/kava/x/kavadist/types" -) - -type BorrowIntegrationTests struct { - testutil.IntegrationTester - - genesisTime time.Time - addrs []sdk.AccAddress -} - -func TestBorrowIntegration(t *testing.T) { - suite.Run(t, new(BorrowIntegrationTests)) -} - -// SetupTest is run automatically before each suite test -func (suite *BorrowIntegrationTests) SetupTest() { - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *BorrowIntegrationTests) TestSingleUserAccumulatesRewardsAfterSyncing() { - userA := suite.addrs[0] - - authBulder := app.NewAuthBankGenesisBuilder(). - WithSimpleModuleAccount(kavadisttypes.ModuleName, cs(c("hard", 1e18))). // Fill kavadist with enough coins to pay out any reward - WithSimpleAccount(userA, cs(c("bnb", 1e12))) // give the user some coins - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithMultipliers(types.MultipliersPerDenoms{{ - Denom: "hard", - Multipliers: types.Multipliers{types.NewMultiplier("large", 12, d("1.0"))}, // keep payout at 1.0 to make maths easier - }}). - WithSimpleBorrowRewardPeriod("bnb", cs(c("hard", 1e6))) // only borrow rewards - - suite.SetApp() - suite.WithGenesisTime(suite.genesisTime) - suite.StartChain( - NewPricefeedGenStateMultiFromTime(suite.App.AppCodec(), suite.genesisTime), - NewHardGenStateMulti(suite.genesisTime).BuildMarshalled(suite.App.AppCodec()), - authBulder.BuildMarshalled(suite.App.AppCodec()), - incentBuilder.BuildMarshalled(suite.App.AppCodec()), - ) - - // Create a borrow (need to first deposit to allow it) - suite.NoError(suite.DeliverHardMsgDeposit(userA, cs(c("bnb", 1e11)))) - suite.NoError(suite.DeliverHardMsgBorrow(userA, cs(c("bnb", 1e10)))) - - // Let time pass to accumulate interest on the borrow - // Use one long block instead of many to reduce any rounding errors, and speed up tests. - suite.NextBlockAfter(1e6 * time.Second) // about 12 days - - // User borrows and repays just to sync their borrow. - suite.NoError(suite.DeliverHardMsgRepay(userA, cs(c("bnb", 1)))) - suite.NoError(suite.DeliverHardMsgBorrow(userA, cs(c("bnb", 1)))) - - // Accumulate more rewards. - // The user still has the same percentage of all borrows (100%) so their rewards should be the same as in the previous block. - suite.NextBlockAfter(1e6 * time.Second) // about 12 days - - msg := types.NewMsgClaimHardReward(userA.String(), types.Selections{ - types.NewSelection("hard", "large"), - }) - - // User claims all their rewards - suite.Require().NoError(suite.DeliverIncentiveMsg(&msg)) - - // The users has always had 100% of borrows, so they should receive all rewards for the previous two blocks. - // Total rewards for each block is block duration * rewards per second - accuracy := 1e-10 // using a very high accuracy to flag future small calculation changes - suite.BalanceInEpsilon(userA, cs(c("bnb", 1e12-1e11+1e10), c("hard", 2*1e6*1e6)), accuracy) -} - -// Test suite used for all keeper tests -type BorrowRewardsTestSuite struct { - suite.Suite - - keeper keeper.Keeper - hardKeeper hardkeeper.Keeper - committeeKeeper committeekeeper.Keeper - - app app.TestApp - ctx sdk.Context - - genesisTime time.Time - addrs []sdk.AccAddress -} - -// SetupTest is run automatically before each suite test -func (suite *BorrowRewardsTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *BorrowRewardsTestSuite) SetupApp() { - suite.app = app.NewTestApp() - - suite.keeper = suite.app.GetIncentiveKeeper() - suite.hardKeeper = suite.app.GetHardKeeper() - suite.committeeKeeper = suite.app.GetCommitteeKeeper() - - suite.ctx = suite.app.NewContext(true, tmproto.Header{Height: 1, Time: suite.genesisTime}) -} - -func (suite *BorrowRewardsTestSuite) SetupWithGenState(authBuilder *app.AuthBankGenesisBuilder, incentBuilder testutil.IncentiveGenesisBuilder, hardBuilder testutil.HardGenesisBuilder) { - suite.SetupApp() - - suite.app.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - authBuilder.BuildMarshalled(suite.app.AppCodec()), - NewPricefeedGenStateMultiFromTime(suite.app.AppCodec(), suite.genesisTime), - hardBuilder.BuildMarshalled(suite.app.AppCodec()), - NewCommitteeGenesisState(suite.app.AppCodec(), 1, suite.addrs[:2]...), - incentBuilder.BuildMarshalled(suite.app.AppCodec()), - ) -} - -func (suite *BorrowRewardsTestSuite) TestAccumulateHardBorrowRewards() { - type args struct { - borrow sdk.Coin - rewardsPerSecond sdk.Coins - timeElapsed int - expectedRewardIndexes types.RewardIndexes - } - type test struct { - name string - args args - } - testCases := []test{ - { - "single reward denom: 7 seconds", - args{ - borrow: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 7, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.000000856478000001"))}, - }, - }, - { - "single reward denom: 1 day", - args{ - borrow: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 86400, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.010571385600010177"))}, - }, - }, - { - "single reward denom: 0 seconds", - args{ - borrow: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 0, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.0"))}, - }, - }, - { - "multiple reward denoms: 7 seconds", - args{ - borrow: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - timeElapsed: 7, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.000000856478000001")), - types.NewRewardIndex("ukava", d("0.000000856478000001")), - }, - }, - }, - { - "multiple reward denoms: 1 day", - args{ - borrow: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - timeElapsed: 86400, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.010571385600010177")), - types.NewRewardIndex("ukava", d("0.010571385600010177")), - }, - }, - }, - { - "multiple reward denoms: 0 seconds", - args{ - borrow: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - timeElapsed: 0, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - types.NewRewardIndex("ukava", d("0.0")), - }, - }, - }, - { - "multiple reward denoms with different rewards per second: 1 day", - args{ - borrow: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 555555)), - timeElapsed: 86400, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.010571385600010177")), - types.NewRewardIndex("ukava", d("0.047999952000046210")), - }, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount( - userAddr, - cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15)), - ) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleBorrowRewardPeriod(tc.args.borrow.Denom, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // User deposits and borrows to increase total borrowed amount - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, sdk.NewCoins(sdk.NewCoin(tc.args.borrow.Denom, tc.args.borrow.Amount.Mul(sdkmath.NewInt(2))))) - suite.Require().NoError(err) - err = suite.hardKeeper.Borrow(suite.ctx, userAddr, sdk.NewCoins(tc.args.borrow)) - suite.Require().NoError(err) - - // Set up chain context at future time - runAtTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - runCtx := suite.ctx.WithBlockTime(runAtTime) - - // Run Hard begin blocker in order to update the denom's index factor - hard.BeginBlocker(runCtx, suite.hardKeeper) - - // Accumulate hard borrow rewards for the deposit denom - multiRewardPeriod, found := suite.keeper.GetHardBorrowRewardPeriods(runCtx, tc.args.borrow.Denom) - suite.Require().True(found) - suite.keeper.AccumulateHardBorrowRewards(runCtx, multiRewardPeriod) - - // Check that each expected reward index matches the current stored reward index for the denom - globalRewardIndexes, found := suite.keeper.GetHardBorrowRewardIndexes(runCtx, tc.args.borrow.Denom) - suite.Require().True(found) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - globalRewardIndex, found := globalRewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, globalRewardIndex) - } - }) - } -} - -func (suite *BorrowRewardsTestSuite) TestInitializeHardBorrowRewards() { - type args struct { - moneyMarketRewardDenoms map[string]sdk.Coins - deposit sdk.Coins - borrow sdk.Coins - expectedClaimBorrowRewardIndexes types.MultiRewardIndexes - } - type test struct { - name string - args args - } - - standardMoneyMarketRewardDenoms := map[string]sdk.Coins{ - "bnb": cs(c("hard", 1)), - "btcb": cs(c("hard", 1), c("ukava", 1)), - } - - testCases := []test{ - { - "single deposit denom, single reward denom", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("bnb", 1000000000000)), - borrow: cs(c("bnb", 100000000000)), - expectedClaimBorrowRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "bnb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - }, - ), - }, - }, - }, - { - "single deposit denom, multiple reward denoms", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("btcb", 1000000000000)), - borrow: cs(c("btcb", 100000000000)), - expectedClaimBorrowRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "btcb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - types.NewRewardIndex("ukava", d("0.0")), - }, - ), - }, - }, - }, - { - "single deposit denom, no reward denoms", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("xrp", 1000000000000)), - borrow: cs(c("xrp", 100000000000)), - expectedClaimBorrowRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "xrp", - nil, - ), - }, - }, - }, - { - "multiple deposit denoms, multiple overlapping reward denoms", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("bnb", 1000000000000), c("btcb", 1000000000000)), - borrow: cs(c("bnb", 100000000000), c("btcb", 100000000000)), - expectedClaimBorrowRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "bnb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - }, - ), - types.NewMultiRewardIndex( - "btcb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - types.NewRewardIndex("ukava", d("0.0")), - }, - ), - }, - }, - }, - { - "multiple deposit denoms, correct discrete reward denoms", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("bnb", 1000000000000), c("xrp", 1000000000000)), - borrow: cs(c("bnb", 100000000000), c("xrp", 100000000000)), - expectedClaimBorrowRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "bnb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - }, - ), - types.NewMultiRewardIndex( - "xrp", - nil, - ), - }, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount( - userAddr, - cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15)), - ) - - incentBuilder := testutil.NewIncentiveGenesisBuilder().WithGenesisTime(suite.genesisTime) - for moneyMarketDenom, rewardsPerSecond := range tc.args.moneyMarketRewardDenoms { - incentBuilder = incentBuilder.WithSimpleBorrowRewardPeriod(moneyMarketDenom, rewardsPerSecond) - } - - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // User deposits - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, tc.args.deposit) - suite.Require().NoError(err) - // User borrows - err = suite.hardKeeper.Borrow(suite.ctx, userAddr, tc.args.borrow) - suite.Require().NoError(err) - - claim, foundClaim := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(foundClaim) - suite.Require().Equal(tc.args.expectedClaimBorrowRewardIndexes, claim.BorrowRewardIndexes) - }) - } -} - -func (suite *BorrowRewardsTestSuite) TestSynchronizeHardBorrowReward() { - type args struct { - incentiveBorrowRewardDenom string - borrow sdk.Coin - rewardsPerSecond sdk.Coins - blockTimes []int - expectedRewardIndexes types.RewardIndexes - expectedRewards sdk.Coins - updateRewardsViaCommmittee bool - updatedBaseDenom string - updatedRewardsPerSecond sdk.Coins - updatedExpectedRewardIndexes types.RewardIndexes - updatedExpectedRewards sdk.Coins - updatedTimeDuration int - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "single reward denom: 10 blocks", - args{ - incentiveBorrowRewardDenom: "bnb", - borrow: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.001223540000173228"))}, - expectedRewards: cs(c("hard", 12235400)), - updateRewardsViaCommmittee: false, - }, - }, - { - "single reward denom: 10 blocks - long block time", - args{ - incentiveBorrowRewardDenom: "bnb", - borrow: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("10.571385603126235340"))}, - expectedRewards: cs(c("hard", 105713856031)), - }, - }, - { - "single reward denom: user reward index updated when reward is zero", - args{ - incentiveBorrowRewardDenom: "ukava", - borrow: c("ukava", 1), // borrow a tiny amount so that rewards round to zero - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.122354003908172328"))}, - expectedRewards: cs(), - updateRewardsViaCommmittee: false, - }, - }, - { - "multiple reward denoms: 10 blocks", - args{ - incentiveBorrowRewardDenom: "bnb", - borrow: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.001223540000173228")), - types.NewRewardIndex("ukava", d("0.001223540000173228")), - }, - expectedRewards: cs(c("hard", 12235400), c("ukava", 12235400)), - }, - }, - { - "multiple reward denoms: 10 blocks - long block time", - args{ - incentiveBorrowRewardDenom: "bnb", - borrow: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("10.571385603126235340")), - types.NewRewardIndex("ukava", d("10.571385603126235340")), - }, - expectedRewards: cs(c("hard", 105713856031), c("ukava", 105713856031)), - }, - }, - { - "multiple reward denoms with different rewards per second: 10 blocks", - args{ - incentiveBorrowRewardDenom: "bnb", - borrow: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 555555)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.001223540000173228")), - types.NewRewardIndex("ukava", d("0.005555550000786558")), - }, - expectedRewards: cs(c("hard", 12235400), c("ukava", 55555500)), - }, - }, - { - "denom is in incentive's hard borrow reward params and has rewards; add new reward type", - args{ - incentiveBorrowRewardDenom: "bnb", - borrow: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{86400}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("1.057138560060101160")), - }, - expectedRewards: cs(c("hard", 10571385601)), - updateRewardsViaCommmittee: true, - updatedBaseDenom: "bnb", - updatedRewardsPerSecond: cs(c("hard", 122354), c("ukava", 100000)), - updatedExpectedRewards: cs(c("hard", 21142771202), c("ukava", 8640000000)), - updatedExpectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("2.114277120120202320")), - types.NewRewardIndex("ukava", d("0.864000000049120715")), - }, - updatedTimeDuration: 86400, - }, - }, - { - "denom is in hard's money market params but not in incentive's hard supply reward params; add reward", - args{ - incentiveBorrowRewardDenom: "bnb", - borrow: c("zzz", 10000000000), - rewardsPerSecond: nil, - blockTimes: []int{100}, - expectedRewardIndexes: types.RewardIndexes{}, - expectedRewards: sdk.Coins{}, - updateRewardsViaCommmittee: true, - updatedBaseDenom: "zzz", - updatedRewardsPerSecond: cs(c("hard", 100000)), - updatedExpectedRewards: cs(c("hard", 8640000000)), - updatedExpectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.864000000049803065")), - }, - updatedTimeDuration: 86400, - }, - }, - { - "denom is in hard's money market params but not in incentive's hard supply reward params; add multiple reward types", - args{ - incentiveBorrowRewardDenom: "bnb", - borrow: c("zzz", 10000000000), - rewardsPerSecond: nil, - blockTimes: []int{100}, - expectedRewardIndexes: types.RewardIndexes{}, - expectedRewards: sdk.Coins{}, - updateRewardsViaCommmittee: true, - updatedBaseDenom: "zzz", - updatedRewardsPerSecond: cs(c("hard", 100000), c("ukava", 100500), c("swap", 500)), - updatedExpectedRewards: cs(c("hard", 8640000000), c("ukava", 8683200001), c("swap", 43200000)), - updatedExpectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.864000000049803065")), - types.NewRewardIndex("ukava", d("0.868320000050052081")), - types.NewRewardIndex("swap", d("0.004320000000249015")), - }, - updatedTimeDuration: 86400, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[2], cs(c("ukava", 1e9))). - WithSimpleAccount(userAddr, cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15))) - - incentBuilder := testutil.NewIncentiveGenesisBuilder().WithGenesisTime(suite.genesisTime) - if tc.args.rewardsPerSecond != nil { - incentBuilder = incentBuilder.WithSimpleBorrowRewardPeriod(tc.args.incentiveBorrowRewardDenom, tc.args.rewardsPerSecond) - } - // Set the minimum borrow to 0 to allow testing small borrows - hardBuilder := NewHardGenStateMulti(suite.genesisTime).WithMinBorrow(sdk.ZeroDec()) - - suite.SetupWithGenState(authBuilder, incentBuilder, hardBuilder) - - // Borrow a fixed amount from another user to dilute primary user's rewards per second. - suite.Require().NoError( - suite.hardKeeper.Deposit(suite.ctx, suite.addrs[2], cs(c("ukava", 200_000_000))), - ) - suite.Require().NoError( - suite.hardKeeper.Borrow(suite.ctx, suite.addrs[2], cs(c("ukava", 100_000_000))), - ) - - // User deposits and borrows to increase total borrowed amount - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, sdk.NewCoins(sdk.NewCoin(tc.args.borrow.Denom, tc.args.borrow.Amount.Mul(sdkmath.NewInt(2))))) - suite.Require().NoError(err) - err = suite.hardKeeper.Borrow(suite.ctx, userAddr, sdk.NewCoins(tc.args.borrow)) - suite.Require().NoError(err) - - // Check that Hard hooks initialized a HardLiquidityProviderClaim - claim, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - multiRewardIndex, _ := claim.BorrowRewardIndexes.GetRewardIndex(tc.args.borrow.Denom) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - currRewardIndex, found := multiRewardIndex.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(sdk.ZeroDec(), currRewardIndex.RewardFactor) - } - - // Run accumulator at several intervals - var timeElapsed int - previousBlockTime := suite.ctx.BlockTime() - for _, t := range tc.args.blockTimes { - timeElapsed += t - updatedBlockTime := previousBlockTime.Add(time.Duration(int(time.Second) * t)) - previousBlockTime = updatedBlockTime - blockCtx := suite.ctx.WithBlockTime(updatedBlockTime) - - // Run Hard begin blocker for each block ctx to update denom's interest factor - hard.BeginBlocker(blockCtx, suite.hardKeeper) - - // Accumulate hard borrow-side rewards - multiRewardPeriod, found := suite.keeper.GetHardBorrowRewardPeriods(blockCtx, tc.args.borrow.Denom) - if found { - suite.keeper.AccumulateHardBorrowRewards(blockCtx, multiRewardPeriod) - } - } - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - - // After we've accumulated, run synchronize - borrow, found := suite.hardKeeper.GetBorrow(suite.ctx, userAddr) - suite.Require().True(found) - suite.Require().NotPanics(func() { - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - }) - - // Check that the global reward index's reward factor and user's claim have been updated as expected - claim, found = suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - globalRewardIndexes, foundGlobalRewardIndexes := suite.keeper.GetHardBorrowRewardIndexes(suite.ctx, tc.args.borrow.Denom) - if len(tc.args.rewardsPerSecond) > 0 { - suite.Require().True(foundGlobalRewardIndexes) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - // Check that global reward index has been updated as expected - globalRewardIndex, found := globalRewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, globalRewardIndex) - - // Check that the user's claim's reward index matches the corresponding global reward index - multiRewardIndex, found := claim.BorrowRewardIndexes.GetRewardIndex(tc.args.borrow.Denom) - suite.Require().True(found) - rewardIndex, found := multiRewardIndex.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, rewardIndex) - - // Check that the user's claim holds the expected amount of reward coins - suite.Require().Equal( - tc.args.expectedRewards.AmountOf(expectedRewardIndex.CollateralType), - claim.Reward.AmountOf(expectedRewardIndex.CollateralType), - ) - } - } - - // Only test cases with reward param updates continue past this point - if !tc.args.updateRewardsViaCommmittee { - return - } - - // If are no initial rewards per second, add new rewards through a committee param change - // 1. Construct incentive's new HardBorrowRewardPeriods param - currIncentiveHardBorrowRewardPeriods := suite.keeper.GetParams(suite.ctx).HardBorrowRewardPeriods - multiRewardPeriod, found := currIncentiveHardBorrowRewardPeriods.GetMultiRewardPeriod(tc.args.borrow.Denom) - if found { - // Borrow denom's reward period exists, but it doesn't have any rewards per second - index, found := currIncentiveHardBorrowRewardPeriods.GetMultiRewardPeriodIndex(tc.args.borrow.Denom) - suite.Require().True(found) - multiRewardPeriod.RewardsPerSecond = tc.args.updatedRewardsPerSecond - currIncentiveHardBorrowRewardPeriods[index] = multiRewardPeriod - } else { - // Borrow denom's reward period does not exist - _, found := currIncentiveHardBorrowRewardPeriods.GetMultiRewardPeriodIndex(tc.args.borrow.Denom) - suite.Require().False(found) - newMultiRewardPeriod := types.NewMultiRewardPeriod(true, tc.args.borrow.Denom, suite.genesisTime, suite.genesisTime.Add(time.Hour*24*365*4), tc.args.updatedRewardsPerSecond) - currIncentiveHardBorrowRewardPeriods = append(currIncentiveHardBorrowRewardPeriods, newMultiRewardPeriod) - } - - // 2. Construct the parameter change proposal to update HardBorrowRewardPeriods param - pubProposal := proposaltypes.NewParameterChangeProposal( - "Update hard borrow rewards", "Adds a new reward coin to the incentive module's hard borrow rewards.", - []proposaltypes.ParamChange{ - { - Subspace: types.ModuleName, // target incentive module - Key: string(types.KeyHardBorrowRewardPeriods), // target hard borrow rewards key - Value: string(suite.app.LegacyAmino().MustMarshalJSON(currIncentiveHardBorrowRewardPeriods)), - }, - }, - ) - - // 3. Ensure proposal is properly formed - err = suite.committeeKeeper.ValidatePubProposal(suite.ctx, pubProposal) - suite.Require().NoError(err) - - // 4. Committee creates proposal - committeeMemberOne := suite.addrs[0] - committeeMemberTwo := suite.addrs[1] - proposalID, err := suite.committeeKeeper.SubmitProposal(suite.ctx, committeeMemberOne, 1, pubProposal) - suite.Require().NoError(err) - - // 5. Committee votes and passes proposal - err = suite.committeeKeeper.AddVote(suite.ctx, proposalID, committeeMemberOne, committeetypes.VOTE_TYPE_YES) - suite.Require().NoError(err) - err = suite.committeeKeeper.AddVote(suite.ctx, proposalID, committeeMemberTwo, committeetypes.VOTE_TYPE_YES) - suite.Require().NoError(err) - - // 6. Check proposal passed - com, found := suite.committeeKeeper.GetCommittee(suite.ctx, 1) - suite.Require().True(found) - proposalPasses := suite.committeeKeeper.GetProposalResult(suite.ctx, proposalID, com) - suite.Require().NoError(err) - suite.Require().True(proposalPasses) - - // 7. Run committee module's begin blocker to enact proposal - suite.NotPanics(func() { - committee.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}, suite.committeeKeeper) - }) - - // We need to accumulate hard supply-side rewards again - multiRewardPeriod, found = suite.keeper.GetHardBorrowRewardPeriods(suite.ctx, tc.args.borrow.Denom) - suite.Require().True(found) - - // But new borrow denoms don't have their PreviousHardBorrowRewardAccrualTime set yet, - // so we need to call the accumulation method once to set the initial reward accrual time - if tc.args.borrow.Denom != tc.args.incentiveBorrowRewardDenom { - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, multiRewardPeriod) - } - - // Now we can jump forward in time and accumulate rewards - updatedBlockTime = previousBlockTime.Add(time.Duration(int(time.Second) * tc.args.updatedTimeDuration)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, multiRewardPeriod) - - // After we've accumulated, run synchronize - borrow, found = suite.hardKeeper.GetBorrow(suite.ctx, userAddr) - suite.Require().True(found) - suite.Require().NotPanics(func() { - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - }) - - // Check that the global reward index's reward factor and user's claim have been updated as expected - globalRewardIndexes, found = suite.keeper.GetHardBorrowRewardIndexes(suite.ctx, tc.args.borrow.Denom) - suite.Require().True(found) - claim, found = suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - - for _, expectedRewardIndex := range tc.args.updatedExpectedRewardIndexes { - // Check that global reward index has been updated as expected - globalRewardIndex, found := globalRewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, globalRewardIndex) - // Check that the user's claim's reward index matches the corresponding global reward index - multiRewardIndex, found := claim.BorrowRewardIndexes.GetRewardIndex(tc.args.borrow.Denom) - suite.Require().True(found) - rewardIndex, found := multiRewardIndex.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, rewardIndex) - - // Check that the user's claim holds the expected amount of reward coins - suite.Require().Equal( - tc.args.updatedExpectedRewards.AmountOf(expectedRewardIndex.CollateralType), - claim.Reward.AmountOf(expectedRewardIndex.CollateralType), - ) - } - }) - } -} - -func (suite *BorrowRewardsTestSuite) TestUpdateHardBorrowIndexDenoms() { - type withdrawModification struct { - coins sdk.Coins - repay bool - } - - type args struct { - initialDeposit sdk.Coins - firstBorrow sdk.Coins - modification withdrawModification - rewardsPerSecond sdk.Coins - expectedBorrowIndexDenoms []string - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "single reward denom: update adds one borrow reward index", - args{ - initialDeposit: cs(c("bnb", 10000000000)), - firstBorrow: cs(c("bnb", 50000000)), - modification: withdrawModification{coins: cs(c("ukava", 500000000))}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedBorrowIndexDenoms: []string{"bnb", "ukava"}, - }, - }, - { - "single reward denom: update adds multiple borrow supply reward indexes", - args{ - initialDeposit: cs(c("btcb", 10000000000)), - firstBorrow: cs(c("btcb", 50000000)), - modification: withdrawModification{coins: cs(c("ukava", 500000000), c("bnb", 50000000000), c("xrp", 50000000000))}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedBorrowIndexDenoms: []string{"btcb", "ukava", "bnb", "xrp"}, - }, - }, - { - "single reward denom: update doesn't add duplicate borrow reward index for same denom", - args{ - initialDeposit: cs(c("bnb", 100000000000)), - firstBorrow: cs(c("bnb", 50000000)), - modification: withdrawModification{coins: cs(c("bnb", 50000000000))}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedBorrowIndexDenoms: []string{"bnb"}, - }, - }, - { - "multiple reward denoms: update adds one borrow reward index", - args{ - initialDeposit: cs(c("bnb", 10000000000)), - firstBorrow: cs(c("bnb", 50000000)), - modification: withdrawModification{coins: cs(c("ukava", 500000000))}, - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - expectedBorrowIndexDenoms: []string{"bnb", "ukava"}, - }, - }, - { - "multiple reward denoms: update adds multiple borrow supply reward indexes", - args{ - initialDeposit: cs(c("btcb", 10000000000)), - firstBorrow: cs(c("btcb", 50000000)), - modification: withdrawModification{coins: cs(c("ukava", 500000000), c("bnb", 50000000000), c("xrp", 50000000000))}, - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - expectedBorrowIndexDenoms: []string{"btcb", "ukava", "bnb", "xrp"}, - }, - }, - { - "multiple reward denoms: update doesn't add duplicate borrow reward index for same denom", - args{ - initialDeposit: cs(c("bnb", 100000000000)), - firstBorrow: cs(c("bnb", 50000000)), - modification: withdrawModification{coins: cs(c("bnb", 50000000000))}, - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - expectedBorrowIndexDenoms: []string{"bnb"}, - }, - }, - { - "single reward denom: fully repaying a denom deletes the denom's supply reward index", - args{ - initialDeposit: cs(c("bnb", 1000000000)), - firstBorrow: cs(c("bnb", 100000000)), - modification: withdrawModification{coins: cs(c("bnb", 1100000000)), repay: true}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedBorrowIndexDenoms: []string{}, - }, - }, - { - "single reward denom: fully repaying a denom deletes only the denom's supply reward index", - args{ - initialDeposit: cs(c("bnb", 1000000000)), - firstBorrow: cs(c("bnb", 100000000), c("ukava", 10000000)), - modification: withdrawModification{coins: cs(c("bnb", 1100000000)), repay: true}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedBorrowIndexDenoms: []string{"ukava"}, - }, - }, - { - "multiple reward denoms: fully repaying a denom deletes the denom's supply reward index", - args{ - initialDeposit: cs(c("bnb", 1000000000)), - firstBorrow: cs(c("bnb", 100000000), c("ukava", 10000000)), - modification: withdrawModification{coins: cs(c("bnb", 1100000000)), repay: true}, - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - expectedBorrowIndexDenoms: []string{"ukava"}, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount( - userAddr, - cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15)), - ). - WithSimpleAccount( - suite.addrs[0], - cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15)), - ) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleBorrowRewardPeriod("bnb", tc.args.rewardsPerSecond). - WithSimpleBorrowRewardPeriod("ukava", tc.args.rewardsPerSecond). - WithSimpleBorrowRewardPeriod("btcb", tc.args.rewardsPerSecond). - WithSimpleBorrowRewardPeriod("xrp", tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // Fill the hard supply to allow user to borrow - err := suite.hardKeeper.Deposit(suite.ctx, suite.addrs[0], tc.args.firstBorrow.Add(tc.args.modification.coins...)) - suite.Require().NoError(err) - - // User deposits initial funds (so that user can borrow) - err = suite.hardKeeper.Deposit(suite.ctx, userAddr, tc.args.initialDeposit) - suite.Require().NoError(err) - - // Confirm that claim exists but no borrow reward indexes have been added - claimAfterDeposit, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - suite.Require().Equal(0, len(claimAfterDeposit.BorrowRewardIndexes)) - - // User borrows (first time) - err = suite.hardKeeper.Borrow(suite.ctx, userAddr, tc.args.firstBorrow) - suite.Require().NoError(err) - - // Confirm that claim's borrow reward indexes have been updated - claimAfterFirstBorrow, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - for _, coin := range tc.args.firstBorrow { - _, hasIndex := claimAfterFirstBorrow.HasBorrowRewardIndex(coin.Denom) - suite.Require().True(hasIndex) - } - suite.Require().True(len(claimAfterFirstBorrow.BorrowRewardIndexes) == len(tc.args.firstBorrow)) - - // User modifies their Borrow by either repaying or borrowing more - if tc.args.modification.repay { - err = suite.hardKeeper.Repay(suite.ctx, userAddr, userAddr, tc.args.modification.coins) - } else { - err = suite.hardKeeper.Borrow(suite.ctx, userAddr, tc.args.modification.coins) - } - suite.Require().NoError(err) - - // Confirm that claim's borrow reward indexes contain expected values - claimAfterModification, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - for _, coin := range tc.args.modification.coins { - _, hasIndex := claimAfterModification.HasBorrowRewardIndex(coin.Denom) - if tc.args.modification.repay { - // Only false if denom is repaid in full - if tc.args.modification.coins.AmountOf(coin.Denom).GTE(tc.args.firstBorrow.AmountOf(coin.Denom)) { - suite.Require().False(hasIndex) - } - } else { - suite.Require().True(hasIndex) - } - } - suite.Require().True(len(claimAfterModification.BorrowRewardIndexes) == len(tc.args.expectedBorrowIndexDenoms)) - }) - } -} - -func (suite *BorrowRewardsTestSuite) TestSimulateHardBorrowRewardSynchronization() { - type args struct { - borrow sdk.Coin - rewardsPerSecond sdk.Coins - blockTimes []int - expectedRewardIndexes types.RewardIndexes - expectedRewards sdk.Coins - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "10 blocks", - args{ - borrow: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.001223540000173228"))}, - expectedRewards: cs(c("hard", 12235400)), - }, - }, - { - "10 blocks - long block time", - args{ - borrow: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("10.571385603126235340"))}, - expectedRewards: cs(c("hard", 105713856031)), - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount(userAddr, cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15))) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleBorrowRewardPeriod(tc.args.borrow.Denom, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // User deposits and borrows to increase total borrowed amount - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, sdk.NewCoins(sdk.NewCoin(tc.args.borrow.Denom, tc.args.borrow.Amount.Mul(sdkmath.NewInt(2))))) - suite.Require().NoError(err) - err = suite.hardKeeper.Borrow(suite.ctx, userAddr, sdk.NewCoins(tc.args.borrow)) - suite.Require().NoError(err) - - // Run accumulator at several intervals - var timeElapsed int - previousBlockTime := suite.ctx.BlockTime() - for _, t := range tc.args.blockTimes { - timeElapsed += t - updatedBlockTime := previousBlockTime.Add(time.Duration(int(time.Second) * t)) - previousBlockTime = updatedBlockTime - blockCtx := suite.ctx.WithBlockTime(updatedBlockTime) - - // Run Hard begin blocker for each block ctx to update denom's interest factor - hard.BeginBlocker(blockCtx, suite.hardKeeper) - - // Accumulate hard borrow-side rewards - multiRewardPeriod, found := suite.keeper.GetHardBorrowRewardPeriods(blockCtx, tc.args.borrow.Denom) - suite.Require().True(found) - suite.keeper.AccumulateHardBorrowRewards(blockCtx, multiRewardPeriod) - } - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - - // Confirm that the user's claim hasn't been synced - claimPre, foundPre := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(foundPre) - multiRewardIndexPre, _ := claimPre.BorrowRewardIndexes.GetRewardIndex(tc.args.borrow.Denom) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - currRewardIndex, found := multiRewardIndexPre.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(sdk.ZeroDec(), currRewardIndex.RewardFactor) - } - - // Check that the synced claim held in memory has properly simulated syncing - syncedClaim := suite.keeper.SimulateHardSynchronization(suite.ctx, claimPre) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - // Check that the user's claim's reward index matches the expected reward index - multiRewardIndex, found := syncedClaim.BorrowRewardIndexes.GetRewardIndex(tc.args.borrow.Denom) - suite.Require().True(found) - rewardIndex, found := multiRewardIndex.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, rewardIndex) - - // Check that the user's claim holds the expected amount of reward coins - suite.Require().Equal( - tc.args.expectedRewards.AmountOf(expectedRewardIndex.CollateralType), - syncedClaim.Reward.AmountOf(expectedRewardIndex.CollateralType), - ) - } - }) - } -} - -func TestBorrowRewardsTestSuite(t *testing.T) { - suite.Run(t, new(BorrowRewardsTestSuite)) -} diff --git a/x/incentive/keeper/rewards_borrow_update_test.go b/x/incentive/keeper/rewards_borrow_update_test.go deleted file mode 100644 index 06187dfa..00000000 --- a/x/incentive/keeper/rewards_borrow_update_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/incentive/types" -) - -// UpdateHardBorrowIndexDenomsTests runs unit tests for the keeper.UpdateHardBorrowIndexDenoms method -type UpdateHardBorrowIndexDenomsTests struct { - unitTester -} - -func TestUpdateHardBorrowIndexDenoms(t *testing.T) { - suite.Run(t, new(UpdateHardBorrowIndexDenomsTests)) -} - -func (suite *UpdateHardBorrowIndexDenomsTests) TestClaimIndexesAreRemovedForDenomsNoLongerBorrowed() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - BorrowRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - suite.storeGlobalBorrowIndexes(claim.BorrowRewardIndexes) - - // remove one denom from the indexes already in the borrow - expectedIndexes := claim.BorrowRewardIndexes[1:] - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(expectedIndexes)...). - Build() - - suite.keeper.UpdateHardBorrowIndexDenoms(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(expectedIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *UpdateHardBorrowIndexDenomsTests) TestClaimIndexesAreAddedForNewlyBorrowedDenoms() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - BorrowRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - globalIndexes := appendUniqueMultiRewardIndex(claim.BorrowRewardIndexes) - suite.storeGlobalBorrowIndexes(globalIndexes) - - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.UpdateHardBorrowIndexDenoms(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *UpdateHardBorrowIndexDenomsTests) TestClaimIndexesAreUnchangedWhenBorrowedDenomsUnchanged() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - BorrowRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - // Set global indexes with same denoms but different values. - // UpdateHardBorrowIndexDenoms should ignore the new values. - suite.storeGlobalBorrowIndexes(increaseAllRewardFactors(claim.BorrowRewardIndexes)) - - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(claim.BorrowRewardIndexes)...). - Build() - - suite.keeper.UpdateHardBorrowIndexDenoms(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(claim.BorrowRewardIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *UpdateHardBorrowIndexDenomsTests) TestEmptyClaimIndexesAreAddedForNewlyBorrowedButNotRewardedDenoms() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - BorrowRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - suite.storeGlobalBorrowIndexes(claim.BorrowRewardIndexes) - - // add a denom to the borrowed amount that is not in the global or claim's indexes - expectedIndexes := appendUniqueEmptyMultiRewardIndex(claim.BorrowRewardIndexes) - borrowedDenoms := extractCollateralTypes(expectedIndexes) - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(borrowedDenoms...). - Build() - - suite.keeper.UpdateHardBorrowIndexDenoms(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(expectedIndexes, syncedClaim.BorrowRewardIndexes) -} diff --git a/x/incentive/keeper/rewards_delegator.go b/x/incentive/keeper/rewards_delegator.go deleted file mode 100644 index 77d58a17..00000000 --- a/x/incentive/keeper/rewards_delegator.go +++ /dev/null @@ -1,208 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/kava-labs/kava/x/incentive/types" -) - -// AccumulateDelegatorRewards calculates new rewards to distribute this block and updates the global indexes to reflect this. -// The provided rewardPeriod must be valid to avoid panics in calculating time durations. -func (k Keeper) AccumulateDelegatorRewards(ctx sdk.Context, rewardPeriod types.MultiRewardPeriod) { - previousAccrualTime, found := k.GetPreviousDelegatorRewardAccrualTime(ctx, rewardPeriod.CollateralType) - if !found { - previousAccrualTime = ctx.BlockTime() - } - - indexes, found := k.GetDelegatorRewardIndexes(ctx, rewardPeriod.CollateralType) - if !found { - indexes = types.RewardIndexes{} - } - - acc := types.NewAccumulator(previousAccrualTime, indexes) - - totalSource := k.getDelegatorTotalSourceShares(ctx, rewardPeriod.CollateralType) - - acc.Accumulate(rewardPeriod, totalSource, ctx.BlockTime()) - - k.SetPreviousDelegatorRewardAccrualTime(ctx, rewardPeriod.CollateralType, acc.PreviousAccumulationTime) - if len(acc.Indexes) > 0 { - // the store panics when setting empty or nil indexes - k.SetDelegatorRewardIndexes(ctx, rewardPeriod.CollateralType, acc.Indexes) - } -} - -// getDelegatorTotalSourceShares fetches the sum of all source shares for a delegator reward. -// In the case of delegation, this is the total tokens staked to bonded validators. -func (k Keeper) getDelegatorTotalSourceShares(ctx sdk.Context, denom string) sdk.Dec { - totalBonded := k.stakingKeeper.TotalBondedTokens(ctx) - - return sdk.NewDecFromInt(totalBonded) -} - -// InitializeDelegatorReward initializes the reward index of a delegator claim -func (k Keeper) InitializeDelegatorReward(ctx sdk.Context, delegator sdk.AccAddress) { - claim, found := k.GetDelegatorClaim(ctx, delegator) - if !found { - claim = types.NewDelegatorClaim(delegator, sdk.Coins{}, nil) - } else { - k.SynchronizeDelegatorRewards(ctx, delegator, nil, false) - claim, _ = k.GetDelegatorClaim(ctx, delegator) - } - - var rewardIndexes types.MultiRewardIndexes - globalRewardIndexes, found := k.GetDelegatorRewardIndexes(ctx, types.BondDenom) - if !found { - globalRewardIndexes = types.RewardIndexes{} - } - rewardIndexes = rewardIndexes.With(types.BondDenom, globalRewardIndexes) - claim.RewardIndexes = rewardIndexes - k.SetDelegatorClaim(ctx, claim) -} - -// SynchronizeDelegatorClaim is a wrapper around SynchronizeDelegatorRewards that returns the synced claim -func (k Keeper) SynchronizeDelegatorClaim(ctx sdk.Context, claim types.DelegatorClaim) (types.DelegatorClaim, error) { - k.SynchronizeDelegatorRewards(ctx, claim.Owner, nil, false) - - claim, found := k.GetDelegatorClaim(ctx, claim.Owner) - if !found { - return claim, types.ErrClaimNotFound - } - return claim, nil -} - -// SynchronizeDelegatorRewards updates the claim object by adding any accumulated rewards, and setting the reward indexes to the global values. -// valAddr and shouldIncludeValidator are used to ignore or include delegations to a particular validator when summing up the total delegation. -// Normally only delegations to Bonded validators are included in the total. This is needed as staking hooks are sometimes called on the wrong -// side of a validator's state update (from this module's perspective). -func (k Keeper) SynchronizeDelegatorRewards(ctx sdk.Context, delegator sdk.AccAddress, valAddr sdk.ValAddress, shouldIncludeValidator bool) { - claim, found := k.GetDelegatorClaim(ctx, delegator) - if !found { - return - } - - globalRewardIndexes, found := k.GetDelegatorRewardIndexes(ctx, types.BondDenom) - if !found { - // The global factor is only not found if - // - the bond denom has not started accumulating rewards yet (either there is no reward specified in params, or the reward start time hasn't been hit) - // - OR it was wrongly deleted from state (factors should never be removed while unsynced claims exist) - // If not found we could either skip this sync, or assume the global factor is zero. - // Skipping will avoid storing unnecessary factors in the claim for non rewarded denoms. - // And in the event a global factor is wrongly deleted, it will avoid this function panicking when calculating rewards. - return - } - - userRewardIndexes, found := claim.RewardIndexes.Get(types.BondDenom) - if !found { - // Normally the reward indexes should always be found. - // However if there were no delegator rewards (ie no reward period in params) then a reward period is added, existing claims will not have the factor. - // So given the reward period was just added, assume the starting value for any global reward indexes, which is an empty slice. - userRewardIndexes = types.RewardIndexes{} - } - - totalDelegated := k.GetTotalDelegated(ctx, delegator, valAddr, shouldIncludeValidator) - - rewardsEarned, err := k.CalculateRewards(userRewardIndexes, globalRewardIndexes, totalDelegated) - if err != nil { - // Global reward factors should never decrease, as it would lead to a negative update to claim.Rewards. - // This panics if a global reward factor decreases or disappears between the old and new indexes. - panic(fmt.Sprintf("corrupted global reward indexes found: %v", err)) - } - - claim.Reward = claim.Reward.Add(rewardsEarned...) - claim.RewardIndexes = claim.RewardIndexes.With(types.BondDenom, globalRewardIndexes) - k.SetDelegatorClaim(ctx, claim) -} - -func (k Keeper) GetTotalDelegated(ctx sdk.Context, delegator sdk.AccAddress, valAddr sdk.ValAddress, shouldIncludeValidator bool) sdk.Dec { - totalDelegated := sdk.ZeroDec() - - delegations := k.stakingKeeper.GetDelegatorDelegations(ctx, delegator, 200) - for _, delegation := range delegations { - validator, found := k.stakingKeeper.GetValidator(ctx, delegation.GetValidatorAddr()) - if !found { - continue - } - - if validator.GetOperator().Equals(valAddr) { - if shouldIncludeValidator { - // do nothing, so the validator is included regardless of bonded status - } else { - // skip this validator - continue - } - } else { - // skip any not bonded validator - if validator.GetStatus() != stakingtypes.Bonded { - continue - } - } - - if validator.GetTokens().IsZero() { - continue - } - - delegatedTokens := validator.TokensFromShares(delegation.GetShares()) - if delegatedTokens.IsNegative() { - continue - } - totalDelegated = totalDelegated.Add(delegatedTokens) - } - return totalDelegated -} - -// SimulateDelegatorSynchronization calculates a user's outstanding delegator rewards by simulating reward synchronization -func (k Keeper) SimulateDelegatorSynchronization(ctx sdk.Context, claim types.DelegatorClaim) types.DelegatorClaim { - for _, ri := range claim.RewardIndexes { - // For each Delegator reward index (there's only one: the bond denom 'ukava') - globalRewardIndexes, foundGlobalRewardIndexes := k.GetDelegatorRewardIndexes(ctx, ri.CollateralType) - if !foundGlobalRewardIndexes { - continue - } - - userRewardIndexes, foundUserRewardIndexes := claim.RewardIndexes.GetRewardIndex(ri.CollateralType) - if !foundUserRewardIndexes { - continue - } - - userRewardIndexIndex, foundUserRewardIndexIndex := claim.RewardIndexes.GetRewardIndexIndex(ri.CollateralType) - if !foundUserRewardIndexIndex { - continue - } - - amtDelegated := k.GetTotalDelegated(ctx, claim.GetOwner(), sdk.ValAddress(claim.Owner.String()), true) - - for _, globalRewardIndex := range globalRewardIndexes { - userRewardIndex, foundUserRewardIndex := userRewardIndexes.RewardIndexes.GetRewardIndex(globalRewardIndex.CollateralType) - if !foundUserRewardIndex { - userRewardIndex = types.NewRewardIndex(globalRewardIndex.CollateralType, sdk.ZeroDec()) - userRewardIndexes.RewardIndexes = append(userRewardIndexes.RewardIndexes, userRewardIndex) - claim.RewardIndexes[userRewardIndexIndex].RewardIndexes = append(claim.RewardIndexes[userRewardIndexIndex].RewardIndexes, userRewardIndex) - } - - globalRewardFactor := globalRewardIndex.RewardFactor - userRewardFactor := userRewardIndex.RewardFactor - rewardsAccumulatedFactor := globalRewardFactor.Sub(userRewardFactor) - if rewardsAccumulatedFactor.IsZero() { - continue - } - - rewardsEarned := rewardsAccumulatedFactor.Mul(amtDelegated).RoundInt() - if rewardsEarned.IsZero() || rewardsEarned.IsNegative() { - continue - } - - factorIndex, foundFactorIndex := userRewardIndexes.RewardIndexes.GetFactorIndex(globalRewardIndex.CollateralType) - if !foundFactorIndex { - continue - } - claim.RewardIndexes[userRewardIndexIndex].RewardIndexes[factorIndex].RewardFactor = globalRewardIndex.RewardFactor - newRewardsCoin := sdk.NewCoin(userRewardIndex.CollateralType, rewardsEarned) - claim.Reward = claim.Reward.Add(newRewardsCoin) - } - } - return claim -} diff --git a/x/incentive/keeper/rewards_delegator_accum_test.go b/x/incentive/keeper/rewards_delegator_accum_test.go deleted file mode 100644 index 883c377b..00000000 --- a/x/incentive/keeper/rewards_delegator_accum_test.go +++ /dev/null @@ -1,307 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/incentive/types" -) - -type AccumulateDelegatorRewardsTests struct { - unitTester -} - -func (suite *AccumulateDelegatorRewardsTests) storedTimeEquals(denom string, expected time.Time) { - storedTime, found := suite.keeper.GetPreviousDelegatorRewardAccrualTime(suite.ctx, denom) - suite.True(found) - suite.Equal(expected, storedTime) -} - -func (suite *AccumulateDelegatorRewardsTests) storedIndexesEqual(denom string, expected types.RewardIndexes) { - storedIndexes, found := suite.keeper.GetDelegatorRewardIndexes(suite.ctx, denom) - suite.Equal(found, expected != nil) - - if found { - suite.Equal(expected, storedIndexes) - } else { - suite.Empty(storedIndexes) - } -} - -func TestAccumulateDelegatorRewards(t *testing.T) { - suite.Run(t, new(AccumulateDelegatorRewardsTests)) -} - -func (suite *AccumulateDelegatorRewardsTests) TestStateUpdatedWhenBlockTimeHasIncreased() { - stakingKeeper := newFakeStakingKeeper().addBondedTokens(1e6) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - suite.storeGlobalDelegatorIndexes(types.MultiRewardIndexes{ - { - CollateralType: types.BondDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - }) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousDelegatorRewardAccrualTime(suite.ctx, types.BondDenom, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - types.BondDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateDelegatorRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(types.BondDenom, newAccrualTime) - suite.storedIndexesEqual(types.BondDenom, types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("7.22"), - }, - { - CollateralType: "ukava", - RewardFactor: d("3.64"), - }, - }) -} - -func (suite *AccumulateDelegatorRewardsTests) TestStateUnchangedWhenBlockTimeHasNotIncreased() { - stakingKeeper := newFakeStakingKeeper().addBondedTokens(1e6) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: types.BondDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalDelegatorIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousDelegatorRewardAccrualTime(suite.ctx, types.BondDenom, previousAccrualTime) - - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - types.BondDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateDelegatorRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(types.BondDenom, previousAccrualTime) - expected, f := previousIndexes.Get(types.BondDenom) - suite.True(f) - suite.storedIndexesEqual(types.BondDenom, expected) -} - -func (suite *AccumulateDelegatorRewardsTests) TestNoAccumulationWhenSourceSharesAreZero() { - stakingKeeper := newFakeStakingKeeper() // zero total bonded - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: types.BondDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalDelegatorIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousDelegatorRewardAccrualTime(suite.ctx, types.BondDenom, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(7 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - types.BondDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateDelegatorRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(types.BondDenom, firstAccrualTime) - expected, f := previousIndexes.Get(types.BondDenom) - suite.True(f) - suite.storedIndexesEqual(types.BondDenom, expected) -} - -func (suite *AccumulateDelegatorRewardsTests) TestStateAddedWhenStateDoesNotExist() { - stakingKeeper := newFakeStakingKeeper().addBondedTokens(1e6) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - period := types.NewMultiRewardPeriod( - true, - types.BondDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - firstAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateDelegatorRewards(suite.ctx, period) - - // After the first accumulation only the current block time should be stored. - // The indexes will be empty as no time has passed since the previous block because it didn't exist. - suite.storedTimeEquals(types.BondDenom, firstAccrualTime) - suite.storedIndexesEqual(types.BondDenom, nil) - - secondAccrualTime := firstAccrualTime.Add(10 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(secondAccrualTime) - - suite.keeper.AccumulateDelegatorRewards(suite.ctx, period) - - // After the second accumulation both current block time and indexes should be stored. - suite.storedTimeEquals(types.BondDenom, secondAccrualTime) - suite.storedIndexesEqual(types.BondDenom, types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.01"), - }, - }) -} - -func (suite *AccumulateDelegatorRewardsTests) TestNoPanicWhenStateDoesNotExist() { - stakingKeeper := newFakeStakingKeeper() - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - period := types.NewMultiRewardPeriod( - true, - types.BondDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(), - ) - - accrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(accrualTime) - - // Accumulate with no source shares and no rewards per second will result in no increment to the indexes. - // No increment and no previous indexes stored, results in an updated of nil. Setting this in the state panics. - // Check there is no panic. - suite.NotPanics(func() { - suite.keeper.AccumulateDelegatorRewards(suite.ctx, period) - }) - - suite.storedTimeEquals(types.BondDenom, accrualTime) - suite.storedIndexesEqual(types.BondDenom, nil) -} - -func (suite *AccumulateDelegatorRewardsTests) TestNoAccumulationWhenBeforeStartTime() { - stakingKeeper := newFakeStakingKeeper().addBondedTokens(1e6) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: types.BondDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalDelegatorIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousDelegatorRewardAccrualTime(suite.ctx, types.BondDenom, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(10 * time.Second) - - period := types.NewMultiRewardPeriod( - true, - types.BondDenom, - firstAccrualTime.Add(time.Nanosecond), // start time after accrual time - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateDelegatorRewards(suite.ctx, period) - - // The accrual time should be updated, but the indexes unchanged - suite.storedTimeEquals(types.BondDenom, firstAccrualTime) - expectedIndexes, f := previousIndexes.Get(types.BondDenom) - suite.True(f) - suite.storedIndexesEqual(types.BondDenom, expectedIndexes) -} - -func (suite *AccumulateDelegatorRewardsTests) TestPanicWhenCurrentTimeLessThanPrevious() { - stakingKeeper := newFakeStakingKeeper().addBondedTokens(1e6) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousDelegatorRewardAccrualTime(suite.ctx, types.BondDenom, previousAccrualTime) - - firstAccrualTime := time.Time{} - - period := types.NewMultiRewardPeriod( - true, - types.BondDenom, - time.Time{}, // start time after accrual time - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.Panics(func() { - suite.keeper.AccumulateDelegatorRewards(suite.ctx, period) - }) -} diff --git a/x/incentive/keeper/rewards_delegator_init_test.go b/x/incentive/keeper/rewards_delegator_init_test.go deleted file mode 100644 index 42015e43..00000000 --- a/x/incentive/keeper/rewards_delegator_init_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package keeper_test - -import ( - "testing" - - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/incentive/types" -) - -// InitializeDelegatorRewardTests runs unit tests for the keeper.InitializeDelegatorReward method -// -// inputs -// - claim in store if it exists (only claim.DelegatorRewardIndexes) -// - global indexes in store -// - delegator function arg -// -// outputs -// - sets or creates a claim -type InitializeDelegatorRewardTests struct { - unitTester -} - -func TestInitializeDelegatorReward(t *testing.T) { - suite.Run(t, new(InitializeDelegatorRewardTests)) -} - -// Hardcoded to use bond denom -func (suite *InitializeDelegatorRewardTests) storeGlobalDelegatorFactor(multiRewardIndexes types.MultiRewardIndexes) { - multiRewardIndex, _ := multiRewardIndexes.GetRewardIndex(types.BondDenom) - suite.keeper.SetDelegatorRewardIndexes(suite.ctx, types.BondDenom, multiRewardIndex.RewardIndexes) -} - -func (suite *InitializeDelegatorRewardTests) TestClaimIndexesAreSetWhenClaimDoesNotExist() { - globalIndex := arbitraryDelegatorRewardIndexes - suite.storeGlobalDelegatorIndexes(globalIndex) - - delegator := arbitraryAddress() - suite.keeper.InitializeDelegatorReward(suite.ctx, delegator) - - syncedClaim, f := suite.keeper.GetDelegatorClaim(suite.ctx, delegator) - suite.True(f) - suite.Equal(globalIndex, syncedClaim.RewardIndexes) -} - -func (suite *InitializeDelegatorRewardTests) TestClaimIsSyncedAndIndexesAreSetWhenClaimDoesExist() { - validatorAddress := arbitraryValidatorAddress() - sk := &fakeStakingKeeper{ - delegations: stakingtypes.Delegations{{ - ValidatorAddress: validatorAddress.String(), - Shares: d("1000"), - }}, - validators: stakingtypes.Validators{{ - OperatorAddress: validatorAddress.String(), - Status: stakingtypes.Bonded, - Tokens: i(1000), - DelegatorShares: d("1000"), - }}, - } - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, sk, nil, nil, nil, nil) - - claim := types.DelegatorClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - RewardIndexes: arbitraryDelegatorRewardIndexes, - } - suite.storeDelegatorClaim(claim) - - // Set the global factor to a value different to one in claim so - // we can detect if it is overwritten. - rewardIndexes, _ := claim.RewardIndexes.Get(types.BondDenom) - globalIndexes := increaseRewardFactors(rewardIndexes) - - // Update the claim object with the new global factor - bondIndex, _ := claim.RewardIndexes.GetRewardIndexIndex(types.BondDenom) - claim.RewardIndexes[bondIndex].RewardIndexes = globalIndexes - suite.storeGlobalDelegatorFactor(claim.RewardIndexes) - - suite.keeper.InitializeDelegatorReward(suite.ctx, claim.Owner) - - syncedClaim, _ := suite.keeper.GetDelegatorClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.RewardIndexes[bondIndex].RewardIndexes) - suite.Truef(syncedClaim.Reward.IsAllGT(claim.Reward), "'%s' not greater than '%s'", syncedClaim.Reward, claim.Reward) -} - -// arbitraryDelegatorRewardIndexes contains only one reward index as there is only ever one bond denom -var arbitraryDelegatorRewardIndexes = types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - types.BondDenom, - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.2")), - types.NewRewardIndex("swp", d("0.2")), - }, - ), -} diff --git a/x/incentive/keeper/rewards_delegator_sync_test.go b/x/incentive/keeper/rewards_delegator_sync_test.go deleted file mode 100644 index 829aacae..00000000 --- a/x/incentive/keeper/rewards_delegator_sync_test.go +++ /dev/null @@ -1,396 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/incentive/types" -) - -// SynchronizeDelegatorRewardTests runs unit tests for the keeper.SynchronizeDelegatorReward method -// -// inputs -// - claim in store if it exists (only claim.DelegatorRewardIndexes and claim.Reward) -// - global index in store -// - function args: delegator address, validator address, shouldIncludeValidator flag -// - delegator's delegations and the corresponding validators -// -// outputs -// - sets or creates a claim -type SynchronizeDelegatorRewardTests struct { - unitTester -} - -func TestSynchronizeDelegatorReward(t *testing.T) { - suite.Run(t, new(SynchronizeDelegatorRewardTests)) -} - -func (suite *SynchronizeDelegatorRewardTests) storeGlobalDelegatorFactor(multiRewardIndexes types.MultiRewardIndexes) { - multiRewardIndex, _ := multiRewardIndexes.GetRewardIndex(types.BondDenom) - suite.keeper.SetDelegatorRewardIndexes(suite.ctx, types.BondDenom, multiRewardIndex.RewardIndexes) -} - -func (suite *SynchronizeDelegatorRewardTests) TestClaimIndexesAreUnchangedWhenGlobalFactorUnchanged() { - delegator := arbitraryAddress() - - stakingKeeper := &fakeStakingKeeper{} // use an empty staking keeper that returns no delegations - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - claim := types.DelegatorClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: delegator, - }, - RewardIndexes: arbitraryDelegatorRewardIndexes, - } - suite.storeDelegatorClaim(claim) - - suite.storeGlobalDelegatorFactor(claim.RewardIndexes) - - suite.keeper.SynchronizeDelegatorRewards(suite.ctx, claim.Owner, nil, false) - - syncedClaim, _ := suite.keeper.GetDelegatorClaim(suite.ctx, claim.Owner) - suite.Equal(claim.RewardIndexes, syncedClaim.RewardIndexes) -} - -func (suite *SynchronizeDelegatorRewardTests) TestClaimIndexesAreUpdatedWhenGlobalFactorIncreased() { - delegator := arbitraryAddress() - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, &fakeStakingKeeper{}, nil, nil, nil, nil) - - claim := types.DelegatorClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: delegator, - }, - RewardIndexes: arbitraryDelegatorRewardIndexes, - } - suite.storeDelegatorClaim(claim) - - rewardIndexes, _ := claim.RewardIndexes.Get(types.BondDenom) - globalIndexes := increaseRewardFactors(rewardIndexes) - - // Update the claim object with the new global factor - bondIndex, _ := claim.RewardIndexes.GetRewardIndexIndex(types.BondDenom) - claim.RewardIndexes[bondIndex].RewardIndexes = globalIndexes - suite.storeGlobalDelegatorFactor(claim.RewardIndexes) - - suite.keeper.SynchronizeDelegatorRewards(suite.ctx, claim.Owner, nil, false) - - syncedClaim, _ := suite.keeper.GetDelegatorClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.RewardIndexes[bondIndex].RewardIndexes) -} - -func (suite *SynchronizeDelegatorRewardTests) TestRewardIsUnchangedWhenGlobalFactorUnchanged() { - delegator := arbitraryAddress() - validatorAddress := arbitraryValidatorAddress() - stakingKeeper := &fakeStakingKeeper{ - delegations: stakingtypes.Delegations{ - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddress.String(), - Shares: d("1000"), - }, - }, - validators: stakingtypes.Validators{ - unslashedBondedValidator(validatorAddress), - }, - } - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - claim := types.DelegatorClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: delegator, - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{{ - CollateralType: types.BondDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", RewardFactor: d("0.1"), - }, - { - CollateralType: "swp", RewardFactor: d("0.2"), - }, - }, - }}, - } - suite.storeDelegatorClaim(claim) - - suite.storeGlobalDelegatorFactor(claim.RewardIndexes) - - suite.keeper.SynchronizeDelegatorRewards(suite.ctx, claim.Owner, nil, false) - - syncedClaim, _ := suite.keeper.GetDelegatorClaim(suite.ctx, claim.Owner) - - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *SynchronizeDelegatorRewardTests) TestRewardIsIncreasedWhenNewRewardAdded() { - delegator := arbitraryAddress() - validatorAddress := arbitraryValidatorAddress() - stakingKeeper := &fakeStakingKeeper{ - delegations: stakingtypes.Delegations{ - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddress.String(), - Shares: d("1000"), - }, - }, - validators: stakingtypes.Validators{ - unslashedBondedValidator(validatorAddress), - }, - } - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - claim := types.DelegatorClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: delegator, - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{}, - } - suite.storeDelegatorClaim(claim) - - newGlobalIndexes := types.MultiRewardIndexes{{ - CollateralType: types.BondDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", RewardFactor: d("0.1"), - }, - { - CollateralType: "swp", RewardFactor: d("0.2"), - }, - }, - }} - suite.storeGlobalDelegatorIndexes(newGlobalIndexes) - - suite.keeper.SynchronizeDelegatorRewards(suite.ctx, claim.Owner, nil, false) - - syncedClaim, _ := suite.keeper.GetDelegatorClaim(suite.ctx, claim.Owner) - - suite.Equal(newGlobalIndexes, syncedClaim.RewardIndexes) - suite.Equal( - cs(c("hard", 100), c("swp", 200)).Add(claim.Reward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeDelegatorRewardTests) TestRewardIsIncreasedWhenGlobalFactorIncreased() { - delegator := arbitraryAddress() - validatorAddress := arbitraryValidatorAddress() - stakingKeeper := &fakeStakingKeeper{ - delegations: stakingtypes.Delegations{ - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddress.String(), - Shares: d("1000"), - }, - }, - validators: stakingtypes.Validators{ - unslashedBondedValidator(validatorAddress), - }, - } - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - claim := types.DelegatorClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: delegator, - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{{ - CollateralType: types.BondDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", RewardFactor: d("0.1"), - }, - { - CollateralType: "swp", RewardFactor: d("0.2"), - }, - }, - }}, - } - suite.storeDelegatorClaim(claim) - - suite.storeGlobalDelegatorIndexes( - types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - types.BondDenom, - types.RewardIndexes{ - { - CollateralType: "hard", RewardFactor: d("0.2"), - }, - { - CollateralType: "swp", RewardFactor: d("0.4"), - }, - }, - ), - }, - ) - - suite.keeper.SynchronizeDelegatorRewards(suite.ctx, claim.Owner, nil, false) - - syncedClaim, _ := suite.keeper.GetDelegatorClaim(suite.ctx, claim.Owner) - - suite.Equal( - cs(c("hard", 100), c("swp", 200)).Add(claim.Reward...), - syncedClaim.Reward, - ) -} - -func unslashedBondedValidator(address sdk.ValAddress) stakingtypes.Validator { - return stakingtypes.Validator{ - OperatorAddress: address.String(), - Status: stakingtypes.Bonded, - - // Set the tokens and shares equal so then - // a _delegator's_ token amount is equal to their shares amount - Tokens: i(1e12), - DelegatorShares: sdk.NewDec(1e12), - } -} - -func unslashedNotBondedValidator(address sdk.ValAddress) stakingtypes.Validator { - return stakingtypes.Validator{ - OperatorAddress: address.String(), - Status: stakingtypes.Unbonding, - - // Set the tokens and shares equal so then - // a _delegator's_ token amount is equal to their shares amount - Tokens: i(1e12), - DelegatorShares: sdk.NewDec(1e12), - } -} - -func (suite *SynchronizeDelegatorRewardTests) TestGetDelegatedWhenValAddrIsNil() { - // when valAddr is nil, get total delegated to bonded validators - delegator := arbitraryAddress() - validatorAddresses := generateValidatorAddresses(4) - stakingKeeper := &fakeStakingKeeper{ - delegations: stakingtypes.Delegations{ - // bonded - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[0].String(), - Shares: d("1"), - }, - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[1].String(), - Shares: d("10"), - }, - // not bonded - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[2].String(), - Shares: d("100"), - }, - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[3].String(), - Shares: d("1000"), - }, - }, - validators: stakingtypes.Validators{ - unslashedBondedValidator(validatorAddresses[0]), - unslashedBondedValidator(validatorAddresses[1]), - unslashedNotBondedValidator(validatorAddresses[2]), - unslashedNotBondedValidator(validatorAddresses[3]), - }, - } - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - suite.Equal( - d("11"), // delegation to bonded validators - suite.keeper.GetTotalDelegated(suite.ctx, delegator, nil, false), - ) -} - -func (suite *SynchronizeDelegatorRewardTests) TestGetDelegatedWhenExcludingAValidator() { - // when valAddr is x, get total delegated to bonded validators excluding those to x - delegator := arbitraryAddress() - validatorAddresses := generateValidatorAddresses(4) - stakingKeeper := &fakeStakingKeeper{ - delegations: stakingtypes.Delegations{ - // bonded - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[0].String(), - Shares: d("1"), - }, - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[1].String(), - Shares: d("10"), - }, - // not bonded - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[2].String(), - Shares: d("100"), - }, - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[3].String(), - Shares: d("1000"), - }, - }, - validators: stakingtypes.Validators{ - unslashedBondedValidator(validatorAddresses[0]), - unslashedBondedValidator(validatorAddresses[1]), - unslashedNotBondedValidator(validatorAddresses[2]), - unslashedNotBondedValidator(validatorAddresses[3]), - }, - } - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - suite.Equal( - d("10"), - suite.keeper.GetTotalDelegated(suite.ctx, delegator, validatorAddresses[0], false), - ) -} - -func (suite *SynchronizeDelegatorRewardTests) TestGetDelegatedWhenIncludingAValidator() { - // when valAddr is x, get total delegated to bonded validators including those to x - delegator := arbitraryAddress() - validatorAddresses := generateValidatorAddresses(4) - stakingKeeper := &fakeStakingKeeper{ - delegations: stakingtypes.Delegations{ - // bonded - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[0].String(), - Shares: d("1"), - }, - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[1].String(), - Shares: d("10"), - }, - // not bonded - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[2].String(), - Shares: d("100"), - }, - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[3].String(), - Shares: d("1000"), - }, - }, - validators: stakingtypes.Validators{ - unslashedBondedValidator(validatorAddresses[0]), - unslashedBondedValidator(validatorAddresses[1]), - unslashedNotBondedValidator(validatorAddresses[2]), - unslashedNotBondedValidator(validatorAddresses[3]), - }, - } - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - suite.Equal( - d("111"), - suite.keeper.GetTotalDelegated(suite.ctx, delegator, validatorAddresses[2], true), - ) -} diff --git a/x/incentive/keeper/rewards_delegator_test.go b/x/incentive/keeper/rewards_delegator_test.go deleted file mode 100644 index 6402e17a..00000000 --- a/x/incentive/keeper/rewards_delegator_test.go +++ /dev/null @@ -1,796 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/testutil" - "github.com/kava-labs/kava/x/incentive/types" -) - -// Test suite used for all keeper tests -type DelegatorRewardsTestSuite struct { - suite.Suite - - keeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - - app app.TestApp - ctx sdk.Context - - genesisTime time.Time - addrs []sdk.AccAddress - validatorAddrs []sdk.ValAddress -} - -// SetupTest is run automatically before each suite test -func (suite *DelegatorRewardsTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - _, allAddrs := app.GeneratePrivKeyAddressPairs(10) - suite.addrs = allAddrs[:5] - for _, a := range allAddrs[5:] { - suite.validatorAddrs = append(suite.validatorAddrs, sdk.ValAddress(a)) - } - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *DelegatorRewardsTestSuite) SetupApp() { - suite.app = app.NewTestApp() - - suite.keeper = suite.app.GetIncentiveKeeper() - suite.stakingKeeper = suite.app.GetStakingKeeper() - - suite.ctx = suite.app.NewContext(true, tmproto.Header{Height: 1, Time: suite.genesisTime, ChainID: app.TestChainId}) -} - -func (suite *DelegatorRewardsTestSuite) SetupWithGenState(authBuilder *app.AuthBankGenesisBuilder, incentBuilder testutil.IncentiveGenesisBuilder) { - suite.SetupApp() - - suite.app.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - authBuilder.BuildMarshalled(suite.app.AppCodec()), - NewStakingGenesisState(suite.app.AppCodec()), - incentBuilder.BuildMarshalled(suite.app.AppCodec()), - ) -} - -func (suite *DelegatorRewardsTestSuite) TestAccumulateDelegatorRewards() { - type args struct { - delegation sdk.Coin - rewardsPerSecond sdk.Coins - timeElapsed int - expectedRewardIndexes types.RewardIndexes - } - type test struct { - name string - args args - } - testCases := []test{ - { - "7 seconds", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 7, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.428239000000000000")), - }, - }, - }, - { - "1 day", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 86400, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("5285.692800000000000000")), - }, - }, - }, - { - "0 seconds", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 0, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - }, - }, - }, - { - "multiple reward coins", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354), c("swp", 567889)), - timeElapsed: 7, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.428239000000000000")), - types.NewRewardIndex("swp", d("1.987611500000000000")), - }, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[0], cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[0]), cs(c("ukava", 1e9))) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleDelegatorRewardPeriod(tc.args.delegation.Denom, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - err := suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[0], tc.args.delegation) - suite.Require().NoError(err) - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[0], suite.validatorAddrs[0], tc.args.delegation) - suite.Require().NoError(err) - - // Delete genesis validator to not influence rewards - suite.app.DeleteGenesisValidator(suite.T(), suite.ctx) - - staking.EndBlocker(suite.ctx, suite.stakingKeeper) - - // Set up chain context at future time - runAtTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - runCtx := suite.ctx.WithBlockTime(runAtTime) - - rewardPeriods, found := suite.keeper.GetDelegatorRewardPeriods(runCtx, tc.args.delegation.Denom) - suite.Require().True(found) - suite.keeper.AccumulateDelegatorRewards(runCtx, rewardPeriods) - - rewardIndexes, _ := suite.keeper.GetDelegatorRewardIndexes(runCtx, tc.args.delegation.Denom) - suite.Require().Equal(tc.args.expectedRewardIndexes, rewardIndexes) - }) - } -} - -func (suite *DelegatorRewardsTestSuite) TestSynchronizeDelegatorReward() { - type args struct { - delegation sdk.Coin - rewardsPerSecond sdk.Coins - blockTimes []int - expectedRewardIndexes types.RewardIndexes - expectedRewards sdk.Coins - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "10 blocks", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("6.117700000000000000")), - }, - expectedRewards: cs(c("hard", 6117700)), - }, - }, - { - "10 blocks - long block time", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("52856.928000000000000000")), - }, - expectedRewards: cs(c("hard", 52856928000)), - }, - }, - { - "delegator reward index updated when reward is zero", - args{ - delegation: c("ukava", 1), - rewardsPerSecond: cs(c("hard", 1)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.000099999900000100")), - }, - expectedRewards: nil, - }, - }, - { - "multiple reward coins", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354), c("swp", 56789)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("6.117700000000000000")), - types.NewRewardIndex("swp", d("2.839450000000000000")), - }, - expectedRewards: cs(c("hard", 6117700), c("swp", 2839450)), - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[0], cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[0]), cs(c("ukava", 1e9))) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleDelegatorRewardPeriod(tc.args.delegation.Denom, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - // Create validator account - staking.BeginBlocker(suite.ctx, suite.stakingKeeper) - selfDelegationCoins := c("ukava", 1_000_000) - err := suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[0], selfDelegationCoins) - suite.Require().NoError(err) - staking.EndBlocker(suite.ctx, suite.stakingKeeper) - - // Delete genesis validator to not influence rewards - suite.app.DeleteGenesisValidator(suite.T(), suite.ctx) - - // Delegator delegates - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[0], suite.validatorAddrs[0], tc.args.delegation) - suite.Require().NoError(err) - - // Check that validator account has been created and delegation was successful - valAcc, found := suite.stakingKeeper.GetValidator(suite.ctx, suite.validatorAddrs[0]) - suite.True(found) - suite.Require().Equal(valAcc.Status, stakingtypes.Bonded) - suite.Require().Equal(valAcc.Tokens, tc.args.delegation.Amount.Add(selfDelegationCoins.Amount)) - - // Check that Staking hooks initialized a DelegatorClaim - claim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - for _, rewardIndex := range claim.RewardIndexes[0].RewardIndexes { - suite.Require().Equal(sdk.ZeroDec(), rewardIndex.RewardFactor) - } - - // Run accumulator at several intervals - var timeElapsed int - previousBlockTime := suite.ctx.BlockTime() - for _, t := range tc.args.blockTimes { - timeElapsed += t - updatedBlockTime := previousBlockTime.Add(time.Duration(int(time.Second) * t)) - previousBlockTime = updatedBlockTime - blockCtx := suite.ctx.WithBlockTime(updatedBlockTime) - - rewardPeriods, found := suite.keeper.GetDelegatorRewardPeriods(blockCtx, tc.args.delegation.Denom) - suite.Require().True(found) - - suite.keeper.AccumulateDelegatorRewards(blockCtx, rewardPeriods) - } - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - - // After we've accumulated, run synchronize - suite.Require().NotPanics(func() { - suite.keeper.SynchronizeDelegatorRewards(suite.ctx, suite.addrs[0], nil, false) - }) - - // Check that reward factor and claim have been updated as expected - rewardIndexes, _ := suite.keeper.GetDelegatorRewardIndexes(suite.ctx, tc.args.delegation.Denom) - for i, rewardPerSecond := range tc.args.rewardsPerSecond { - rewardFactor, _ := rewardIndexes.Get(rewardPerSecond.Denom) - suite.Require().Equal(tc.args.expectedRewardIndexes[i].RewardFactor, rewardFactor) - } - - claim, found = suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - for i, delegatorRewardIndex := range claim.RewardIndexes[0].RewardIndexes { - suite.Require().Equal(tc.args.expectedRewardIndexes[i].RewardFactor, delegatorRewardIndex.RewardFactor) - } - suite.Require().Equal(tc.args.expectedRewards, claim.Reward) - }) - } -} - -func (suite *DelegatorRewardsTestSuite) TestSimulateDelegatorRewardSynchronization() { - type args struct { - delegation sdk.Coin - rewardsPerSecond sdk.Coins - blockTimes []int - expectedRewardIndexes types.RewardIndexes - expectedRewards sdk.Coins - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "10 blocks", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("6.117700000000000000"))}, - expectedRewards: cs(c("hard", 6117700)), - }, - }, - { - "10 blocks - long block time", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("52856.928000000000000000"))}, - expectedRewards: cs(c("hard", 52856928000)), - }, - }, - { - "multiple rewards coins", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354), c("swp", 56789)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("6.117700000000000000")), - types.NewRewardIndex("swp", d("2.839450000000000000")), - }, - expectedRewards: cs(c("hard", 6117700), c("swp", 2839450)), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[0], cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[0]), cs(c("ukava", 1e9))) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleDelegatorRewardPeriod(tc.args.delegation.Denom, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - // Delegator delegates - err := suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[0], tc.args.delegation) - suite.Require().NoError(err) - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[0], suite.validatorAddrs[0], tc.args.delegation) - suite.Require().NoError(err) - - // Delete genesis validator to not influence rewards - suite.app.DeleteGenesisValidator(suite.T(), suite.ctx) - - staking.EndBlocker(suite.ctx, suite.stakingKeeper) - - // Check that Staking hooks initialized a DelegatorClaim - claim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - for _, rewardIndex := range claim.RewardIndexes[0].RewardIndexes { - suite.Require().Equal(sdk.ZeroDec(), rewardIndex.RewardFactor) - } - - // Run accumulator at several intervals - var timeElapsed int - previousBlockTime := suite.ctx.BlockTime() - for _, t := range tc.args.blockTimes { - timeElapsed += t - updatedBlockTime := previousBlockTime.Add(time.Duration(int(time.Second) * t)) - previousBlockTime = updatedBlockTime - blockCtx := suite.ctx.WithBlockTime(updatedBlockTime) - - // Accumulate delegator rewards - rewardPeriods, found := suite.keeper.GetDelegatorRewardPeriods(blockCtx, tc.args.delegation.Denom) - suite.Require().True(found) - suite.keeper.AccumulateDelegatorRewards(blockCtx, rewardPeriods) - } - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - - // Check that the synced claim held in memory has properly simulated syncing - syncedClaim := suite.keeper.SimulateDelegatorSynchronization(suite.ctx, claim) - - for i, expectedRewardIndex := range tc.args.expectedRewardIndexes { - // Check that the user's claim's reward index matches the expected reward index - multiRewardIndex, found := syncedClaim.RewardIndexes.Get(types.BondDenom) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, multiRewardIndex[i]) - - // Check that the user's claim holds the expected amount of reward coins - suite.Require().Equal( - tc.args.expectedRewards.AmountOf(expectedRewardIndex.CollateralType), - syncedClaim.Reward.AmountOf(expectedRewardIndex.CollateralType), - ) - } - }) - } -} - -func (suite *DelegatorRewardsTestSuite) deliverMsgCreateValidator(ctx sdk.Context, address sdk.ValAddress, selfDelegation sdk.Coin) error { - msg, err := stakingtypes.NewMsgCreateValidator( - address, - ed25519.GenPrivKey().PubKey(), - selfDelegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - sdkmath.NewInt(1_000_000), - ) - if err != nil { - return err - } - - msgServer := stakingkeeper.NewMsgServerImpl(suite.stakingKeeper) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.ctx), msg) - return err -} - -func (suite *DelegatorRewardsTestSuite) deliverMsgDelegate(ctx sdk.Context, delegator sdk.AccAddress, validator sdk.ValAddress, amount sdk.Coin) error { - msg := stakingtypes.NewMsgDelegate( - delegator, - validator, - amount, - ) - - msgServer := stakingkeeper.NewMsgServerImpl(suite.stakingKeeper) - _, err := msgServer.Delegate(sdk.WrapSDKContext(suite.ctx), msg) - return err -} - -func (suite *DelegatorRewardsTestSuite) deliverMsgRedelegate(ctx sdk.Context, delegator sdk.AccAddress, sourceValidator, destinationValidator sdk.ValAddress, amount sdk.Coin) error { - msg := stakingtypes.NewMsgBeginRedelegate( - delegator, - sourceValidator, - destinationValidator, - amount, - ) - - msgServer := stakingkeeper.NewMsgServerImpl(suite.stakingKeeper) - _, err := msgServer.BeginRedelegate(sdk.WrapSDKContext(suite.ctx), msg) - return err -} - -// given a user has a delegation to a bonded validator, when the validator starts unbonding, the user does not accumulate rewards -func (suite *DelegatorRewardsTestSuite) TestUnbondingValidatorSyncsClaim() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[0], cs(c("ukava", 1e9))). - WithSimpleAccount(suite.addrs[2], cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[0]), cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[1]), cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[2]), cs(c("ukava", 1e9))) - - rewardsPerSecond := cs(c("hard", 122354)) - bondDenom := "ukava" - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleDelegatorRewardPeriod(bondDenom, rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - blockDuration := 10 * time.Second - - // Reduce the size of the validator set - stakingParams := suite.app.GetStakingKeeper().GetParams(suite.ctx) - stakingParams.MaxValidators = 2 - suite.app.GetStakingKeeper().SetParams(suite.ctx, stakingParams) - - // Create 3 validators - err := suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[0], c(bondDenom, 10_000_000)) - suite.Require().NoError(err) - err = suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[1], c(bondDenom, 5_000_000)) - suite.Require().NoError(err) - err = suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[2], c(bondDenom, 1_000_000)) - suite.Require().NoError(err) - - // End the block so top validators become bonded - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(1 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) // height and time in header are ignored by module begin blockers - - // Delegate to a bonded validator from the test user. This will initialize their incentive claim. - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[0], suite.validatorAddrs[1], c(bondDenom, 1_000_000)) - suite.Require().NoError(err) - - // Start a new block to accumulate some delegation rewards for the user. - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(2 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) // height and time in header are ignored by module begin blockers - - // Delegate to the unbonded validator to push it into the bonded validator set, pushing out the user's delegated validator - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[2], suite.validatorAddrs[2], c(bondDenom, 8_000_000)) - suite.Require().NoError(err) - - // End the block to start unbonding the user's validator - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - // but don't start the next block as it will accumulate delegator rewards and we won't be able to tell if the user's reward was synced. - - // Check that the user's claim has been synced. ie rewards added, index updated - claim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - - rewardIndexes, found := suite.keeper.GetDelegatorRewardIndexes(suite.ctx, bondDenom) - suite.Require().True(found) - globalIndex, found := rewardIndexes.Get(rewardsPerSecond[0].Denom) - suite.Require().True(found) - claimIndex, found := claim.RewardIndexes.GetRewardIndex(bondDenom) - suite.Require().True(found) - suite.Require().Equal(globalIndex, claimIndex.RewardIndexes[0].RewardFactor) - - suite.Require().Equal( - cs(c(rewardsPerSecond[0].Denom, 76471)), - claim.Reward, - ) - - // Run another block and check the claim is not accumulating more rewards - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(3 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) - - suite.keeper.SynchronizeDelegatorRewards(suite.ctx, suite.addrs[0], nil, false) - - // rewards are the same as before - laterClaim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().Equal(claim.Reward, laterClaim.Reward) - - // claim index has been updated to latest global value - laterClaimIndex, found := laterClaim.RewardIndexes.GetRewardIndex(bondDenom) - suite.Require().True(found) - rewardIndexes, found = suite.keeper.GetDelegatorRewardIndexes(suite.ctx, bondDenom) - suite.Require().True(found) - globalIndex, found = rewardIndexes.Get(rewardsPerSecond[0].Denom) - suite.Require().True(found) - suite.Require().Equal(globalIndex, laterClaimIndex.RewardIndexes[0].RewardFactor) -} - -// given a user has a delegation to an unbonded validator, when the validator becomes bonded, the user starts accumulating rewards -func (suite *DelegatorRewardsTestSuite) TestBondingValidatorSyncsClaim() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[0], cs(c("ukava", 1e9))). - WithSimpleAccount(suite.addrs[2], cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[0]), cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[1]), cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[2]), cs(c("ukava", 1e9))) - - rewardsPerSecond := cs(c("hard", 122354)) - bondDenom := "ukava" - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleDelegatorRewardPeriod(bondDenom, rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - blockDuration := 10 * time.Second - - // Reduce the size of the validator set - stakingParams := suite.app.GetStakingKeeper().GetParams(suite.ctx) - stakingParams.MaxValidators = 2 - suite.app.GetStakingKeeper().SetParams(suite.ctx, stakingParams) - - // Create 3 validators - err := suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[0], c(bondDenom, 10_000_000)) - suite.Require().NoError(err) - err = suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[1], c(bondDenom, 5_000_000)) - suite.Require().NoError(err) - err = suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[2], c(bondDenom, 1_000_000)) - suite.Require().NoError(err) - - // End the block so top validators become bonded - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(1 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) // height and time in header are ignored by module begin blockers - - // Delegate to an unbonded validator from the test user. This will initialize their incentive claim. - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[0], suite.validatorAddrs[2], c(bondDenom, 1_000_000)) - suite.Require().NoError(err) - - // Start a new block to accumulate some delegation rewards globally. - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(2 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) - - // Delegate to the user's unbonded validator to push it into the bonded validator set - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[2], suite.validatorAddrs[2], c(bondDenom, 4_000_000)) - suite.Require().NoError(err) - - // End the block to bond the user's validator - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - // but don't start the next block as it will accumulate delegator rewards and we won't be able to tell if the user's reward was synced. - - // Check that the user's claim has been synced. ie rewards added, index updated - claim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - - rewardIndexes, found := suite.keeper.GetDelegatorRewardIndexes(suite.ctx, bondDenom) - suite.Require().True(found) - globalIndex, found := rewardIndexes.Get(rewardsPerSecond[0].Denom) - suite.Require().True(found) - claimIndex, found := claim.RewardIndexes.GetRewardIndex(bondDenom) - suite.Require().True(found) - suite.Require().Equal(globalIndex, claimIndex.RewardIndexes[0].RewardFactor) - - suite.Require().Equal( - sdk.Coins(nil), - claim.Reward, - ) - - // Run another block and check the claim is accumulating more rewards - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(3 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) - - suite.keeper.SynchronizeDelegatorRewards(suite.ctx, suite.addrs[0], nil, false) - - // rewards are greater than before - laterClaim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().True(laterClaim.Reward.IsAllGT(claim.Reward)) - - // claim index has been updated to latest global value - laterClaimIndex, found := laterClaim.RewardIndexes.GetRewardIndex(bondDenom) - suite.Require().True(found) - rewardIndexes, found = suite.keeper.GetDelegatorRewardIndexes(suite.ctx, bondDenom) - suite.Require().True(found) - globalIndex, found = rewardIndexes.Get(rewardsPerSecond[0].Denom) - suite.Require().True(found) - suite.Require().Equal(globalIndex, laterClaimIndex.RewardIndexes[0].RewardFactor) -} - -// If a validator is slashed delegators should have their claims synced -func (suite *DelegatorRewardsTestSuite) TestSlashingValidatorSyncsClaim() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[0], cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[0]), cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[1]), cs(c("ukava", 1e9))) - - rewardsPerSecond := cs(c("hard", 122354)) - bondDenom := "ukava" - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleDelegatorRewardPeriod(bondDenom, rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - blockDuration := 10 * time.Second - - // Reduce the size of the validator set - stakingParams := suite.app.GetStakingKeeper().GetParams(suite.ctx) - stakingParams.MaxValidators = 2 - suite.app.GetStakingKeeper().SetParams(suite.ctx, stakingParams) - - // Create 2 validators - err := suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[0], c(bondDenom, 10_000_000)) - suite.Require().NoError(err) - err = suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[1], c(bondDenom, 10_000_000)) - suite.Require().NoError(err) - - // End the block so validators become bonded - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(1 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) // height and time in header are ignored by module begin blockers - - // Delegate to a bonded validator from the test user. This will initialize their incentive claim. - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[0], suite.validatorAddrs[1], c(bondDenom, 1_000_000)) - suite.Require().NoError(err) - - // Check that claim has been created with synced reward index but no reward coins - initialClaim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.True(found) - initialGlobalIndex, found := suite.keeper.GetDelegatorRewardIndexes(suite.ctx, bondDenom) - suite.True(found) - initialClaimIndex, found := initialClaim.RewardIndexes.GetRewardIndex(bondDenom) - suite.True(found) - suite.Require().Equal(initialGlobalIndex, initialClaimIndex.RewardIndexes) - suite.True(initialClaim.Reward.Empty()) // Initial claim should not have any rewards - - // Start a new block to accumulate some delegation rewards for the user. - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(2 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) // height and time in header are ignored by module begin blockers - - // Fetch validator and slash them - stakingKeeper := suite.app.GetStakingKeeper() - validator, found := stakingKeeper.GetValidator(suite.ctx, suite.validatorAddrs[1]) - suite.Require().True(found) - suite.Require().True(validator.GetTokens().IsPositive()) - fraction := sdk.NewDecWithPrec(5, 1) - - consAddr, err := validator.GetConsAddr() - suite.Require().NoError(err) - - stakingKeeper.Slash(suite.ctx, consAddr, suite.ctx.BlockHeight(), 10, fraction) - - // Check that the user's claim has been synced. ie rewards added, index updated - claim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - globalIndex, found := suite.keeper.GetDelegatorRewardIndexes(suite.ctx, bondDenom) - suite.Require().True(found) - claimIndex, found := claim.RewardIndexes.GetRewardIndex(bondDenom) - suite.Require().True(found) - suite.Require().Equal(globalIndex, claimIndex.RewardIndexes) - - // Check that rewards were added - suite.Require().Equal( - cs(c(rewardsPerSecond[0].Denom, 58264)), - claim.Reward, - ) - - // Check that reward factor increased from initial value - suite.True(claimIndex.RewardIndexes[0].RewardFactor.GT(initialClaimIndex.RewardIndexes[0].RewardFactor)) -} - -// Given a delegation to a bonded validator, when a user redelegates everything to another (bonded) validator, the user's claim is synced -func (suite *DelegatorRewardsTestSuite) TestRedelegationSyncsClaim() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[0], cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[0]), cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[1]), cs(c("ukava", 1e9))) - - rewardsPerSecond := cs(c("hard", 122354)) - bondDenom := "ukava" - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleDelegatorRewardPeriod(bondDenom, rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime) - blockDuration := 10 * time.Second - - // Create 2 validators - err := suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[0], c(bondDenom, 10_000_000)) - suite.Require().NoError(err) - err = suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[1], c(bondDenom, 5_000_000)) - suite.Require().NoError(err) - - // Delete genesis validator to not influence rewards - suite.app.DeleteGenesisValidator(suite.T(), suite.ctx) - - // Delegatefrom the test user. This will initialize their incentive claim. - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[0], suite.validatorAddrs[0], c(bondDenom, 1_000_000)) - suite.Require().NoError(err) - - // Start a new block to accumulate some delegation rewards globally. - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(1 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) // height and time in header are ignored by module begin blockers - - // Redelegate the user's delegation between the two validators. This should trigger hooks that sync the user's claim. - err = suite.deliverMsgRedelegate(suite.ctx, suite.addrs[0], suite.validatorAddrs[0], suite.validatorAddrs[1], c(bondDenom, 1_000_000)) - suite.Require().NoError(err) - - // Check that the user's claim has been synced. ie rewards added, index updated - claim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - - globalIndex, found := suite.keeper.GetDelegatorRewardIndexes(suite.ctx, bondDenom) - suite.Require().True(found) - claimIndex, found := claim.RewardIndexes.GetRewardIndex(bondDenom) - suite.Require().True(found) - suite.Require().Equal(globalIndex, claimIndex.RewardIndexes) - suite.Require().Equal( - cs(c(rewardsPerSecond[0].Denom, 76471)), - claim.Reward, - ) -} - -func TestDelegatorRewardsTestSuite(t *testing.T) { - suite.Run(t, new(DelegatorRewardsTestSuite)) -} diff --git a/x/incentive/keeper/rewards_earn.go b/x/incentive/keeper/rewards_earn.go deleted file mode 100644 index 6d176efd..00000000 --- a/x/incentive/keeper/rewards_earn.go +++ /dev/null @@ -1,363 +0,0 @@ -package keeper - -import ( - "errors" - "fmt" - "sort" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - earntypes "github.com/kava-labs/kava/x/earn/types" - "github.com/kava-labs/kava/x/incentive/types" - - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" -) - -// AccumulateEarnRewards calculates new rewards to distribute this block and updates the global indexes to reflect this. -// The provided rewardPeriod must be valid to avoid panics in calculating time durations. -func (k Keeper) AccumulateEarnRewards(ctx sdk.Context, rewardPeriod types.MultiRewardPeriod) error { - if rewardPeriod.CollateralType == "bkava" { - return k.accumulateEarnBkavaRewards(ctx, rewardPeriod) - } - - k.accumulateEarnRewards( - ctx, - rewardPeriod.CollateralType, - rewardPeriod.Start, - rewardPeriod.End, - sdk.NewDecCoinsFromCoins(rewardPeriod.RewardsPerSecond...), - ) - - return nil -} - -func GetProportionalRewardsPerSecond( - rewardPeriod types.MultiRewardPeriod, - totalBkavaSupply sdkmath.Int, - singleBkavaSupply sdkmath.Int, -) sdk.DecCoins { - // Rate per bkava-xxx = rewardsPerSecond * % of bkava-xxx - // = rewardsPerSecond * (bkava-xxx / total bkava) - // = (rewardsPerSecond * bkava-xxx) / total bkava - - newRate := sdk.NewDecCoins() - - // Prevent division by zero, if there are no total shares then there are no - // rewards. - if totalBkavaSupply.IsZero() { - return newRate - } - - for _, rewardCoin := range rewardPeriod.RewardsPerSecond { - scaledAmount := sdk.NewDecFromInt(rewardCoin.Amount). - Mul(sdk.NewDecFromInt(singleBkavaSupply)). - Quo(sdk.NewDecFromInt(totalBkavaSupply)) - - newRate = newRate.Add(sdk.NewDecCoinFromDec(rewardCoin.Denom, scaledAmount)) - } - - return newRate -} - -// accumulateEarnBkavaRewards does the same as AccumulateEarnRewards but for -// *all* bkava vaults. -func (k Keeper) accumulateEarnBkavaRewards(ctx sdk.Context, rewardPeriod types.MultiRewardPeriod) error { - // All bkava vault denoms - bkavaVaultsDenoms := make(map[string]bool) - - // bkava vault denoms from earn records (non-empty vaults) - k.earnKeeper.IterateVaultRecords(ctx, func(record earntypes.VaultRecord) (stop bool) { - if k.liquidKeeper.IsDerivativeDenom(ctx, record.TotalShares.Denom) { - bkavaVaultsDenoms[record.TotalShares.Denom] = true - } - - return false - }) - - // bkava vault denoms from past incentive indexes, may include vaults - // that were fully withdrawn. - k.IterateEarnRewardIndexes(ctx, func(vaultDenom string, indexes types.RewardIndexes) (stop bool) { - if k.liquidKeeper.IsDerivativeDenom(ctx, vaultDenom) { - bkavaVaultsDenoms[vaultDenom] = true - } - - return false - }) - - totalBkavaValue, err := k.liquidKeeper.GetTotalDerivativeValue(ctx) - if err != nil { - return err - } - - i := 0 - sortedBkavaVaultsDenoms := make([]string, len(bkavaVaultsDenoms)) - for vaultDenom := range bkavaVaultsDenoms { - sortedBkavaVaultsDenoms[i] = vaultDenom - i++ - } - - // Sort the vault denoms to ensure deterministic iteration order. - sort.Strings(sortedBkavaVaultsDenoms) - - // Accumulate rewards for each bkava vault. - for _, bkavaDenom := range sortedBkavaVaultsDenoms { - derivativeValue, err := k.liquidKeeper.GetDerivativeValue(ctx, bkavaDenom) - if err != nil { - return err - } - - k.accumulateBkavaEarnRewards( - ctx, - bkavaDenom, - rewardPeriod.Start, - rewardPeriod.End, - GetProportionalRewardsPerSecond( - rewardPeriod, - totalBkavaValue.Amount, - derivativeValue.Amount, - ), - ) - } - - return nil -} - -func (k Keeper) accumulateBkavaEarnRewards( - ctx sdk.Context, - collateralType string, - periodStart time.Time, - periodEnd time.Time, - periodRewardsPerSecond sdk.DecCoins, -) { - // Collect staking rewards for this validator, does not have any start/end - // period time restrictions. - stakingRewards := k.collectDerivativeStakingRewards(ctx, collateralType) - - // Collect incentive rewards - // **Total rewards** for vault per second, NOT per share - perSecondRewards := k.collectPerSecondRewards( - ctx, - collateralType, - periodStart, - periodEnd, - periodRewardsPerSecond, - ) - - // **Total rewards** for vault per second, NOT per share - rewards := stakingRewards.Add(perSecondRewards...) - - // Distribute rewards by incrementing indexes - indexes, found := k.GetEarnRewardIndexes(ctx, collateralType) - if !found { - indexes = types.RewardIndexes{} - } - - totalSourceShares := k.getEarnTotalSourceShares(ctx, collateralType) - var increment types.RewardIndexes - if totalSourceShares.GT(sdk.ZeroDec()) { - // Divide total rewards by total shares to get the reward **per share** - // Leave as nil if no source shares - increment = types.NewRewardIndexesFromCoins(rewards).Quo(totalSourceShares) - } - updatedIndexes := indexes.Add(increment) - - if len(updatedIndexes) > 0 { - // the store panics when setting empty or nil indexes - k.SetEarnRewardIndexes(ctx, collateralType, updatedIndexes) - } -} - -func (k Keeper) collectDerivativeStakingRewards(ctx sdk.Context, collateralType string) sdk.DecCoins { - rewards, err := k.liquidKeeper.CollectStakingRewardsByDenom(ctx, collateralType, types.IncentiveMacc) - if err != nil { - if !errors.Is(err, distrtypes.ErrNoValidatorDistInfo) && - !errors.Is(err, distrtypes.ErrEmptyDelegationDistInfo) { - panic(fmt.Sprintf("failed to collect staking rewards for %s: %s", collateralType, err)) - } - - // otherwise there's no validator or delegation yet - rewards = nil - } - - // Bug with NewDecCoinsFromCoins when calling passing 0 amount Coin, see - // https://github.com/cosmos/cosmos-sdk/pull/12903 - // Fix is in Cosmos-SDK v0.47.0 - var decCoins sdk.DecCoins - for _, coin := range rewards { - if coin.IsValid() { - decCoins = append(decCoins, sdk.NewDecCoinFromCoin(coin)) - } - } - - return decCoins -} - -func (k Keeper) collectPerSecondRewards( - ctx sdk.Context, - collateralType string, - periodStart time.Time, - periodEnd time.Time, - periodRewardsPerSecond sdk.DecCoins, -) sdk.DecCoins { - previousAccrualTime, found := k.GetEarnRewardAccrualTime(ctx, collateralType) - if !found { - previousAccrualTime = ctx.BlockTime() - } - - rewards, accumulatedTo := types.CalculatePerSecondRewards( - periodStart, - periodEnd, - periodRewardsPerSecond, - previousAccrualTime, - ctx.BlockTime(), - ) - - k.SetEarnRewardAccrualTime(ctx, collateralType, accumulatedTo) - - // Don't need to move funds as they're assumed to be in the IncentiveMacc module account already. - return rewards -} - -func (k Keeper) accumulateEarnRewards( - ctx sdk.Context, - collateralType string, - periodStart time.Time, - periodEnd time.Time, - periodRewardsPerSecond sdk.DecCoins, -) { - previousAccrualTime, found := k.GetEarnRewardAccrualTime(ctx, collateralType) - if !found { - previousAccrualTime = ctx.BlockTime() - } - - indexes, found := k.GetEarnRewardIndexes(ctx, collateralType) - if !found { - indexes = types.RewardIndexes{} - } - - acc := types.NewAccumulator(previousAccrualTime, indexes) - - totalSourceShares := k.getEarnTotalSourceShares(ctx, collateralType) - - acc.AccumulateDecCoins( - periodStart, - periodEnd, - periodRewardsPerSecond, - totalSourceShares, - ctx.BlockTime(), - ) - - k.SetEarnRewardAccrualTime(ctx, collateralType, acc.PreviousAccumulationTime) - if len(acc.Indexes) > 0 { - // the store panics when setting empty or nil indexes - k.SetEarnRewardIndexes(ctx, collateralType, acc.Indexes) - } -} - -// getEarnTotalSourceShares fetches the sum of all source shares for a earn reward. -// In the case of earn, these are the total (earn module) shares in a particular vault. -func (k Keeper) getEarnTotalSourceShares(ctx sdk.Context, vaultDenom string) sdk.Dec { - totalShares, found := k.earnKeeper.GetVaultTotalShares(ctx, vaultDenom) - if !found { - return sdk.ZeroDec() - } - return totalShares.Amount -} - -// InitializeEarnReward creates a new claim with zero rewards and indexes matching the global indexes. -// If the claim already exists it just updates the indexes. -func (k Keeper) InitializeEarnReward(ctx sdk.Context, vaultDenom string, owner sdk.AccAddress) { - claim, found := k.GetEarnClaim(ctx, owner) - if !found { - claim = types.NewEarnClaim(owner, sdk.Coins{}, nil) - } - - globalRewardIndexes, found := k.GetEarnRewardIndexes(ctx, vaultDenom) - if !found { - globalRewardIndexes = types.RewardIndexes{} - } - claim.RewardIndexes = claim.RewardIndexes.With(vaultDenom, globalRewardIndexes) - - k.SetEarnClaim(ctx, claim) -} - -// SynchronizeEarnReward updates the claim object by adding any accumulated rewards -// and updating the reward index value. -func (k Keeper) SynchronizeEarnReward( - ctx sdk.Context, - vaultDenom string, - owner sdk.AccAddress, - shares sdk.Dec, -) { - claim, found := k.GetEarnClaim(ctx, owner) - if !found { - return - } - claim = k.synchronizeEarnReward(ctx, claim, vaultDenom, owner, shares) - - k.SetEarnClaim(ctx, claim) -} - -// synchronizeEarnReward updates the reward and indexes in a earn claim for one vault. -func (k *Keeper) synchronizeEarnReward( - ctx sdk.Context, - claim types.EarnClaim, - vaultDenom string, - owner sdk.AccAddress, - shares sdk.Dec, -) types.EarnClaim { - globalRewardIndexes, found := k.GetEarnRewardIndexes(ctx, vaultDenom) - if !found { - // The global factor is only not found if - // - the vault has not started accumulating rewards yet (either there is no reward specified in params, or the reward start time hasn't been hit) - // - OR it was wrongly deleted from state (factors should never be removed while unsynced claims exist) - // If not found we could either skip this sync, or assume the global factor is zero. - // Skipping will avoid storing unnecessary factors in the claim for non rewarded vaults. - // And in the event a global factor is wrongly deleted, it will avoid this function panicking when calculating rewards. - return claim - } - - userRewardIndexes, found := claim.RewardIndexes.Get(vaultDenom) - if !found { - // Normally the reward indexes should always be found. - // But if a vault was not rewarded then becomes rewarded (ie a reward period is added to params), then the indexes will be missing from claims for that vault. - // So given the reward period was just added, assume the starting value for any global reward indexes, which is an empty slice. - userRewardIndexes = types.RewardIndexes{} - } - - newRewards, err := k.CalculateRewards(userRewardIndexes, globalRewardIndexes, shares) - if err != nil { - // Global reward factors should never decrease, as it would lead to a negative update to claim.Rewards. - // This panics if a global reward factor decreases or disappears between the old and new indexes. - panic(fmt.Sprintf("corrupted global reward indexes found: %v", err)) - } - - claim.Reward = claim.Reward.Add(newRewards...) - claim.RewardIndexes = claim.RewardIndexes.With(vaultDenom, globalRewardIndexes) - - return claim -} - -// GetSynchronizedEarnClaim fetches a earn claim from the store and syncs rewards for all rewarded vaults. -func (k Keeper) GetSynchronizedEarnClaim(ctx sdk.Context, owner sdk.AccAddress) (types.EarnClaim, bool) { - claim, found := k.GetEarnClaim(ctx, owner) - if !found { - return types.EarnClaim{}, false - } - - shares, found := k.earnKeeper.GetVaultAccountShares(ctx, owner) - if !found { - shares = earntypes.NewVaultShares() - } - - k.IterateEarnRewardIndexes(ctx, func(vaultDenom string, _ types.RewardIndexes) bool { - vaultAmount := shares.AmountOf(vaultDenom) - claim = k.synchronizeEarnReward(ctx, claim, vaultDenom, owner, vaultAmount) - - return false - }) - - return claim, true -} diff --git a/x/incentive/keeper/rewards_earn_accum_integration_test.go b/x/incentive/keeper/rewards_earn_accum_integration_test.go deleted file mode 100644 index 892323db..00000000 --- a/x/incentive/keeper/rewards_earn_accum_integration_test.go +++ /dev/null @@ -1,649 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - abci "github.com/cometbft/cometbft/abci/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - earntypes "github.com/kava-labs/kava/x/earn/types" - "github.com/kava-labs/kava/x/incentive/testutil" - "github.com/kava-labs/kava/x/incentive/types" -) - -type AccumulateEarnRewardsIntegrationTests struct { - testutil.IntegrationTester - - keeper TestKeeper - userAddrs []sdk.AccAddress - valAddrs []sdk.ValAddress -} - -func TestAccumulateEarnRewardsIntegrationTests(t *testing.T) { - suite.Run(t, new(AccumulateEarnRewardsIntegrationTests)) -} - -func (suite *AccumulateEarnRewardsIntegrationTests) SetupTest() { - suite.IntegrationTester.SetupTest() - - suite.keeper = TestKeeper{ - Keeper: suite.App.GetIncentiveKeeper(), - } - - _, addrs := app.GeneratePrivKeyAddressPairs(5) - suite.userAddrs = addrs[0:2] - suite.valAddrs = []sdk.ValAddress{ - sdk.ValAddress(addrs[2]), - sdk.ValAddress(addrs[3]), - } - - // Setup app with test state - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(addrs[0], cs(c("ukava", 1e12))). - WithSimpleAccount(addrs[1], cs(c("ukava", 1e12))). - WithSimpleAccount(addrs[2], cs(c("ukava", 1e12))). - WithSimpleAccount(addrs[3], cs(c("ukava", 1e12))) - - incentiveBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.GenesisTime). - WithSimpleEarnRewardPeriod("bkava", cs()) - - savingsBuilder := testutil.NewSavingsGenesisBuilder(). - WithSupportedDenoms("bkava") - - earnBuilder := testutil.NewEarnGenesisBuilder(). - WithAllowedVaults(earntypes.AllowedVault{ - Denom: "bkava", - Strategies: earntypes.StrategyTypes{earntypes.STRATEGY_TYPE_SAVINGS}, - IsPrivateVault: false, - AllowedDepositors: nil, - }) - - stakingBuilder := testutil.NewStakingGenesisBuilder() - - mintBuilder := testutil.NewMintGenesisBuilder(). - WithInflationMax(sdk.OneDec()). - WithInflationMin(sdk.OneDec()). - WithMinter(sdk.OneDec(), sdk.ZeroDec()). - WithMintDenom("ukava") - - suite.StartChainWithBuilders( - authBuilder, - incentiveBuilder, - savingsBuilder, - earnBuilder, - stakingBuilder, - mintBuilder, - ) -} - -func (suite *AccumulateEarnRewardsIntegrationTests) TestStateUpdatedWhenBlockTimeHasIncreased() { - suite.AddIncentiveEarnMultiRewardPeriod( - types.NewMultiRewardPeriod( - true, - "bkava", // reward period is set for "bkava" to apply to all vaults - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ), - ) - - derivative0, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[0], c("ukava", 800000)) - suite.NoError(err) - derivative1, err := suite.MintLiquidAnyValAddr(suite.userAddrs[1], suite.valAddrs[1], c("ukava", 200000)) - suite.NoError(err) - - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[0], derivative0, earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[1], derivative1, earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: derivative0.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: derivative1.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - - suite.keeper.storeGlobalEarnIndexes(suite.Ctx, globalIndexes) - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, derivative0.Denom, suite.Ctx.BlockTime()) - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, derivative1.Denom, suite.Ctx.BlockTime()) - - val0 := suite.GetAbciValidator(suite.valAddrs[0]) - val1 := suite.GetAbciValidator(suite.valAddrs[1]) - - // Mint tokens, distribute to validators, claim staking rewards - // 1 hour later - _, resBeginBlock := suite.NextBlockAfterWithReq( - 1*time.Hour, - abci.RequestEndBlock{}, - abci.RequestBeginBlock{ - LastCommitInfo: abci.CommitInfo{ - Votes: []abci.VoteInfo{ - { - Validator: val0, - SignedLastBlock: true, - }, - { - Validator: val1, - SignedLastBlock: true, - }, - }, - }, - }, - ) - - validatorRewards, _ := suite.GetBeginBlockClaimedStakingRewards(resBeginBlock) - - suite.Require().Contains(validatorRewards, suite.valAddrs[1].String(), "there should be claim events for validator 0") - suite.Require().Contains(validatorRewards, suite.valAddrs[0].String(), "there should be claim events for validator 1") - - // check time and factors - - suite.StoredEarnTimeEquals(derivative0.Denom, suite.Ctx.BlockTime()) - suite.StoredEarnTimeEquals(derivative1.Denom, suite.Ctx.BlockTime()) - - stakingRewardIndexes0 := sdk.NewDecFromInt(validatorRewards[suite.valAddrs[0].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(derivative0.Amount)) - - stakingRewardIndexes1 := sdk.NewDecFromInt(validatorRewards[suite.valAddrs[1].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(derivative1.Amount)) - - suite.StoredEarnIndexesEqual(derivative0.Denom, types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("7.22"), - }, - { - CollateralType: "ukava", - RewardFactor: d("3.64").Add(stakingRewardIndexes0), - }, - }) - suite.StoredEarnIndexesEqual(derivative1.Denom, types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("7.22"), - }, - { - CollateralType: "ukava", - RewardFactor: d("3.64").Add(stakingRewardIndexes1), - }, - }) -} - -func (suite *AccumulateEarnRewardsIntegrationTests) TestStateUpdatedWhenBlockTimeHasIncreased_partialDeposit() { - suite.AddIncentiveEarnMultiRewardPeriod( - types.NewMultiRewardPeriod( - true, - "bkava", // reward period is set for "bkava" to apply to all vaults - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ), - ) - - // 800000bkava0 minted, 700000 deposited - // 200000bkava1 minted, 100000 deposited - derivative0, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[0], c("ukava", 800000)) - suite.NoError(err) - derivative1, err := suite.MintLiquidAnyValAddr(suite.userAddrs[1], suite.valAddrs[1], c("ukava", 200000)) - suite.NoError(err) - - depositAmount0 := c(derivative0.Denom, 700000) - depositAmount1 := c(derivative1.Denom, 100000) - - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[0], depositAmount0, earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[1], depositAmount1, earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: derivative0.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: derivative1.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - - suite.keeper.storeGlobalEarnIndexes(suite.Ctx, globalIndexes) - - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, derivative0.Denom, suite.Ctx.BlockTime()) - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, derivative1.Denom, suite.Ctx.BlockTime()) - - val0 := suite.GetAbciValidator(suite.valAddrs[0]) - val1 := suite.GetAbciValidator(suite.valAddrs[1]) - - // Mint tokens, distribute to validators, claim staking rewards - // 1 hour later - _, resBeginBlock := suite.NextBlockAfterWithReq( - 1*time.Hour, - abci.RequestEndBlock{}, - abci.RequestBeginBlock{ - LastCommitInfo: abci.CommitInfo{ - Votes: []abci.VoteInfo{ - { - Validator: val0, - SignedLastBlock: true, - }, - { - Validator: val1, - SignedLastBlock: true, - }, - }, - }, - }, - ) - - validatorRewards, _ := suite.GetBeginBlockClaimedStakingRewards(resBeginBlock) - - suite.Require().Contains(validatorRewards, suite.valAddrs[1].String(), "there should be claim events for validator 0") - suite.Require().Contains(validatorRewards, suite.valAddrs[0].String(), "there should be claim events for validator 1") - - // check time and factors - - suite.StoredEarnTimeEquals(derivative0.Denom, suite.Ctx.BlockTime()) - suite.StoredEarnTimeEquals(derivative1.Denom, suite.Ctx.BlockTime()) - - // Divided by deposit amounts, not bank supply amounts - stakingRewardIndexes0 := sdk.NewDecFromInt(validatorRewards[suite.valAddrs[0].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(depositAmount0.Amount)) - - stakingRewardIndexes1 := sdk.NewDecFromInt(validatorRewards[suite.valAddrs[1].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(depositAmount1.Amount)) - - // Slightly increased rewards due to less bkava deposited - suite.StoredEarnIndexesEqual(derivative0.Denom, types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("8.248571428571428571"), - }, - { - CollateralType: "ukava", - RewardFactor: d("4.154285714285714286").Add(stakingRewardIndexes0), - }, - }) - - suite.StoredEarnIndexesEqual(derivative1.Denom, types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("14.42"), - }, - { - CollateralType: "ukava", - RewardFactor: d("7.24").Add(stakingRewardIndexes1), - }, - }) -} - -func (suite *AccumulateEarnRewardsIntegrationTests) TestStateUnchangedWhenBlockTimeHasNotIncreased() { - derivative0, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[0], c("ukava", 1000000)) - suite.NoError(err) - derivative1, err := suite.MintLiquidAnyValAddr(suite.userAddrs[1], suite.valAddrs[1], c("ukava", 1000000)) - suite.NoError(err) - - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[0], derivative0, earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[1], derivative1, earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: derivative0.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: derivative1.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.keeper.storeGlobalEarnIndexes(suite.Ctx, previousIndexes) - - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, derivative0.Denom, suite.Ctx.BlockTime()) - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, derivative1.Denom, suite.Ctx.BlockTime()) - - period := types.NewMultiRewardPeriod( - true, - "bkava", - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - // Must manually accumulate rewards as BeginBlockers only run when the block time increases - // This does not run any x/mint or x/distribution BeginBlockers - suite.keeper.AccumulateEarnRewards(suite.Ctx, period) - - // check time and factors - - suite.StoredEarnTimeEquals(derivative0.Denom, suite.Ctx.BlockTime()) - suite.StoredEarnTimeEquals(derivative1.Denom, suite.Ctx.BlockTime()) - - expected, f := previousIndexes.Get(derivative0.Denom) - suite.True(f) - suite.StoredEarnIndexesEqual(derivative0.Denom, expected) - - expected, f = previousIndexes.Get(derivative1.Denom) - suite.True(f) - suite.StoredEarnIndexesEqual(derivative1.Denom, expected) -} - -func (suite *AccumulateEarnRewardsIntegrationTests) TestNoAccumulationWhenSourceSharesAreZero() { - suite.AddIncentiveEarnMultiRewardPeriod( - types.NewMultiRewardPeriod( - true, - "bkava", // reward period is set for "bkava" to apply to all vaults - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ), - ) - - derivative0, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[0], c("ukava", 1000000)) - suite.NoError(err) - derivative1, err := suite.MintLiquidAnyValAddr(suite.userAddrs[1], suite.valAddrs[1], c("ukava", 1000000)) - suite.NoError(err) - - // No earn deposits - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: derivative0.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: derivative1.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.keeper.storeGlobalEarnIndexes(suite.Ctx, previousIndexes) - - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, derivative0.Denom, suite.Ctx.BlockTime()) - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, derivative1.Denom, suite.Ctx.BlockTime()) - - val0 := suite.GetAbciValidator(suite.valAddrs[0]) - val1 := suite.GetAbciValidator(suite.valAddrs[1]) - - // Mint tokens, distribute to validators, claim staking rewards - // 1 hour later - _, _ = suite.NextBlockAfterWithReq( - 1*time.Hour, - abci.RequestEndBlock{}, - abci.RequestBeginBlock{ - LastCommitInfo: abci.CommitInfo{ - Votes: []abci.VoteInfo{ - { - Validator: val0, - SignedLastBlock: true, - }, - { - Validator: val1, - SignedLastBlock: true, - }, - }, - }, - }, - ) - // check time and factors - - suite.StoredEarnTimeEquals(derivative0.Denom, suite.Ctx.BlockTime()) - suite.StoredEarnTimeEquals(derivative1.Denom, suite.Ctx.BlockTime()) - - expected, f := previousIndexes.Get(derivative0.Denom) - suite.True(f) - suite.StoredEarnIndexesEqual(derivative0.Denom, expected) - - expected, f = previousIndexes.Get(derivative1.Denom) - suite.True(f) - suite.StoredEarnIndexesEqual(derivative1.Denom, expected) -} - -func (suite *AccumulateEarnRewardsIntegrationTests) TestStateAddedWhenStateDoesNotExist() { - suite.AddIncentiveEarnMultiRewardPeriod( - types.NewMultiRewardPeriod( - true, - "bkava", // reward period is set for "bkava" to apply to all vaults - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ), - ) - - derivative0, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[0], c("ukava", 1000000)) - suite.NoError(err) - derivative1, err := suite.MintLiquidAnyValAddr(suite.userAddrs[1], suite.valAddrs[1], c("ukava", 1000000)) - suite.NoError(err) - - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[0], derivative0, earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[1], derivative1, earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - - val0 := suite.GetAbciValidator(suite.valAddrs[0]) - val1 := suite.GetAbciValidator(suite.valAddrs[1]) - - _, resBeginBlock := suite.NextBlockAfterWithReq( - 1*time.Hour, - abci.RequestEndBlock{}, - abci.RequestBeginBlock{ - LastCommitInfo: abci.CommitInfo{ - Votes: []abci.VoteInfo{ - { - Validator: val0, - SignedLastBlock: true, - }, - { - Validator: val1, - SignedLastBlock: true, - }, - }, - }, - }, - ) - - // After the second accumulation both current block time and indexes should be stored. - suite.StoredEarnTimeEquals(derivative0.Denom, suite.Ctx.BlockTime()) - suite.StoredEarnTimeEquals(derivative1.Denom, suite.Ctx.BlockTime()) - - validatorRewards0, _ := suite.GetBeginBlockClaimedStakingRewards(resBeginBlock) - - firstStakingRewardIndexes0 := sdk.NewDecFromInt(validatorRewards0[suite.valAddrs[0].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(derivative0.Amount)) - - firstStakingRewardIndexes1 := sdk.NewDecFromInt(validatorRewards0[suite.valAddrs[1].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(derivative1.Amount)) - - // After the first accumulation only the current block time should be stored. - // The indexes will be empty as no time has passed since the previous block because it didn't exist. - suite.StoredEarnTimeEquals(derivative0.Denom, suite.Ctx.BlockTime()) - suite.StoredEarnTimeEquals(derivative1.Denom, suite.Ctx.BlockTime()) - - // First accumulation can have staking rewards, but no other rewards - suite.StoredEarnIndexesEqual(derivative0.Denom, types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: firstStakingRewardIndexes0, - }, - }) - suite.StoredEarnIndexesEqual(derivative1.Denom, types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: firstStakingRewardIndexes1, - }, - }) - - _, resBeginBlock = suite.NextBlockAfterWithReq( - 1*time.Hour, - abci.RequestEndBlock{}, - abci.RequestBeginBlock{ - LastCommitInfo: abci.CommitInfo{ - Votes: []abci.VoteInfo{ - { - Validator: val0, - SignedLastBlock: true, - }, - { - Validator: val1, - SignedLastBlock: true, - }, - }, - }, - }, - ) - - // After the second accumulation both current block time and indexes should be stored. - suite.StoredEarnTimeEquals(derivative0.Denom, suite.Ctx.BlockTime()) - suite.StoredEarnTimeEquals(derivative1.Denom, suite.Ctx.BlockTime()) - - validatorRewards1, _ := suite.GetBeginBlockClaimedStakingRewards(resBeginBlock) - - secondStakingRewardIndexes0 := sdk.NewDecFromInt(validatorRewards1[suite.valAddrs[0].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(derivative0.Amount)) - - secondStakingRewardIndexes1 := sdk.NewDecFromInt(validatorRewards1[suite.valAddrs[1].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(derivative1.Amount)) - - // Second accumulation has both staking rewards and incentive rewards - // ukava incentive rewards: 3600 * 1000 / (2 * 1000000) == 1.8 - suite.StoredEarnIndexesEqual(derivative0.Denom, types.RewardIndexes{ - { - CollateralType: "ukava", - // Incentive rewards + both staking rewards - RewardFactor: d("1.8").Add(firstStakingRewardIndexes0).Add(secondStakingRewardIndexes0), - }, - { - CollateralType: "earn", - RewardFactor: d("3.6"), - }, - }) - suite.StoredEarnIndexesEqual(derivative1.Denom, types.RewardIndexes{ - { - CollateralType: "ukava", - // Incentive rewards + both staking rewards - RewardFactor: d("1.8").Add(firstStakingRewardIndexes1).Add(secondStakingRewardIndexes1), - }, - { - CollateralType: "earn", - RewardFactor: d("3.6"), - }, - }) -} - -func (suite *AccumulateEarnRewardsIntegrationTests) TestNoPanicWhenStateDoesNotExist() { - derivative0, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[0], c("ukava", 1000000)) - suite.NoError(err) - derivative1, err := suite.MintLiquidAnyValAddr(suite.userAddrs[1], suite.valAddrs[1], c("ukava", 1000000)) - suite.NoError(err) - - period := types.NewMultiRewardPeriod( - true, - "bkava", - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(), - ) - - // Accumulate with no earn shares and no rewards per second will result in no increment to the indexes. - // No increment and no previous indexes stored, results in an updated of nil. Setting this in the state panics. - // Check there is no panic. - suite.NotPanics(func() { - // This does not update any state, as there are no bkava vaults - // to iterate over, denoms are unknown - suite.keeper.AccumulateEarnRewards(suite.Ctx, period) - }) - - // Times are not stored for vaults with no state - suite.StoredEarnTimeEquals(derivative0.Denom, time.Time{}) - suite.StoredEarnTimeEquals(derivative1.Denom, time.Time{}) - suite.StoredEarnIndexesEqual(derivative0.Denom, nil) - suite.StoredEarnIndexesEqual(derivative1.Denom, nil) -} diff --git a/x/incentive/keeper/rewards_earn_accum_test.go b/x/incentive/keeper/rewards_earn_accum_test.go deleted file mode 100644 index c83e47ed..00000000 --- a/x/incentive/keeper/rewards_earn_accum_test.go +++ /dev/null @@ -1,781 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - earntypes "github.com/kava-labs/kava/x/earn/types" - "github.com/kava-labs/kava/x/incentive/types" -) - -type AccumulateEarnRewardsTests struct { - unitTester -} - -func (suite *AccumulateEarnRewardsTests) storedTimeEquals(vaultDenom string, expected time.Time) { - storedTime, found := suite.keeper.GetEarnRewardAccrualTime(suite.ctx, vaultDenom) - suite.Equal(found, expected != time.Time{}, "expected time is %v but time found = %v", expected, found) - if found { - suite.Equal(expected, storedTime) - } else { - suite.Empty(storedTime) - } -} - -func (suite *AccumulateEarnRewardsTests) storedIndexesEqual(vaultDenom string, expected types.RewardIndexes) { - storedIndexes, found := suite.keeper.GetEarnRewardIndexes(suite.ctx, vaultDenom) - suite.Equal(found, expected != nil, "expected indexes is %v but indexes found = %v", expected, found) - if found { - suite.Equal(expected, storedIndexes) - } else { - suite.Empty(storedIndexes) - } -} - -func TestAccumulateEarnRewards(t *testing.T) { - suite.Run(t, new(AccumulateEarnRewardsTests)) -} - -func (suite *AccumulateEarnRewardsTests) TestStateUpdatedWhenBlockTimeHasIncreased() { - vaultDenom := "usdx" - - earnKeeper := newFakeEarnKeeper().addVault(vaultDenom, earntypes.NewVaultShare(vaultDenom, d("1000000"))) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, earnKeeper) - - suite.storeGlobalEarnIndexes(types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - }) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - vaultDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(vaultDenom, newAccrualTime) - suite.storedIndexesEqual(vaultDenom, types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("7.22"), - }, - { - CollateralType: "ukava", - RewardFactor: d("3.64"), - }, - }) -} - -func (suite *AccumulateEarnRewardsTests) TestStateUpdatedWhenBlockTimeHasIncreased_bkava() { - vaultDenom1 := "bkava-meow" - vaultDenom2 := "bkava-woof" - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - earnKeeper := newFakeEarnKeeper(). - addVault(vaultDenom1, earntypes.NewVaultShare(vaultDenom1, d("800000"))). - addVault(vaultDenom2, earntypes.NewVaultShare(vaultDenom2, d("200000"))) - - liquidKeeper := newFakeLiquidKeeper(). - addDerivative(suite.ctx, vaultDenom1, i(800000)). - addDerivative(suite.ctx, vaultDenom2, i(200000)) - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, liquidKeeper, earnKeeper) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: vaultDenom2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - - suite.storeGlobalEarnIndexes(globalIndexes) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom1, previousAccrualTime) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom2, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - rewardPeriod := types.NewMultiRewardPeriod( - true, - "bkava", // reward period is set for "bkava" to apply to all vaults - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - suite.keeper.AccumulateEarnRewards(suite.ctx, rewardPeriod) - - // check time and factors - - suite.storedTimeEquals(vaultDenom1, newAccrualTime) - suite.storedTimeEquals(vaultDenom2, newAccrualTime) - - // Each vault gets the same ukava per second, assuming shares prices are the same. - // The share amount determines how much is actually distributed to the vault. - expectedIndexes := types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("7.22"), - }, - { - CollateralType: "ukava", - RewardFactor: d("3.64"). // base incentive - Add(d("360")), // staking rewards, 10% of total bkava per second - }, - } - - suite.storedIndexesEqual(vaultDenom1, expectedIndexes) - suite.storedIndexesEqual(vaultDenom2, expectedIndexes) -} - -func (suite *AccumulateEarnRewardsTests) TestStateUpdatedWhenBlockTimeHasIncreased_bkava_partialDeposit() { - vaultDenom1 := "bkava-meow" - vaultDenom2 := "bkava-woof" - - vaultDenom1Supply := i(800000) - vaultDenom2Supply := i(200000) - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - liquidKeeper := newFakeLiquidKeeper(). - addDerivative(suite.ctx, vaultDenom1, vaultDenom1Supply). - addDerivative(suite.ctx, vaultDenom2, vaultDenom2Supply) - - vault1Shares := d("700000") - vault2Shares := d("100000") - - // More bkava minted than deposited into earn - // Rewards are higher per-share as a result - earnKeeper := newFakeEarnKeeper(). - addVault(vaultDenom1, earntypes.NewVaultShare(vaultDenom1, vault1Shares)). - addVault(vaultDenom2, earntypes.NewVaultShare(vaultDenom2, vault2Shares)) - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, liquidKeeper, earnKeeper) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: vaultDenom2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - - suite.storeGlobalEarnIndexes(globalIndexes) - - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom1, previousAccrualTime) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom2, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - rewardPeriod := types.NewMultiRewardPeriod( - true, - "bkava", // reward period is set for "bkava" to apply to all vaults - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - suite.keeper.AccumulateEarnRewards(suite.ctx, rewardPeriod) - - // check time and factors - - suite.storedTimeEquals(vaultDenom1, newAccrualTime) - suite.storedTimeEquals(vaultDenom2, newAccrualTime) - - // Slightly increased rewards due to less bkava deposited - suite.storedIndexesEqual(vaultDenom1, types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("8.248571428571428571"), - }, - { - CollateralType: "ukava", - RewardFactor: d("4.154285714285714286"). // base incentive - Add(sdk.NewDecFromInt(vaultDenom1Supply). // staking rewards - QuoInt64(10). - MulInt64(3600). - Quo(vault1Shares), - ), - }, - }) - - // Much higher rewards per share because only a small amount of bkava is - // deposited. The **total** amount of incentives distributed to this vault - // is still the same proportional amount. - - // Fixed amount total rewards distributed to the vault - // Fewer shares deposited -> higher rewards per share - - // 7.2ukava shares per second for 1 hour (started with 0.04) - // total rewards claimable = 7.2 * 100000 shares = 720000 ukava - - // 720000ukava distributed which is 20% of total bkava ukava rewards - // total rewards for *all* bkava vaults for 1 hour - // = 1000ukava per second * 3600 == 3600000ukava - // vaultDenom2 has 20% of the total bkava amount so it should get 20% of 3600000ukava == 720000ukava - - vault2expectedIndexes := types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("14.42"), - }, - { - CollateralType: "ukava", - RewardFactor: d("7.24"). - Add(sdk.NewDecFromInt(vaultDenom2Supply). - QuoInt64(10). - MulInt64(3600). - Quo(vault2Shares), - ), - }, - } - suite.storedIndexesEqual(vaultDenom2, vault2expectedIndexes) -} - -func (suite *AccumulateEarnRewardsTests) TestStateUnchangedWhenBlockTimeHasNotIncreased() { - vaultDenom := "usdx" - - earnKeeper := newFakeEarnKeeper().addVault(vaultDenom, earntypes.NewVaultShare(vaultDenom, d("1000000"))) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, earnKeeper) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom, previousAccrualTime) - - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - vaultDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(vaultDenom, previousAccrualTime) - expected, f := previousIndexes.Get(vaultDenom) - suite.True(f) - suite.storedIndexesEqual(vaultDenom, expected) -} - -func (suite *AccumulateEarnRewardsTests) TestStateUnchangedWhenBlockTimeHasNotIncreased_bkava() { - vaultDenom1 := "bkava-meow" - vaultDenom2 := "bkava-woof" - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - earnKeeper := newFakeEarnKeeper(). - addVault(vaultDenom1, earntypes.NewVaultShare(vaultDenom1, d("1000000"))). - addVault(vaultDenom2, earntypes.NewVaultShare(vaultDenom2, d("1000000"))) - - liquidKeeper := newFakeLiquidKeeper(). - addDerivative(suite.ctx, vaultDenom1, i(1000000)). - addDerivative(suite.ctx, vaultDenom2, i(1000000)) - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, liquidKeeper, earnKeeper) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: vaultDenom2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(previousIndexes) - - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom1, previousAccrualTime) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom2, previousAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - "bkava", - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(vaultDenom1, previousAccrualTime) - suite.storedTimeEquals(vaultDenom2, previousAccrualTime) - - expected, f := previousIndexes.Get(vaultDenom1) - suite.True(f) - suite.storedIndexesEqual(vaultDenom1, expected) - - expected, f = previousIndexes.Get(vaultDenom2) - suite.True(f) - suite.storedIndexesEqual(vaultDenom2, expected) -} - -func (suite *AccumulateEarnRewardsTests) TestNoAccumulationWhenSourceSharesAreZero() { - vaultDenom := "usdx" - - earnKeeper := newFakeEarnKeeper() // no vault, so no source shares - liquidKeeper := newFakeLiquidKeeper() - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, liquidKeeper, earnKeeper) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(7 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - vaultDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(vaultDenom, firstAccrualTime) - expected, f := previousIndexes.Get(vaultDenom) - suite.True(f) - suite.storedIndexesEqual(vaultDenom, expected) -} - -func (suite *AccumulateEarnRewardsTests) TestNoAccumulationWhenSourceSharesAreZero_bkava() { - vaultDenom1 := "bkava-meow" - vaultDenom2 := "bkava-woof" - - earnKeeper := newFakeEarnKeeper() // no vault, so no source shares - liquidKeeper := newFakeLiquidKeeper() - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, liquidKeeper, earnKeeper) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: vaultDenom2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom1, previousAccrualTime) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom2, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(7 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - "bkava", - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - // TODO: There are no bkava vaults to iterate over, so the accrual times are - // not updated - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(vaultDenom1, firstAccrualTime) - suite.storedTimeEquals(vaultDenom2, firstAccrualTime) - - expected, f := previousIndexes.Get(vaultDenom1) - suite.True(f) - suite.storedIndexesEqual(vaultDenom1, expected) - - expected, f = previousIndexes.Get(vaultDenom2) - suite.True(f) - suite.storedIndexesEqual(vaultDenom2, expected) -} - -func (suite *AccumulateEarnRewardsTests) TestStateAddedWhenStateDoesNotExist() { - vaultDenom := "usdx" - - earnKeeper := newFakeEarnKeeper().addVault(vaultDenom, earntypes.NewVaultShare(vaultDenom, d("1000000"))) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, earnKeeper) - - period := types.NewMultiRewardPeriod( - true, - vaultDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), - ) - - firstAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // After the first accumulation only the current block time should be stored. - // The indexes will be empty as no time has passed since the previous block because it didn't exist. - suite.storedTimeEquals(vaultDenom, firstAccrualTime) - suite.storedIndexesEqual(vaultDenom, nil) - - secondAccrualTime := firstAccrualTime.Add(10 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(secondAccrualTime) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // After the second accumulation both current block time and indexes should be stored. - suite.storedTimeEquals(vaultDenom, secondAccrualTime) - suite.storedIndexesEqual(vaultDenom, types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.01"), - }, - }) -} - -func (suite *AccumulateEarnRewardsTests) TestStateAddedWhenStateDoesNotExist_bkava() { - vaultDenom1 := "bkava-meow" - vaultDenom2 := "bkava-woof" - - firstAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - earnKeeper := newFakeEarnKeeper(). - addVault(vaultDenom1, earntypes.NewVaultShare(vaultDenom1, d("1000000"))). - addVault(vaultDenom2, earntypes.NewVaultShare(vaultDenom2, d("1000000"))) - - liquidKeeper := newFakeLiquidKeeper(). - addDerivative(suite.ctx, vaultDenom1, i(1000000)). - addDerivative(suite.ctx, vaultDenom2, i(1000000)) - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, liquidKeeper, earnKeeper) - - period := types.NewMultiRewardPeriod( - true, - "bkava", - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), - ) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // After the first accumulation only the current block time should be stored. - // The indexes will be empty as no time has passed since the previous block because it didn't exist. - suite.storedTimeEquals(vaultDenom1, firstAccrualTime) - suite.storedTimeEquals(vaultDenom2, firstAccrualTime) - - suite.storedIndexesEqual(vaultDenom1, nil) - suite.storedIndexesEqual(vaultDenom2, nil) - - secondAccrualTime := firstAccrualTime.Add(10 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(secondAccrualTime) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // After the second accumulation both current block time and indexes should be stored. - suite.storedTimeEquals(vaultDenom1, secondAccrualTime) - suite.storedTimeEquals(vaultDenom2, secondAccrualTime) - - expectedIndexes := types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.01"), - }, - { - CollateralType: "ukava", - // 10% of total bkava for rewards per second for 10 seconds - // 1ukava per share per second + regular 0.005ukava incentive rewards - RewardFactor: d("1.005"), - }, - } - - suite.storedIndexesEqual(vaultDenom1, expectedIndexes) - suite.storedIndexesEqual(vaultDenom2, expectedIndexes) -} - -func (suite *AccumulateEarnRewardsTests) TestNoPanicWhenStateDoesNotExist() { - vaultDenom := "usdx" - - earnKeeper := newFakeEarnKeeper() - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, earnKeeper) - - period := types.NewMultiRewardPeriod( - true, - vaultDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(), - ) - - accrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(accrualTime) - - // Accumulate with no earn shares and no rewards per second will result in no increment to the indexes. - // No increment and no previous indexes stored, results in an updated of nil. Setting this in the state panics. - // Check there is no panic. - suite.NotPanics(func() { - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - }) - - suite.storedTimeEquals(vaultDenom, accrualTime) - suite.storedIndexesEqual(vaultDenom, nil) -} - -func (suite *AccumulateEarnRewardsTests) TestNoPanicWhenStateDoesNotExist_bkava() { - vaultDenom1 := "bkava-meow" - vaultDenom2 := "bkava-woof" - - earnKeeper := newFakeEarnKeeper() - liquidKeeper := newFakeLiquidKeeper() - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, liquidKeeper, earnKeeper) - - period := types.NewMultiRewardPeriod( - true, - "bkava", - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(), - ) - - accrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(accrualTime) - - // Accumulate with no earn shares and no rewards per second will result in no increment to the indexes. - // No increment and no previous indexes stored, results in an updated of nil. Setting this in the state panics. - // Check there is no panic. - suite.NotPanics(func() { - // This does not update any state, as there are no bkava vaults - // to iterate over, denoms are unknown - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - }) - - // Times are not stored for vaults with no state - suite.storedTimeEquals(vaultDenom1, time.Time{}) - suite.storedTimeEquals(vaultDenom2, time.Time{}) - suite.storedIndexesEqual(vaultDenom1, nil) - suite.storedIndexesEqual(vaultDenom2, nil) -} - -func (suite *AccumulateEarnRewardsTests) TestNoAccumulationWhenBeforeStartTime() { - vaultDenom := "usdx" - - earnKeeper := newFakeEarnKeeper().addVault(vaultDenom, earntypes.NewVaultShare(vaultDenom, d("1000000"))) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, earnKeeper) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(10 * time.Second) - - period := types.NewMultiRewardPeriod( - true, - vaultDenom, - firstAccrualTime.Add(time.Nanosecond), // start time after accrual time - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // The accrual time should be updated, but the indexes unchanged - suite.storedTimeEquals(vaultDenom, firstAccrualTime) - expectedIndexes, f := previousIndexes.Get(vaultDenom) - suite.True(f) - suite.storedIndexesEqual(vaultDenom, expectedIndexes) -} - -func (suite *AccumulateEarnRewardsTests) TestPanicWhenCurrentTimeLessThanPrevious() { - vaultDenom := "usdx" - - earnKeeper := newFakeEarnKeeper().addVault(vaultDenom, earntypes.NewVaultShare(vaultDenom, d("1000000"))) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, earnKeeper) - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom, previousAccrualTime) - - firstAccrualTime := time.Time{} - - period := types.NewMultiRewardPeriod( - true, - vaultDenom, - time.Time{}, // start time after accrual time - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.Panics(func() { - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - }) -} diff --git a/x/incentive/keeper/rewards_earn_init_test.go b/x/incentive/keeper/rewards_earn_init_test.go deleted file mode 100644 index 4931ae0b..00000000 --- a/x/incentive/keeper/rewards_earn_init_test.go +++ /dev/null @@ -1,195 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/incentive/types" -) - -// InitializeEarnRewardTests runs unit tests for the keeper.InitializeEarnReward method -// -// inputs -// - claim in store if it exists -// - global indexes in store -// -// outputs -// - sets or creates a claim -type InitializeEarnRewardTests struct { - unitTester -} - -func TestInitializeEarnReward(t *testing.T) { - suite.Run(t, new(InitializeEarnRewardTests)) -} - -func (suite *InitializeEarnRewardTests) TestClaimAddedWhenClaimDoesNotExistAndNoRewards() { - // When a claim doesn't exist, and a user deposits to a non-rewarded pool; - // then a claim is added with no rewards and no indexes - - vaultDenom := "usdx" - - // no global indexes stored as this pool is not rewarded - - owner := arbitraryAddress() - - suite.keeper.InitializeEarnReward(suite.ctx, vaultDenom, owner) - - syncedClaim, found := suite.keeper.GetEarnClaim(suite.ctx, owner) - suite.True(found) - // A new claim should have empty indexes. It doesn't strictly need the vaultDenom either. - expectedIndexes := types.MultiRewardIndexes{{ - CollateralType: vaultDenom, - RewardIndexes: nil, - }} - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // a new claim should start with 0 rewards - suite.Equal(sdk.Coins(nil), syncedClaim.Reward) -} - -func (suite *InitializeEarnRewardTests) TestClaimAddedWhenClaimDoesNotExistAndRewardsExist() { - // When a claim doesn't exist, and a user deposits to a rewarded pool; - // then a claim is added with no rewards and indexes matching the global indexes - - vaultDenom := "usdx" - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(globalIndexes) - - owner := arbitraryAddress() - - suite.keeper.InitializeEarnReward(suite.ctx, vaultDenom, owner) - - syncedClaim, found := suite.keeper.GetEarnClaim(suite.ctx, owner) - suite.True(found) - // a new claim should start with the current global indexes - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // a new claim should start with 0 rewards - suite.Equal(sdk.Coins(nil), syncedClaim.Reward) -} - -func (suite *InitializeEarnRewardTests) TestClaimUpdatedWhenClaimExistsAndNoRewards() { - // When a claim exists, and a user deposits to a new non-rewarded pool; - // then the claim's rewards don't change - - preexistingvaultDenom := "preexisting" - preexistingIndexes := types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - } - - newVaultDenom := "btcb:usdx" - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: preexistingvaultDenom, - RewardIndexes: preexistingIndexes, - }, - }, - } - suite.storeEarnClaim(claim) - - // no global indexes stored as the new pool is not rewarded - - suite.keeper.InitializeEarnReward(suite.ctx, newVaultDenom, claim.Owner) - - syncedClaim, _ := suite.keeper.GetEarnClaim(suite.ctx, claim.Owner) - // The preexisting indexes shouldn't be changed. It doesn't strictly need the new vaultDenom either. - expectedIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingvaultDenom, - RewardIndexes: preexistingIndexes, - }, - { - CollateralType: newVaultDenom, - RewardIndexes: nil, - }, - } - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // init should never alter the rewards - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *InitializeEarnRewardTests) TestClaimUpdatedWhenClaimExistsAndRewardsExist() { - // When a claim exists, and a user deposits to a new rewarded pool; - // then the claim's rewards don't change and the indexes are updated to match the global indexes - - preexistingvaultDenom := "preexisting" - preexistingIndexes := types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - } - - newVaultDenom := "btcb:usdx" - newIndexes := types.RewardIndexes{ - { - CollateralType: "otherrewarddenom", - RewardFactor: d("1000.001"), - }, - } - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: preexistingvaultDenom, - RewardIndexes: preexistingIndexes, - }, - }, - } - suite.storeEarnClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingvaultDenom, - RewardIndexes: increaseRewardFactors(preexistingIndexes), - }, - { - CollateralType: newVaultDenom, - RewardIndexes: newIndexes, - }, - } - suite.storeGlobalEarnIndexes(globalIndexes) - - suite.keeper.InitializeEarnReward(suite.ctx, newVaultDenom, claim.Owner) - - syncedClaim, _ := suite.keeper.GetEarnClaim(suite.ctx, claim.Owner) - // only the indexes for the new pool should be updated - expectedIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingvaultDenom, - RewardIndexes: preexistingIndexes, - }, - { - CollateralType: newVaultDenom, - RewardIndexes: newIndexes, - }, - } - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // init should never alter the rewards - suite.Equal(claim.Reward, syncedClaim.Reward) -} diff --git a/x/incentive/keeper/rewards_earn_proportional_test.go b/x/incentive/keeper/rewards_earn_proportional_test.go deleted file mode 100644 index 76805c18..00000000 --- a/x/incentive/keeper/rewards_earn_proportional_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/types" - "github.com/stretchr/testify/require" -) - -func TestGetProportionalRewardPeriod(t *testing.T) { - tests := []struct { - name string - giveRewardPeriod types.MultiRewardPeriod - giveTotalBkavaSupply sdkmath.Int - giveSingleBkavaSupply sdkmath.Int - wantRewardsPerSecond sdk.DecCoins - }{ - { - "full amount", - types.NewMultiRewardPeriod( - true, - "", - time.Time{}, - time.Time{}, - cs(c("ukava", 100), c("hard", 200)), - ), - i(100), - i(100), - toDcs(c("ukava", 100), c("hard", 200)), - }, - { - "3/4 amount", - types.NewMultiRewardPeriod( - true, - "", - time.Time{}, - time.Time{}, - cs(c("ukava", 100), c("hard", 200)), - ), - i(10_000000), - i(7_500000), - toDcs(c("ukava", 75), c("hard", 150)), - }, - { - "half amount", - types.NewMultiRewardPeriod( - true, - "", - time.Time{}, - time.Time{}, - cs(c("ukava", 100), c("hard", 200)), - ), - i(100), - i(50), - toDcs(c("ukava", 50), c("hard", 100)), - }, - { - "under 1 unit", - types.NewMultiRewardPeriod( - true, - "", - time.Time{}, - time.Time{}, - cs(c("ukava", 100), c("hard", 200)), - ), - i(1000), // total bkava - i(1), // bkava supply of this specific vault - dcs(dc("ukava", "0.1"), dc("hard", "0.2")), // rewards per second rounded to 0 if under 1ukava/1hard - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - rewardsPerSecond := keeper.GetProportionalRewardsPerSecond( - tt.giveRewardPeriod, - tt.giveTotalBkavaSupply, - tt.giveSingleBkavaSupply, - ) - - require.Equal(t, tt.wantRewardsPerSecond, rewardsPerSecond) - }) - } -} diff --git a/x/incentive/keeper/rewards_earn_staking_integration_test.go b/x/incentive/keeper/rewards_earn_staking_integration_test.go deleted file mode 100644 index 59466c13..00000000 --- a/x/incentive/keeper/rewards_earn_staking_integration_test.go +++ /dev/null @@ -1,191 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - abci "github.com/cometbft/cometbft/abci/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/app" - earntypes "github.com/kava-labs/kava/x/earn/types" - "github.com/kava-labs/kava/x/incentive/testutil" - "github.com/kava-labs/kava/x/incentive/types" - "github.com/stretchr/testify/suite" -) - -type EarnStakingRewardsIntegrationTestSuite struct { - testutil.IntegrationTester - - keeper TestKeeper - userAddrs []sdk.AccAddress - valAddrs []sdk.ValAddress -} - -func TestEarnStakingRewardsIntegrationTestSuite(t *testing.T) { - suite.Run(t, new(EarnStakingRewardsIntegrationTestSuite)) -} - -func (suite *EarnStakingRewardsIntegrationTestSuite) SetupTest() { - suite.IntegrationTester.SetupTest() - - suite.keeper = TestKeeper{ - Keeper: suite.App.GetIncentiveKeeper(), - } - - _, addrs := app.GeneratePrivKeyAddressPairs(5) - suite.userAddrs = addrs[0:2] - suite.valAddrs = []sdk.ValAddress{ - sdk.ValAddress(addrs[2]), - sdk.ValAddress(addrs[3]), - } - - // Setup app with test state - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(addrs[0], cs(c("ukava", 1e12))). - WithSimpleAccount(addrs[1], cs(c("ukava", 1e12))). - WithSimpleAccount(addrs[2], cs(c("ukava", 1e12))). - WithSimpleAccount(addrs[3], cs(c("ukava", 1e12))) - - incentiveBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.GenesisTime). - WithSimpleEarnRewardPeriod("bkava", cs()) - - savingsBuilder := testutil.NewSavingsGenesisBuilder(). - WithSupportedDenoms("bkava") - - earnBuilder := testutil.NewEarnGenesisBuilder(). - WithAllowedVaults(earntypes.AllowedVault{ - Denom: "bkava", - Strategies: earntypes.StrategyTypes{earntypes.STRATEGY_TYPE_SAVINGS}, - IsPrivateVault: false, - AllowedDepositors: nil, - }) - - stakingBuilder := testutil.NewStakingGenesisBuilder() - - mintBuilder := testutil.NewMintGenesisBuilder(). - WithInflationMax(sdk.OneDec()). - WithInflationMin(sdk.OneDec()). - WithMinter(sdk.OneDec(), sdk.ZeroDec()). - WithMintDenom("ukava") - - suite.StartChainWithBuilders( - authBuilder, - incentiveBuilder, - savingsBuilder, - earnBuilder, - stakingBuilder, - mintBuilder, - ) -} - -func (suite *EarnStakingRewardsIntegrationTestSuite) TestStakingRewardsDistributed() { - // derivative 1: 8 total staked, 7 to earn, 1 not in earn - // derivative 2: 2 total staked, 1 to earn, 1 not in earn - userMintAmount0 := c("ukava", 8e9) - userMintAmount1 := c("ukava", 2e9) - - userDepositAmount0 := i(7e9) - userDepositAmount1 := i(1e9) - - // Create two validators - derivative0, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[0], userMintAmount0) - suite.Require().NoError(err) - - derivative1, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[1], userMintAmount1) - suite.Require().NoError(err) - - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[0], sdk.NewCoin(derivative0.Denom, userDepositAmount0), earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[0], sdk.NewCoin(derivative1.Denom, userDepositAmount1), earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - - // Get derivative denoms - lq := suite.App.GetLiquidKeeper() - vaultDenom1 := lq.GetLiquidStakingTokenDenom(suite.valAddrs[0]) - vaultDenom2 := lq.GetLiquidStakingTokenDenom(suite.valAddrs[1]) - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.Ctx = suite.Ctx.WithBlockTime(previousAccrualTime) - - initialVault1RewardFactor := d("0.04") - initialVault2RewardFactor := d("0.04") - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: initialVault1RewardFactor, - }, - }, - }, - { - CollateralType: vaultDenom2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: initialVault2RewardFactor, - }, - }, - }, - } - - suite.keeper.storeGlobalEarnIndexes(suite.Ctx, globalIndexes) - - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, vaultDenom1, suite.Ctx.BlockTime()) - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, vaultDenom2, suite.Ctx.BlockTime()) - - val := suite.GetAbciValidator(suite.valAddrs[0]) - - // Mint tokens, distribute to validators, claim staking rewards - // 1 hour later - _, resBeginBlock := suite.NextBlockAfterWithReq( - 1*time.Hour, - abci.RequestEndBlock{}, - abci.RequestBeginBlock{ - LastCommitInfo: abci.CommitInfo{ - Votes: []abci.VoteInfo{{ - Validator: val, - SignedLastBlock: true, - }}, - }, - }, - ) - - // check time and factors - suite.StoredEarnTimeEquals(vaultDenom1, suite.Ctx.BlockTime()) - suite.StoredEarnTimeEquals(vaultDenom2, suite.Ctx.BlockTime()) - - validatorRewards, _ := suite.GetBeginBlockClaimedStakingRewards(resBeginBlock) - - suite.Require().Contains(validatorRewards, suite.valAddrs[0].String(), "there should be claim events for validator 1") - suite.Require().Contains(validatorRewards, suite.valAddrs[1].String(), "there should be claim events for validator 2") - - // Total staking rewards / total source shares (**deposited in earn** not total minted) - // types.RewardIndexes.Quo() uses Dec.Quo() which uses bankers rounding. - // So we need to use Dec.Quo() to also round vs Dec.QuoInt() which truncates - expectedIndexes1 := sdk.NewDecFromInt(validatorRewards[suite.valAddrs[0].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(userDepositAmount0)) - - expectedIndexes2 := sdk.NewDecFromInt(validatorRewards[suite.valAddrs[1].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(userDepositAmount1)) - - // Only contains staking rewards - suite.StoredEarnIndexesEqual(vaultDenom1, types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: initialVault1RewardFactor.Add(expectedIndexes1), - }, - }) - - suite.StoredEarnIndexesEqual(vaultDenom2, types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: initialVault2RewardFactor.Add(expectedIndexes2), - }, - }) -} diff --git a/x/incentive/keeper/rewards_earn_staking_test.go b/x/incentive/keeper/rewards_earn_staking_test.go deleted file mode 100644 index 5df7ed17..00000000 --- a/x/incentive/keeper/rewards_earn_staking_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package keeper_test - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - earntypes "github.com/kava-labs/kava/x/earn/types" - "github.com/kava-labs/kava/x/incentive/types" -) - -func (suite *AccumulateEarnRewardsTests) TestStakingRewardsDistributed() { - vaultDenom1 := "bkava-meow" - vaultDenom2 := "bkava-woof" - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - vaultDenom1Supply := i(800000) - vaultDenom2Supply := i(200000) - - liquidKeeper := newFakeLiquidKeeper(). - addDerivative(suite.ctx, vaultDenom1, vaultDenom1Supply). - addDerivative(suite.ctx, vaultDenom2, vaultDenom2Supply) - - vault1Shares := d("700000") - vault2Shares := d("100000") - - // More bkava minted than deposited into earn - // Rewards are higher per-share as a result - earnKeeper := newFakeEarnKeeper(). - addVault(vaultDenom1, earntypes.NewVaultShare(vaultDenom1, vault1Shares)). - addVault(vaultDenom2, earntypes.NewVaultShare(vaultDenom2, vault2Shares)) - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, liquidKeeper, earnKeeper) - - initialVault1RewardFactor := d("0.04") - initialVault2RewardFactor := d("0.04") - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: initialVault1RewardFactor, - }, - }, - }, - { - CollateralType: vaultDenom2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: initialVault2RewardFactor, - }, - }, - }, - } - - suite.storeGlobalEarnIndexes(globalIndexes) - - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom1, previousAccrualTime) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom2, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - rewardPeriod := types.NewMultiRewardPeriod( - true, - "bkava", // reward period is set for "bkava" to apply to all vaults - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(), // no incentives, so only the staking rewards are distributed - ) - suite.keeper.AccumulateEarnRewards(suite.ctx, rewardPeriod) - - // check time and factors - - suite.storedTimeEquals(vaultDenom1, newAccrualTime) - suite.storedTimeEquals(vaultDenom2, newAccrualTime) - - // Only contains staking rewards - suite.storedIndexesEqual(vaultDenom1, types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: initialVault1RewardFactor. - Add(sdk.NewDecFromInt(vaultDenom1Supply). - QuoInt64(10). - MulInt64(3600). - Quo(vault1Shares)), - }, - }) - - suite.storedIndexesEqual(vaultDenom2, types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: initialVault2RewardFactor. - Add(sdk.NewDecFromInt(vaultDenom2Supply). - QuoInt64(10). - MulInt64(3600). - Quo(vault2Shares)), - }, - }) -} diff --git a/x/incentive/keeper/rewards_earn_sync_test.go b/x/incentive/keeper/rewards_earn_sync_test.go deleted file mode 100644 index e557f4a8..00000000 --- a/x/incentive/keeper/rewards_earn_sync_test.go +++ /dev/null @@ -1,473 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - earntypes "github.com/kava-labs/kava/x/earn/types" - "github.com/kava-labs/kava/x/incentive/types" -) - -// SynchronizeEarnRewardTests runs unit tests for the keeper.SynchronizeEarnReward method -// -// inputs -// - claim in store (only claim.RewardIndexes, claim.Reward) -// - global indexes in store -// - shares function arg -// -// outputs -// - sets a claim -type SynchronizeEarnRewardTests struct { - unitTester -} - -func TestSynchronizeEarnReward(t *testing.T) { - suite.Run(t, new(SynchronizeEarnRewardTests)) -} - -func (suite *SynchronizeEarnRewardTests) TestClaimUpdatedWhenGlobalIndexesHaveIncreased() { - // This is the normal case - // Given some time has passed (meaning the global indexes have increased) - // When the claim is synced - // The user earns rewards for the time passed, and the claim indexes are updated - - originalReward := arbitraryCoins() - vaultDenom := "cats" - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeEarnClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(globalIndexes) - - userShares := d("1000000000") - - suite.keeper.SynchronizeEarnReward(suite.ctx, vaultDenom, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetEarnClaim(suite.ctx, claim.Owner) - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * user shares - suite.Equal( - cs(c("rewarddenom", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeEarnRewardTests) TestClaimUnchangedWhenGlobalIndexesUnchanged() { - // It should be safe to call SynchronizeEarnReward multiple times - - vaultDenom := "cats" - unchangingIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - } - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: unchangingIndexes, - } - suite.storeEarnClaim(claim) - - suite.storeGlobalEarnIndexes(unchangingIndexes) - - userShares := d("1000000000") - - suite.keeper.SynchronizeEarnReward(suite.ctx, vaultDenom, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetEarnClaim(suite.ctx, claim.Owner) - // claim should have the same rewards and indexes as before - suite.Equal(claim, syncedClaim) -} - -func (suite *SynchronizeEarnRewardTests) TestClaimUpdatedWhenNewRewardAdded() { - // When a new reward is added (via gov) for a vault the user has already deposited to, and the claim is synced; - // Then the user earns rewards for the time since the reward was added, and the indexes are added to the claim. - - originalReward := arbitraryCoins() - newlyRewardVaultDenom := "newlyRewardedVault" - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "currentlyRewardedVault", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeEarnClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: "currentlyRewardedVault", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: newlyRewardVaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(globalIndexes) - - userShares := d("1000000000") - - suite.keeper.SynchronizeEarnReward(suite.ctx, newlyRewardVaultDenom, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetEarnClaim(suite.ctx, claim.Owner) - // the new indexes should be added to the claim, but the old ones should be unchanged - newlyRewrdedIndexes, _ := globalIndexes.Get(newlyRewardVaultDenom) - expectedIndexes := claim.RewardIndexes.With(newlyRewardVaultDenom, newlyRewrdedIndexes) - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * shares for the synced vault - // The old index for `newlyrewarded` isn't in the claim, so it's added starting at 0 for calculating the reward. - suite.Equal( - cs(c("otherreward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeEarnRewardTests) TestClaimUnchangedWhenNoReward() { - // When a vault is not rewarded but the user has deposited to that vault, and the claim is synced; - // Then the claim should be the same. - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeEarnClaim(claim) - - vaultDenom := "nonRewardVault" - // No global indexes stored as this vault is not rewarded - - userShares := d("1000000000") - - suite.keeper.SynchronizeEarnReward(suite.ctx, vaultDenom, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetEarnClaim(suite.ctx, claim.Owner) - suite.Equal(claim, syncedClaim) -} - -func (suite *SynchronizeEarnRewardTests) TestClaimUpdatedWhenNewRewardDenomAdded() { - // When a new reward coin is added (via gov) to an already rewarded vault (that the user has already deposited to), and the claim is synced; - // Then the user earns rewards for the time since the reward was added, and the new indexes are added. - - originalReward := arbitraryCoins() - vaultDenom := "cats" - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeEarnClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(globalIndexes) - - userShares := d("1000000000") - - suite.keeper.SynchronizeEarnReward(suite.ctx, vaultDenom, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetEarnClaim(suite.ctx, claim.Owner) - // indexes should have the new reward denom added - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * shares - // The old index for `otherreward` isn't in the claim, so it's added starting at 0 for calculating the reward. - suite.Equal( - cs(c("reward", 1_000_001_000_000), c("otherreward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeEarnRewardTests) TestClaimUpdatedWhenGlobalIndexesIncreasedAndSourceIsZero() { - // Given some time has passed (meaning the global indexes have increased) - // When the claim is synced, but the user has no shares - // The user earns no rewards for the time passed, but the claim indexes are updated - - vaultDenom := "cats" - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeEarnClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(globalIndexes) - - userShares := d("0") - - suite.keeper.SynchronizeEarnReward(suite.ctx, vaultDenom, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetEarnClaim(suite.ctx, claim.Owner) - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // reward is unchanged - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *SynchronizeEarnRewardTests) TestGetSyncedClaim_ClaimUnchangedWhenNoGlobalIndexes() { - vaultDenom_1 := "usdx" - owner := arbitraryAddress() - - earnKeeper := newFakeEarnKeeper(). - addDeposit(owner, earntypes.NewVaultShare("usdx", d("1000000000"))) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, earnKeeper) - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: owner, - Reward: nil, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: vaultDenom_1, - RewardIndexes: nil, // this state only happens because Init stores empty indexes - }, - }, - } - suite.storeEarnClaim(claim) - - // no global indexes for any vault - - syncedClaim, f := suite.keeper.GetSynchronizedEarnClaim(suite.ctx, claim.Owner) - suite.True(f) - - // indexes are unchanged - suite.Equal(claim.RewardIndexes, syncedClaim.RewardIndexes) - // reward is unchanged - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *SynchronizeEarnRewardTests) TestGetSyncedClaim_ClaimUpdatedWhenMissingIndexAndHasNoSourceShares() { - vaultDenom_1 := "usdx" - vaultDenom_2 := "ukava" - owner := arbitraryAddress() - - // owner has no shares in any vault - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, newFakeEarnKeeper()) - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: owner, - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: vaultDenom_1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom1", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeEarnClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom_1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom1", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: vaultDenom_2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom2", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(globalIndexes) - - syncedClaim, f := suite.keeper.GetSynchronizedEarnClaim(suite.ctx, claim.Owner) - suite.True(f) - - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // reward is unchanged - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *SynchronizeEarnRewardTests) TestGetSyncedClaim_ClaimUpdatedWhenMissingIndexButHasSourceShares() { - VaultDenom_1 := "usdx" - VaultDenom_2 := "ukava" - owner := arbitraryAddress() - - earnKeeper := newFakeEarnKeeper(). - addVault(VaultDenom_1, earntypes.NewVaultShare(VaultDenom_1, d("1000000000"))). - addVault(VaultDenom_2, earntypes.NewVaultShare(VaultDenom_2, d("1000000000"))). - addDeposit(owner, earntypes.NewVaultShare(VaultDenom_1, d("1000000000"))). - addDeposit(owner, earntypes.NewVaultShare(VaultDenom_2, d("1000000000"))) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, earnKeeper) - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: owner, - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: VaultDenom_1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom1", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeEarnClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: VaultDenom_1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom1", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: VaultDenom_2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom2", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(globalIndexes) - - syncedClaim, f := suite.keeper.GetSynchronizedEarnClaim(suite.ctx, claim.Owner) - suite.True(f) - - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // reward is incremented - expectedReward := cs(c("rewarddenom1", 1_000_001_000_000), c("rewarddenom2", 2_000_002_000_000)) - suite.Equal(claim.Reward.Add(expectedReward...), syncedClaim.Reward) -} diff --git a/x/incentive/keeper/rewards_savings.go b/x/incentive/keeper/rewards_savings.go deleted file mode 100644 index 1b843bdf..00000000 --- a/x/incentive/keeper/rewards_savings.go +++ /dev/null @@ -1,150 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/incentive/types" - savingstypes "github.com/kava-labs/kava/x/savings/types" -) - -// AccumulateSavingsRewards calculates new rewards to distribute this block and updates the global indexes -func (k Keeper) AccumulateSavingsRewards(ctx sdk.Context, rewardPeriod types.MultiRewardPeriod) { - previousAccrualTime, found := k.GetSavingsRewardAccrualTime(ctx, rewardPeriod.CollateralType) - if !found { - previousAccrualTime = ctx.BlockTime() - } - - indexes, found := k.GetSavingsRewardIndexes(ctx, rewardPeriod.CollateralType) - if !found { - indexes = types.RewardIndexes{} - } - - acc := types.NewAccumulator(previousAccrualTime, indexes) - - savingsMacc := k.accountKeeper.GetModuleAccount(ctx, savingstypes.ModuleName) - maccCoins := k.bankKeeper.GetAllBalances(ctx, savingsMacc.GetAddress()) - denomBalance := maccCoins.AmountOf(rewardPeriod.CollateralType) - - acc.Accumulate(rewardPeriod, sdk.NewDecFromInt(denomBalance), ctx.BlockTime()) - - k.SetSavingsRewardAccrualTime(ctx, rewardPeriod.CollateralType, acc.PreviousAccumulationTime) - - if len(acc.Indexes) > 0 { - // the store panics when setting empty or nil indexes - k.SetSavingsRewardIndexes(ctx, rewardPeriod.CollateralType, acc.Indexes) - } -} - -// InitializeSavingsReward initializes a savings claim by creating the claim and -// setting the reward factor indexes -func (k Keeper) InitializeSavingsReward(ctx sdk.Context, deposit savingstypes.Deposit) { - claim, found := k.GetSavingsClaim(ctx, deposit.Depositor) - if !found { - claim = types.NewSavingsClaim(deposit.Depositor, sdk.Coins{}, nil) - } - - rewardIndexes := claim.RewardIndexes - for _, coin := range deposit.Amount { - globalRewardIndexes, found := k.GetSavingsRewardIndexes(ctx, coin.Denom) - if !found { - globalRewardIndexes = types.RewardIndexes{} - } - rewardIndexes = rewardIndexes.With(coin.Denom, globalRewardIndexes) - } - claim.RewardIndexes = rewardIndexes - - k.SetSavingsClaim(ctx, claim) -} - -// SynchronizeSavingsReward updates the claim object by adding any accumulated rewards -// and updating the reward index value -func (k Keeper) SynchronizeSavingsReward(ctx sdk.Context, deposit savingstypes.Deposit, incomingDenoms []string) { - claim, found := k.GetSavingsClaim(ctx, deposit.Depositor) - if !found { - return - } - - // Set the reward factor on claim to the global reward factor for each incoming denom - for _, denom := range incomingDenoms { - globalRewardIndexes, found := k.GetSavingsRewardIndexes(ctx, denom) - if !found { - globalRewardIndexes = types.RewardIndexes{} - } - claim.RewardIndexes = claim.RewardIndexes.With(denom, globalRewardIndexes) - } - - // Existing denoms have their reward indexes + reward amount synced - existingDenoms := setDifference(getDenoms(deposit.Amount), incomingDenoms) - for _, denom := range existingDenoms { - claim = k.synchronizeSingleSavingsReward(ctx, claim, denom, sdk.NewDecFromInt(deposit.Amount.AmountOf(denom))) - } - - k.SetSavingsClaim(ctx, claim) -} - -// synchronizeSingleSavingsReward synchronizes a single rewarded savings denom in a savings claim. -// It returns the claim without setting in the store. -// The public methods for accessing and modifying claims are preferred over this one. Direct modification of claims is easy to get wrong. -func (k Keeper) synchronizeSingleSavingsReward(ctx sdk.Context, claim types.SavingsClaim, denom string, sourceShares sdk.Dec) types.SavingsClaim { - globalRewardIndexes, found := k.GetSavingsRewardIndexes(ctx, denom) - if !found { - // The global factor is only not found if - // - the savings denom has not started accumulating rewards yet (either there is no reward specified in params, or the reward start time hasn't been hit) - // - OR it was wrongly deleted from state (factors should never be removed while unsynced claims exist) - // If not found we could either skip this sync, or assume the global factor is zero. - // Skipping will avoid storing unnecessary factors in the claim for non rewarded denoms. - // And in the event a global factor is wrongly deleted, it will avoid this function panicking when calculating rewards. - return claim - } - - userRewardIndexes, found := claim.RewardIndexes.Get(denom) - if !found { - // Normally the reward indexes should always be found. - // But if a denom was not rewarded then becomes rewarded (ie a reward period is added to params), then the indexes will be missing from claims for that supplied denom. - // So given the reward period was just added, assume the starting value for any global reward indexes, which is an empty slice. - userRewardIndexes = types.RewardIndexes{} - } - - newRewards, err := k.CalculateRewards(userRewardIndexes, globalRewardIndexes, sourceShares) - if err != nil { - // Global reward factors should never decrease, as it would lead to a negative update to claim.Rewards. - // This panics if a global reward factor decreases or disappears between the old and new indexes. - panic(fmt.Sprintf("corrupted global reward indexes found: %v", err)) - } - - claim.Reward = claim.Reward.Add(newRewards...) - claim.RewardIndexes = claim.RewardIndexes.With(denom, globalRewardIndexes) - - return claim -} - -// GetSynchronizedSavingsClaim fetches a savings claim from the store and syncs rewards for all rewarded pools. -func (k Keeper) GetSynchronizedSavingsClaim(ctx sdk.Context, owner sdk.AccAddress) (types.SavingsClaim, bool) { - claim, found := k.GetSavingsClaim(ctx, owner) - if !found { - return types.SavingsClaim{}, false - } - - deposit, found := k.savingsKeeper.GetDeposit(ctx, owner) - if !found { - return types.SavingsClaim{}, false - } - - for _, coin := range deposit.Amount { - claim = k.synchronizeSingleSavingsReward(ctx, claim, coin.Denom, sdk.NewDecFromInt(coin.Amount)) - } - - return claim, true -} - -// SynchronizeSavingsClaim syncs a savings reward claim from its store -func (k Keeper) SynchronizeSavingsClaim(ctx sdk.Context, owner sdk.AccAddress) { - deposit, found := k.savingsKeeper.GetDeposit(ctx, owner) - if !found { - return - } - - k.SynchronizeSavingsReward(ctx, deposit, []string{}) -} diff --git a/x/incentive/keeper/rewards_savings_accum_test.go b/x/incentive/keeper/rewards_savings_accum_test.go deleted file mode 100644 index 2485669a..00000000 --- a/x/incentive/keeper/rewards_savings_accum_test.go +++ /dev/null @@ -1,163 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - savingskeeper "github.com/kava-labs/kava/x/savings/keeper" - savingstypes "github.com/kava-labs/kava/x/savings/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/testutil" - "github.com/kava-labs/kava/x/incentive/types" -) - -// Test suite used for all keeper tests -type SavingsRewardsTestSuite struct { - suite.Suite - - keeper keeper.Keeper - savingsKeeper savingskeeper.Keeper - - app app.TestApp - ctx sdk.Context - - genesisTime time.Time - addrs []sdk.AccAddress -} - -// SetupTest is run automatically before each suite test -func (suite *SavingsRewardsTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - _, allAddrs := app.GeneratePrivKeyAddressPairs(10) - suite.addrs = allAddrs[:5] - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *SavingsRewardsTestSuite) SetupApp() { - suite.app = app.NewTestApp() - - suite.keeper = suite.app.GetIncentiveKeeper() - suite.savingsKeeper = suite.app.GetSavingsKeeper() - - suite.ctx = suite.app.NewContext(true, tmproto.Header{Height: 1, Time: suite.genesisTime}) -} - -func (suite *SavingsRewardsTestSuite) SetupWithGenState(authBuilder *app.AuthBankGenesisBuilder, incentBuilder testutil.IncentiveGenesisBuilder, - savingsGenesis savingstypes.GenesisState, -) { - suite.SetupApp() - - suite.app.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - authBuilder.BuildMarshalled(suite.app.AppCodec()), - app.GenesisState{savingstypes.ModuleName: suite.app.AppCodec().MustMarshalJSON(&savingsGenesis)}, - incentBuilder.BuildMarshalled(suite.app.AppCodec()), - ) -} - -func (suite *SavingsRewardsTestSuite) TestAccumulateSavingsRewards() { - type args struct { - deposit sdk.Coin - rewardsPerSecond sdk.Coins - timeElapsed int - expectedRewardIndexes types.RewardIndexes - } - type test struct { - name string - args args - } - testCases := []test{ - { - "7 seconds", - args{ - deposit: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 7, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.856478000000000000")), - }, - }, - }, - { - "1 day", - args{ - deposit: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 86400, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("10571.385600000000000000")), - }, - }, - }, - { - "0 seconds", - args{ - deposit: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 0, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - }, - }, - }, - { - "multiple reward coins", - args{ - deposit: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354), c("bnb", 567889)), - timeElapsed: 7, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("bnb", d("3.97522300000000000")), - types.NewRewardIndex("hard", d("0.856478000000000000")), - }, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - params := savingstypes.NewParams( - []string{"ukava"}, - ) - deposits := savingstypes.Deposits{ - savingstypes.NewDeposit( - suite.addrs[0], - sdk.NewCoins(tc.args.deposit), - ), - } - savingsGenesis := savingstypes.NewGenesisState(params, deposits) - - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[0], cs(c("ukava", 1e9))). - WithSimpleModuleAccount(savingstypes.ModuleName, sdk.NewCoins(tc.args.deposit)) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleSavingsRewardPeriod(tc.args.deposit.Denom, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder, savingsGenesis) - - // Set up chain context at future time - runAtTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - runCtx := suite.ctx.WithBlockTime(runAtTime) - - rewardPeriods, found := suite.keeper.GetSavingsRewardPeriods(runCtx, tc.args.deposit.Denom) - suite.Require().True(found) - suite.keeper.AccumulateSavingsRewards(runCtx, rewardPeriods) - - rewardIndexes, _ := suite.keeper.GetSavingsRewardIndexes(runCtx, tc.args.deposit.Denom) - suite.Require().Equal(tc.args.expectedRewardIndexes, rewardIndexes) - }) - } -} - -func TestSavingsRewardsTestSuite(t *testing.T) { - suite.Run(t, new(SavingsRewardsTestSuite)) -} diff --git a/x/incentive/keeper/rewards_savings_init_test.go b/x/incentive/keeper/rewards_savings_init_test.go deleted file mode 100644 index f9b7bac2..00000000 --- a/x/incentive/keeper/rewards_savings_init_test.go +++ /dev/null @@ -1,194 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/incentive/types" - savingstypes "github.com/kava-labs/kava/x/savings/types" -) - -// InitializeSavingsRewardTests runs unit tests for the keeper.InitializeSavingsReward method -type InitializeSavingsRewardTests struct { - unitTester -} - -func TestInitializeSavingsRewardTests(t *testing.T) { - suite.Run(t, new(InitializeSavingsRewardTests)) -} - -func (suite *InitializeSavingsRewardTests) TestClaimAddedWhenClaimDoesNotExistAndNoRewards() { - // When a claim doesn't exist, and a user deposits to a non-rewarded pool; - // then a claim is added with no rewards and no indexes - - // no global indexes stored as this pool is not rewarded - - owner := arbitraryAddress() - - amount := sdk.NewCoin("test", sdk.OneInt()) - deposit := savingstypes.NewDeposit(owner, sdk.NewCoins(amount)) - - suite.keeper.InitializeSavingsReward(suite.ctx, deposit) - - syncedClaim, found := suite.keeper.GetSavingsClaim(suite.ctx, owner) - suite.True(found) - // A new claim should have empty indexes. It doesn't strictly need the poolID either. - expectedIndexes := types.MultiRewardIndexes{{ - CollateralType: amount.Denom, - RewardIndexes: nil, - }} - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // a new claim should start with 0 rewards - suite.Equal(sdk.Coins(nil), syncedClaim.Reward) -} - -func (suite *InitializeSavingsRewardTests) TestClaimAddedWhenClaimDoesNotExistAndRewardsExist() { - // When a claim doesn't exist, and a user deposits to a rewarded pool; - // then a claim is added with no rewards and indexes matching the global indexes - - amount := sdk.NewCoin("test", sdk.OneInt()) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: amount.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalSavingsIndexes(globalIndexes) - - owner := arbitraryAddress() - - deposit := savingstypes.NewDeposit(owner, sdk.NewCoins(amount)) - suite.keeper.InitializeSavingsReward(suite.ctx, deposit) - - syncedClaim, found := suite.keeper.GetSavingsClaim(suite.ctx, owner) - suite.True(found) - // a new claim should start with the current global indexes - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // a new claim should start with 0 rewards - suite.Equal(sdk.Coins(nil), syncedClaim.Reward) -} - -func (suite *InitializeSavingsRewardTests) TestClaimUpdatedWhenClaimExistsAndNoRewards() { - // When a claim exists, and a user deposits to a new non-rewarded denom; - // then the claim's rewards don't change - - preexistingDenom := "preexisting" - preexistingIndexes := types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - } - - claim := types.SavingsClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: preexistingDenom, - RewardIndexes: preexistingIndexes, - }, - }, - } - suite.storeSavingsClaim(claim) - - // no global indexes stored as the new denom is not rewarded - newDenom := "test" - deposit := savingstypes.NewDeposit(claim.Owner, sdk.NewCoins(sdk.NewCoin(newDenom, sdk.OneInt()))) - suite.keeper.InitializeSavingsReward(suite.ctx, deposit) - - syncedClaim, found := suite.keeper.GetSavingsClaim(suite.ctx, claim.Owner) - suite.True(found) - - // The preexisting indexes shouldn't be changed. It doesn't strictly need the new denom either. - expectedIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingDenom, - RewardIndexes: preexistingIndexes, - }, - { - CollateralType: newDenom, - RewardIndexes: nil, - }, - } - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // init should never alter the rewards - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *InitializeSavingsRewardTests) TestClaimUpdatedWhenClaimExistsAndRewardsExist() { - // When a claim exists, and a user deposits to a new rewarded denom; - // then the claim's rewards don't change and the indexes are updated to match the global indexes - - preexistingDenom := "preexisting" - preexistingIndexes := types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - } - - newDenom := "test" - newIndexes := types.RewardIndexes{ - { - CollateralType: "otherrewarddenom", - RewardFactor: d("1000.001"), - }, - } - - claim := types.SavingsClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: preexistingDenom, - RewardIndexes: preexistingIndexes, - }, - }, - } - suite.storeSavingsClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingDenom, - RewardIndexes: increaseRewardFactors(preexistingIndexes), - }, - { - CollateralType: newDenom, - RewardIndexes: newIndexes, - }, - } - suite.storeGlobalSavingsIndexes(globalIndexes) - - deposit := savingstypes.NewDeposit(claim.Owner, sdk.NewCoins(sdk.NewCoin(newDenom, sdk.OneInt()))) - suite.keeper.InitializeSavingsReward(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetSavingsClaim(suite.ctx, claim.Owner) - // only the indexes for the new denom should be updated - expectedIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingDenom, - RewardIndexes: preexistingIndexes, - }, - { - CollateralType: newDenom, - RewardIndexes: newIndexes, - }, - } - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // init should never alter the rewards - suite.Equal(claim.Reward, syncedClaim.Reward) -} diff --git a/x/incentive/keeper/rewards_savings_sync_test.go b/x/incentive/keeper/rewards_savings_sync_test.go deleted file mode 100644 index 4e7c5439..00000000 --- a/x/incentive/keeper/rewards_savings_sync_test.go +++ /dev/null @@ -1,245 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/incentive/types" - savingstypes "github.com/kava-labs/kava/x/savings/types" -) - -// SynchronizeSavingsRewardTests runs unit tests for the keeper.SynchronizeSavingsReward method -type SynchronizeSavingsRewardTests struct { - unitTester -} - -func TestSynchronizeSavingsReward(t *testing.T) { - suite.Run(t, new(SynchronizeSavingsRewardTests)) -} - -func (suite *SynchronizeSavingsRewardTests) TestClaimUpdatedWhenGlobalIndexesHaveIncreased() { - // This is the normal case - // Given some time has passed (meaning the global indexes have increased) - // When the claim is synced - // The user earns rewards for the time passed, and the claim indexes are updated - - originalReward := arbitraryCoins() - denom := "test" - - claim := types.SavingsClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSavingsClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalSavingsIndexes(globalIndexes) - - userShares := i(1e9) - deposit := savingstypes.NewDeposit(claim.Owner, sdk.NewCoins(sdk.NewCoin(denom, userShares))) - suite.keeper.SynchronizeSavingsReward(suite.ctx, deposit, []string{}) - - syncedClaim, _ := suite.keeper.GetSavingsClaim(suite.ctx, claim.Owner) - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * user shares - suite.Equal( - cs(c("rewarddenom", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeSavingsRewardTests) TestClaimUnchangedWhenGlobalIndexesUnchanged() { - denom := "test" - unchangingIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - } - - claim := types.SavingsClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: unchangingIndexes, - } - suite.storeSavingsClaim(claim) - - suite.storeGlobalSavingsIndexes(unchangingIndexes) - - userShares := i(1e9) - deposit := savingstypes.NewDeposit(claim.Owner, sdk.NewCoins(sdk.NewCoin(denom, userShares))) - suite.keeper.SynchronizeSavingsReward(suite.ctx, deposit, []string{}) - - syncedClaim, _ := suite.keeper.GetSavingsClaim(suite.ctx, claim.Owner) - // claim should have the same rewards and indexes as before - suite.Equal(claim, syncedClaim) -} - -func (suite *SynchronizeSavingsRewardTests) TestClaimUpdatedWhenNewRewardAdded() { - originalReward := arbitraryCoins() - newlyRewardedDenom := "newlyRewardedDenom" - - claim := types.SavingsClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "currentlyRewardedDenom", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSavingsClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: "currentlyRewardedDenom", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: newlyRewardedDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalSavingsIndexes(globalIndexes) - - userShares := i(1e9) - deposit := savingstypes.NewDeposit(claim.Owner, - sdk.NewCoins( - sdk.NewCoin("currentlyRewardedDenom", userShares), - sdk.NewCoin(newlyRewardedDenom, userShares), - ), - ) - - suite.keeper.SynchronizeSavingsReward(suite.ctx, deposit, []string{newlyRewardedDenom}) - - syncedClaim, _ := suite.keeper.GetSavingsClaim(suite.ctx, claim.Owner) - // the new indexes should be added to the claim and the old ones should be updated - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * shares for the synced deposit - // The old index for `newlyrewarded` isn't in the claim, so it's added starting at 0 for calculating the reward. - suite.Equal( - cs(c("reward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeSavingsRewardTests) TestClaimUpdatedWhenNewRewardDenomAdded() { - // When a new reward coin is added (via gov) to an already rewarded denom (that the user has already deposited to), and the claim is synced; - // Then the user earns rewards for the time since the reward was added, and the new indexes are added. - - originalReward := arbitraryCoins() - denom := "base" - - claim := types.SavingsClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSavingsClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalSavingsIndexes(globalIndexes) - - userShares := i(1e9) - deposit := savingstypes.NewDeposit(claim.Owner, sdk.NewCoins(sdk.NewCoin(denom, userShares))) - suite.keeper.SynchronizeSavingsReward(suite.ctx, deposit, []string{}) - - syncedClaim, _ := suite.keeper.GetSavingsClaim(suite.ctx, claim.Owner) - // indexes should have the new reward denom added - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * shares - // The old index for `otherreward` isn't in the claim, so it's added starting at 0 for calculating the reward. - suite.Equal( - cs(c("reward", 1_000_001_000_000), c("otherreward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func getDenoms(coins sdk.Coins) []string { - denoms := []string{} - for _, coin := range coins { - denoms = append(denoms, coin.Denom) - } - return denoms -} diff --git a/x/incentive/keeper/rewards_supply.go b/x/incentive/keeper/rewards_supply.go deleted file mode 100644 index bc97694b..00000000 --- a/x/incentive/keeper/rewards_supply.go +++ /dev/null @@ -1,312 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - hardtypes "github.com/kava-labs/kava/x/hard/types" - "github.com/kava-labs/kava/x/incentive/types" -) - -// AccumulateHardSupplyRewards calculates new rewards to distribute this block and updates the global indexes to reflect this. -// The provided rewardPeriod must be valid to avoid panics in calculating time durations. -func (k Keeper) AccumulateHardSupplyRewards(ctx sdk.Context, rewardPeriod types.MultiRewardPeriod) { - previousAccrualTime, found := k.GetPreviousHardSupplyRewardAccrualTime(ctx, rewardPeriod.CollateralType) - if !found { - previousAccrualTime = ctx.BlockTime() - } - - indexes, found := k.GetHardSupplyRewardIndexes(ctx, rewardPeriod.CollateralType) - if !found { - indexes = types.RewardIndexes{} - } - - acc := types.NewAccumulator(previousAccrualTime, indexes) - - totalSource := k.getHardSupplyTotalSourceShares(ctx, rewardPeriod.CollateralType) - - acc.Accumulate(rewardPeriod, totalSource, ctx.BlockTime()) - - k.SetPreviousHardSupplyRewardAccrualTime(ctx, rewardPeriod.CollateralType, acc.PreviousAccumulationTime) - if len(acc.Indexes) > 0 { - // the store panics when setting empty or nil indexes - k.SetHardSupplyRewardIndexes(ctx, rewardPeriod.CollateralType, acc.Indexes) - } -} - -// getHardSupplyTotalSourceShares fetches the sum of all source shares for a supply reward. -// In the case of hard supply, this is the total supplied divided by the supply interest factor. -// This gives the "pre interest" value of the total supplied. -func (k Keeper) getHardSupplyTotalSourceShares(ctx sdk.Context, denom string) sdk.Dec { - totalSuppliedCoins, found := k.hardKeeper.GetSuppliedCoins(ctx) - if !found { - // assume no coins have been supplied - totalSuppliedCoins = sdk.NewCoins() - } - totalSupplied := totalSuppliedCoins.AmountOf(denom) - - interestFactor, found := k.hardKeeper.GetSupplyInterestFactor(ctx, denom) - if !found { - // assume nothing has been borrowed so the factor starts at it's default value - interestFactor = sdk.OneDec() - } - - // return supplied/factor to get the "pre interest" value of the current total supplied - return sdk.NewDecFromInt(totalSupplied).Quo(interestFactor) -} - -// InitializeHardSupplyReward initializes the supply-side of a hard liquidity provider claim -// by creating the claim and setting the supply reward factor index -func (k Keeper) InitializeHardSupplyReward(ctx sdk.Context, deposit hardtypes.Deposit) { - claim, found := k.GetHardLiquidityProviderClaim(ctx, deposit.Depositor) - if !found { - claim = types.NewHardLiquidityProviderClaim(deposit.Depositor, sdk.Coins{}, nil, nil) - } - - var supplyRewardIndexes types.MultiRewardIndexes - for _, coin := range deposit.Amount { - globalRewardIndexes, found := k.GetHardSupplyRewardIndexes(ctx, coin.Denom) - if !found { - globalRewardIndexes = types.RewardIndexes{} - } - supplyRewardIndexes = supplyRewardIndexes.With(coin.Denom, globalRewardIndexes) - } - - claim.SupplyRewardIndexes = supplyRewardIndexes - k.SetHardLiquidityProviderClaim(ctx, claim) -} - -// SynchronizeHardSupplyReward updates the claim object by adding any accumulated rewards -// and updating the reward index value -func (k Keeper) SynchronizeHardSupplyReward(ctx sdk.Context, deposit hardtypes.Deposit) { - claim, found := k.GetHardLiquidityProviderClaim(ctx, deposit.Depositor) - if !found { - return - } - - // Source shares for hard deposits is their normalized deposit amount - normalizedDeposit, err := deposit.NormalizedDeposit() - if err != nil { - panic(fmt.Sprintf("during deposit reward sync, could not get normalized deposit for %s: %s", deposit.Depositor, err.Error())) - } - - for _, normedDeposit := range normalizedDeposit { - claim = k.synchronizeSingleHardSupplyReward(ctx, claim, normedDeposit.Denom, normedDeposit.Amount) - } - k.SetHardLiquidityProviderClaim(ctx, claim) -} - -// synchronizeSingleHardSupplyReward synchronizes a single rewarded supply denom in a hard claim. -// It returns the claim without setting in the store. -// The public methods for accessing and modifying claims are preferred over this one. Direct modification of claims is easy to get wrong. -func (k Keeper) synchronizeSingleHardSupplyReward(ctx sdk.Context, claim types.HardLiquidityProviderClaim, denom string, sourceShares sdk.Dec) types.HardLiquidityProviderClaim { - globalRewardIndexes, found := k.GetHardSupplyRewardIndexes(ctx, denom) - if !found { - // The global factor is only not found if - // - the supply denom has not started accumulating rewards yet (either there is no reward specified in params, or the reward start time hasn't been hit) - // - OR it was wrongly deleted from state (factors should never be removed while unsynced claims exist) - // If not found we could either skip this sync, or assume the global factor is zero. - // Skipping will avoid storing unnecessary factors in the claim for non rewarded denoms. - // And in the event a global factor is wrongly deleted, it will avoid this function panicking when calculating rewards. - return claim - } - - userRewardIndexes, found := claim.SupplyRewardIndexes.Get(denom) - if !found { - // Normally the reward indexes should always be found. - // But if a denom was not rewarded then becomes rewarded (ie a reward period is added to params), then the indexes will be missing from claims for that supplied denom. - // So given the reward period was just added, assume the starting value for any global reward indexes, which is an empty slice. - userRewardIndexes = types.RewardIndexes{} - } - - newRewards, err := k.CalculateRewards(userRewardIndexes, globalRewardIndexes, sourceShares) - if err != nil { - // Global reward factors should never decrease, as it would lead to a negative update to claim.Rewards. - // This panics if a global reward factor decreases or disappears between the old and new indexes. - panic(fmt.Sprintf("corrupted global reward indexes found: %v", err)) - } - - claim.Reward = claim.Reward.Add(newRewards...) - claim.SupplyRewardIndexes = claim.SupplyRewardIndexes.With(denom, globalRewardIndexes) - - return claim -} - -// UpdateHardSupplyIndexDenoms adds any new deposit denoms to the claim's supply reward index -func (k Keeper) UpdateHardSupplyIndexDenoms(ctx sdk.Context, deposit hardtypes.Deposit) { - claim, found := k.GetHardLiquidityProviderClaim(ctx, deposit.Depositor) - if !found { - claim = types.NewHardLiquidityProviderClaim(deposit.Depositor, sdk.Coins{}, nil, nil) - } - - depositDenoms := getDenoms(deposit.Amount) - supplyRewardIndexDenoms := claim.SupplyRewardIndexes.GetCollateralTypes() - - supplyRewardIndexes := claim.SupplyRewardIndexes - - // Create a new multi-reward index in the claim for every new deposit denom - uniqueDepositDenoms := setDifference(depositDenoms, supplyRewardIndexDenoms) - - for _, denom := range uniqueDepositDenoms { - globalSupplyRewardIndexes, found := k.GetHardSupplyRewardIndexes(ctx, denom) - if !found { - globalSupplyRewardIndexes = types.RewardIndexes{} - } - supplyRewardIndexes = supplyRewardIndexes.With(denom, globalSupplyRewardIndexes) - } - - // Delete multi-reward index from claim if the collateral type is no longer deposited - uniqueSupplyRewardDenoms := setDifference(supplyRewardIndexDenoms, depositDenoms) - - for _, denom := range uniqueSupplyRewardDenoms { - supplyRewardIndexes = supplyRewardIndexes.RemoveRewardIndex(denom) - } - - claim.SupplyRewardIndexes = supplyRewardIndexes - k.SetHardLiquidityProviderClaim(ctx, claim) -} - -// SynchronizeHardLiquidityProviderClaim adds any accumulated rewards -func (k Keeper) SynchronizeHardLiquidityProviderClaim(ctx sdk.Context, owner sdk.AccAddress) { - // Synchronize any hard liquidity supply-side rewards - deposit, foundDeposit := k.hardKeeper.GetDeposit(ctx, owner) - if foundDeposit { - k.SynchronizeHardSupplyReward(ctx, deposit) - } - - // Synchronize any hard liquidity borrow-side rewards - borrow, foundBorrow := k.hardKeeper.GetBorrow(ctx, owner) - if foundBorrow { - k.SynchronizeHardBorrowReward(ctx, borrow) - } -} - -// SimulateHardSynchronization calculates a user's outstanding hard rewards by simulating reward synchronization -func (k Keeper) SimulateHardSynchronization(ctx sdk.Context, claim types.HardLiquidityProviderClaim) types.HardLiquidityProviderClaim { - // 1. Simulate Hard supply-side rewards - for _, ri := range claim.SupplyRewardIndexes { - globalRewardIndexes, foundGlobalRewardIndexes := k.GetHardSupplyRewardIndexes(ctx, ri.CollateralType) - if !foundGlobalRewardIndexes { - continue - } - - userRewardIndexes, foundUserRewardIndexes := claim.SupplyRewardIndexes.GetRewardIndex(ri.CollateralType) - if !foundUserRewardIndexes { - continue - } - - userRewardIndexIndex, foundUserRewardIndexIndex := claim.SupplyRewardIndexes.GetRewardIndexIndex(ri.CollateralType) - if !foundUserRewardIndexIndex { - continue - } - - for _, globalRewardIndex := range globalRewardIndexes { - userRewardIndex, foundUserRewardIndex := userRewardIndexes.RewardIndexes.GetRewardIndex(globalRewardIndex.CollateralType) - if !foundUserRewardIndex { - userRewardIndex = types.NewRewardIndex(globalRewardIndex.CollateralType, sdk.ZeroDec()) - userRewardIndexes.RewardIndexes = append(userRewardIndexes.RewardIndexes, userRewardIndex) - claim.SupplyRewardIndexes[userRewardIndexIndex].RewardIndexes = append(claim.SupplyRewardIndexes[userRewardIndexIndex].RewardIndexes, userRewardIndex) - } - - globalRewardFactor := globalRewardIndex.RewardFactor - userRewardFactor := userRewardIndex.RewardFactor - rewardsAccumulatedFactor := globalRewardFactor.Sub(userRewardFactor) - if rewardsAccumulatedFactor.IsZero() { - continue - } - deposit, found := k.hardKeeper.GetDeposit(ctx, claim.GetOwner()) - if !found { - continue - } - newRewardsAmount := rewardsAccumulatedFactor.Mul(sdk.NewDecFromInt(deposit.Amount.AmountOf(ri.CollateralType))).RoundInt() - if newRewardsAmount.IsZero() || newRewardsAmount.IsNegative() { - continue - } - - factorIndex, foundFactorIndex := userRewardIndexes.RewardIndexes.GetFactorIndex(globalRewardIndex.CollateralType) - if !foundFactorIndex { - continue - } - claim.SupplyRewardIndexes[userRewardIndexIndex].RewardIndexes[factorIndex].RewardFactor = globalRewardIndex.RewardFactor - newRewardsCoin := sdk.NewCoin(userRewardIndex.CollateralType, newRewardsAmount) - claim.Reward = claim.Reward.Add(newRewardsCoin) - } - } - - // 2. Simulate Hard borrow-side rewards - for _, ri := range claim.BorrowRewardIndexes { - globalRewardIndexes, foundGlobalRewardIndexes := k.GetHardBorrowRewardIndexes(ctx, ri.CollateralType) - if !foundGlobalRewardIndexes { - continue - } - - userRewardIndexes, foundUserRewardIndexes := claim.BorrowRewardIndexes.GetRewardIndex(ri.CollateralType) - if !foundUserRewardIndexes { - continue - } - - userRewardIndexIndex, foundUserRewardIndexIndex := claim.BorrowRewardIndexes.GetRewardIndexIndex(ri.CollateralType) - if !foundUserRewardIndexIndex { - continue - } - - for _, globalRewardIndex := range globalRewardIndexes { - userRewardIndex, foundUserRewardIndex := userRewardIndexes.RewardIndexes.GetRewardIndex(globalRewardIndex.CollateralType) - if !foundUserRewardIndex { - userRewardIndex = types.NewRewardIndex(globalRewardIndex.CollateralType, sdk.ZeroDec()) - userRewardIndexes.RewardIndexes = append(userRewardIndexes.RewardIndexes, userRewardIndex) - claim.BorrowRewardIndexes[userRewardIndexIndex].RewardIndexes = append(claim.BorrowRewardIndexes[userRewardIndexIndex].RewardIndexes, userRewardIndex) - } - - globalRewardFactor := globalRewardIndex.RewardFactor - userRewardFactor := userRewardIndex.RewardFactor - rewardsAccumulatedFactor := globalRewardFactor.Sub(userRewardFactor) - if rewardsAccumulatedFactor.IsZero() { - continue - } - borrow, found := k.hardKeeper.GetBorrow(ctx, claim.GetOwner()) - if !found { - continue - } - newRewardsAmount := rewardsAccumulatedFactor.Mul(sdk.NewDecFromInt(borrow.Amount.AmountOf(ri.CollateralType))).RoundInt() - if newRewardsAmount.IsZero() || newRewardsAmount.IsNegative() { - continue - } - - factorIndex, foundFactorIndex := userRewardIndexes.RewardIndexes.GetFactorIndex(globalRewardIndex.CollateralType) - if !foundFactorIndex { - continue - } - claim.BorrowRewardIndexes[userRewardIndexIndex].RewardIndexes[factorIndex].RewardFactor = globalRewardIndex.RewardFactor - newRewardsCoin := sdk.NewCoin(userRewardIndex.CollateralType, newRewardsAmount) - claim.Reward = claim.Reward.Add(newRewardsCoin) - } - } - - return claim -} - -// Set setDifference: A - B -func setDifference(a, b []string) (diff []string) { - m := make(map[string]bool) - - for _, item := range b { - m[item] = true - } - - for _, item := range a { - if _, ok := m[item]; !ok { - diff = append(diff, item) - } - } - return -} - -func getDenoms(coins sdk.Coins) []string { - denoms := []string{} - for _, coin := range coins { - denoms = append(denoms, coin.Denom) - } - return denoms -} diff --git a/x/incentive/keeper/rewards_supply_accum_test.go b/x/incentive/keeper/rewards_supply_accum_test.go deleted file mode 100644 index 179a1b18..00000000 --- a/x/incentive/keeper/rewards_supply_accum_test.go +++ /dev/null @@ -1,321 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/incentive/types" -) - -type AccumulateSupplyRewardsTests struct { - unitTester -} - -func (suite *AccumulateSupplyRewardsTests) storedTimeEquals(denom string, expected time.Time) { - storedTime, found := suite.keeper.GetPreviousHardSupplyRewardAccrualTime(suite.ctx, denom) - suite.True(found) - suite.Equal(expected, storedTime) -} - -func (suite *AccumulateSupplyRewardsTests) storedIndexesEqual(denom string, expected types.RewardIndexes) { - storedIndexes, found := suite.keeper.GetHardSupplyRewardIndexes(suite.ctx, denom) - suite.Equal(found, expected != nil) - - if found { - suite.Equal(expected, storedIndexes) - } else { - suite.Empty(storedIndexes) - } -} - -func TestAccumulateSupplyRewards(t *testing.T) { - suite.Run(t, new(AccumulateSupplyRewardsTests)) -} - -func (suite *AccumulateSupplyRewardsTests) TestStateUpdatedWhenBlockTimeHasIncreased() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalSupply(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - suite.storeGlobalSupplyIndexes(types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - }) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardSupplyRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(denom, newAccrualTime) - suite.storedIndexesEqual(denom, types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("7.22"), - }, - { - CollateralType: "ukava", - RewardFactor: d("3.64"), - }, - }) -} - -func (suite *AccumulateSupplyRewardsTests) TestStateUnchangedWhenBlockTimeHasNotIncreased() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalSupply(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalSupplyIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardSupplyRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(denom, previousAccrualTime) - expected, f := previousIndexes.Get(denom) - suite.True(f) - suite.storedIndexesEqual(denom, expected) -} - -func (suite *AccumulateSupplyRewardsTests) TestNoAccumulationWhenSourceSharesAreZero() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper() // zero total supplys - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalSupplyIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardSupplyRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(7 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(denom, firstAccrualTime) - expected, f := previousIndexes.Get(denom) - suite.True(f) - suite.storedIndexesEqual(denom, expected) -} - -func (suite *AccumulateSupplyRewardsTests) TestStateAddedWhenStateDoesNotExist() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalSupply(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - firstAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, period) - - // After the first accumulation only the current block time should be stored. - // The indexes will be empty as no time has passed since the previous block because it didn't exist. - suite.storedTimeEquals(denom, firstAccrualTime) - suite.storedIndexesEqual(denom, nil) - - secondAccrualTime := firstAccrualTime.Add(10 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(secondAccrualTime) - - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, period) - - // After the second accumulation both current block time and indexes should be stored. - suite.storedTimeEquals(denom, secondAccrualTime) - suite.storedIndexesEqual(denom, types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.01"), - }, - }) -} - -func (suite *AccumulateSupplyRewardsTests) TestNoPanicWhenStateDoesNotExist() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper() - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(), - ) - - accrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(accrualTime) - - // Accumulate with no source shares and no rewards per second will result in no increment to the indexes. - // No increment and no previous indexes stored, results in an updated of nil. Setting this in the state panics. - // Check there is no panic. - suite.NotPanics(func() { - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, period) - }) - - suite.storedTimeEquals(denom, accrualTime) - suite.storedIndexesEqual(denom, nil) -} - -func (suite *AccumulateSupplyRewardsTests) TestNoAccumulationWhenBeforeStartTime() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalSupply(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalSupplyIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardSupplyRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(10 * time.Second) - - period := types.NewMultiRewardPeriod( - true, - denom, - firstAccrualTime.Add(time.Nanosecond), // start time after accrual time - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, period) - - // The accrual time should be updated, but the indexes unchanged - suite.storedTimeEquals(denom, firstAccrualTime) - expectedIndexes, f := previousIndexes.Get(denom) - suite.True(f) - suite.storedIndexesEqual(denom, expectedIndexes) -} - -func (suite *AccumulateSupplyRewardsTests) TestPanicWhenCurrentTimeLessThanPrevious() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalSupply(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardSupplyRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - firstAccrualTime := time.Time{} - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Time{}, // start time after accrual time - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.Panics(func() { - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, period) - }) -} diff --git a/x/incentive/keeper/rewards_supply_init_test.go b/x/incentive/keeper/rewards_supply_init_test.go deleted file mode 100644 index 4075cfb1..00000000 --- a/x/incentive/keeper/rewards_supply_init_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/incentive/types" -) - -// InitializeHardSupplyRewardTests runs unit tests for the keeper.InitializeHardSupplyReward method -type InitializeHardSupplyRewardTests struct { - unitTester -} - -func TestInitializeHardSupplyReward(t *testing.T) { - suite.Run(t, new(InitializeHardSupplyRewardTests)) -} - -func (suite *InitializeHardSupplyRewardTests) TestClaimIndexesAreSetWhenClaimExists() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - // Indexes should always be empty when initialize is called. - // If initialize is called then the user must have repaid their deposit positions, - // which means UpdateHardSupplyIndexDenoms was called and should have remove indexes. - SupplyRewardIndexes: types.MultiRewardIndexes{}, - } - suite.storeHardClaim(claim) - - globalIndexes := nonEmptyMultiRewardIndexes - suite.storeGlobalSupplyIndexes(globalIndexes) - - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.InitializeHardSupplyReward(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *InitializeHardSupplyRewardTests) TestClaimIndexesAreSetWhenClaimDoesNotExist() { - globalIndexes := nonEmptyMultiRewardIndexes - suite.storeGlobalSupplyIndexes(globalIndexes) - - owner := arbitraryAddress() - deposit := NewHardDepositBuilder(owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.InitializeHardSupplyReward(suite.ctx, deposit) - - syncedClaim, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, owner) - suite.True(found) - suite.Equal(globalIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *InitializeHardSupplyRewardTests) TestClaimIndexesAreSetEmptyForMissingIndexes() { - globalIndexes := nonEmptyMultiRewardIndexes - suite.storeGlobalSupplyIndexes(globalIndexes) - - owner := arbitraryAddress() - // Supply a denom that is not in the global indexes. - // This happens when a deposit denom has no rewards associated with it. - expectedIndexes := appendUniqueEmptyMultiRewardIndex(globalIndexes) - depositedDenoms := extractCollateralTypes(expectedIndexes) - deposit := NewHardDepositBuilder(owner). - WithArbitrarySourceShares(depositedDenoms...). - Build() - - suite.keeper.InitializeHardSupplyReward(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, owner) - suite.Equal(expectedIndexes, syncedClaim.SupplyRewardIndexes) -} diff --git a/x/incentive/keeper/rewards_supply_sync_test.go b/x/incentive/keeper/rewards_supply_sync_test.go deleted file mode 100644 index 10c18185..00000000 --- a/x/incentive/keeper/rewards_supply_sync_test.go +++ /dev/null @@ -1,342 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - hardtypes "github.com/kava-labs/kava/x/hard/types" - "github.com/kava-labs/kava/x/incentive/types" -) - -// SynchronizeHardSupplyRewardTests runs unit tests for the keeper.SynchronizeHardSupplyReward method -type SynchronizeHardSupplyRewardTests struct { - unitTester -} - -func TestSynchronizeHardSupplyReward(t *testing.T) { - suite.Run(t, new(SynchronizeHardSupplyRewardTests)) -} - -func (suite *SynchronizeHardSupplyRewardTests) TestClaimIndexesAreUpdatedWhenGlobalIndexesHaveIncreased() { - // This is the normal case - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - SupplyRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - - globalIndexes := increaseAllRewardFactors(nonEmptyMultiRewardIndexes) - suite.storeGlobalSupplyIndexes(globalIndexes) - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(claim.SupplyRewardIndexes)...). - Build() - - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *SynchronizeHardSupplyRewardTests) TestClaimIndexesAreUnchangedWhenGlobalIndexesUnchanged() { - // It should be safe to call SynchronizeHardSupplyReward multiple times - - unchangingIndexes := nonEmptyMultiRewardIndexes - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - SupplyRewardIndexes: unchangingIndexes, - } - suite.storeHardClaim(claim) - - suite.storeGlobalSupplyIndexes(unchangingIndexes) - - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(unchangingIndexes)...). - Build() - - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(unchangingIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *SynchronizeHardSupplyRewardTests) TestClaimIndexesAreUpdatedWhenNewRewardAdded() { - // When a new reward is added (via gov) for a hard deposit denom the user has already deposited, and the claim is synced; - // Then the new reward's index should be added to the claim. - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - SupplyRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - - globalIndexes := appendUniqueMultiRewardIndex(nonEmptyMultiRewardIndexes) - suite.storeGlobalSupplyIndexes(globalIndexes) - - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *SynchronizeHardSupplyRewardTests) TestClaimIndexesAreUpdatedWhenNewRewardDenomAdded() { - // When a new reward coin is added (via gov) to an already rewarded deposit denom (that the user has already deposited), and the claim is synced; - // Then the new reward coin's index should be added to the claim. - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - SupplyRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - - globalIndexes := appendUniqueRewardIndexToFirstItem(nonEmptyMultiRewardIndexes) - suite.storeGlobalSupplyIndexes(globalIndexes) - - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *SynchronizeHardSupplyRewardTests) TestRewardIsIncrementedWhenGlobalIndexesHaveIncreased() { - // This is the normal case - // Given some time has passed (meaning the global indexes have increased) - // When the claim is synced - // The user earns rewards for the time passed - - originalReward := arbitraryCoins() - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - SupplyRewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "depositdenom", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeHardClaim(claim) - - suite.storeGlobalSupplyIndexes(types.MultiRewardIndexes{ - { - CollateralType: "depositdenom", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("2000.002"), - }, - }, - }, - }) - - deposit := NewHardDepositBuilder(claim.Owner). - WithSourceShares("depositdenom", 1e9). - Build() - - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - - // new reward is (new index - old index) * deposit amount - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal( - cs(c("rewarddenom", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeHardSupplyRewardTests) TestRewardIsIncrementedWhenNewRewardAdded() { - // When a new reward is added (via gov) for a hard deposit denom the user has already deposited, and the claim is synced - // Then the user earns rewards for the time since the reward was added - - originalReward := arbitraryCoins() - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - SupplyRewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "rewarded", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeHardClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: "rewarded", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: "newlyrewarded", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalSupplyIndexes(globalIndexes) - - deposit := NewHardDepositBuilder(claim.Owner). - WithSourceShares("rewarded", 1e9). - WithSourceShares("newlyrewarded", 1e9). - Build() - - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - - // new reward is (new index - old index) * deposit amount for each deposited denom - // The old index for `newlyrewarded` isn't in the claim, so it's added starting at 0 for calculating the reward. - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal( - cs(c("otherreward", 1_000_001_000_000), c("reward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeHardSupplyRewardTests) TestRewardIsIncrementedWhenNewRewardDenomAdded() { - // When a new reward coin is added (via gov) to an already rewarded deposit denom (that the user has already deposited), and the claim is synced; - // Then the user earns rewards for the time since the reward was added - - originalReward := arbitraryCoins() - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - SupplyRewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "deposited", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeHardClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: "deposited", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalSupplyIndexes(globalIndexes) - - deposit := NewHardDepositBuilder(claim.Owner). - WithSourceShares("deposited", 1e9). - Build() - - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - - // new reward is (new index - old index) * deposit amount for each deposited denom - // The old index for `otherreward` isn't in the claim, so it's added starting at 0 for calculating the reward. - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal( - cs(c("reward", 1_000_001_000_000), c("otherreward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -// HardDepositBuilder is a tool for creating a hard deposit in tests. -// The builder inherits from hard.Deposit, so fields can be accessed directly if a helper method doesn't exist. -type HardDepositBuilder struct { - hardtypes.Deposit -} - -// NewHardDepositBuilder creates a HardDepositBuilder containing an empty deposit. -func NewHardDepositBuilder(depositor sdk.AccAddress) HardDepositBuilder { - return HardDepositBuilder{ - Deposit: hardtypes.Deposit{ - Depositor: depositor, - }, - } -} - -// Build assembles and returns the final deposit. -func (builder HardDepositBuilder) Build() hardtypes.Deposit { return builder.Deposit } - -// WithSourceShares adds a deposit amount and factor such that the source shares for this deposit is equal to specified. -// With a factor of 1, the deposit amount is the source shares. This picks an arbitrary factor to ensure factors are accounted for in production code. -func (builder HardDepositBuilder) WithSourceShares(denom string, shares int64) HardDepositBuilder { - if !builder.Amount.AmountOf(denom).Equal(sdk.ZeroInt()) { - panic("adding to amount with existing denom not implemented") - } - if _, f := builder.Index.GetInterestFactor(denom); f { - panic("adding to indexes with existing denom not implemented") - } - - // pick arbitrary factor - factor := sdk.MustNewDecFromStr("2") - - // Calculate deposit amount that would equal the requested source shares given the above factor. - amt := sdkmath.NewInt(shares).Mul(factor.RoundInt()) - - builder.Amount = builder.Amount.Add(sdk.NewCoin(denom, amt)) - builder.Index = builder.Index.SetInterestFactor(denom, factor) - return builder -} - -// WithArbitrarySourceShares adds arbitrary deposit amounts and indexes for each specified denom. -func (builder HardDepositBuilder) WithArbitrarySourceShares(denoms ...string) HardDepositBuilder { - const arbitraryShares = 1e9 - for _, denom := range denoms { - builder = builder.WithSourceShares(denom, arbitraryShares) - } - return builder -} diff --git a/x/incentive/keeper/rewards_supply_test.go b/x/incentive/keeper/rewards_supply_test.go deleted file mode 100644 index 2780a843..00000000 --- a/x/incentive/keeper/rewards_supply_test.go +++ /dev/null @@ -1,1030 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - proposaltypes "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/committee" - committeekeeper "github.com/kava-labs/kava/x/committee/keeper" - committeetypes "github.com/kava-labs/kava/x/committee/types" - "github.com/kava-labs/kava/x/hard" - hardkeeper "github.com/kava-labs/kava/x/hard/keeper" - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/testutil" - "github.com/kava-labs/kava/x/incentive/types" - kavadisttypes "github.com/kava-labs/kava/x/kavadist/types" -) - -type SupplyIntegrationTests struct { - testutil.IntegrationTester - - genesisTime time.Time - addrs []sdk.AccAddress -} - -func TestSupplyIntegration(t *testing.T) { - suite.Run(t, new(SupplyIntegrationTests)) -} - -// SetupTest is run automatically before each suite test -func (suite *SupplyIntegrationTests) SetupTest() { - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *SupplyIntegrationTests) TestSingleUserAccumulatesRewardsAfterSyncing() { - userA := suite.addrs[0] - - authBulder := app.NewAuthBankGenesisBuilder(). - WithSimpleModuleAccount(kavadisttypes.ModuleName, cs(c("hard", 1e18))). // Fill kavadist with enough coins to pay out any reward - WithSimpleAccount(userA, cs(c("bnb", 1e12))) // give the user some coins - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithMultipliers(types.MultipliersPerDenoms{{ - Denom: "hard", - Multipliers: types.Multipliers{types.NewMultiplier("large", 12, d("1.0"))}, // keep payout at 1.0 to make maths easier - }}). - WithSimpleSupplyRewardPeriod("bnb", cs(c("hard", 1e6))) // only borrow rewards - - suite.SetApp() - - suite.WithGenesisTime(suite.genesisTime) - suite.StartChain( - NewPricefeedGenStateMultiFromTime(suite.App.AppCodec(), suite.genesisTime), - NewHardGenStateMulti(suite.genesisTime).BuildMarshalled(suite.App.AppCodec()), - authBulder.BuildMarshalled(suite.App.AppCodec()), - incentBuilder.BuildMarshalled(suite.App.AppCodec()), - ) - - // Create a deposit - suite.NoError(suite.DeliverHardMsgDeposit(userA, cs(c("bnb", 1e11)))) - // Also create a borrow so interest accumulates on the deposit - suite.NoError(suite.DeliverHardMsgBorrow(userA, cs(c("bnb", 1e10)))) - - // Let time pass to accumulate interest on the deposit - // Use one long block instead of many to reduce any rounding errors, and speed up tests. - suite.NextBlockAfter(1e6 * time.Second) // about 12 days - - // User withdraw and redeposits just to sync their deposit. - suite.NoError(suite.DeliverHardMsgWithdraw(userA, cs(c("bnb", 1)))) - suite.NoError(suite.DeliverHardMsgDeposit(userA, cs(c("bnb", 1)))) - - // Accumulate more rewards. - // The user still has the same percentage of all deposits (100%) so their rewards should be the same as in the previous block. - suite.NextBlockAfter(1e6 * time.Second) // about 12 days - - msg := types.NewMsgClaimHardReward( - userA.String(), - types.Selections{ - types.NewSelection("hard", "large"), - }) - - // User claims all their rewards - suite.Require().NoError(suite.DeliverIncentiveMsg(&msg)) - - // The users has always had 100% of deposits, so they should receive all rewards for the previous two blocks. - // Total rewards for each block is block duration * rewards per second - accuracy := 1e-10 // using a very high accuracy to flag future small calculation changes - suite.BalanceInEpsilon(userA, cs(c("bnb", 1e12-1e11+1e10), c("hard", 2*1e6*1e6)), accuracy) -} - -// Test suite used for all keeper tests -type SupplyRewardsTestSuite struct { - suite.Suite - - keeper keeper.Keeper - hardKeeper hardkeeper.Keeper - committeeKeeper committeekeeper.Keeper - - app app.TestApp - ctx sdk.Context - - genesisTime time.Time - addrs []sdk.AccAddress -} - -// SetupTest is run automatically before each suite test -func (suite *SupplyRewardsTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *SupplyRewardsTestSuite) SetupApp() { - suite.app = app.NewTestApp() - - suite.keeper = suite.app.GetIncentiveKeeper() - suite.hardKeeper = suite.app.GetHardKeeper() - suite.committeeKeeper = suite.app.GetCommitteeKeeper() - - suite.ctx = suite.app.NewContext(true, tmproto.Header{Height: 1, Time: suite.genesisTime}) -} - -func (suite *SupplyRewardsTestSuite) SetupWithGenState(authBuilder *app.AuthBankGenesisBuilder, incentBuilder testutil.IncentiveGenesisBuilder, hardBuilder testutil.HardGenesisBuilder) { - suite.SetupApp() - - suite.app.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - authBuilder.BuildMarshalled(suite.app.AppCodec()), - NewPricefeedGenStateMultiFromTime(suite.app.AppCodec(), suite.genesisTime), - hardBuilder.BuildMarshalled(suite.app.AppCodec()), - NewCommitteeGenesisState(suite.app.AppCodec(), 1, suite.addrs[:2]...), - incentBuilder.BuildMarshalled(suite.app.AppCodec()), - ) -} - -func (suite *SupplyRewardsTestSuite) TestAccumulateHardSupplyRewards() { - type args struct { - deposit sdk.Coin - rewardsPerSecond sdk.Coins - timeElapsed int - expectedRewardIndexes types.RewardIndexes - } - type test struct { - name string - args args - } - testCases := []test{ - { - "single reward denom: 7 seconds", - args{ - deposit: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 7, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.000000856478000000"))}, - }, - }, - { - "single reward denom: 1 day", - args{ - deposit: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 86400, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.010571385600000000"))}, - }, - }, - { - "single reward denom: 0 seconds", - args{ - deposit: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 0, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.0"))}, - }, - }, - { - "multiple reward denoms: 7 seconds", - args{ - deposit: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - timeElapsed: 7, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.000000856478000000")), - types.NewRewardIndex("ukava", d("0.000000856478000000")), - }, - }, - }, - { - "multiple reward denoms: 1 day", - args{ - deposit: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - timeElapsed: 86400, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.010571385600000000")), - types.NewRewardIndex("ukava", d("0.010571385600000000")), - }, - }, - }, - { - "multiple reward denoms: 0 seconds", - args{ - deposit: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - timeElapsed: 0, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - types.NewRewardIndex("ukava", d("0.0")), - }, - }, - }, - { - "multiple reward denoms with different rewards per second: 1 day", - args{ - deposit: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 555555)), - timeElapsed: 86400, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.010571385600000000")), - types.NewRewardIndex("ukava", d("0.047999952000000000")), - }, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount( - userAddr, - cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15)), - ) - // suite.SetupWithGenState(authBuilder) - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime) - if tc.args.rewardsPerSecond != nil { - incentBuilder = incentBuilder.WithSimpleSupplyRewardPeriod(tc.args.deposit.Denom, tc.args.rewardsPerSecond) - } - - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // User deposits to increase total supplied amount - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, sdk.NewCoins(tc.args.deposit)) - suite.Require().NoError(err) - - // Set up chain context at future time - runAtTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - runCtx := suite.ctx.WithBlockTime(runAtTime) - - // Run Hard begin blocker in order to update the denom's index factor - hard.BeginBlocker(runCtx, suite.hardKeeper) - - // Accumulate hard supply rewards for the deposit denom - multiRewardPeriod, found := suite.keeper.GetHardSupplyRewardPeriods(runCtx, tc.args.deposit.Denom) - suite.Require().True(found) - suite.keeper.AccumulateHardSupplyRewards(runCtx, multiRewardPeriod) - - // Check that each expected reward index matches the current stored reward index for the denom - globalRewardIndexes, found := suite.keeper.GetHardSupplyRewardIndexes(runCtx, tc.args.deposit.Denom) - if len(tc.args.rewardsPerSecond) > 0 { - suite.Require().True(found) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - globalRewardIndex, found := globalRewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, globalRewardIndex) - } - } else { - suite.Require().False(found) - } - }) - } -} - -func (suite *SupplyRewardsTestSuite) TestInitializeHardSupplyRewards() { - type args struct { - moneyMarketRewardDenoms map[string]sdk.Coins - deposit sdk.Coins - expectedClaimSupplyRewardIndexes types.MultiRewardIndexes - } - type test struct { - name string - args args - } - - standardMoneyMarketRewardDenoms := map[string]sdk.Coins{ - "bnb": cs(c("hard", 1)), - "btcb": cs(c("hard", 1), c("ukava", 1)), - } - - testCases := []test{ - { - "single deposit denom, single reward denom", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("bnb", 1000000000000)), - expectedClaimSupplyRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "bnb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - }, - ), - }, - }, - }, - { - "single deposit denom, multiple reward denoms", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("btcb", 1000000000000)), - expectedClaimSupplyRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "btcb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - types.NewRewardIndex("ukava", d("0.0")), - }, - ), - }, - }, - }, - { - "single deposit denom, no reward denoms", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("xrp", 1000000000000)), - expectedClaimSupplyRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "xrp", - nil, - ), - }, - }, - }, - { - "multiple deposit denoms, multiple overlapping reward denoms", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("bnb", 1000000000000), c("btcb", 1000000000000)), - expectedClaimSupplyRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "bnb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - }, - ), - types.NewMultiRewardIndex( - "btcb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - types.NewRewardIndex("ukava", d("0.0")), - }, - ), - }, - }, - }, - { - "multiple deposit denoms, correct discrete reward denoms", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("bnb", 1000000000000), c("xrp", 1000000000000)), - expectedClaimSupplyRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "bnb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - }, - ), - types.NewMultiRewardIndex( - "xrp", - nil, - ), - }, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount( - userAddr, - cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15)), - ) - - incentBuilder := testutil.NewIncentiveGenesisBuilder().WithGenesisTime(suite.genesisTime) - for moneyMarketDenom, rewardsPerSecond := range tc.args.moneyMarketRewardDenoms { - incentBuilder = incentBuilder.WithSimpleSupplyRewardPeriod(moneyMarketDenom, rewardsPerSecond) - } - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // User deposits - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, tc.args.deposit) - suite.Require().NoError(err) - - claim, foundClaim := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(foundClaim) - suite.Require().Equal(tc.args.expectedClaimSupplyRewardIndexes, claim.SupplyRewardIndexes) - }) - } -} - -func (suite *SupplyRewardsTestSuite) TestSynchronizeHardSupplyReward() { - type args struct { - incentiveSupplyRewardDenom string - deposit sdk.Coin - rewardsPerSecond sdk.Coins - blockTimes []int - expectedRewardIndexes types.RewardIndexes - expectedRewards sdk.Coins - updateRewardsViaCommmittee bool - updatedBaseDenom string - updatedRewardsPerSecond sdk.Coins - updatedExpectedRewardIndexes types.RewardIndexes - updatedExpectedRewards sdk.Coins - updatedTimeDuration int - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "single reward denom: 10 blocks", - args{ - incentiveSupplyRewardDenom: "bnb", - deposit: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.001223540000000000"))}, - expectedRewards: cs(c("hard", 12235400)), - updateRewardsViaCommmittee: false, - }, - }, - { - "single reward denom: 10 blocks - long block time", - args{ - incentiveSupplyRewardDenom: "bnb", - deposit: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("10.571385600000000000"))}, - expectedRewards: cs(c("hard", 105713856000)), - updateRewardsViaCommmittee: false, - }, - }, - { - "single reward denom: user reward index updated when reward is zero", - args{ - incentiveSupplyRewardDenom: "ukava", - deposit: c("ukava", 1), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.122353998776460010"))}, - expectedRewards: cs(), - updateRewardsViaCommmittee: false, - }, - }, - { - "multiple reward denoms: 10 blocks", - args{ - incentiveSupplyRewardDenom: "bnb", - deposit: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.001223540000000000")), - types.NewRewardIndex("ukava", d("0.001223540000000000")), - }, - expectedRewards: cs(c("hard", 12235400), c("ukava", 12235400)), - updateRewardsViaCommmittee: false, - }, - }, - { - "multiple reward denoms: 10 blocks - long block time", - args{ - incentiveSupplyRewardDenom: "bnb", - deposit: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("10.571385600000000000")), - types.NewRewardIndex("ukava", d("10.571385600000000000")), - }, - expectedRewards: cs(c("hard", 105713856000), c("ukava", 105713856000)), - updateRewardsViaCommmittee: false, - }, - }, - { - "multiple reward denoms with different rewards per second: 10 blocks", - args{ - incentiveSupplyRewardDenom: "bnb", - deposit: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 555555)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.001223540000000000")), - types.NewRewardIndex("ukava", d("0.005555550000000000")), - }, - expectedRewards: cs(c("hard", 12235400), c("ukava", 55555500)), - updateRewardsViaCommmittee: false, - }, - }, - { - "denom is in incentive's hard supply reward params and has rewards; add new reward type", - args{ - incentiveSupplyRewardDenom: "bnb", - deposit: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{86400}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("1.057138560000000000")), - }, - expectedRewards: cs(c("hard", 10571385600)), - updateRewardsViaCommmittee: true, - updatedBaseDenom: "bnb", - updatedRewardsPerSecond: cs(c("hard", 122354), c("ukava", 100000)), - updatedExpectedRewards: cs(c("hard", 21142771200), c("ukava", 8640000000)), - updatedExpectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("2.114277120000000000")), - types.NewRewardIndex("ukava", d("0.864000000000000000")), - }, - updatedTimeDuration: 86400, - }, - }, - { - "denom is in hard's money market params but not in incentive's hard supply reward params; add reward", - args{ - incentiveSupplyRewardDenom: "bnb", - deposit: c("zzz", 10000000000), - rewardsPerSecond: nil, - blockTimes: []int{100}, - expectedRewardIndexes: types.RewardIndexes{}, - expectedRewards: sdk.Coins{}, - updateRewardsViaCommmittee: true, - updatedBaseDenom: "zzz", - updatedRewardsPerSecond: cs(c("hard", 100000)), - updatedExpectedRewards: cs(c("hard", 8640000000)), - updatedExpectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.864")), - }, - updatedTimeDuration: 86400, - }, - }, - { - "denom is in hard's money market params but not in incentive's hard supply reward params; add multiple reward types", - args{ - incentiveSupplyRewardDenom: "bnb", - deposit: c("zzz", 10000000000), - rewardsPerSecond: nil, - blockTimes: []int{100}, - expectedRewardIndexes: types.RewardIndexes{}, - expectedRewards: sdk.Coins{}, - updateRewardsViaCommmittee: true, - updatedBaseDenom: "zzz", - updatedRewardsPerSecond: cs(c("hard", 100000), c("ukava", 100500), c("swap", 500)), - updatedExpectedRewards: cs(c("hard", 8640000000), c("ukava", 8683200000), c("swap", 43200000)), - updatedExpectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.864")), - types.NewRewardIndex("ukava", d("0.86832")), - types.NewRewardIndex("swap", d("0.00432")), - }, - updatedTimeDuration: 86400, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[2], cs(c("ukava", 1e9))). - WithSimpleAccount(userAddr, cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15))) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime) - if tc.args.rewardsPerSecond != nil { - incentBuilder = incentBuilder.WithSimpleSupplyRewardPeriod(tc.args.incentiveSupplyRewardDenom, tc.args.rewardsPerSecond) - } - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // Deposit a fixed amount from another user to dilute primary user's rewards per second. - suite.Require().NoError( - suite.hardKeeper.Deposit(suite.ctx, suite.addrs[2], cs(c("ukava", 100_000_000))), - ) - - // User deposits and borrows to increase total borrowed amount - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, sdk.NewCoins(tc.args.deposit)) - suite.Require().NoError(err) - - // Check that Hard hooks initialized a HardLiquidityProviderClaim with 0 reward indexes - claim, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - multiRewardIndex, _ := claim.SupplyRewardIndexes.GetRewardIndex(tc.args.deposit.Denom) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - currRewardIndex, found := multiRewardIndex.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(sdk.ZeroDec(), currRewardIndex.RewardFactor) - } - - // Run accumulator at several intervals - var timeElapsed int - previousBlockTime := suite.ctx.BlockTime() - for _, t := range tc.args.blockTimes { - timeElapsed += t - updatedBlockTime := previousBlockTime.Add(time.Duration(int(time.Second) * t)) - previousBlockTime = updatedBlockTime - blockCtx := suite.ctx.WithBlockTime(updatedBlockTime) - - // Run Hard begin blocker for each block ctx to update denom's interest factor - hard.BeginBlocker(blockCtx, suite.hardKeeper) - - // Accumulate hard supply-side rewards - multiRewardPeriod, found := suite.keeper.GetHardSupplyRewardPeriods(blockCtx, tc.args.deposit.Denom) - if found { - suite.keeper.AccumulateHardSupplyRewards(blockCtx, multiRewardPeriod) - } - } - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - - // After we've accumulated, run synchronize - deposit, found := suite.hardKeeper.GetDeposit(suite.ctx, userAddr) - suite.Require().True(found) - suite.Require().NotPanics(func() { - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - }) - - // Check that the global reward index's reward factor and user's claim have been updated as expected - claim, found = suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - globalRewardIndexes, foundGlobalRewardIndexes := suite.keeper.GetHardSupplyRewardIndexes(suite.ctx, tc.args.deposit.Denom) - if len(tc.args.rewardsPerSecond) > 0 { - suite.Require().True(foundGlobalRewardIndexes) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - // Check that global reward index has been updated as expected - globalRewardIndex, found := globalRewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, globalRewardIndex) - - // Check that the user's claim's reward index matches the corresponding global reward index - multiRewardIndex, found := claim.SupplyRewardIndexes.GetRewardIndex(tc.args.deposit.Denom) - suite.Require().True(found) - rewardIndex, found := multiRewardIndex.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, rewardIndex) - - // Check that the user's claim holds the expected amount of reward coins - suite.Require().Equal( - tc.args.expectedRewards.AmountOf(expectedRewardIndex.CollateralType), - claim.Reward.AmountOf(expectedRewardIndex.CollateralType), - ) - } - } - - // Only test cases with reward param updates continue past this point - if !tc.args.updateRewardsViaCommmittee { - return - } - - // If are no initial rewards per second, add new rewards through a committee param change - // 1. Construct incentive's new HardSupplyRewardPeriods param - currIncentiveHardSupplyRewardPeriods := suite.keeper.GetParams(suite.ctx).HardSupplyRewardPeriods - multiRewardPeriod, found := currIncentiveHardSupplyRewardPeriods.GetMultiRewardPeriod(tc.args.deposit.Denom) - if found { - // Deposit denom's reward period exists, but it doesn't have any rewards per second - index, found := currIncentiveHardSupplyRewardPeriods.GetMultiRewardPeriodIndex(tc.args.deposit.Denom) - suite.Require().True(found) - multiRewardPeriod.RewardsPerSecond = tc.args.updatedRewardsPerSecond - currIncentiveHardSupplyRewardPeriods[index] = multiRewardPeriod - } else { - // Deposit denom's reward period does not exist - _, found := currIncentiveHardSupplyRewardPeriods.GetMultiRewardPeriodIndex(tc.args.deposit.Denom) - suite.Require().False(found) - newMultiRewardPeriod := types.NewMultiRewardPeriod(true, tc.args.deposit.Denom, suite.genesisTime, suite.genesisTime.Add(time.Hour*24*365*4), tc.args.updatedRewardsPerSecond) - currIncentiveHardSupplyRewardPeriods = append(currIncentiveHardSupplyRewardPeriods, newMultiRewardPeriod) - } - - // 2. Construct the parameter change proposal to update HardSupplyRewardPeriods param - pubProposal := proposaltypes.NewParameterChangeProposal( - "Update hard supply rewards", "Adds a new reward coin to the incentive module's hard supply rewards.", - []proposaltypes.ParamChange{ - { - Subspace: types.ModuleName, // target incentive module - Key: string(types.KeyHardSupplyRewardPeriods), // target hard supply rewards key - Value: string(suite.app.LegacyAmino().MustMarshalJSON(&currIncentiveHardSupplyRewardPeriods)), - }, - }, - ) - - // 3. Ensure proposal is properly formed - err = suite.committeeKeeper.ValidatePubProposal(suite.ctx, pubProposal) - suite.Require().NoError(err) - - // 4. Committee creates proposal - committeeMemberOne := suite.addrs[0] - committeeMemberTwo := suite.addrs[1] - proposalID, err := suite.committeeKeeper.SubmitProposal(suite.ctx, committeeMemberOne, 1, pubProposal) - suite.Require().NoError(err) - - // 5. Committee votes and passes proposal - err = suite.committeeKeeper.AddVote(suite.ctx, proposalID, committeeMemberOne, committeetypes.VOTE_TYPE_YES) - suite.Require().NoError(err) - err = suite.committeeKeeper.AddVote(suite.ctx, proposalID, committeeMemberTwo, committeetypes.VOTE_TYPE_YES) - suite.Require().NoError(err) - - // 6. Check proposal passed - com, found := suite.committeeKeeper.GetCommittee(suite.ctx, 1) - suite.Require().True(found) - proposalPasses := suite.committeeKeeper.GetProposalResult(suite.ctx, proposalID, com) - suite.Require().True(proposalPasses) - - // 7. Run committee module's begin blocker to enact proposal - suite.NotPanics(func() { - committee.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}, suite.committeeKeeper) - }) - - // We need to accumulate hard supply-side rewards again - multiRewardPeriod, found = suite.keeper.GetHardSupplyRewardPeriods(suite.ctx, tc.args.deposit.Denom) - suite.Require().True(found) - - // But new deposit denoms don't have their PreviousHardSupplyRewardAccrualTime set yet, - // so we need to call the accumulation method once to set the initial reward accrual time - if tc.args.deposit.Denom != tc.args.incentiveSupplyRewardDenom { - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, multiRewardPeriod) - } - - // Now we can jump forward in time and accumulate rewards - updatedBlockTime = previousBlockTime.Add(time.Duration(int(time.Second) * tc.args.updatedTimeDuration)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, multiRewardPeriod) - - // After we've accumulated, run synchronize - deposit, found = suite.hardKeeper.GetDeposit(suite.ctx, userAddr) - suite.Require().True(found) - suite.Require().NotPanics(func() { - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - }) - - // Check that the global reward index's reward factor and user's claim have been updated as expected - globalRewardIndexes, found = suite.keeper.GetHardSupplyRewardIndexes(suite.ctx, tc.args.deposit.Denom) - suite.Require().True(found) - claim, found = suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - for _, expectedRewardIndex := range tc.args.updatedExpectedRewardIndexes { - // Check that global reward index has been updated as expected - globalRewardIndex, found := globalRewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, globalRewardIndex) - - // Check that the user's claim's reward index matches the corresponding global reward index - multiRewardIndex, found := claim.SupplyRewardIndexes.GetRewardIndex(tc.args.deposit.Denom) - suite.Require().True(found) - rewardIndex, found := multiRewardIndex.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, rewardIndex) - - // Check that the user's claim holds the expected amount of reward coins - suite.Require().Equal( - tc.args.updatedExpectedRewards.AmountOf(expectedRewardIndex.CollateralType), - claim.Reward.AmountOf(expectedRewardIndex.CollateralType), - ) - } - }) - } -} - -func (suite *SupplyRewardsTestSuite) TestUpdateHardSupplyIndexDenoms() { - type depositModification struct { - coins sdk.Coins - withdraw bool - } - - type args struct { - firstDeposit sdk.Coins - modification depositModification - rewardsPerSecond sdk.Coins - expectedSupplyIndexDenoms []string - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "single reward denom: update adds one supply reward index", - args{ - firstDeposit: cs(c("bnb", 10000000000)), - modification: depositModification{coins: cs(c("ukava", 10000000000))}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedSupplyIndexDenoms: []string{"bnb", "ukava"}, - }, - }, - { - "single reward denom: update adds multiple supply reward indexes", - args{ - firstDeposit: cs(c("bnb", 10000000000)), - modification: depositModification{coins: cs(c("ukava", 10000000000), c("btcb", 10000000000), c("xrp", 10000000000))}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedSupplyIndexDenoms: []string{"bnb", "ukava", "btcb", "xrp"}, - }, - }, - { - "single reward denom: update doesn't add duplicate supply reward index for same denom", - args{ - firstDeposit: cs(c("bnb", 10000000000)), - modification: depositModification{coins: cs(c("bnb", 5000000000))}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedSupplyIndexDenoms: []string{"bnb"}, - }, - }, - { - "multiple reward denoms: update adds one supply reward index", - args{ - firstDeposit: cs(c("bnb", 10000000000)), - modification: depositModification{coins: cs(c("ukava", 10000000000))}, - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - expectedSupplyIndexDenoms: []string{"bnb", "ukava"}, - }, - }, - { - "multiple reward denoms: update adds multiple supply reward indexes", - args{ - firstDeposit: cs(c("bnb", 10000000000)), - modification: depositModification{coins: cs(c("ukava", 10000000000), c("btcb", 10000000000), c("xrp", 10000000000))}, - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - expectedSupplyIndexDenoms: []string{"bnb", "ukava", "btcb", "xrp"}, - }, - }, - { - "multiple reward denoms: update doesn't add duplicate supply reward index for same denom", - args{ - firstDeposit: cs(c("bnb", 10000000000)), - modification: depositModification{coins: cs(c("bnb", 5000000000))}, - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - expectedSupplyIndexDenoms: []string{"bnb"}, - }, - }, - { - "single reward denom: fully withdrawing a denom deletes the denom's supply reward index", - args{ - firstDeposit: cs(c("bnb", 1000000000)), - modification: depositModification{coins: cs(c("bnb", 1100000000)), withdraw: true}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedSupplyIndexDenoms: []string{}, - }, - }, - { - "single reward denom: fully withdrawing a denom deletes only the denom's supply reward index", - args{ - firstDeposit: cs(c("bnb", 1000000000), c("ukava", 100000000)), - modification: depositModification{coins: cs(c("bnb", 1100000000)), withdraw: true}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedSupplyIndexDenoms: []string{"ukava"}, - }, - }, - { - "multiple reward denoms: fully repaying a denom deletes the denom's supply reward index", - args{ - firstDeposit: cs(c("bnb", 1000000000)), - modification: depositModification{coins: cs(c("bnb", 1100000000)), withdraw: true}, - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - expectedSupplyIndexDenoms: []string{}, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount( - userAddr, - cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15)), - ) - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleSupplyRewardPeriod("bnb", tc.args.rewardsPerSecond). - WithSimpleSupplyRewardPeriod("ukava", tc.args.rewardsPerSecond). - WithSimpleSupplyRewardPeriod("btcb", tc.args.rewardsPerSecond). - WithSimpleSupplyRewardPeriod("xrp", tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // User deposits (first time) - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, tc.args.firstDeposit) - suite.Require().NoError(err) - - // Confirm that a claim was created and populated with the correct supply indexes - claimAfterFirstDeposit, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - for _, coin := range tc.args.firstDeposit { - _, hasIndex := claimAfterFirstDeposit.HasSupplyRewardIndex(coin.Denom) - suite.Require().True(hasIndex) - } - suite.Require().True(len(claimAfterFirstDeposit.SupplyRewardIndexes) == len(tc.args.firstDeposit)) - - // User modifies their Deposit by withdrawing or depositing more - if tc.args.modification.withdraw { - err = suite.hardKeeper.Withdraw(suite.ctx, userAddr, tc.args.modification.coins) - } else { - err = suite.hardKeeper.Deposit(suite.ctx, userAddr, tc.args.modification.coins) - } - suite.Require().NoError(err) - - // Confirm that the claim contains all expected supply indexes - claimAfterModification, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - for _, denom := range tc.args.expectedSupplyIndexDenoms { - _, hasIndex := claimAfterModification.HasSupplyRewardIndex(denom) - suite.Require().True(hasIndex) - } - suite.Require().True(len(claimAfterModification.SupplyRewardIndexes) == len(tc.args.expectedSupplyIndexDenoms)) - }) - } -} - -func (suite *SupplyRewardsTestSuite) TestSimulateHardSupplyRewardSynchronization() { - type args struct { - deposit sdk.Coin - rewardsPerSecond sdk.Coins - blockTimes []int - expectedRewardIndexes types.RewardIndexes - expectedRewards sdk.Coins - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "10 blocks", - args{ - deposit: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.001223540000000000"))}, - expectedRewards: cs(c("hard", 12235400)), - }, - }, - { - "10 blocks - long block time", - args{ - deposit: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("10.571385600000000000"))}, - expectedRewards: cs(c("hard", 105713856000)), - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount( - userAddr, - cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15)), - ) - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleSupplyRewardPeriod(tc.args.deposit.Denom, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // User deposits and borrows to increase total borrowed amount - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, sdk.NewCoins(tc.args.deposit)) - suite.Require().NoError(err) - - // Run accumulator at several intervals - var timeElapsed int - previousBlockTime := suite.ctx.BlockTime() - for _, t := range tc.args.blockTimes { - timeElapsed += t - updatedBlockTime := previousBlockTime.Add(time.Duration(int(time.Second) * t)) - previousBlockTime = updatedBlockTime - blockCtx := suite.ctx.WithBlockTime(updatedBlockTime) - - // Run Hard begin blocker for each block ctx to update denom's interest factor - hard.BeginBlocker(blockCtx, suite.hardKeeper) - - // Accumulate hard supply-side rewards - multiRewardPeriod, found := suite.keeper.GetHardSupplyRewardPeriods(blockCtx, tc.args.deposit.Denom) - suite.Require().True(found) - suite.keeper.AccumulateHardSupplyRewards(blockCtx, multiRewardPeriod) - } - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - - // Confirm that the user's claim hasn't been synced - claimPre, foundPre := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(foundPre) - multiRewardIndexPre, _ := claimPre.SupplyRewardIndexes.GetRewardIndex(tc.args.deposit.Denom) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - currRewardIndex, found := multiRewardIndexPre.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(sdk.ZeroDec(), currRewardIndex.RewardFactor) - } - - // Check that the synced claim held in memory has properly simulated syncing - syncedClaim := suite.keeper.SimulateHardSynchronization(suite.ctx, claimPre) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - // Check that the user's claim's reward index matches the expected reward index - multiRewardIndex, found := syncedClaim.SupplyRewardIndexes.GetRewardIndex(tc.args.deposit.Denom) - suite.Require().True(found) - rewardIndex, found := multiRewardIndex.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, rewardIndex) - - // Check that the user's claim holds the expected amount of reward coins - suite.Require().Equal( - tc.args.expectedRewards.AmountOf(expectedRewardIndex.CollateralType), - syncedClaim.Reward.AmountOf(expectedRewardIndex.CollateralType), - ) - } - }) - } -} - -func TestSupplyRewardsTestSuite(t *testing.T) { - suite.Run(t, new(SupplyRewardsTestSuite)) -} diff --git a/x/incentive/keeper/rewards_supply_update_test.go b/x/incentive/keeper/rewards_supply_update_test.go deleted file mode 100644 index fd04f878..00000000 --- a/x/incentive/keeper/rewards_supply_update_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/incentive/types" -) - -// UpdateHardSupplyIndexDenomsTests runs unit tests for the keeper.UpdateHardSupplyIndexDenoms method -type UpdateHardSupplyIndexDenomsTests struct { - unitTester -} - -func TestUpdateHardSupplyIndexDenoms(t *testing.T) { - suite.Run(t, new(UpdateHardSupplyIndexDenomsTests)) -} - -func (suite *UpdateHardSupplyIndexDenomsTests) TestClaimIndexesAreRemovedForDenomsNoLongerSupplied() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - SupplyRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - suite.storeGlobalSupplyIndexes(claim.SupplyRewardIndexes) - - // remove one denom from the indexes already in the deposit - expectedIndexes := claim.SupplyRewardIndexes[1:] - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(expectedIndexes)...). - Build() - - suite.keeper.UpdateHardSupplyIndexDenoms(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(expectedIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *UpdateHardSupplyIndexDenomsTests) TestClaimIndexesAreAddedForNewlySuppliedDenoms() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - SupplyRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - globalIndexes := appendUniqueMultiRewardIndex(claim.SupplyRewardIndexes) - suite.storeGlobalSupplyIndexes(globalIndexes) - - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.UpdateHardSupplyIndexDenoms(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *UpdateHardSupplyIndexDenomsTests) TestClaimIndexesAreUnchangedWhenSuppliedDenomsUnchanged() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - SupplyRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - // Set global indexes with same denoms but different values. - // UpdateHardSupplyIndexDenoms should ignore the new values. - suite.storeGlobalSupplyIndexes(increaseAllRewardFactors(claim.SupplyRewardIndexes)) - - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(claim.SupplyRewardIndexes)...). - Build() - - suite.keeper.UpdateHardSupplyIndexDenoms(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(claim.SupplyRewardIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *UpdateHardSupplyIndexDenomsTests) TestEmptyClaimIndexesAreAddedForNewlySuppliedButNotRewardedDenoms() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - SupplyRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - suite.storeGlobalSupplyIndexes(claim.SupplyRewardIndexes) - - // add a denom to the deposited amount that is not in the global or claim's indexes - expectedIndexes := appendUniqueEmptyMultiRewardIndex(claim.SupplyRewardIndexes) - depositedDenoms := extractCollateralTypes(expectedIndexes) - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(depositedDenoms...). - Build() - - suite.keeper.UpdateHardSupplyIndexDenoms(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(expectedIndexes, syncedClaim.SupplyRewardIndexes) -} diff --git a/x/incentive/keeper/rewards_swap.go b/x/incentive/keeper/rewards_swap.go deleted file mode 100644 index 7f468c96..00000000 --- a/x/incentive/keeper/rewards_swap.go +++ /dev/null @@ -1,130 +0,0 @@ -package keeper - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/incentive/types" -) - -// AccumulateSwapRewards calculates new rewards to distribute this block and updates the global indexes to reflect this. -// The provided rewardPeriod must be valid to avoid panics in calculating time durations. -func (k Keeper) AccumulateSwapRewards(ctx sdk.Context, rewardPeriod types.MultiRewardPeriod) { - previousAccrualTime, found := k.GetSwapRewardAccrualTime(ctx, rewardPeriod.CollateralType) - if !found { - previousAccrualTime = ctx.BlockTime() - } - - indexes, found := k.GetSwapRewardIndexes(ctx, rewardPeriod.CollateralType) - if !found { - indexes = types.RewardIndexes{} - } - - acc := types.NewAccumulator(previousAccrualTime, indexes) - - totalSource := k.getSwapTotalSourceShares(ctx, rewardPeriod.CollateralType) - - acc.Accumulate(rewardPeriod, totalSource, ctx.BlockTime()) - - k.SetSwapRewardAccrualTime(ctx, rewardPeriod.CollateralType, acc.PreviousAccumulationTime) - if len(acc.Indexes) > 0 { - // the store panics when setting empty or nil indexes - k.SetSwapRewardIndexes(ctx, rewardPeriod.CollateralType, acc.Indexes) - } -} - -// getSwapTotalSourceShares fetches the sum of all source shares for a swap reward. -// In the case of swap, these are the total (swap module) shares in a particular pool. -func (k Keeper) getSwapTotalSourceShares(ctx sdk.Context, poolID string) sdk.Dec { - totalShares, found := k.swapKeeper.GetPoolShares(ctx, poolID) - if !found { - totalShares = sdk.ZeroInt() - } - return sdk.NewDecFromInt(totalShares) -} - -// InitializeSwapReward creates a new claim with zero rewards and indexes matching the global indexes. -// If the claim already exists it just updates the indexes. -func (k Keeper) InitializeSwapReward(ctx sdk.Context, poolID string, owner sdk.AccAddress) { - claim, found := k.GetSwapClaim(ctx, owner) - if !found { - claim = types.NewSwapClaim(owner, sdk.Coins{}, nil) - } - - globalRewardIndexes, found := k.GetSwapRewardIndexes(ctx, poolID) - if !found { - globalRewardIndexes = types.RewardIndexes{} - } - claim.RewardIndexes = claim.RewardIndexes.With(poolID, globalRewardIndexes) - - k.SetSwapClaim(ctx, claim) -} - -// SynchronizeSwapReward updates the claim object by adding any accumulated rewards -// and updating the reward index value. -func (k Keeper) SynchronizeSwapReward(ctx sdk.Context, poolID string, owner sdk.AccAddress, shares sdkmath.Int) { - claim, found := k.GetSwapClaim(ctx, owner) - if !found { - return - } - claim = k.synchronizeSwapReward(ctx, claim, poolID, owner, shares) - - k.SetSwapClaim(ctx, claim) -} - -// synchronizeSwapReward updates the reward and indexes in a swap claim for one pool. -func (k *Keeper) synchronizeSwapReward(ctx sdk.Context, claim types.SwapClaim, poolID string, owner sdk.AccAddress, shares sdkmath.Int) types.SwapClaim { - globalRewardIndexes, found := k.GetSwapRewardIndexes(ctx, poolID) - if !found { - // The global factor is only not found if - // - the pool has not started accumulating rewards yet (either there is no reward specified in params, or the reward start time hasn't been hit) - // - OR it was wrongly deleted from state (factors should never be removed while unsynced claims exist) - // If not found we could either skip this sync, or assume the global factor is zero. - // Skipping will avoid storing unnecessary factors in the claim for non rewarded pools. - // And in the event a global factor is wrongly deleted, it will avoid this function panicking when calculating rewards. - return claim - } - - userRewardIndexes, found := claim.RewardIndexes.Get(poolID) - if !found { - // Normally the reward indexes should always be found. - // But if a pool was not rewarded then becomes rewarded (ie a reward period is added to params), then the indexes will be missing from claims for that pool. - // So given the reward period was just added, assume the starting value for any global reward indexes, which is an empty slice. - userRewardIndexes = types.RewardIndexes{} - } - - newRewards, err := k.CalculateRewards(userRewardIndexes, globalRewardIndexes, sdk.NewDecFromInt(shares)) - if err != nil { - // Global reward factors should never decrease, as it would lead to a negative update to claim.Rewards. - // This panics if a global reward factor decreases or disappears between the old and new indexes. - panic(fmt.Sprintf("corrupted global reward indexes found: %v", err)) - } - - claim.Reward = claim.Reward.Add(newRewards...) - claim.RewardIndexes = claim.RewardIndexes.With(poolID, globalRewardIndexes) - - return claim -} - -// GetSynchronizedSwapClaim fetches a swap claim from the store and syncs rewards for all rewarded pools. -func (k Keeper) GetSynchronizedSwapClaim(ctx sdk.Context, owner sdk.AccAddress) (types.SwapClaim, bool) { - claim, found := k.GetSwapClaim(ctx, owner) - if !found { - return types.SwapClaim{}, false - } - - k.IterateSwapRewardIndexes(ctx, func(poolID string, _ types.RewardIndexes) bool { - shares, found := k.swapKeeper.GetDepositorSharesAmount(ctx, owner, poolID) - if !found { - shares = sdk.ZeroInt() - } - - claim = k.synchronizeSwapReward(ctx, claim, poolID, owner, shares) - - return false - }) - - return claim, true -} diff --git a/x/incentive/keeper/rewards_swap_accum_test.go b/x/incentive/keeper/rewards_swap_accum_test.go deleted file mode 100644 index bb09e866..00000000 --- a/x/incentive/keeper/rewards_swap_accum_test.go +++ /dev/null @@ -1,320 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/incentive/types" -) - -type AccumulateSwapRewardsTests struct { - unitTester -} - -func (suite *AccumulateSwapRewardsTests) storedTimeEquals(poolID string, expected time.Time) { - storedTime, found := suite.keeper.GetSwapRewardAccrualTime(suite.ctx, poolID) - suite.True(found) - suite.Equal(expected, storedTime) -} - -func (suite *AccumulateSwapRewardsTests) storedIndexesEqual(poolID string, expected types.RewardIndexes) { - storedIndexes, found := suite.keeper.GetSwapRewardIndexes(suite.ctx, poolID) - suite.Equal(found, expected != nil) - if found { - suite.Equal(expected, storedIndexes) - } else { - suite.Empty(storedIndexes) - } -} - -func TestAccumulateSwapRewards(t *testing.T) { - suite.Run(t, new(AccumulateSwapRewardsTests)) -} - -func (suite *AccumulateSwapRewardsTests) TestStateUpdatedWhenBlockTimeHasIncreased() { - pool := "btc:usdx" - - swapKeeper := newFakeSwapKeeper().addPool(pool, i(1e6)) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - suite.storeGlobalSwapIndexes(types.MultiRewardIndexes{ - { - CollateralType: pool, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "swap", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - }) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetSwapRewardAccrualTime(suite.ctx, pool, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - pool, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("swap", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateSwapRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(pool, newAccrualTime) - suite.storedIndexesEqual(pool, types.RewardIndexes{ - { - CollateralType: "swap", - RewardFactor: d("7.22"), - }, - { - CollateralType: "ukava", - RewardFactor: d("3.64"), - }, - }) -} - -func (suite *AccumulateSwapRewardsTests) TestStateUnchangedWhenBlockTimeHasNotIncreased() { - pool := "btc:usdx" - - swapKeeper := newFakeSwapKeeper().addPool(pool, i(1e6)) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: pool, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "swap", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetSwapRewardAccrualTime(suite.ctx, pool, previousAccrualTime) - - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - pool, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("swap", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateSwapRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(pool, previousAccrualTime) - expected, f := previousIndexes.Get(pool) - suite.True(f) - suite.storedIndexesEqual(pool, expected) -} - -func (suite *AccumulateSwapRewardsTests) TestNoAccumulationWhenSourceSharesAreZero() { - pool := "btc:usdx" - - swapKeeper := newFakeSwapKeeper() // no pools, so no source shares - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: pool, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "swap", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetSwapRewardAccrualTime(suite.ctx, pool, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(7 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - pool, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("swap", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateSwapRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(pool, firstAccrualTime) - expected, f := previousIndexes.Get(pool) - suite.True(f) - suite.storedIndexesEqual(pool, expected) -} - -func (suite *AccumulateSwapRewardsTests) TestStateAddedWhenStateDoesNotExist() { - pool := "btc:usdx" - - swapKeeper := newFakeSwapKeeper().addPool(pool, i(1e6)) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - period := types.NewMultiRewardPeriod( - true, - pool, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("swap", 2000), c("ukava", 1000)), - ) - - firstAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateSwapRewards(suite.ctx, period) - - // After the first accumulation only the current block time should be stored. - // The indexes will be empty as no time has passed since the previous block because it didn't exist. - suite.storedTimeEquals(pool, firstAccrualTime) - suite.storedIndexesEqual(pool, nil) - - secondAccrualTime := firstAccrualTime.Add(10 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(secondAccrualTime) - - suite.keeper.AccumulateSwapRewards(suite.ctx, period) - - // After the second accumulation both current block time and indexes should be stored. - suite.storedTimeEquals(pool, secondAccrualTime) - suite.storedIndexesEqual(pool, types.RewardIndexes{ - { - CollateralType: "swap", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.01"), - }, - }) -} - -func (suite *AccumulateSwapRewardsTests) TestNoPanicWhenStateDoesNotExist() { - pool := "btc:usdx" - - swapKeeper := newFakeSwapKeeper() - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - period := types.NewMultiRewardPeriod( - true, - pool, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(), - ) - - accrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(accrualTime) - - // Accumulate with no swap shares and no rewards per second will result in no increment to the indexes. - // No increment and no previous indexes stored, results in an updated of nil. Setting this in the state panics. - // Check there is no panic. - suite.NotPanics(func() { - suite.keeper.AccumulateSwapRewards(suite.ctx, period) - }) - - suite.storedTimeEquals(pool, accrualTime) - suite.storedIndexesEqual(pool, nil) -} - -func (suite *AccumulateSwapRewardsTests) TestNoAccumulationWhenBeforeStartTime() { - pool := "btc:usdx" - - swapKeeper := newFakeSwapKeeper().addPool(pool, i(1e6)) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: pool, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "swap", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetSwapRewardAccrualTime(suite.ctx, pool, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(10 * time.Second) - - period := types.NewMultiRewardPeriod( - true, - pool, - firstAccrualTime.Add(time.Nanosecond), // start time after accrual time - distantFuture, - cs(c("swap", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateSwapRewards(suite.ctx, period) - - // The accrual time should be updated, but the indexes unchanged - suite.storedTimeEquals(pool, firstAccrualTime) - expectedIndexes, f := previousIndexes.Get(pool) - suite.True(f) - suite.storedIndexesEqual(pool, expectedIndexes) -} - -func (suite *AccumulateSwapRewardsTests) TestPanicWhenCurrentTimeLessThanPrevious() { - pool := "btc:usdx" - - swapKeeper := newFakeSwapKeeper().addPool(pool, i(1e6)) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetSwapRewardAccrualTime(suite.ctx, pool, previousAccrualTime) - - firstAccrualTime := time.Time{} - - period := types.NewMultiRewardPeriod( - true, - pool, - time.Time{}, // start time after accrual time - distantFuture, - cs(c("swap", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.Panics(func() { - suite.keeper.AccumulateSwapRewards(suite.ctx, period) - }) -} diff --git a/x/incentive/keeper/rewards_swap_init_test.go b/x/incentive/keeper/rewards_swap_init_test.go deleted file mode 100644 index 37619e38..00000000 --- a/x/incentive/keeper/rewards_swap_init_test.go +++ /dev/null @@ -1,195 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/incentive/types" -) - -// InitializeSwapRewardTests runs unit tests for the keeper.InitializeSwapReward method -// -// inputs -// - claim in store if it exists -// - global indexes in store -// -// outputs -// - sets or creates a claim -type InitializeSwapRewardTests struct { - unitTester -} - -func TestInitializeSwapReward(t *testing.T) { - suite.Run(t, new(InitializeSwapRewardTests)) -} - -func (suite *InitializeSwapRewardTests) TestClaimAddedWhenClaimDoesNotExistAndNoRewards() { - // When a claim doesn't exist, and a user deposits to a non-rewarded pool; - // then a claim is added with no rewards and no indexes - - poolID := "base:quote" - - // no global indexes stored as this pool is not rewarded - - owner := arbitraryAddress() - - suite.keeper.InitializeSwapReward(suite.ctx, poolID, owner) - - syncedClaim, found := suite.keeper.GetSwapClaim(suite.ctx, owner) - suite.True(found) - // A new claim should have empty indexes. It doesn't strictly need the poolID either. - expectedIndexes := types.MultiRewardIndexes{{ - CollateralType: poolID, - RewardIndexes: nil, - }} - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // a new claim should start with 0 rewards - suite.Equal(sdk.Coins(nil), syncedClaim.Reward) -} - -func (suite *InitializeSwapRewardTests) TestClaimAddedWhenClaimDoesNotExistAndRewardsExist() { - // When a claim doesn't exist, and a user deposits to a rewarded pool; - // then a claim is added with no rewards and indexes matching the global indexes - - poolID := "base:quote" - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: poolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(globalIndexes) - - owner := arbitraryAddress() - - suite.keeper.InitializeSwapReward(suite.ctx, poolID, owner) - - syncedClaim, found := suite.keeper.GetSwapClaim(suite.ctx, owner) - suite.True(found) - // a new claim should start with the current global indexes - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // a new claim should start with 0 rewards - suite.Equal(sdk.Coins(nil), syncedClaim.Reward) -} - -func (suite *InitializeSwapRewardTests) TestClaimUpdatedWhenClaimExistsAndNoRewards() { - // When a claim exists, and a user deposits to a new non-rewarded pool; - // then the claim's rewards don't change - - preexistingPoolID := "preexisting" - preexistingIndexes := types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - } - - newPoolID := "btcb:usdx" - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: preexistingPoolID, - RewardIndexes: preexistingIndexes, - }, - }, - } - suite.storeSwapClaim(claim) - - // no global indexes stored as the new pool is not rewarded - - suite.keeper.InitializeSwapReward(suite.ctx, newPoolID, claim.Owner) - - syncedClaim, _ := suite.keeper.GetSwapClaim(suite.ctx, claim.Owner) - // The preexisting indexes shouldn't be changed. It doesn't strictly need the new poolID either. - expectedIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingPoolID, - RewardIndexes: preexistingIndexes, - }, - { - CollateralType: newPoolID, - RewardIndexes: nil, - }, - } - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // init should never alter the rewards - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *InitializeSwapRewardTests) TestClaimUpdatedWhenClaimExistsAndRewardsExist() { - // When a claim exists, and a user deposits to a new rewarded pool; - // then the claim's rewards don't change and the indexes are updated to match the global indexes - - preexistingPoolID := "preexisting" - preexistingIndexes := types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - } - - newPoolID := "btcb:usdx" - newIndexes := types.RewardIndexes{ - { - CollateralType: "otherrewarddenom", - RewardFactor: d("1000.001"), - }, - } - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: preexistingPoolID, - RewardIndexes: preexistingIndexes, - }, - }, - } - suite.storeSwapClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingPoolID, - RewardIndexes: increaseRewardFactors(preexistingIndexes), - }, - { - CollateralType: newPoolID, - RewardIndexes: newIndexes, - }, - } - suite.storeGlobalSwapIndexes(globalIndexes) - - suite.keeper.InitializeSwapReward(suite.ctx, newPoolID, claim.Owner) - - syncedClaim, _ := suite.keeper.GetSwapClaim(suite.ctx, claim.Owner) - // only the indexes for the new pool should be updated - expectedIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingPoolID, - RewardIndexes: preexistingIndexes, - }, - { - CollateralType: newPoolID, - RewardIndexes: newIndexes, - }, - } - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // init should never alter the rewards - suite.Equal(claim.Reward, syncedClaim.Reward) -} diff --git a/x/incentive/keeper/rewards_swap_sync_test.go b/x/incentive/keeper/rewards_swap_sync_test.go deleted file mode 100644 index 97fda931..00000000 --- a/x/incentive/keeper/rewards_swap_sync_test.go +++ /dev/null @@ -1,470 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/incentive/types" -) - -// SynchronizeSwapRewardTests runs unit tests for the keeper.SynchronizeSwapReward method -// -// inputs -// - claim in store (only claim.RewardIndexes, claim.Reward) -// - global indexes in store -// - shares function arg -// -// outputs -// - sets a claim -type SynchronizeSwapRewardTests struct { - unitTester -} - -func TestSynchronizeSwapReward(t *testing.T) { - suite.Run(t, new(SynchronizeSwapRewardTests)) -} - -func (suite *SynchronizeSwapRewardTests) TestClaimUpdatedWhenGlobalIndexesHaveIncreased() { - // This is the normal case - // Given some time has passed (meaning the global indexes have increased) - // When the claim is synced - // The user earns rewards for the time passed, and the claim indexes are updated - - originalReward := arbitraryCoins() - poolID := "base:quote" - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: poolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSwapClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: poolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(globalIndexes) - - userShares := i(1e9) - - suite.keeper.SynchronizeSwapReward(suite.ctx, poolID, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetSwapClaim(suite.ctx, claim.Owner) - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * user shares - suite.Equal( - cs(c("rewarddenom", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeSwapRewardTests) TestClaimUnchangedWhenGlobalIndexesUnchanged() { - // It should be safe to call SynchronizeSwapReward multiple times - - poolID := "base:quote" - unchangingIndexes := types.MultiRewardIndexes{ - { - CollateralType: poolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - } - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: unchangingIndexes, - } - suite.storeSwapClaim(claim) - - suite.storeGlobalSwapIndexes(unchangingIndexes) - - userShares := i(1e9) - - suite.keeper.SynchronizeSwapReward(suite.ctx, poolID, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetSwapClaim(suite.ctx, claim.Owner) - // claim should have the same rewards and indexes as before - suite.Equal(claim, syncedClaim) -} - -func (suite *SynchronizeSwapRewardTests) TestClaimUpdatedWhenNewRewardAdded() { - // When a new reward is added (via gov) for a pool the user has already deposited to, and the claim is synced; - // Then the user earns rewards for the time since the reward was added, and the indexes are added to the claim. - - originalReward := arbitraryCoins() - newlyRewardPoolID := "newlyRewardedPool" - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "currentlyRewardedPool", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSwapClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: "currentlyRewardedPool", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: newlyRewardPoolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(globalIndexes) - - userShares := i(1e9) - - suite.keeper.SynchronizeSwapReward(suite.ctx, newlyRewardPoolID, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetSwapClaim(suite.ctx, claim.Owner) - // the new indexes should be added to the claim, but the old ones should be unchanged - newlyRewrdedIndexes, _ := globalIndexes.Get(newlyRewardPoolID) - expectedIndexes := claim.RewardIndexes.With(newlyRewardPoolID, newlyRewrdedIndexes) - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * shares for the synced pool - // The old index for `newlyrewarded` isn't in the claim, so it's added starting at 0 for calculating the reward. - suite.Equal( - cs(c("otherreward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeSwapRewardTests) TestClaimUnchangedWhenNoReward() { - // When a pool is not rewarded but the user has deposited to that pool, and the claim is synced; - // Then the claim should be the same. - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeSwapClaim(claim) - - poolID := "nonRewardPool" - // No global indexes stored as this pool is not rewarded - - userShares := i(1e9) - - suite.keeper.SynchronizeSwapReward(suite.ctx, poolID, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetSwapClaim(suite.ctx, claim.Owner) - suite.Equal(claim, syncedClaim) -} - -func (suite *SynchronizeSwapRewardTests) TestClaimUpdatedWhenNewRewardDenomAdded() { - // When a new reward coin is added (via gov) to an already rewarded pool (that the user has already deposited to), and the claim is synced; - // Then the user earns rewards for the time since the reward was added, and the new indexes are added. - - originalReward := arbitraryCoins() - poolID := "base:quote" - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: poolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSwapClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: poolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(globalIndexes) - - userShares := i(1e9) - - suite.keeper.SynchronizeSwapReward(suite.ctx, poolID, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetSwapClaim(suite.ctx, claim.Owner) - // indexes should have the new reward denom added - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * shares - // The old index for `otherreward` isn't in the claim, so it's added starting at 0 for calculating the reward. - suite.Equal( - cs(c("reward", 1_000_001_000_000), c("otherreward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeSwapRewardTests) TestClaimUpdatedWhenGlobalIndexesIncreasedAndSourceIsZero() { - // Given some time has passed (meaning the global indexes have increased) - // When the claim is synced, but the user has no shares - // The user earns no rewards for the time passed, but the claim indexes are updated - - poolID := "base:quote" - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: poolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSwapClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: poolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(globalIndexes) - - userShares := i(0) - - suite.keeper.SynchronizeSwapReward(suite.ctx, poolID, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetSwapClaim(suite.ctx, claim.Owner) - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // reward is unchanged - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *SynchronizeSwapRewardTests) TestGetSyncedClaim_ClaimUnchangedWhenNoGlobalIndexes() { - poolID_1 := "btcb:usdx" - owner := arbitraryAddress() - - swapKeeper := newFakeSwapKeeper(). - addDeposit(poolID_1, owner, i(1e9)) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: owner, - Reward: nil, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: poolID_1, - RewardIndexes: nil, // this state only happens because Init stores empty indexes - }, - }, - } - suite.storeSwapClaim(claim) - - // no global indexes for any pool - - syncedClaim, f := suite.keeper.GetSynchronizedSwapClaim(suite.ctx, claim.Owner) - suite.True(f) - - // indexes are unchanged - suite.Equal(claim.RewardIndexes, syncedClaim.RewardIndexes) - // reward is unchanged - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *SynchronizeSwapRewardTests) TestGetSyncedClaim_ClaimUpdatedWhenMissingIndexAndHasNoSourceShares() { - poolID_1 := "btcb:usdx" - poolID_2 := "ukava:usdx" - owner := arbitraryAddress() - - // owner has no shares in any pool - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, newFakeSwapKeeper(), nil, nil, nil) - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: owner, - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: poolID_1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom1", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSwapClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: poolID_1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom1", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: poolID_2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom2", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(globalIndexes) - - syncedClaim, f := suite.keeper.GetSynchronizedSwapClaim(suite.ctx, claim.Owner) - suite.True(f) - - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // reward is unchanged - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *SynchronizeSwapRewardTests) TestGetSyncedClaim_ClaimUpdatedWhenMissingIndexButHasSourceShares() { - poolID_1 := "btcb:usdx" - poolID_2 := "ukava:usdx" - owner := arbitraryAddress() - - swapKeeper := newFakeSwapKeeper(). - addDeposit(poolID_1, owner, i(1e9)). - addDeposit(poolID_2, owner, i(1e9)) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: owner, - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: poolID_1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom1", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSwapClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: poolID_1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom1", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: poolID_2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom2", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(globalIndexes) - - syncedClaim, f := suite.keeper.GetSynchronizedSwapClaim(suite.ctx, claim.Owner) - suite.True(f) - - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // reward is incremented - expectedReward := cs(c("rewarddenom1", 1_000_001_000_000), c("rewarddenom2", 2_000_002_000_000)) - suite.Equal(claim.Reward.Add(expectedReward...), syncedClaim.Reward) -} diff --git a/x/incentive/keeper/rewards_usdx.go b/x/incentive/keeper/rewards_usdx.go deleted file mode 100644 index ada24147..00000000 --- a/x/incentive/keeper/rewards_usdx.go +++ /dev/null @@ -1,198 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - cdptypes "github.com/kava-labs/kava/x/cdp/types" - "github.com/kava-labs/kava/x/incentive/types" -) - -// AccumulateUSDXMintingRewards calculates new rewards to distribute this block and updates the global indexes to reflect this. -// The provided rewardPeriod must be valid to avoid panics in calculating time durations. -func (k Keeper) AccumulateUSDXMintingRewards(ctx sdk.Context, rewardPeriod types.RewardPeriod) { - previousAccrualTime, found := k.GetPreviousUSDXMintingAccrualTime(ctx, rewardPeriod.CollateralType) - if !found { - previousAccrualTime = ctx.BlockTime() - } - - factor, found := k.GetUSDXMintingRewardFactor(ctx, rewardPeriod.CollateralType) - if !found { - factor = sdk.ZeroDec() - } - // wrap in RewardIndexes for compatibility with Accumulator - indexes := types.RewardIndexes{}.With(types.USDXMintingRewardDenom, factor) - - acc := types.NewAccumulator(previousAccrualTime, indexes) - - totalSource := k.getUSDXTotalSourceShares(ctx, rewardPeriod.CollateralType) - - acc.Accumulate(types.NewMultiRewardPeriodFromRewardPeriod(rewardPeriod), totalSource, ctx.BlockTime()) - - k.SetPreviousUSDXMintingAccrualTime(ctx, rewardPeriod.CollateralType, acc.PreviousAccumulationTime) - - factor, found = acc.Indexes.Get(types.USDXMintingRewardDenom) - if !found { - panic("could not find factor that should never be missing when accumulating usdx rewards") - } - k.SetUSDXMintingRewardFactor(ctx, rewardPeriod.CollateralType, factor) -} - -// getUSDXTotalSourceShares fetches the sum of all source shares for a usdx minting reward. -// In the case of usdx minting, this is the total debt from all cdps of a particular type, divided by the cdp interest factor. -// This gives the "pre interest" value of the total debt. -func (k Keeper) getUSDXTotalSourceShares(ctx sdk.Context, collateralType string) sdk.Dec { - totalPrincipal := k.cdpKeeper.GetTotalPrincipal(ctx, collateralType, cdptypes.DefaultStableDenom) - - cdpFactor, found := k.cdpKeeper.GetInterestFactor(ctx, collateralType) - if !found { - // assume nothing has been borrowed so the factor starts at it's default value - cdpFactor = sdk.OneDec() - } - // return debt/factor to get the "pre interest" value of the current total debt - return sdk.NewDecFromInt(totalPrincipal).Quo(cdpFactor) -} - -// InitializeUSDXMintingClaim creates or updates a claim such that no new rewards are accrued, but any existing rewards are not lost. -// this function should be called after a cdp is created. If a user previously had a cdp, then closed it, they shouldn't -// accrue rewards during the period the cdp was closed. By setting the reward factor to the current global reward factor, -// any unclaimed rewards are preserved, but no new rewards are added. -func (k Keeper) InitializeUSDXMintingClaim(ctx sdk.Context, cdp cdptypes.CDP) { - claim, found := k.GetUSDXMintingClaim(ctx, cdp.Owner) - if !found { // this is the owner's first usdx minting reward claim - claim = types.NewUSDXMintingClaim(cdp.Owner, sdk.NewCoin(types.USDXMintingRewardDenom, sdk.ZeroInt()), types.RewardIndexes{}) - } - - globalRewardFactor, found := k.GetUSDXMintingRewardFactor(ctx, cdp.Type) - if !found { - globalRewardFactor = sdk.ZeroDec() - } - claim.RewardIndexes = claim.RewardIndexes.With(cdp.Type, globalRewardFactor) - - k.SetUSDXMintingClaim(ctx, claim) -} - -// SynchronizeUSDXMintingReward updates the claim object by adding any accumulated rewards and updating the reward index value. -// this should be called before a cdp is modified. -func (k Keeper) SynchronizeUSDXMintingReward(ctx sdk.Context, cdp cdptypes.CDP) { - claim, found := k.GetUSDXMintingClaim(ctx, cdp.Owner) - if !found { - return - } - - sourceShares, err := cdp.GetNormalizedPrincipal() - if err != nil { - panic(fmt.Sprintf("during usdx reward sync, could not get normalized principal for %s: %s", cdp.Owner, err.Error())) - } - - claim = k.synchronizeSingleUSDXMintingReward(ctx, claim, cdp.Type, sourceShares) - - k.SetUSDXMintingClaim(ctx, claim) -} - -// synchronizeSingleUSDXMintingReward synchronizes a single rewarded cdp collateral type in a usdx minting claim. -// It returns the claim without setting in the store. -// The public methods for accessing and modifying claims are preferred over this one. Direct modification of claims is easy to get wrong. -func (k Keeper) synchronizeSingleUSDXMintingReward(ctx sdk.Context, claim types.USDXMintingClaim, ctype string, sourceShares sdk.Dec) types.USDXMintingClaim { - globalRewardFactor, found := k.GetUSDXMintingRewardFactor(ctx, ctype) - if !found { - // The global factor is only not found if - // - the cdp collateral type has not started accumulating rewards yet (either there is no reward specified in params, or the reward start time hasn't been hit) - // - OR it was wrongly deleted from state (factors should never be removed while unsynced claims exist) - // If not found we could either skip this sync, or assume the global factor is zero. - // Skipping will avoid storing unnecessary factors in the claim for non rewarded denoms. - // And in the event a global factor is wrongly deleted, it will avoid this function panicking when calculating rewards. - return claim - } - - userRewardFactor, found := claim.RewardIndexes.Get(ctype) - if !found { - // Normally the factor should always be found, as it is added when the cdp is created in InitializeUSDXMintingClaim. - // However if a cdp type is not rewarded then becomes rewarded (ie a reward period is added to params), existing cdps will not have the factor in their claims. - // So assume the factor is the starting value for any global factor: 0. - userRewardFactor = sdk.ZeroDec() - } - - newRewardsAmount, err := k.CalculateSingleReward(userRewardFactor, globalRewardFactor, sourceShares) - if err != nil { - // Global reward factors should never decrease, as it would lead to a negative update to claim.Rewards. - // This panics if a global reward factor decreases or disappears between the old and new indexes. - panic(fmt.Sprintf("corrupted global reward indexes found: %v", err)) - } - newRewardsCoin := sdk.NewCoin(types.USDXMintingRewardDenom, newRewardsAmount) - - claim.Reward = claim.Reward.Add(newRewardsCoin) - claim.RewardIndexes = claim.RewardIndexes.With(ctype, globalRewardFactor) - - return claim -} - -// SimulateUSDXMintingSynchronization calculates a user's outstanding USDX minting rewards by simulating reward synchronization -func (k Keeper) SimulateUSDXMintingSynchronization(ctx sdk.Context, claim types.USDXMintingClaim) types.USDXMintingClaim { - for _, ri := range claim.RewardIndexes { - _, found := k.GetUSDXMintingRewardPeriod(ctx, ri.CollateralType) - if !found { - continue - } - - globalRewardFactor, found := k.GetUSDXMintingRewardFactor(ctx, ri.CollateralType) - if !found { - globalRewardFactor = sdk.ZeroDec() - } - - // the owner has an existing usdx minting reward claim - index, hasRewardIndex := claim.HasRewardIndex(ri.CollateralType) - if !hasRewardIndex { // this is the owner's first usdx minting reward for this collateral type - claim.RewardIndexes = append(claim.RewardIndexes, types.NewRewardIndex(ri.CollateralType, globalRewardFactor)) - } - userRewardFactor := claim.RewardIndexes[index].RewardFactor - rewardsAccumulatedFactor := globalRewardFactor.Sub(userRewardFactor) - if rewardsAccumulatedFactor.IsZero() { - continue - } - - claim.RewardIndexes[index].RewardFactor = globalRewardFactor - - cdp, found := k.cdpKeeper.GetCdpByOwnerAndCollateralType(ctx, claim.GetOwner(), ri.CollateralType) - if !found { - continue - } - newRewardsAmount := rewardsAccumulatedFactor.Mul(sdk.NewDecFromInt(cdp.GetTotalPrincipal().Amount)).RoundInt() - if newRewardsAmount.IsZero() { - continue - } - newRewardsCoin := sdk.NewCoin(types.USDXMintingRewardDenom, newRewardsAmount) - claim.Reward = claim.Reward.Add(newRewardsCoin) - } - - return claim -} - -// SynchronizeUSDXMintingClaim updates the claim object by adding any rewards that have accumulated. -// Returns the updated claim object -func (k Keeper) SynchronizeUSDXMintingClaim(ctx sdk.Context, claim types.USDXMintingClaim) (types.USDXMintingClaim, error) { - for _, ri := range claim.RewardIndexes { - cdp, found := k.cdpKeeper.GetCdpByOwnerAndCollateralType(ctx, claim.Owner, ri.CollateralType) - if !found { - // if the cdp for this collateral type has been closed, no updates are needed - continue - } - claim = k.synchronizeRewardAndReturnClaim(ctx, cdp) - } - return claim, nil -} - -// this function assumes a claim already exists, so don't call it if that's not the case -func (k Keeper) synchronizeRewardAndReturnClaim(ctx sdk.Context, cdp cdptypes.CDP) types.USDXMintingClaim { - k.SynchronizeUSDXMintingReward(ctx, cdp) - claim, _ := k.GetUSDXMintingClaim(ctx, cdp.Owner) - return claim -} - -// ZeroUSDXMintingClaim zeroes out the claim object's rewards and returns the updated claim object -func (k Keeper) ZeroUSDXMintingClaim(ctx sdk.Context, claim types.USDXMintingClaim) types.USDXMintingClaim { - claim.Reward = sdk.NewCoin(claim.Reward.Denom, sdk.ZeroInt()) - k.SetUSDXMintingClaim(ctx, claim) - return claim -} diff --git a/x/incentive/keeper/rewards_usdx_accum_test.go b/x/incentive/keeper/rewards_usdx_accum_test.go deleted file mode 100644 index 4b7283a6..00000000 --- a/x/incentive/keeper/rewards_usdx_accum_test.go +++ /dev/null @@ -1,234 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/incentive/types" -) - -type AccumulateUSDXRewardsTests struct { - usdxRewardsUnitTester -} - -func (suite *AccumulateUSDXRewardsTests) storedTimeEquals(cType string, expected time.Time) { - storedTime, found := suite.keeper.GetPreviousUSDXMintingAccrualTime(suite.ctx, cType) - suite.True(found) - suite.Equal(expected, storedTime) -} - -func (suite *AccumulateUSDXRewardsTests) storedIndexesEqual(cType string, expected sdk.Dec) { - storedIndexes, found := suite.keeper.GetUSDXMintingRewardFactor(suite.ctx, cType) - suite.True(found) - suite.Equal(expected, storedIndexes) -} - -func TestAccumulateUSDXRewards(t *testing.T) { - suite.Run(t, new(AccumulateUSDXRewardsTests)) -} - -func (suite *AccumulateUSDXRewardsTests) TestStateUpdatedWhenBlockTimeHasIncreased() { - cType := "bnb-a" - - cdpKeeper := newFakeCDPKeeper().addTotalPrincipal(i(1e6)).addInterestFactor(d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, cdpKeeper, nil, nil, nil, nil, nil, nil, nil) - - suite.storeGlobalUSDXIndexes(types.RewardIndexes{ - { - CollateralType: cType, - RewardFactor: d("0.04"), - }, - }) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousUSDXMintingAccrualTime(suite.ctx, cType, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - period := types.NewRewardPeriod( - true, - cType, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - c("ukava", 1000), - ) - - suite.keeper.AccumulateUSDXMintingRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(cType, newAccrualTime) - suite.storedIndexesEqual(cType, d("3.64")) -} - -func (suite *AccumulateUSDXRewardsTests) TestStateUnchangedWhenBlockTimeHasNotIncreased() { - cType := "bnb-a" - - cdpKeeper := newFakeCDPKeeper().addTotalPrincipal(i(1e6)).addInterestFactor(d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, cdpKeeper, nil, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.RewardIndexes{ - { - CollateralType: cType, - RewardFactor: d("0.04"), - }, - } - suite.storeGlobalUSDXIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousUSDXMintingAccrualTime(suite.ctx, cType, previousAccrualTime) - - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - period := types.NewRewardPeriod( - true, - cType, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - c("ukava", 2000), - ) - - suite.keeper.AccumulateUSDXMintingRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(cType, previousAccrualTime) - expected, f := previousIndexes.Get(cType) - suite.True(f) - suite.storedIndexesEqual(cType, expected) -} - -func (suite *AccumulateUSDXRewardsTests) TestNoAccumulationWhenSourceSharesAreZero() { - cType := "bnb-a" - - cdpKeeper := newFakeCDPKeeper() // zero total borrows - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, cdpKeeper, nil, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.RewardIndexes{ - { - CollateralType: cType, - RewardFactor: d("0.04"), - }, - } - suite.storeGlobalUSDXIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousUSDXMintingAccrualTime(suite.ctx, cType, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(7 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - period := types.NewRewardPeriod( - true, - cType, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - c("ukava", 1000), - ) - - suite.keeper.AccumulateUSDXMintingRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(cType, firstAccrualTime) - expected, f := previousIndexes.Get(cType) - suite.True(f) - suite.storedIndexesEqual(cType, expected) -} - -func (suite *AccumulateUSDXRewardsTests) TestStateAddedWhenStateDoesNotExist() { - cType := "bnb-a" - - cdpKeeper := newFakeCDPKeeper().addTotalPrincipal(i(1e6)).addInterestFactor(d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, cdpKeeper, nil, nil, nil, nil, nil, nil, nil) - - period := types.NewRewardPeriod( - true, - cType, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - c("ukava", 1000), - ) - - firstAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateUSDXMintingRewards(suite.ctx, period) - - // After the first accumulation the current block time should be stored and the factor will be zero. - suite.storedTimeEquals(cType, firstAccrualTime) - suite.storedIndexesEqual(cType, sdk.ZeroDec()) - - secondAccrualTime := firstAccrualTime.Add(10 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(secondAccrualTime) - - suite.keeper.AccumulateUSDXMintingRewards(suite.ctx, period) - - // After the second accumulation both current block time and indexes should be stored. - suite.storedTimeEquals(cType, secondAccrualTime) - suite.storedIndexesEqual(cType, d("0.01")) -} - -func (suite *AccumulateUSDXRewardsTests) TestNoAccumulationWhenBeforeStartTime() { - cType := "bnb-a" - - cdpKeeper := newFakeCDPKeeper().addTotalPrincipal(i(1e6)).addInterestFactor(d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, cdpKeeper, nil, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.RewardIndexes{ - { - CollateralType: cType, - RewardFactor: d("0.04"), - }, - } - suite.storeGlobalUSDXIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousUSDXMintingAccrualTime(suite.ctx, cType, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(10 * time.Second) - - period := types.NewRewardPeriod( - true, - cType, - firstAccrualTime.Add(time.Nanosecond), // start time after accrual time - distantFuture, - c("ukava", 1000), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateUSDXMintingRewards(suite.ctx, period) - - // The accrual time should be updated, but the indexes unchanged - suite.storedTimeEquals(cType, firstAccrualTime) - expected, f := previousIndexes.Get(cType) - suite.True(f) - suite.storedIndexesEqual(cType, expected) -} - -func (suite *AccumulateUSDXRewardsTests) TestPanicWhenCurrentTimeLessThanPrevious() { - cType := "bnb-a" - - cdpKeeper := newFakeCDPKeeper().addTotalPrincipal(i(1e6)).addInterestFactor(d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, cdpKeeper, nil, nil, nil, nil, nil, nil, nil) - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousUSDXMintingAccrualTime(suite.ctx, cType, previousAccrualTime) - - firstAccrualTime := time.Time{} - - period := types.NewRewardPeriod( - true, - cType, - time.Time{}, // start time after accrual time - distantFuture, - c("ukava", 1000), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.Panics(func() { - suite.keeper.AccumulateUSDXMintingRewards(suite.ctx, period) - }) -} diff --git a/x/incentive/keeper/rewards_usdx_test.go b/x/incentive/keeper/rewards_usdx_test.go deleted file mode 100644 index eb45570e..00000000 --- a/x/incentive/keeper/rewards_usdx_test.go +++ /dev/null @@ -1,510 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - proposaltypes "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - cdpkeeper "github.com/kava-labs/kava/x/cdp/keeper" - cdptypes "github.com/kava-labs/kava/x/cdp/types" - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/testutil" - "github.com/kava-labs/kava/x/incentive/types" - kavadisttypes "github.com/kava-labs/kava/x/kavadist/types" -) - -type USDXIntegrationTests struct { - testutil.IntegrationTester - - genesisTime time.Time - addrs []sdk.AccAddress -} - -func TestUSDXIntegration(t *testing.T) { - suite.Run(t, new(USDXIntegrationTests)) -} - -// SetupTest is run automatically before each suite test -func (suite *USDXIntegrationTests) SetupTest() { - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *USDXIntegrationTests) ProposeAndVoteOnNewRewardPeriods(committeeID uint64, voter sdk.AccAddress, newPeriods types.RewardPeriods) { - suite.ProposeAndVoteOnNewParams( - voter, - committeeID, - []proposaltypes.ParamChange{{ - Subspace: types.ModuleName, - Key: string(types.KeyUSDXMintingRewardPeriods), - Value: string(types.ModuleCdc.LegacyAmino.MustMarshalJSON(newPeriods)), - }}) -} - -func (suite *USDXIntegrationTests) TestSingleUserAccumulatesRewardsAfterSyncing() { - userA := suite.addrs[0] - - authBulder := app.NewAuthBankGenesisBuilder(). - WithSimpleModuleAccount(kavadisttypes.ModuleName, cs(c(types.USDXMintingRewardDenom, 1e18))). // Fill kavadist with enough coins to pay out any reward - WithSimpleAccount(userA, cs(c("bnb", 1e12))) // give the user some coins - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithMultipliers(types.MultipliersPerDenoms{{ - Denom: types.USDXMintingRewardDenom, - Multipliers: types.Multipliers{types.NewMultiplier("large", 12, d("1.0"))}, // keep payout at 1.0 to make maths easier - }}). - WithSimpleUSDXRewardPeriod("bnb-a", c(types.USDXMintingRewardDenom, 1e6)) - - suite.SetApp() - suite.WithGenesisTime(suite.genesisTime) - suite.StartChain( - NewPricefeedGenStateMultiFromTime(suite.App.AppCodec(), suite.genesisTime), - NewCDPGenStateMulti(suite.App.AppCodec()), - authBulder.BuildMarshalled(suite.App.AppCodec()), - incentBuilder.BuildMarshalled(suite.App.AppCodec()), - ) - - // User creates a CDP to begin earning rewards. - suite.NoError( - suite.DeliverMsgCreateCDP(userA, c("bnb", 1e10), c(cdptypes.DefaultStableDenom, 1e9), "bnb-a"), - ) - - // Let time pass to accumulate interest on the deposit - // Use one long block instead of many to reduce any rounding errors, and speed up tests. - suite.NextBlockAfter(1e6 * time.Second) // about 12 days - - // User repays and borrows just to sync their CDP - suite.NoError( - suite.DeliverCDPMsgRepay(userA, "bnb-a", c(cdptypes.DefaultStableDenom, 1)), - ) - suite.NoError( - suite.DeliverCDPMsgBorrow(userA, "bnb-a", c(cdptypes.DefaultStableDenom, 1)), - ) - - // Accumulate more rewards. - // The user still has the same percentage of all CDP debt (100%) so their rewards should be the same as in the previous block. - suite.NextBlockAfter(1e6 * time.Second) // about 12 days - - // User claims all their rewards - msg := types.NewMsgClaimUSDXMintingReward(userA.String(), "large") - suite.Require().NoError(suite.DeliverIncentiveMsg(&msg)) - - // The users has always had 100% of cdp debt, so they should receive all rewards for the previous two blocks. - // Total rewards for each block is block duration * rewards per second - accuracy := 1e-18 // using a very high accuracy to flag future small calculation changes - suite.BalanceInEpsilon(userA, cs(c("bnb", 1e12-1e10), c(cdptypes.DefaultStableDenom, 1e9), c(types.USDXMintingRewardDenom, 2*1e6*1e6)), accuracy) -} - -func (suite *USDXIntegrationTests) TestSingleUserAccumulatesRewardsWithoutSyncing() { - user := suite.addrs[0] - initialCollateral := c("bnb", 1e9) - - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleModuleAccount(kavadisttypes.ModuleName, cs(c(types.USDXMintingRewardDenom, 1e18))). // Fill kavadist with enough coins to pay out any reward - WithSimpleAccount(user, cs(initialCollateral)) - - collateralType := "bnb-a" - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithMultipliers(types.MultipliersPerDenoms{{ - Denom: types.USDXMintingRewardDenom, - Multipliers: types.Multipliers{types.NewMultiplier("large", 12, d("1.0"))}, // keep payout at 1.0 to make maths easier - }}). - WithSimpleUSDXRewardPeriod(collateralType, c(types.USDXMintingRewardDenom, 1e6)) - - suite.SetApp() - suite.WithGenesisTime(suite.genesisTime) - suite.StartChain( - authBuilder.BuildMarshalled(suite.App.AppCodec()), - NewPricefeedGenStateMultiFromTime(suite.App.AppCodec(), suite.genesisTime), - NewCDPGenStateMulti(suite.App.AppCodec()), - incentBuilder.BuildMarshalled(suite.App.AppCodec()), - ) - - // Setup cdp state containing one CDP - suite.NoError( - suite.DeliverMsgCreateCDP(user, initialCollateral, c("usdx", 1e8), collateralType), - ) - - // Skip ahead a few blocks blocks to accumulate both interest and usdx reward for the cdp - // Don't sync the CDP between the blocks - suite.NextBlockAfter(1e6 * time.Second) // about 12 days - suite.NextBlockAfter(1e6 * time.Second) - suite.NextBlockAfter(1e6 * time.Second) - - msg := types.NewMsgClaimUSDXMintingReward(user.String(), "large") - suite.Require().NoError(suite.DeliverIncentiveMsg(&msg)) - - // The users has always had 100% of cdp debt, so they should receive all rewards for the previous two blocks. - // Total rewards for each block is block duration * rewards per second - accuracy := 1e-18 // using a very high accuracy to flag future small calculation changes - suite.BalanceInEpsilon(user, cs(c(cdptypes.DefaultStableDenom, 1e8), c(types.USDXMintingRewardDenom, 3*1e6*1e6)), accuracy) -} - -func (suite *USDXIntegrationTests) TestReinstatingRewardParamsDoesNotTriggerOverPayments() { - userA := suite.addrs[0] - userB := suite.addrs[1] - - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleModuleAccount(kavadisttypes.ModuleName, cs(c(types.USDXMintingRewardDenom, 1e18))). // Fill kavadist with enough coins to pay out any reward - WithSimpleAccount(userA, cs(c("bnb", 1e10))). - WithSimpleAccount(userB, cs(c("bnb", 1e10))) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithMultipliers(types.MultipliersPerDenoms{{ - Denom: types.USDXMintingRewardDenom, - Multipliers: types.Multipliers{types.NewMultiplier("large", 12, d("1.0"))}, // keep payout at 1.0 to make maths easier - }}). - WithSimpleUSDXRewardPeriod("bnb-a", c(types.USDXMintingRewardDenom, 1e6)) - - suite.SetApp() - suite.WithGenesisTime(suite.genesisTime) - suite.StartChain( - authBuilder.BuildMarshalled(suite.App.AppCodec()), - NewPricefeedGenStateMultiFromTime(suite.App.AppCodec(), suite.genesisTime), - NewCDPGenStateMulti(suite.App.AppCodec()), - incentBuilder.BuildMarshalled(suite.App.AppCodec()), - NewCommitteeGenesisState(suite.App.AppCodec(), 0, userA), // create a committtee to change params - ) - - // Accumulate some CDP rewards, requires creating a cdp so the total borrowed isn't 0. - suite.NoError( - suite.DeliverMsgCreateCDP(userA, c("bnb", 1e10), c("usdx", 1e9), "bnb-a"), - ) - suite.NextBlockAfter(1e6 * time.Second) - - // Remove the USDX reward period - suite.ProposeAndVoteOnNewRewardPeriods(0, userA, types.RewardPeriods{}) - // next block so proposal is enacted - suite.NextBlockAfter(1 * time.Second) - - // Create a CDP when there is no reward periods. In a previous version the claim object would not be created, leading to the bug. - // Withdraw the same amount of usdx as the first cdp currently has. This make the reward maths easier, as rewards will be split 50:50 between each cdp. - firstCDP, f := suite.App.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.Ctx, userA, "bnb-a") - suite.True(f) - firstCDPTotalPrincipal := firstCDP.GetTotalPrincipal() - suite.NoError( - suite.DeliverMsgCreateCDP(userB, c("bnb", 1e10), firstCDPTotalPrincipal, "bnb-a"), - ) - - // Add back the reward period - suite.ProposeAndVoteOnNewRewardPeriods(0, userA, - types.RewardPeriods{types.NewRewardPeriod( - true, - "bnb-a", - suite.Ctx.BlockTime(), // start accumulating again from this block - suite.genesisTime.Add(365*24*time.Hour), - c(types.USDXMintingRewardDenom, 1e6), - )}, - ) - // next block so proposal is enacted - suite.NextBlockAfter(1 * time.Second) - - // Sync the cdp and claim by borrowing a bit - // In a previous version this would create the cdp with incorrect indexes, leading to overpayment. - suite.NoError( - suite.DeliverCDPMsgBorrow(userB, "bnb-a", c(cdptypes.DefaultStableDenom, 1)), - ) - - // Claim rewards - msg := types.NewMsgClaimUSDXMintingReward(userB.String(), "large") - suite.Require().NoError(suite.DeliverIncentiveMsg(&msg)) - - // The cdp had half the total borrows for a 1s block. So should earn half the rewards for that block - suite.BalanceInEpsilon( - userB, - cs(firstCDPTotalPrincipal.Add(c(cdptypes.DefaultStableDenom, 1)), c(types.USDXMintingRewardDenom, 0.5*1e6)), - 1e-18, // using very high accuracy to catch small changes to the calculations - ) -} - -// Test suite used for all keeper tests -type USDXRewardsTestSuite struct { - suite.Suite - - keeper keeper.Keeper - cdpKeeper cdpkeeper.Keeper - - app app.TestApp - ctx sdk.Context - - genesisTime time.Time - addrs []sdk.AccAddress -} - -// SetupTest is run automatically before each suite test -func (suite *USDXRewardsTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *USDXRewardsTestSuite) SetupApp() { - suite.app = app.NewTestApp() - - suite.keeper = suite.app.GetIncentiveKeeper() - suite.cdpKeeper = suite.app.GetCDPKeeper() - - suite.ctx = suite.app.NewContext(true, tmproto.Header{Height: 1, Time: suite.genesisTime}) -} - -func (suite *USDXRewardsTestSuite) SetupWithGenState(authBuilder *app.AuthBankGenesisBuilder, incentBuilder testutil.IncentiveGenesisBuilder) { - suite.SetupApp() - - suite.app.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - authBuilder.BuildMarshalled(suite.app.AppCodec()), - NewPricefeedGenStateMultiFromTime(suite.app.AppCodec(), suite.genesisTime), - NewCDPGenStateMulti(suite.app.AppCodec()), - incentBuilder.BuildMarshalled(suite.app.AppCodec()), - ) -} - -func (suite *USDXRewardsTestSuite) TestAccumulateUSDXMintingRewards() { - type args struct { - ctype string - rewardsPerSecond sdk.Coin - initialTotalPrincipal sdk.Coin - timeElapsed int - expectedRewardFactor sdk.Dec - } - type test struct { - name string - args args - } - testCases := []test{ - { - "7 seconds", - args{ - ctype: "bnb-a", - rewardsPerSecond: c("ukava", 122354), - initialTotalPrincipal: c("usdx", 1000000000000), - timeElapsed: 7, - expectedRewardFactor: d("0.000000856478000000"), - }, - }, - { - "1 day", - args{ - ctype: "bnb-a", - rewardsPerSecond: c("ukava", 122354), - initialTotalPrincipal: c("usdx", 1000000000000), - timeElapsed: 86400, - expectedRewardFactor: d("0.0105713856"), - }, - }, - { - "0 seconds", - args{ - ctype: "bnb-a", - rewardsPerSecond: c("ukava", 122354), - initialTotalPrincipal: c("usdx", 1000000000000), - timeElapsed: 0, - expectedRewardFactor: d("0.0"), - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - incentBuilder := testutil.NewIncentiveGenesisBuilder().WithGenesisTime(suite.genesisTime).WithSimpleUSDXRewardPeriod(tc.args.ctype, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(app.NewAuthBankGenesisBuilder(), incentBuilder) - - // setup cdp state - suite.cdpKeeper.SetTotalPrincipal(suite.ctx, tc.args.ctype, cdptypes.DefaultStableDenom, tc.args.initialTotalPrincipal.Amount) - - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - rewardPeriod, found := suite.keeper.GetUSDXMintingRewardPeriod(suite.ctx, tc.args.ctype) - suite.Require().True(found) - suite.keeper.AccumulateUSDXMintingRewards(suite.ctx, rewardPeriod) - - rewardFactor, _ := suite.keeper.GetUSDXMintingRewardFactor(suite.ctx, tc.args.ctype) - suite.Require().Equal(tc.args.expectedRewardFactor, rewardFactor) - }) - } -} - -func (suite *USDXRewardsTestSuite) TestSynchronizeUSDXMintingReward() { - type args struct { - ctype string - rewardsPerSecond sdk.Coin - initialCollateral sdk.Coin - initialPrincipal sdk.Coin - blockTimes []int - expectedRewardFactor sdk.Dec - expectedRewards sdk.Coin - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "10 blocks", - args{ - ctype: "bnb-a", - rewardsPerSecond: c("ukava", 122354), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 10000000000), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardFactor: d("0.001223540000000000"), - expectedRewards: c("ukava", 12235400), - }, - }, - { - "10 blocks - long block time", - args{ - ctype: "bnb-a", - rewardsPerSecond: c("ukava", 122354), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 10000000000), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardFactor: d("10.57138560000000000"), - expectedRewards: c("ukava", 105713856000), - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount(suite.addrs[0], cs(tc.args.initialCollateral)) - incentBuilder := testutil.NewIncentiveGenesisBuilder().WithGenesisTime(suite.genesisTime).WithSimpleUSDXRewardPeriod(tc.args.ctype, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - // setup cdp state - err := suite.cdpKeeper.AddCdp(suite.ctx, suite.addrs[0], tc.args.initialCollateral, tc.args.initialPrincipal, tc.args.ctype) - suite.Require().NoError(err) - - claim, found := suite.keeper.GetUSDXMintingClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().Equal(sdk.ZeroDec(), claim.RewardIndexes[0].RewardFactor) - - var timeElapsed int - previousBlockTime := suite.ctx.BlockTime() - for _, t := range tc.args.blockTimes { - timeElapsed += t - updatedBlockTime := previousBlockTime.Add(time.Duration(int(time.Second) * t)) - previousBlockTime = updatedBlockTime - blockCtx := suite.ctx.WithBlockTime(updatedBlockTime) - rewardPeriod, found := suite.keeper.GetUSDXMintingRewardPeriod(blockCtx, tc.args.ctype) - suite.Require().True(found) - suite.keeper.AccumulateUSDXMintingRewards(blockCtx, rewardPeriod) - } - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - cdp, found := suite.cdpKeeper.GetCdpByOwnerAndCollateralType(suite.ctx, suite.addrs[0], tc.args.ctype) - suite.Require().True(found) - suite.Require().NotPanics(func() { - suite.keeper.SynchronizeUSDXMintingReward(suite.ctx, cdp) - }) - - rewardFactor, _ := suite.keeper.GetUSDXMintingRewardFactor(suite.ctx, tc.args.ctype) - suite.Require().Equal(tc.args.expectedRewardFactor, rewardFactor) - - claim, found = suite.keeper.GetUSDXMintingClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().Equal(tc.args.expectedRewardFactor, claim.RewardIndexes[0].RewardFactor) - suite.Require().Equal(tc.args.expectedRewards, claim.Reward) - }) - } -} - -func (suite *USDXRewardsTestSuite) TestSimulateUSDXMintingRewardSynchronization() { - type args struct { - ctype string - rewardsPerSecond sdk.Coin - initialCollateral sdk.Coin - initialPrincipal sdk.Coin - blockTimes []int - expectedRewardFactor sdk.Dec - expectedRewards sdk.Coin - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "10 blocks", - args{ - ctype: "bnb-a", - rewardsPerSecond: c("ukava", 122354), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 10000000000), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardFactor: d("0.001223540000000000"), - expectedRewards: c("ukava", 12235400), - }, - }, - { - "10 blocks - long block time", - args{ - ctype: "bnb-a", - rewardsPerSecond: c("ukava", 122354), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 10000000000), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardFactor: d("10.57138560000000000"), - expectedRewards: c("ukava", 105713856000), - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount(suite.addrs[0], cs(tc.args.initialCollateral)) - incentBuilder := testutil.NewIncentiveGenesisBuilder().WithGenesisTime(suite.genesisTime).WithSimpleUSDXRewardPeriod(tc.args.ctype, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - // setup cdp state - err := suite.cdpKeeper.AddCdp(suite.ctx, suite.addrs[0], tc.args.initialCollateral, tc.args.initialPrincipal, tc.args.ctype) - suite.Require().NoError(err) - - claim, found := suite.keeper.GetUSDXMintingClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().Equal(sdk.ZeroDec(), claim.RewardIndexes[0].RewardFactor) - - var timeElapsed int - previousBlockTime := suite.ctx.BlockTime() - for _, t := range tc.args.blockTimes { - timeElapsed += t - updatedBlockTime := previousBlockTime.Add(time.Duration(int(time.Second) * t)) - previousBlockTime = updatedBlockTime - blockCtx := suite.ctx.WithBlockTime(updatedBlockTime) - rewardPeriod, found := suite.keeper.GetUSDXMintingRewardPeriod(blockCtx, tc.args.ctype) - suite.Require().True(found) - suite.keeper.AccumulateUSDXMintingRewards(blockCtx, rewardPeriod) - } - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - - claim, found = suite.keeper.GetUSDXMintingClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().Equal(claim.RewardIndexes[0].RewardFactor, sdk.ZeroDec()) - suite.Require().Equal(claim.Reward, sdk.NewCoin("ukava", sdk.ZeroInt())) - - updatedClaim := suite.keeper.SimulateUSDXMintingSynchronization(suite.ctx, claim) - suite.Require().Equal(tc.args.expectedRewardFactor, updatedClaim.RewardIndexes[0].RewardFactor) - suite.Require().Equal(tc.args.expectedRewards, updatedClaim.Reward) - }) - } -} - -func TestUSDXRewardsTestSuite(t *testing.T) { - suite.Run(t, new(USDXRewardsTestSuite)) -} diff --git a/x/incentive/keeper/rewards_usdx_unit_test.go b/x/incentive/keeper/rewards_usdx_unit_test.go deleted file mode 100644 index 61240e85..00000000 --- a/x/incentive/keeper/rewards_usdx_unit_test.go +++ /dev/null @@ -1,302 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - cdptypes "github.com/kava-labs/kava/x/cdp/types" - "github.com/kava-labs/kava/x/incentive/types" -) - -// usdxRewardsUnitTester contains common methods for running unit tests for keeper methods related to the USDX minting rewards -type usdxRewardsUnitTester struct { - unitTester -} - -func (suite *usdxRewardsUnitTester) storeGlobalUSDXIndexes(indexes types.RewardIndexes) { - for _, ri := range indexes { - suite.keeper.SetUSDXMintingRewardFactor(suite.ctx, ri.CollateralType, ri.RewardFactor) - } -} - -func (suite *usdxRewardsUnitTester) storeClaim(claim types.USDXMintingClaim) { - suite.keeper.SetUSDXMintingClaim(suite.ctx, claim) -} - -type InitializeUSDXMintingClaimTests struct { - usdxRewardsUnitTester -} - -func TestInitializeUSDXMintingClaims(t *testing.T) { - suite.Run(t, new(InitializeUSDXMintingClaimTests)) -} - -func (suite *InitializeUSDXMintingClaimTests) TestClaimIndexIsSetWhenClaimDoesNotExist() { - collateralType := "bnb-a" - - cdp := NewCDPBuilder(arbitraryAddress(), collateralType).Build() - - globalIndexes := types.RewardIndexes{{ - CollateralType: collateralType, - RewardFactor: d("0.2"), - }} - suite.storeGlobalUSDXIndexes(globalIndexes) - - suite.keeper.InitializeUSDXMintingClaim(suite.ctx, cdp) - - syncedClaim, f := suite.keeper.GetUSDXMintingClaim(suite.ctx, cdp.Owner) - suite.True(f) - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) -} - -func (suite *InitializeUSDXMintingClaimTests) TestClaimIndexIsSetWhenClaimExists() { - collateralType := "bnb-a" - - claim := types.USDXMintingClaim{ - BaseClaim: types.BaseClaim{ - Owner: arbitraryAddress(), - }, - RewardIndexes: types.RewardIndexes{{ - CollateralType: collateralType, - RewardFactor: d("0.1"), - }}, - } - suite.storeClaim(claim) - - globalIndexes := types.RewardIndexes{{ - CollateralType: collateralType, - RewardFactor: d("0.2"), - }} - suite.storeGlobalUSDXIndexes(globalIndexes) - - cdp := NewCDPBuilder(claim.Owner, collateralType).Build() - - suite.keeper.InitializeUSDXMintingClaim(suite.ctx, cdp) - - syncedClaim, _ := suite.keeper.GetUSDXMintingClaim(suite.ctx, cdp.Owner) - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) -} - -type SynchronizeUSDXMintingRewardTests struct { - usdxRewardsUnitTester -} - -func TestSynchronizeUSDXMintingReward(t *testing.T) { - suite.Run(t, new(SynchronizeUSDXMintingRewardTests)) -} - -func (suite *SynchronizeUSDXMintingRewardTests) TestRewardUnchangedWhenGlobalIndexesUnchanged() { - unchangingRewardIndexes := nonEmptyRewardIndexes - collateralType := extractFirstCollateralType(unchangingRewardIndexes) - - claim := types.USDXMintingClaim{ - BaseClaim: types.BaseClaim{ - Owner: arbitraryAddress(), - Reward: c(types.USDXMintingRewardDenom, 0), - }, - RewardIndexes: unchangingRewardIndexes, - } - suite.storeClaim(claim) - - suite.storeGlobalUSDXIndexes(unchangingRewardIndexes) - - cdp := NewCDPBuilder(claim.Owner, collateralType).WithSourceShares(1e12).Build() - - suite.keeper.SynchronizeUSDXMintingReward(suite.ctx, cdp) - - syncedClaim, _ := suite.keeper.GetUSDXMintingClaim(suite.ctx, claim.Owner) - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *SynchronizeUSDXMintingRewardTests) TestRewardIsIncrementedWhenGlobalIndexIncreased() { - collateralType := "bnb-a" - - claim := types.USDXMintingClaim{ - BaseClaim: types.BaseClaim{ - Owner: arbitraryAddress(), - Reward: c(types.USDXMintingRewardDenom, 0), - }, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: collateralType, - RewardFactor: d("0.1"), - }, - }, - } - suite.storeClaim(claim) - - globalIndexes := types.RewardIndexes{ - { - CollateralType: collateralType, - RewardFactor: d("0.2"), - }, - } - suite.storeGlobalUSDXIndexes(globalIndexes) - - cdp := NewCDPBuilder(claim.Owner, collateralType).WithSourceShares(1e12).Build() - - suite.keeper.SynchronizeUSDXMintingReward(suite.ctx, cdp) - - syncedClaim, _ := suite.keeper.GetUSDXMintingClaim(suite.ctx, claim.Owner) - // reward is ( new index - old index ) * cdp.TotalPrincipal - suite.Equal(c(types.USDXMintingRewardDenom, 1e11), syncedClaim.Reward) -} - -func (suite *SynchronizeUSDXMintingRewardTests) TestClaimIndexIsUpdatedWhenGlobalIndexIncreased() { - claimsRewardIndexes := nonEmptyRewardIndexes - collateralType := extractFirstCollateralType(claimsRewardIndexes) - - claim := types.USDXMintingClaim{ - BaseClaim: types.BaseClaim{ - Owner: arbitraryAddress(), - Reward: c(types.USDXMintingRewardDenom, 0), - }, - RewardIndexes: claimsRewardIndexes, - } - suite.storeClaim(claim) - - globalIndexes := increaseRewardFactors(claimsRewardIndexes) - suite.storeGlobalUSDXIndexes(globalIndexes) - - cdp := NewCDPBuilder(claim.Owner, collateralType).Build() - - suite.keeper.SynchronizeUSDXMintingReward(suite.ctx, cdp) - - syncedClaim, _ := suite.keeper.GetUSDXMintingClaim(suite.ctx, claim.Owner) - - // Only the claim's index for `collateralType` should have been changed - i, _ := globalIndexes.Get(collateralType) - expectedIndexes := claimsRewardIndexes.With(collateralType, i) - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) -} - -func (suite *SynchronizeUSDXMintingRewardTests) TestClaimIndexIsUpdatedWhenNewRewardAddedAndClaimAlreadyExists() { - claimsRewardIndexes := types.RewardIndexes{ - { - CollateralType: "bnb-a", - RewardFactor: d("0.1"), - }, - { - CollateralType: "busd-b", - RewardFactor: d("0.4"), - }, - } - newRewardIndex := types.NewRewardIndex("xrp-a", d("0.0001")) - - claim := types.USDXMintingClaim{ - BaseClaim: types.BaseClaim{ - Owner: arbitraryAddress(), - Reward: c(types.USDXMintingRewardDenom, 0), - }, - RewardIndexes: claimsRewardIndexes, - } - suite.storeClaim(claim) - - globalIndexes := increaseRewardFactors(claimsRewardIndexes) - globalIndexes = append(globalIndexes, newRewardIndex) - suite.storeGlobalUSDXIndexes(globalIndexes) - - cdp := NewCDPBuilder(claim.Owner, newRewardIndex.CollateralType).Build() - - suite.keeper.SynchronizeUSDXMintingReward(suite.ctx, cdp) - - syncedClaim, _ := suite.keeper.GetUSDXMintingClaim(suite.ctx, claim.Owner) - - // Only the claim's index for `collateralType` should have been changed - expectedIndexes := claimsRewardIndexes.With(newRewardIndex.CollateralType, newRewardIndex.RewardFactor) - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) -} - -func (suite *SynchronizeUSDXMintingRewardTests) TestClaimIsUnchangedWhenGlobalFactorMissing() { - claimsRewardIndexes := nonEmptyRewardIndexes - claim := types.USDXMintingClaim{ - BaseClaim: types.BaseClaim{ - Owner: arbitraryAddress(), - Reward: c(types.USDXMintingRewardDenom, 0), - }, - RewardIndexes: claimsRewardIndexes, - } - suite.storeClaim(claim) - // don't store any reward indexes - - // create a cdp with collateral type that doesn't exist in the claim's indexes, and does not have a corresponding global factor - cdp := NewCDPBuilder(claim.Owner, "unrewardedcollateral").WithSourceShares(1e12).Build() - - suite.keeper.SynchronizeUSDXMintingReward(suite.ctx, cdp) - - syncedClaim, _ := suite.keeper.GetUSDXMintingClaim(suite.ctx, claim.Owner) - suite.Equal(claim.RewardIndexes, syncedClaim.RewardIndexes) - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -// CDPBuilder is a tool for creating a CDP in tests. -// The builder inherits from cdp.CDP, so fields can be accessed directly if a helper method doesn't exist. -type CDPBuilder struct { - cdptypes.CDP -} - -// NewCDPBuilder creates a CdpBuilder containing a CDP with owner and collateral type set. -func NewCDPBuilder(owner sdk.AccAddress, collateralType string) CDPBuilder { - return CDPBuilder{ - CDP: cdptypes.CDP{ - Owner: owner, - Type: collateralType, - // The zero value of Principal and AccumulatedFees (type sdk.Coin) is invalid as the denom is "" - // Set them to the default denom, but with 0 amount. - Principal: c(cdptypes.DefaultStableDenom, 0), - AccumulatedFees: c(cdptypes.DefaultStableDenom, 0), - // zero value of sdk.Dec causes nil pointer panics - InterestFactor: sdk.OneDec(), - }, - } -} - -// Build assembles and returns the final deposit. -func (builder CDPBuilder) Build() cdptypes.CDP { return builder.CDP } - -// WithSourceShares adds a principal amount and interest factor such that the source shares for this CDP is equal to specified. -// With a factor of 1, the total principal is the source shares. This picks an arbitrary factor to ensure factors are accounted for in production code. -func (builder CDPBuilder) WithSourceShares(shares int64) CDPBuilder { - if !builder.GetTotalPrincipal().Amount.Equal(sdk.ZeroInt()) { - panic("setting source shares on cdp with existing principal or fees not implemented") - } - if !(builder.InterestFactor.IsNil() || builder.InterestFactor.Equal(sdk.OneDec())) { - panic("setting source shares on cdp with existing interest factor not implemented") - } - // pick arbitrary interest factor - factor := sdkmath.NewInt(2) - - // Calculate deposit amount that would equal the requested source shares given the above factor. - principal := sdkmath.NewInt(shares).Mul(factor) - - builder.Principal = sdk.NewCoin(cdptypes.DefaultStableDenom, principal) - builder.InterestFactor = sdk.NewDecFromInt(factor) - - return builder -} - -func (builder CDPBuilder) WithPrincipal(principal sdkmath.Int) CDPBuilder { - builder.Principal = sdk.NewCoin(cdptypes.DefaultStableDenom, principal) - return builder -} - -var nonEmptyRewardIndexes = types.RewardIndexes{ - { - CollateralType: "bnb-a", - RewardFactor: d("0.1"), - }, - { - CollateralType: "busd-b", - RewardFactor: d("0.4"), - }, -} - -func extractFirstCollateralType(indexes types.RewardIndexes) string { - if len(indexes) == 0 { - panic("cannot extract a collateral type from 0 length RewardIndexes") - } - return indexes[0].CollateralType -} diff --git a/x/incentive/keeper/unit_test.go b/x/incentive/keeper/unit_test.go deleted file mode 100644 index 8e459dd0..00000000 --- a/x/incentive/keeper/unit_test.go +++ /dev/null @@ -1,877 +0,0 @@ -package keeper_test - -import ( - "fmt" - "strings" - "time" - - sdkmath "cosmossdk.io/math" - db "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" - "github.com/stretchr/testify/suite" - - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/kava-labs/kava/app" - cdptypes "github.com/kava-labs/kava/x/cdp/types" - earntypes "github.com/kava-labs/kava/x/earn/types" - - hardtypes "github.com/kava-labs/kava/x/hard/types" - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/types" -) - -// NewTestContext sets up a basic context with an in-memory db -func NewTestContext(requiredStoreKeys ...storetypes.StoreKey) sdk.Context { - memDB := db.NewMemDB() - cms := store.NewCommitMultiStore(memDB) - - for _, key := range requiredStoreKeys { - cms.MountStoreWithDB(key, storetypes.StoreTypeIAVL, nil) - } - - if err := cms.LoadLatestVersion(); err != nil { - panic(err) - } - - return sdk.NewContext(cms, tmprototypes.Header{}, false, log.NewNopLogger()) -} - -// unitTester is a wrapper around suite.Suite, with common functionality for keeper unit tests. -// It can be embedded in structs the same way as suite.Suite. -type unitTester struct { - suite.Suite - keeper keeper.Keeper - ctx sdk.Context - - cdc codec.Codec - incentiveStoreKey storetypes.StoreKey -} - -func (suite *unitTester) SetupSuite() { - tApp := app.NewTestApp() - suite.cdc = tApp.AppCodec() - - suite.incentiveStoreKey = sdk.NewKVStoreKey(types.StoreKey) -} - -func (suite *unitTester) SetupTest() { - suite.ctx = NewTestContext(suite.incentiveStoreKey) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, nil) -} - -func (suite *unitTester) TearDownTest() { - suite.keeper = keeper.Keeper{} - suite.ctx = sdk.Context{} -} - -func (suite *unitTester) NewKeeper( - paramSubspace types.ParamSubspace, - bk types.BankKeeper, cdpk types.CdpKeeper, hk types.HardKeeper, - ak types.AccountKeeper, stk types.StakingKeeper, swk types.SwapKeeper, - svk types.SavingsKeeper, lqk types.LiquidKeeper, ek types.EarnKeeper, -) keeper.Keeper { - return keeper.NewKeeper( - suite.cdc, suite.incentiveStoreKey, paramSubspace, - bk, cdpk, hk, ak, stk, swk, svk, lqk, ek, - nil, nil, nil, - ) -} - -func (suite *unitTester) storeGlobalBorrowIndexes(indexes types.MultiRewardIndexes) { - for _, i := range indexes { - suite.keeper.SetHardBorrowRewardIndexes(suite.ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (suite *unitTester) storeGlobalSupplyIndexes(indexes types.MultiRewardIndexes) { - for _, i := range indexes { - suite.keeper.SetHardSupplyRewardIndexes(suite.ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (suite *unitTester) storeGlobalDelegatorIndexes(multiRewardIndexes types.MultiRewardIndexes) { - // Hardcoded to use bond denom - multiRewardIndex, _ := multiRewardIndexes.GetRewardIndex(types.BondDenom) - suite.keeper.SetDelegatorRewardIndexes(suite.ctx, types.BondDenom, multiRewardIndex.RewardIndexes) -} - -func (suite *unitTester) storeGlobalSwapIndexes(indexes types.MultiRewardIndexes) { - for _, i := range indexes { - suite.keeper.SetSwapRewardIndexes(suite.ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (suite *unitTester) storeGlobalSavingsIndexes(indexes types.MultiRewardIndexes) { - for _, i := range indexes { - suite.keeper.SetSavingsRewardIndexes(suite.ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (suite *unitTester) storeGlobalEarnIndexes(indexes types.MultiRewardIndexes) { - for _, i := range indexes { - suite.keeper.SetEarnRewardIndexes(suite.ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (suite *unitTester) storeHardClaim(claim types.HardLiquidityProviderClaim) { - suite.keeper.SetHardLiquidityProviderClaim(suite.ctx, claim) -} - -func (suite *unitTester) storeDelegatorClaim(claim types.DelegatorClaim) { - suite.keeper.SetDelegatorClaim(suite.ctx, claim) -} - -func (suite *unitTester) storeSwapClaim(claim types.SwapClaim) { - suite.keeper.SetSwapClaim(suite.ctx, claim) -} - -func (suite *unitTester) storeSavingsClaim(claim types.SavingsClaim) { - suite.keeper.SetSavingsClaim(suite.ctx, claim) -} - -func (suite *unitTester) storeEarnClaim(claim types.EarnClaim) { - suite.keeper.SetEarnClaim(suite.ctx, claim) -} - -type TestKeeperBuilder struct { - cdc codec.Codec - key storetypes.StoreKey - paramSubspace types.ParamSubspace - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - cdpKeeper types.CdpKeeper - hardKeeper types.HardKeeper - stakingKeeper types.StakingKeeper - swapKeeper types.SwapKeeper - savingsKeeper types.SavingsKeeper - liquidKeeper types.LiquidKeeper - earnKeeper types.EarnKeeper - - // Keepers used for APY queries - mintKeeper types.MintKeeper - distrKeeper types.DistrKeeper - pricefeedKeeper types.PricefeedKeeper -} - -func (suite *unitTester) NewTestKeeper( - paramSubspace types.ParamSubspace, -) *TestKeeperBuilder { - if !paramSubspace.HasKeyTable() { - paramSubspace = paramSubspace.WithKeyTable(types.ParamKeyTable()) - } - - return &TestKeeperBuilder{ - cdc: suite.cdc, - key: suite.incentiveStoreKey, - paramSubspace: paramSubspace, - accountKeeper: nil, - bankKeeper: nil, - cdpKeeper: nil, - hardKeeper: nil, - stakingKeeper: nil, - swapKeeper: nil, - savingsKeeper: nil, - liquidKeeper: nil, - earnKeeper: nil, - mintKeeper: nil, - distrKeeper: nil, - pricefeedKeeper: nil, - } -} - -func (tk *TestKeeperBuilder) WithPricefeedKeeper(k types.PricefeedKeeper) *TestKeeperBuilder { - tk.pricefeedKeeper = k - return tk -} - -func (tk *TestKeeperBuilder) WithDistrKeeper(k types.DistrKeeper) *TestKeeperBuilder { - tk.distrKeeper = k - return tk -} - -func (tk *TestKeeperBuilder) WithBankKeeper(k types.BankKeeper) *TestKeeperBuilder { - tk.bankKeeper = k - return tk -} - -func (tk *TestKeeperBuilder) WithStakingKeeper(k types.StakingKeeper) *TestKeeperBuilder { - tk.stakingKeeper = k - return tk -} - -func (tk *TestKeeperBuilder) WithMintKeeper(k types.MintKeeper) *TestKeeperBuilder { - tk.mintKeeper = k - return tk -} - -func (tk *TestKeeperBuilder) WithEarnKeeper(k types.EarnKeeper) *TestKeeperBuilder { - tk.earnKeeper = k - return tk -} - -func (tk *TestKeeperBuilder) WithLiquidKeeper(k types.LiquidKeeper) *TestKeeperBuilder { - tk.liquidKeeper = k - return tk -} - -func (tk *TestKeeperBuilder) Build() keeper.Keeper { - return keeper.NewKeeper( - tk.cdc, tk.key, tk.paramSubspace, - tk.bankKeeper, tk.cdpKeeper, tk.hardKeeper, tk.accountKeeper, - tk.stakingKeeper, tk.swapKeeper, tk.savingsKeeper, tk.liquidKeeper, - tk.earnKeeper, tk.mintKeeper, tk.distrKeeper, tk.pricefeedKeeper, - ) -} - -// fakeParamSubspace is a stub paramSpace to simplify keeper unit test setup. -type fakeParamSubspace struct { - params types.Params -} - -func (subspace *fakeParamSubspace) GetParamSet(_ sdk.Context, ps paramtypes.ParamSet) { - *(ps.(*types.Params)) = subspace.params -} - -func (subspace *fakeParamSubspace) SetParamSet(_ sdk.Context, ps paramtypes.ParamSet) { - subspace.params = *(ps.(*types.Params)) -} - -func (subspace *fakeParamSubspace) HasKeyTable() bool { - // return true so the keeper does not try to call WithKeyTable, which does nothing - return true -} - -func (subspace *fakeParamSubspace) WithKeyTable(paramtypes.KeyTable) paramtypes.Subspace { - // return an non-functional subspace to satisfy the interface - return paramtypes.Subspace{} -} - -// fakeSwapKeeper is a stub swap keeper. -// It can be used to return values to the incentive keeper without having to initialize a full swap keeper. -type fakeSwapKeeper struct { - poolShares map[string]sdkmath.Int - depositShares map[string](map[string]sdkmath.Int) -} - -var _ types.SwapKeeper = newFakeSwapKeeper() - -func newFakeSwapKeeper() *fakeSwapKeeper { - return &fakeSwapKeeper{ - poolShares: map[string]sdkmath.Int{}, - depositShares: map[string](map[string]sdkmath.Int){}, - } -} - -func (k *fakeSwapKeeper) addPool(id string, shares sdkmath.Int) *fakeSwapKeeper { - k.poolShares[id] = shares - return k -} - -func (k *fakeSwapKeeper) addDeposit(poolID string, depositor sdk.AccAddress, shares sdkmath.Int) *fakeSwapKeeper { - if k.depositShares[poolID] == nil { - k.depositShares[poolID] = map[string]sdkmath.Int{} - } - k.depositShares[poolID][depositor.String()] = shares - return k -} - -func (k *fakeSwapKeeper) GetPoolShares(_ sdk.Context, poolID string) (sdkmath.Int, bool) { - shares, ok := k.poolShares[poolID] - return shares, ok -} - -func (k *fakeSwapKeeper) GetDepositorSharesAmount(_ sdk.Context, depositor sdk.AccAddress, poolID string) (sdkmath.Int, bool) { - shares, found := k.depositShares[poolID][depositor.String()] - return shares, found -} - -// fakeHardKeeper is a stub hard keeper. -// It can be used to return values to the incentive keeper without having to initialize a full hard keeper. -type fakeHardKeeper struct { - borrows fakeHardState - deposits fakeHardState -} - -type fakeHardState struct { - total sdk.Coins - interestFactors map[string]sdk.Dec -} - -func newFakeHardState() fakeHardState { - return fakeHardState{ - total: nil, - interestFactors: map[string]sdk.Dec{}, // initialize map to avoid panics on read - } -} - -var _ types.HardKeeper = newFakeHardKeeper() - -func newFakeHardKeeper() *fakeHardKeeper { - return &fakeHardKeeper{ - borrows: newFakeHardState(), - deposits: newFakeHardState(), - } -} - -func (k *fakeHardKeeper) addTotalBorrow(coin sdk.Coin, factor sdk.Dec) *fakeHardKeeper { - k.borrows.total = k.borrows.total.Add(coin) - k.borrows.interestFactors[coin.Denom] = factor - return k -} - -func (k *fakeHardKeeper) addTotalSupply(coin sdk.Coin, factor sdk.Dec) *fakeHardKeeper { - k.deposits.total = k.deposits.total.Add(coin) - k.deposits.interestFactors[coin.Denom] = factor - return k -} - -func (k *fakeHardKeeper) GetBorrowedCoins(_ sdk.Context) (sdk.Coins, bool) { - if k.borrows.total == nil { - return nil, false - } - return k.borrows.total, true -} - -func (k *fakeHardKeeper) GetSuppliedCoins(_ sdk.Context) (sdk.Coins, bool) { - if k.deposits.total == nil { - return nil, false - } - return k.deposits.total, true -} - -func (k *fakeHardKeeper) GetBorrowInterestFactor(_ sdk.Context, denom string) (sdk.Dec, bool) { - f, ok := k.borrows.interestFactors[denom] - return f, ok -} - -func (k *fakeHardKeeper) GetSupplyInterestFactor(_ sdk.Context, denom string) (sdk.Dec, bool) { - f, ok := k.deposits.interestFactors[denom] - return f, ok -} - -func (k *fakeHardKeeper) GetBorrow(_ sdk.Context, _ sdk.AccAddress) (hardtypes.Borrow, bool) { - panic("unimplemented") -} - -func (k *fakeHardKeeper) GetDeposit(_ sdk.Context, _ sdk.AccAddress) (hardtypes.Deposit, bool) { - panic("unimplemented") -} - -// fakeStakingKeeper is a stub staking keeper. -// It can be used to return values to the incentive keeper without having to initialize a full staking keeper. -type fakeStakingKeeper struct { - delegations stakingtypes.Delegations - validators stakingtypes.Validators -} - -var _ types.StakingKeeper = newFakeStakingKeeper() - -func newFakeStakingKeeper() *fakeStakingKeeper { return &fakeStakingKeeper{} } - -func (k *fakeStakingKeeper) addBondedTokens(amount int64) *fakeStakingKeeper { - if len(k.validators) != 0 { - panic("cannot set total bonded if keeper already has validators set") - } - // add a validator with all the tokens - k.validators = append(k.validators, stakingtypes.Validator{ - Status: stakingtypes.Bonded, - Tokens: sdkmath.NewInt(amount), - }) - return k -} - -func (k *fakeStakingKeeper) TotalBondedTokens(_ sdk.Context) sdkmath.Int { - total := sdk.ZeroInt() - for _, val := range k.validators { - if val.GetStatus() == stakingtypes.Bonded { - total = total.Add(val.GetBondedTokens()) - } - } - return total -} - -func (k *fakeStakingKeeper) GetDelegatorDelegations(_ sdk.Context, delegator sdk.AccAddress, maxRetrieve uint16) []stakingtypes.Delegation { - return k.delegations -} - -func (k *fakeStakingKeeper) GetValidator(_ sdk.Context, addr sdk.ValAddress) (stakingtypes.Validator, bool) { - for _, val := range k.validators { - if val.GetOperator().Equals(addr) { - return val, true - } - } - return stakingtypes.Validator{}, false -} - -func (k *fakeStakingKeeper) GetValidatorDelegations(_ sdk.Context, valAddr sdk.ValAddress) []stakingtypes.Delegation { - var delegations stakingtypes.Delegations - for _, d := range k.delegations { - if d.GetValidatorAddr().Equals(valAddr) { - delegations = append(delegations, d) - } - } - return delegations -} - -// fakeCDPKeeper is a stub cdp keeper. -// It can be used to return values to the incentive keeper without having to initialize a full cdp keeper. -type fakeCDPKeeper struct { - interestFactor *sdk.Dec - totalPrincipal sdkmath.Int -} - -var _ types.CdpKeeper = newFakeCDPKeeper() - -func newFakeCDPKeeper() *fakeCDPKeeper { - return &fakeCDPKeeper{ - interestFactor: nil, - totalPrincipal: sdk.ZeroInt(), - } -} - -func (k *fakeCDPKeeper) addInterestFactor(f sdk.Dec) *fakeCDPKeeper { - k.interestFactor = &f - return k -} - -func (k *fakeCDPKeeper) addTotalPrincipal(p sdkmath.Int) *fakeCDPKeeper { - k.totalPrincipal = p - return k -} - -func (k *fakeCDPKeeper) GetInterestFactor(_ sdk.Context, collateralType string) (sdk.Dec, bool) { - if k.interestFactor != nil { - return *k.interestFactor, true - } - return sdk.Dec{}, false -} - -func (k *fakeCDPKeeper) GetTotalPrincipal(_ sdk.Context, collateralType string, principalDenom string) sdkmath.Int { - return k.totalPrincipal -} - -func (k *fakeCDPKeeper) GetCdpByOwnerAndCollateralType(_ sdk.Context, owner sdk.AccAddress, collateralType string) (cdptypes.CDP, bool) { - return cdptypes.CDP{}, false -} - -func (k *fakeCDPKeeper) GetCollateral(_ sdk.Context, collateralType string) (cdptypes.CollateralParam, bool) { - return cdptypes.CollateralParam{}, false -} - -// fakeEarnKeeper is a stub earn keeper. -// It can be used to return values to the incentive keeper without having to initialize a full earn keeper. -type fakeEarnKeeper struct { - vaultShares map[string]earntypes.VaultShare - depositShares map[string]earntypes.VaultShares -} - -var _ types.EarnKeeper = newFakeEarnKeeper() - -func newFakeEarnKeeper() *fakeEarnKeeper { - return &fakeEarnKeeper{ - vaultShares: map[string]earntypes.VaultShare{}, - depositShares: map[string]earntypes.VaultShares{}, - } -} - -func (k *fakeEarnKeeper) addVault(vaultDenom string, shares earntypes.VaultShare) *fakeEarnKeeper { - k.vaultShares[vaultDenom] = shares - return k -} - -func (k *fakeEarnKeeper) addDeposit( - depositor sdk.AccAddress, - shares earntypes.VaultShare, -) *fakeEarnKeeper { - if k.depositShares[depositor.String()] == nil { - k.depositShares[depositor.String()] = earntypes.NewVaultShares() - } - - k.depositShares[depositor.String()] = k.depositShares[depositor.String()].Add(shares) - - return k -} - -func (k *fakeEarnKeeper) GetVaultTotalShares( - ctx sdk.Context, - denom string, -) (shares earntypes.VaultShare, found bool) { - vaultShares, found := k.vaultShares[denom] - return vaultShares, found -} - -func (k *fakeEarnKeeper) GetVaultTotalValue(ctx sdk.Context, denom string) (sdk.Coin, error) { - vaultShares, found := k.vaultShares[denom] - if !found { - return sdk.NewCoin(denom, sdk.ZeroInt()), nil - } - - return sdk.NewCoin(denom, vaultShares.Amount.RoundInt()), nil -} - -func (k *fakeEarnKeeper) GetVaultAccountShares( - ctx sdk.Context, - acc sdk.AccAddress, -) (shares earntypes.VaultShares, found bool) { - accShares, found := k.depositShares[acc.String()] - return accShares, found -} - -func (k *fakeEarnKeeper) IterateVaultRecords( - ctx sdk.Context, - cb func(record earntypes.VaultRecord) (stop bool), -) { - for _, vaultShares := range k.vaultShares { - cb(earntypes.VaultRecord{ - TotalShares: vaultShares, - }) - } -} - -// fakeLiquidKeeper is a stub liquid keeper. -// It can be used to return values to the incentive keeper without having to initialize a full liquid keeper. -type fakeLiquidKeeper struct { - derivatives map[string]sdkmath.Int - lastRewardClaim map[string]time.Time -} - -var _ types.LiquidKeeper = newFakeLiquidKeeper() - -func newFakeLiquidKeeper() *fakeLiquidKeeper { - return &fakeLiquidKeeper{ - derivatives: map[string]sdkmath.Int{}, - lastRewardClaim: map[string]time.Time{}, - } -} - -func (k *fakeLiquidKeeper) addDerivative( - ctx sdk.Context, - denom string, - supply sdkmath.Int, -) *fakeLiquidKeeper { - k.derivatives[denom] = supply - k.lastRewardClaim[denom] = ctx.BlockTime() - return k -} - -func (k *fakeLiquidKeeper) IsDerivativeDenom(ctx sdk.Context, denom string) bool { - return strings.HasPrefix(denom, "bkava-") -} - -func (k *fakeLiquidKeeper) GetAllDerivativeDenoms(ctx sdk.Context) (denoms []string) { - for denom := range k.derivatives { - denoms = append(denoms, denom) - } - - return denoms -} - -func (k *fakeLiquidKeeper) GetTotalDerivativeValue(ctx sdk.Context) (sdk.Coin, error) { - totalSupply := sdk.ZeroInt() - for _, supply := range k.derivatives { - totalSupply = totalSupply.Add(supply) - } - - return sdk.NewCoin("ukava", totalSupply), nil -} - -func (k *fakeLiquidKeeper) GetDerivativeValue(ctx sdk.Context, denom string) (sdk.Coin, error) { - supply, found := k.derivatives[denom] - if !found { - return sdk.NewCoin("ukava", sdk.ZeroInt()), nil - } - - return sdk.NewCoin("ukava", supply), nil -} - -func (k *fakeLiquidKeeper) CollectStakingRewardsByDenom( - ctx sdk.Context, - derivativeDenom string, - destinationModAccount string, -) (sdk.Coins, error) { - amt := k.getRewardAmount(ctx, derivativeDenom) - - return sdk.NewCoins(sdk.NewCoin("ukava", amt)), nil -} - -func (k *fakeLiquidKeeper) getRewardAmount( - ctx sdk.Context, - derivativeDenom string, -) sdkmath.Int { - amt, found := k.derivatives[derivativeDenom] - if !found { - // No error - return sdk.ZeroInt() - } - - lastRewardClaim, found := k.lastRewardClaim[derivativeDenom] - if !found { - panic("last reward claim not found") - } - - duration := int64(ctx.BlockTime().Sub(lastRewardClaim).Seconds()) - if duration <= 0 { - return sdk.ZeroInt() - } - - // Reward amount just set to 10% of the derivative supply per second - return amt.QuoRaw(10).MulRaw(duration) -} - -type fakeDistrKeeper struct { - communityTax sdk.Dec -} - -var _ types.DistrKeeper = newFakeDistrKeeper() - -func newFakeDistrKeeper() *fakeDistrKeeper { - return &fakeDistrKeeper{} -} - -func (k *fakeDistrKeeper) setCommunityTax(percent sdk.Dec) *fakeDistrKeeper { - k.communityTax = percent - return k -} - -func (k *fakeDistrKeeper) GetCommunityTax(ctx sdk.Context) (percent sdk.Dec) { - return k.communityTax -} - -type fakeMintKeeper struct { - minter minttypes.Minter -} - -var _ types.MintKeeper = newFakeMintKeeper() - -func newFakeMintKeeper() *fakeMintKeeper { - return &fakeMintKeeper{} -} - -func (k *fakeMintKeeper) setMinter(minter minttypes.Minter) *fakeMintKeeper { - k.minter = minter - return k -} - -func (k *fakeMintKeeper) GetMinter(ctx sdk.Context) (minter minttypes.Minter) { - return k.minter -} - -type fakePricefeedKeeper struct { - prices map[string]pricefeedtypes.CurrentPrice -} - -var _ types.PricefeedKeeper = newFakePricefeedKeeper() - -func newFakePricefeedKeeper() *fakePricefeedKeeper { - return &fakePricefeedKeeper{ - prices: map[string]pricefeedtypes.CurrentPrice{}, - } -} - -func (k *fakePricefeedKeeper) setPrice(price pricefeedtypes.CurrentPrice) *fakePricefeedKeeper { - k.prices[price.MarketID] = price - return k -} - -func (k *fakePricefeedKeeper) GetCurrentPrice(ctx sdk.Context, marketID string) (pricefeedtypes.CurrentPrice, error) { - price, found := k.prices[marketID] - if !found { - return pricefeedtypes.CurrentPrice{}, fmt.Errorf("price not found for market %s", marketID) - } - - return price, nil -} - -type fakeBankKeeper struct { - supply map[string]sdkmath.Int -} - -var _ types.BankKeeper = newFakeBankKeeper() - -func newFakeBankKeeper() *fakeBankKeeper { - return &fakeBankKeeper{ - supply: map[string]sdkmath.Int{}, - } -} - -func (k *fakeBankKeeper) setSupply(coins ...sdk.Coin) *fakeBankKeeper { - for _, coin := range coins { - k.supply[coin.Denom] = coin.Amount - } - - return k -} - -func (k *fakeBankKeeper) SendCoinsFromModuleToAccount( - ctx sdk.Context, - senderModule string, - recipientAddr sdk.AccAddress, - amt sdk.Coins, -) error { - panic("not implemented") -} - -func (k *fakeBankKeeper) GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins { - panic("not implemented") -} - -func (k *fakeBankKeeper) GetSupply(ctx sdk.Context, denom string) sdk.Coin { - supply, found := k.supply[denom] - if !found { - return sdk.NewCoin(denom, sdk.ZeroInt()) - } - - return sdk.NewCoin(denom, supply) -} - -// Assorted Testing Data - -// note: amino panics when encoding times ≥ the start of year 10000. -var distantFuture = time.Date(9000, 1, 1, 0, 0, 0, 0, time.UTC) - -func arbitraryCoins() sdk.Coins { - return cs(c("btcb", 1)) -} - -func arbitraryAddress() sdk.AccAddress { - _, addresses := app.GeneratePrivKeyAddressPairs(1) - return addresses[0] -} - -func arbitraryValidatorAddress() sdk.ValAddress { - return generateValidatorAddresses(1)[0] -} - -func generateValidatorAddresses(n int) []sdk.ValAddress { - _, addresses := app.GeneratePrivKeyAddressPairs(n) - var valAddresses []sdk.ValAddress - for _, a := range addresses { - valAddresses = append(valAddresses, sdk.ValAddress(a)) - } - return valAddresses -} - -var nonEmptyMultiRewardIndexes = types.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: "btcb", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.2"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.4"), - }, - }, - }, -} - -func extractCollateralTypes(indexes types.MultiRewardIndexes) []string { - var denoms []string - for _, ri := range indexes { - denoms = append(denoms, ri.CollateralType) - } - return denoms -} - -func increaseAllRewardFactors(indexes types.MultiRewardIndexes) types.MultiRewardIndexes { - increasedIndexes := make(types.MultiRewardIndexes, len(indexes)) - copy(increasedIndexes, indexes) - - for i := range increasedIndexes { - increasedIndexes[i].RewardIndexes = increaseRewardFactors(increasedIndexes[i].RewardIndexes) - } - return increasedIndexes -} - -func increaseRewardFactors(indexes types.RewardIndexes) types.RewardIndexes { - increasedIndexes := make(types.RewardIndexes, len(indexes)) - copy(increasedIndexes, indexes) - - for i := range increasedIndexes { - increasedIndexes[i].RewardFactor = increasedIndexes[i].RewardFactor.MulInt64(2) - } - return increasedIndexes -} - -func appendUniqueMultiRewardIndex(indexes types.MultiRewardIndexes) types.MultiRewardIndexes { - const uniqueDenom = "uniquedenom" - - for _, mri := range indexes { - if mri.CollateralType == uniqueDenom { - panic(fmt.Sprintf("tried to add unique multi reward index with denom '%s', but denom already existed", uniqueDenom)) - } - } - - return append(indexes, types.NewMultiRewardIndex( - uniqueDenom, - types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - ), - ) -} - -func appendUniqueEmptyMultiRewardIndex(indexes types.MultiRewardIndexes) types.MultiRewardIndexes { - const uniqueDenom = "uniquedenom" - - for _, mri := range indexes { - if mri.CollateralType == uniqueDenom { - panic(fmt.Sprintf("tried to add unique multi reward index with denom '%s', but denom already existed", uniqueDenom)) - } - } - - return append(indexes, types.NewMultiRewardIndex(uniqueDenom, nil)) -} - -func appendUniqueRewardIndexToFirstItem(indexes types.MultiRewardIndexes) types.MultiRewardIndexes { - newIndexes := make(types.MultiRewardIndexes, len(indexes)) - copy(newIndexes, indexes) - - newIndexes[0].RewardIndexes = appendUniqueRewardIndex(newIndexes[0].RewardIndexes) - return newIndexes -} - -func appendUniqueRewardIndex(indexes types.RewardIndexes) types.RewardIndexes { - const uniqueDenom = "uniquereward" - - for _, mri := range indexes { - if mri.CollateralType == uniqueDenom { - panic(fmt.Sprintf("tried to add unique reward index with denom '%s', but denom already existed", uniqueDenom)) - } - } - - return append( - indexes, - types.NewRewardIndex(uniqueDenom, d("0.02")), - ) -} diff --git a/x/incentive/legacy/go.mod b/x/incentive/legacy/go.mod deleted file mode 100644 index e69de29b..00000000 diff --git a/x/incentive/legacy/v0_15/types.go b/x/incentive/legacy/v0_15/types.go deleted file mode 100644 index 58f6f912..00000000 --- a/x/incentive/legacy/v0_15/types.go +++ /dev/null @@ -1,171 +0,0 @@ -package v0_15 - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName The name that will be used throughout the module - ModuleName = "incentive" -) - -// GenesisState is the state that must be provided at genesis. -type GenesisState struct { - Params Params `json:"params" yaml:"params"` - - USDXRewardState GenesisRewardState `json:"usdx_reward_state" yaml:"usdx_reward_state"` - HardSupplyRewardState GenesisRewardState `json:"hard_supply_reward_state" yaml:"hard_supply_reward_state"` - HardBorrowRewardState GenesisRewardState `json:"hard_borrow_reward_state" yaml:"hard_borrow_reward_state"` - DelegatorRewardState GenesisRewardState `json:"delegator_reward_state" yaml:"delegator_reward_state"` - SwapRewardState GenesisRewardState `json:"swap_reward_state" yaml:"swap_reward_state"` - - USDXMintingClaims USDXMintingClaims `json:"usdx_minting_claims" yaml:"usdx_minting_claims"` - HardLiquidityProviderClaims HardLiquidityProviderClaims `json:"hard_liquidity_provider_claims" yaml:"hard_liquidity_provider_claims"` - DelegatorClaims DelegatorClaims `json:"delegator_claims" yaml:"delegator_claims"` - SwapClaims SwapClaims `json:"swap_claims" yaml:"swap_claims"` -} - -// Params governance parameters for the incentive module -type Params struct { - USDXMintingRewardPeriods RewardPeriods `json:"usdx_minting_reward_periods" yaml:"usdx_minting_reward_periods"` - HardSupplyRewardPeriods MultiRewardPeriods `json:"hard_supply_reward_periods" yaml:"hard_supply_reward_periods"` - HardBorrowRewardPeriods MultiRewardPeriods `json:"hard_borrow_reward_periods" yaml:"hard_borrow_reward_periods"` - DelegatorRewardPeriods MultiRewardPeriods `json:"delegator_reward_periods" yaml:"delegator_reward_periods"` - SwapRewardPeriods MultiRewardPeriods `json:"swap_reward_periods" yaml:"swap_reward_periods"` - ClaimMultipliers MultipliersPerDenom `json:"claim_multipliers" yaml:"claim_multipliers"` - ClaimEnd time.Time `json:"claim_end" yaml:"claim_end"` -} - -// RewardPeriods array of RewardPeriod -type RewardPeriods []RewardPeriod - -// RewardPeriod stores the state of an ongoing reward -type RewardPeriod struct { - Active bool `json:"active" yaml:"active"` - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - Start time.Time `json:"start" yaml:"start"` - End time.Time `json:"end" yaml:"end"` - RewardsPerSecond sdk.Coin `json:"rewards_per_second" yaml:"rewards_per_second"` // per second reward payouts -} - -// GenesisRewardState groups together the global state for a particular reward so it can be exported in genesis. -type GenesisRewardState struct { - AccumulationTimes AccumulationTimes `json:"accumulation_times" yaml:"accumulation_times"` - MultiRewardIndexes MultiRewardIndexes `json:"multi_reward_indexes" yaml:"multi_reward_indexes"` -} - -// AccumulationTimes slice of GenesisAccumulationTime -type AccumulationTimes []AccumulationTime - -// AccumulationTime stores the previous reward distribution time and its corresponding collateral type -type AccumulationTime struct { - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - PreviousAccumulationTime time.Time `json:"previous_accumulation_time" yaml:"previous_accumulation_time"` -} - -// MultiRewardIndexes slice of MultiRewardIndex -type MultiRewardIndexes []MultiRewardIndex - -// MultiRewardIndex stores reward accumulation information on multiple reward types -type MultiRewardIndex struct { - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - RewardIndexes RewardIndexes `json:"reward_indexes" yaml:"reward_indexes"` -} - -// RewardIndexes slice of RewardIndex -type RewardIndexes []RewardIndex - -// RewardIndex stores reward accumulation information -type RewardIndex struct { - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - RewardFactor sdk.Dec `json:"reward_factor" yaml:"reward_factor"` -} - -// USDXMintingClaims slice of USDXMintingClaim -type USDXMintingClaims []USDXMintingClaim - -// USDXMintingClaim is for USDX minting rewards -type USDXMintingClaim struct { - BaseClaim `json:"base_claim" yaml:"base_claim"` - RewardIndexes RewardIndexes `json:"reward_indexes" yaml:"reward_indexes"` -} - -// BaseClaim is a common type shared by all Claims -type BaseClaim struct { - Owner sdk.AccAddress `json:"owner" yaml:"owner"` - Reward sdk.Coin `json:"reward" yaml:"reward"` -} - -// HardLiquidityProviderClaims slice of HardLiquidityProviderClaim -type HardLiquidityProviderClaims []HardLiquidityProviderClaim - -// HardLiquidityProviderClaim stores the hard liquidity provider rewards that can be claimed by owner -type HardLiquidityProviderClaim struct { - BaseMultiClaim `json:"base_claim" yaml:"base_claim"` - SupplyRewardIndexes MultiRewardIndexes `json:"supply_reward_indexes" yaml:"supply_reward_indexes"` - BorrowRewardIndexes MultiRewardIndexes `json:"borrow_reward_indexes" yaml:"borrow_reward_indexes"` -} - -// BaseMultiClaim is a common type shared by all Claims with multiple reward denoms -type BaseMultiClaim struct { - Owner sdk.AccAddress `json:"owner" yaml:"owner"` - Reward sdk.Coins `json:"reward" yaml:"reward"` -} - -// DelegatorClaim slice of DelegatorClaim -type DelegatorClaims []DelegatorClaim - -// DelegatorClaim stores delegation rewards that can be claimed by owner -type DelegatorClaim struct { - BaseMultiClaim `json:"base_claim" yaml:"base_claim"` - RewardIndexes MultiRewardIndexes `json:"reward_indexes" yaml:"reward_indexes"` -} - -// SwapClaims slice of SwapClaim -type SwapClaims []SwapClaim - -// SwapClaim stores the swap rewards that can be claimed by owner -type SwapClaim struct { - BaseMultiClaim `json:"base_claim" yaml:"base_claim"` - RewardIndexes MultiRewardIndexes `json:"reward_indexes" yaml:"reward_indexes"` -} - -// MultiRewardPeriods array of MultiRewardPeriod -type MultiRewardPeriods []MultiRewardPeriod - -// MultiRewardPeriod supports multiple reward types -type MultiRewardPeriod struct { - Active bool `json:"active" yaml:"active"` - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - Start time.Time `json:"start" yaml:"start"` - End time.Time `json:"end" yaml:"end"` - RewardsPerSecond sdk.Coins `json:"rewards_per_second" yaml:"rewards_per_second"` // per second reward payouts -} - -// MultipliersPerDenom is a map of denoms to a set of multipliers -type MultipliersPerDenom []struct { - Denom string `json:"denom" yaml:"denom"` - Multipliers Multipliers `json:"multipliers" yaml:"multipliers"` -} - -// Multipliers is a slice of Multiplier -type Multipliers []Multiplier - -// Multiplier amount the claim rewards get increased by, along with how long the claim rewards are locked -type Multiplier struct { - Name MultiplierName `json:"name" yaml:"name"` - MonthsLockup int64 `json:"months_lockup" yaml:"months_lockup"` - Factor sdk.Dec `json:"factor" yaml:"factor"` -} - -// MultiplierName is the user facing ID for a multiplier. There is a restricted set of possible values. -type MultiplierName string - -// Available reward multipliers names -const ( - Small MultiplierName = "small" - Medium MultiplierName = "medium" - Large MultiplierName = "large" -) diff --git a/x/incentive/legacy/v0_16/migrate.go b/x/incentive/legacy/v0_16/migrate.go deleted file mode 100644 index 5015cfb4..00000000 --- a/x/incentive/legacy/v0_16/migrate.go +++ /dev/null @@ -1,174 +0,0 @@ -package v0_16 - -import ( - v015incentive "github.com/kava-labs/kava/x/incentive/legacy/v0_15" - v016incentive "github.com/kava-labs/kava/x/incentive/types" -) - -func migrateMultiRewardPerids(oldPeriods v015incentive.MultiRewardPeriods) v016incentive.MultiRewardPeriods { - newPeriods := make(v016incentive.MultiRewardPeriods, len(oldPeriods)) - for i, oldPeriod := range oldPeriods { - newPeriods[i] = v016incentive.MultiRewardPeriod{ - Active: oldPeriod.Active, - CollateralType: oldPeriod.CollateralType, - Start: oldPeriod.Start, - End: oldPeriod.End, - RewardsPerSecond: oldPeriod.RewardsPerSecond, - } - } - return newPeriods -} - -func migrateRewardPeriods(oldPeriods v015incentive.RewardPeriods) v016incentive.RewardPeriods { - newPeriods := make(v016incentive.RewardPeriods, len(oldPeriods)) - for i, oldPeriod := range oldPeriods { - newPeriods[i] = v016incentive.RewardPeriod{ - Active: oldPeriod.Active, - CollateralType: oldPeriod.CollateralType, - Start: oldPeriod.Start, - End: oldPeriod.End, - RewardsPerSecond: oldPeriod.RewardsPerSecond, - } - } - return newPeriods -} - -func migrateMultipliersPerDenom(oldMpds v015incentive.MultipliersPerDenom) []v016incentive.MultipliersPerDenom { - mpds := make([]v016incentive.MultipliersPerDenom, len(oldMpds)) - for i, oldMpd := range oldMpds { - multipliers := make(v016incentive.Multipliers, len(oldMpd.Multipliers)) - for i, multiplier := range oldMpd.Multipliers { - multipliers[i] = v016incentive.Multiplier{ - Name: string(multiplier.Name), - MonthsLockup: multiplier.MonthsLockup, - Factor: multiplier.Factor, - } - } - mpds[i] = v016incentive.MultipliersPerDenom{ - Denom: oldMpd.Denom, - Multipliers: multipliers, - } - } - return mpds -} - -func migrateParams(params v015incentive.Params) v016incentive.Params { - return v016incentive.Params{ - USDXMintingRewardPeriods: migrateRewardPeriods(params.USDXMintingRewardPeriods), - HardSupplyRewardPeriods: migrateMultiRewardPerids(params.HardSupplyRewardPeriods), - HardBorrowRewardPeriods: migrateMultiRewardPerids(params.HardBorrowRewardPeriods), - DelegatorRewardPeriods: migrateMultiRewardPerids(params.DelegatorRewardPeriods), - SwapRewardPeriods: migrateMultiRewardPerids(params.SwapRewardPeriods), - ClaimMultipliers: migrateMultipliersPerDenom(params.ClaimMultipliers), - ClaimEnd: params.ClaimEnd, - } -} - -func migrateRewardState(oldRewardState v015incentive.GenesisRewardState) v016incentive.GenesisRewardState { - allTimes := make(v016incentive.AccumulationTimes, len(oldRewardState.AccumulationTimes)) - for i, at := range oldRewardState.AccumulationTimes { - allTimes[i] = v016incentive.AccumulationTime{ - CollateralType: at.CollateralType, - PreviousAccumulationTime: at.PreviousAccumulationTime, - } - } - return v016incentive.GenesisRewardState{ - AccumulationTimes: allTimes, - MultiRewardIndexes: migrateMultiRewardIndexes(oldRewardState.MultiRewardIndexes), - } -} - -func migrateMultiRewardIndexes(oldMultiRewardIndexes v015incentive.MultiRewardIndexes) v016incentive.MultiRewardIndexes { - multiRewardIndexes := make(v016incentive.MultiRewardIndexes, len(oldMultiRewardIndexes)) - for i, multiRewardIndex := range oldMultiRewardIndexes { - multiRewardIndexes[i] = v016incentive.MultiRewardIndex{ - CollateralType: multiRewardIndex.CollateralType, - RewardIndexes: migrateRewadIndexes(multiRewardIndex.RewardIndexes), - } - } - return multiRewardIndexes -} - -func migrateRewadIndexes(oldRewardIndexes v015incentive.RewardIndexes) v016incentive.RewardIndexes { - rewardIndexes := make(v016incentive.RewardIndexes, len(oldRewardIndexes)) - for j, rewardIndex := range oldRewardIndexes { - rewardIndexes[j] = v016incentive.RewardIndex{ - CollateralType: rewardIndex.CollateralType, - RewardFactor: rewardIndex.RewardFactor, - } - } - return rewardIndexes -} - -func migrateUSDXMintingClaims(oldClaims v015incentive.USDXMintingClaims) v016incentive.USDXMintingClaims { - claims := make(v016incentive.USDXMintingClaims, len(oldClaims)) - for i, oldClaim := range oldClaims { - claims[i] = v016incentive.USDXMintingClaim{ - BaseClaim: v016incentive.BaseClaim{ - Owner: oldClaim.BaseClaim.Owner, - Reward: oldClaim.BaseClaim.Reward, - }, - RewardIndexes: migrateRewadIndexes(oldClaim.RewardIndexes), - } - } - return claims -} - -func migrateHardLiquidityProviderClaims(oldClaims v015incentive.HardLiquidityProviderClaims) v016incentive.HardLiquidityProviderClaims { - claims := make(v016incentive.HardLiquidityProviderClaims, len(oldClaims)) - for i, oldClaim := range oldClaims { - claims[i] = v016incentive.HardLiquidityProviderClaim{ - BaseMultiClaim: v016incentive.BaseMultiClaim{ - Owner: oldClaim.BaseMultiClaim.Owner, - Reward: oldClaim.BaseMultiClaim.Reward, - }, - SupplyRewardIndexes: migrateMultiRewardIndexes(oldClaim.SupplyRewardIndexes), - BorrowRewardIndexes: migrateMultiRewardIndexes(oldClaim.BorrowRewardIndexes), - } - } - return claims -} - -func migrateDelegatorClaims(oldClaims v015incentive.DelegatorClaims) v016incentive.DelegatorClaims { - claims := make(v016incentive.DelegatorClaims, len(oldClaims)) - for i, oldClaim := range oldClaims { - claims[i] = v016incentive.DelegatorClaim{ - BaseMultiClaim: v016incentive.BaseMultiClaim{ - Owner: oldClaim.BaseMultiClaim.Owner, - Reward: oldClaim.BaseMultiClaim.Reward, - }, - RewardIndexes: migrateMultiRewardIndexes(oldClaim.RewardIndexes), - } - } - return claims -} - -func migrateSwapClaims(oldClaims v015incentive.SwapClaims) v016incentive.SwapClaims { - claims := make(v016incentive.SwapClaims, len(oldClaims)) - for i, oldClaim := range oldClaims { - claims[i] = v016incentive.SwapClaim{ - BaseMultiClaim: v016incentive.BaseMultiClaim{ - Owner: oldClaim.BaseMultiClaim.Owner, - Reward: oldClaim.BaseMultiClaim.Reward, - }, - RewardIndexes: migrateMultiRewardIndexes(oldClaim.RewardIndexes), - } - } - return claims -} - -// Migrate converts v0.15 incentive state and returns it in v0.16 format -func Migrate(oldState v015incentive.GenesisState) *v016incentive.GenesisState { - return &v016incentive.GenesisState{ - Params: migrateParams(oldState.Params), - USDXRewardState: migrateRewardState(oldState.USDXRewardState), - HardSupplyRewardState: migrateRewardState(oldState.HardSupplyRewardState), - HardBorrowRewardState: migrateRewardState(oldState.HardBorrowRewardState), - DelegatorRewardState: migrateRewardState(oldState.DelegatorRewardState), - SwapRewardState: migrateRewardState(oldState.SwapRewardState), - USDXMintingClaims: migrateUSDXMintingClaims(oldState.USDXMintingClaims), - HardLiquidityProviderClaims: migrateHardLiquidityProviderClaims(oldState.HardLiquidityProviderClaims), - DelegatorClaims: migrateDelegatorClaims(oldState.DelegatorClaims), - SwapClaims: migrateSwapClaims(oldState.SwapClaims), - } -} diff --git a/x/incentive/legacy/v0_16/migrate_test.go b/x/incentive/legacy/v0_16/migrate_test.go deleted file mode 100644 index 0cfb1014..00000000 --- a/x/incentive/legacy/v0_16/migrate_test.go +++ /dev/null @@ -1,560 +0,0 @@ -package v0_16 - -import ( - "io/ioutil" - "path/filepath" - "testing" - "time" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - app "github.com/kava-labs/kava/app" - v015incentive "github.com/kava-labs/kava/x/incentive/legacy/v0_15" - v016incentive "github.com/kava-labs/kava/x/incentive/types" -) - -type migrateTestSuite struct { - suite.Suite - - addresses []sdk.AccAddress - cdc codec.Codec - legacyCdc *codec.LegacyAmino -} - -func (s *migrateTestSuite) SetupTest() { - app.SetSDKConfig() - - config := app.MakeEncodingConfig() - s.cdc = config.Marshaler - - legacyCodec := codec.NewLegacyAmino() - s.legacyCdc = legacyCodec - - _, accAddresses := app.GeneratePrivKeyAddressPairs(10) - s.addresses = accAddresses -} - -func (s *migrateTestSuite) TestMigrate_JSON() { - file := filepath.Join("testdata", "v15-incentive.json") - data, err := ioutil.ReadFile(file) - s.Require().NoError(err) - var v15genstate v015incentive.GenesisState - err = s.legacyCdc.UnmarshalJSON(data, &v15genstate) - s.Require().NoError(err) - genstate := Migrate(v15genstate) - actual := s.cdc.MustMarshalJSON(genstate) - - file = filepath.Join("testdata", "v16-incentive.json") - expected, err := ioutil.ReadFile(file) - s.Require().NoError(err) - s.Require().JSONEq(string(expected), string(actual)) -} - -func (s *migrateTestSuite) TestMigrate_GenState() { - v15genstate := v015incentive.GenesisState{ - Params: v015incentive.Params{ - ClaimEnd: time.Date(2020, time.March, 1, 2, 0, 0, 0, time.UTC), - USDXMintingRewardPeriods: []v015incentive.RewardPeriod{ - { - Active: true, - CollateralType: "usdx", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoin("usdx", sdkmath.NewInt(10)), - }, - }, - HardSupplyRewardPeriods: v015incentive.MultiRewardPeriods{ - { - Active: true, - CollateralType: "usdx", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(10))), - }, - }, - HardBorrowRewardPeriods: v015incentive.MultiRewardPeriods{ - { - Active: true, - CollateralType: "bnb", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10))), - }, - }, - DelegatorRewardPeriods: v015incentive.MultiRewardPeriods{ - { - Active: true, - CollateralType: "bnb", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10))), - }, - }, - SwapRewardPeriods: v015incentive.MultiRewardPeriods{ - { - Active: true, - CollateralType: "bnb", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10))), - }, - }, - ClaimMultipliers: v015incentive.MultipliersPerDenom{ - { - Denom: "usdx", - Multipliers: v015incentive.Multipliers{ - { - Name: v015incentive.Small, - MonthsLockup: 6, - Factor: sdk.MustNewDecFromStr("0.5"), - }, - { - Name: v015incentive.Large, - MonthsLockup: 12, - Factor: sdk.MustNewDecFromStr("0.8"), - }, - { - Name: v015incentive.Medium, - MonthsLockup: 9, - Factor: sdk.MustNewDecFromStr("0.7"), - }, - }, - }, - }, - }, - USDXRewardState: v015incentive.GenesisRewardState{ - AccumulationTimes: v015incentive.AccumulationTimes{ - { - CollateralType: "usdx", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "usdx", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.15"), - }, - }, - }, - }, - }, - USDXMintingClaims: v015incentive.USDXMintingClaims{ - { - BaseClaim: v015incentive.BaseClaim{ - Owner: s.addresses[0], - Reward: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - }, - RewardIndexes: v015incentive.RewardIndexes{ - { - CollateralType: "kava", - RewardFactor: sdk.MustNewDecFromStr("0.5"), - }, - }, - }, - }, - HardSupplyRewardState: v015incentive.GenesisRewardState{ - AccumulationTimes: v015incentive.AccumulationTimes{ - { - CollateralType: "usdx", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "usdx", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.15"), - }, - }, - }, - }, - }, - HardBorrowRewardState: v015incentive.GenesisRewardState{ - AccumulationTimes: v015incentive.AccumulationTimes{ - { - CollateralType: "hard", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "hard", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.15"), - }, - }, - }, - }, - }, - DelegatorRewardState: v015incentive.GenesisRewardState{ - AccumulationTimes: v015incentive.AccumulationTimes{ - { - CollateralType: "usdx", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "usdx", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.15"), - }, - }, - }, - }, - }, - SwapRewardState: v015incentive.GenesisRewardState{ - AccumulationTimes: v015incentive.AccumulationTimes{ - { - CollateralType: "swap", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "swap", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - }, - HardLiquidityProviderClaims: v015incentive.HardLiquidityProviderClaims{ - { - BaseMultiClaim: v015incentive.BaseMultiClaim{ - Owner: s.addresses[1], - Reward: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100))), - }, - SupplyRewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - BorrowRewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - }, - }, - DelegatorClaims: v015incentive.DelegatorClaims{ - { - BaseMultiClaim: v015incentive.BaseMultiClaim{ - Owner: s.addresses[1], - Reward: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100))), - }, - RewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - }, - }, - SwapClaims: v015incentive.SwapClaims{ - { - BaseMultiClaim: v015incentive.BaseMultiClaim{ - Owner: s.addresses[1], - Reward: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100))), - }, - RewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - }, - }, - } - expected := v016incentive.GenesisState{ - USDXRewardState: v016incentive.GenesisRewardState{ - AccumulationTimes: v016incentive.AccumulationTimes{ - { - CollateralType: "usdx", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "usdx", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.15"), - }, - }, - }, - }, - }, - Params: v016incentive.Params{ - ClaimEnd: time.Date(2020, time.March, 1, 2, 0, 0, 0, time.UTC), - USDXMintingRewardPeriods: []v016incentive.RewardPeriod{ - { - Active: true, - CollateralType: "usdx", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoin("usdx", sdkmath.NewInt(10)), - }, - }, - HardSupplyRewardPeriods: v016incentive.MultiRewardPeriods{ - { - Active: true, - CollateralType: "usdx", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(10))), - }, - }, - HardBorrowRewardPeriods: v016incentive.MultiRewardPeriods{ - { - Active: true, - CollateralType: "bnb", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10))), - }, - }, - DelegatorRewardPeriods: v016incentive.MultiRewardPeriods{ - { - Active: true, - CollateralType: "bnb", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10))), - }, - }, - SwapRewardPeriods: v016incentive.MultiRewardPeriods{ - { - Active: true, - CollateralType: "bnb", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10))), - }, - }, - ClaimMultipliers: []v016incentive.MultipliersPerDenom{ - { - Denom: "usdx", - Multipliers: v016incentive.Multipliers{ - { - Name: "small", - MonthsLockup: 6, - Factor: sdk.MustNewDecFromStr("0.5"), - }, - { - Name: "large", - MonthsLockup: 12, - Factor: sdk.MustNewDecFromStr("0.8"), - }, - { - Name: "medium", - MonthsLockup: 9, - Factor: sdk.MustNewDecFromStr("0.7"), - }, - }, - }, - }, - }, - USDXMintingClaims: v016incentive.USDXMintingClaims{ - { - BaseClaim: v016incentive.BaseClaim{ - Owner: s.addresses[0], - Reward: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - }, - RewardIndexes: v016incentive.RewardIndexes{ - { - CollateralType: "kava", - RewardFactor: sdk.MustNewDecFromStr("0.5"), - }, - }, - }, - }, - HardSupplyRewardState: v016incentive.GenesisRewardState{ - AccumulationTimes: v016incentive.AccumulationTimes{ - { - CollateralType: "usdx", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "usdx", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.15"), - }, - }, - }, - }, - }, - HardBorrowRewardState: v016incentive.GenesisRewardState{ - AccumulationTimes: v016incentive.AccumulationTimes{ - { - CollateralType: "hard", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "hard", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.15"), - }, - }, - }, - }, - }, - DelegatorRewardState: v016incentive.GenesisRewardState{ - AccumulationTimes: v016incentive.AccumulationTimes{ - { - CollateralType: "usdx", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "usdx", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.15"), - }, - }, - }, - }, - }, - SwapRewardState: v016incentive.GenesisRewardState{ - AccumulationTimes: v016incentive.AccumulationTimes{ - { - CollateralType: "swap", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "swap", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - }, - HardLiquidityProviderClaims: v016incentive.HardLiquidityProviderClaims{ - { - BaseMultiClaim: v016incentive.BaseMultiClaim{ - Owner: s.addresses[1], - Reward: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100))), - }, - SupplyRewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - BorrowRewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - }, - }, - DelegatorClaims: v016incentive.DelegatorClaims{ - { - BaseMultiClaim: v016incentive.BaseMultiClaim{ - Owner: s.addresses[1], - Reward: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100))), - }, - RewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - }, - }, - SwapClaims: v016incentive.SwapClaims{ - { - BaseMultiClaim: v016incentive.BaseMultiClaim{ - Owner: s.addresses[1], - Reward: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100))), - }, - RewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - }, - }, - } - genState := Migrate(v15genstate) - s.Require().Equal(expected, *genState) -} - -func TestIncentiveMigrateTestSuite(t *testing.T) { - suite.Run(t, new(migrateTestSuite)) -} diff --git a/x/incentive/legacy/v0_16/testdata/v15-incentive.json b/x/incentive/legacy/v0_16/testdata/v15-incentive.json deleted file mode 100644 index baca2819..00000000 --- a/x/incentive/legacy/v0_16/testdata/v15-incentive.json +++ /dev/null @@ -1,400 +0,0 @@ -{ - "params": { - "usdx_minting_reward_periods": [ - { - "active": true, - "rewards_per_second": { - "amount": "122354", - "denom": "ukava" - }, - "collateral_type": "bnb-a", - "start": "2021-07-20T14:00:00Z", - "end": "2024-10-16T14:00:00Z" - }, - { - "active": true, - "rewards_per_second": { - "amount": "23809", - "denom": "ukava" - }, - "collateral_type": "hard-a", - "start": "2021-07-20T14:00:00Z", - "end": "2024-10-16T14:00:00Z" - } - ], - "hard_supply_reward_periods": [ - { - "active": true, - "collateral_type": "bnb", - "start": "2021-07-20T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { - "amount": "123455", - "denom": "hard" - } - ] - }, - { - "active": true, - "collateral_type": "hard", - "start": "2021-07-20T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { - "amount": "123455", - "denom": "hard" - } - ] - } - ], - "hard_borrow_reward_periods": [ - { - "active": true, - "collateral_type": "bnb", - "start": "2020-01-01T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { - "amount": "12345", - "denom": "hard" - } - ] - }, - { - "active": true, - "collateral_type": "btcb", - "start": "2020-01-01T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { - "amount": "12345", - "denom": "hard" - } - ] - } - ], - "delegator_reward_periods": [ - { - "active": true, - "collateral_type": "ukava", - "start": "2020-01-01T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { - "amount": "316880", - "denom": "hard" - }, - { - "amount": "316880", - "denom": "swp" - } - ] - } - ], - "swap_reward_periods": [ - { - "active": true, - "collateral_type": "ukava:usdx", - "start": "2021-07-14T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { - "amount": "316880", - "denom": "swp" - }, - { - "amount": "31688", - "denom": "ukava" - } - ] - }, - { - "active": true, - "collateral_type": "swp:usdx", - "start": "2021-07-14T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { - "amount": "616880", - "denom": "swp" - }, - { - "amount": "31688", - "denom": "ukava" - } - ] - } - ], - "claim_multipliers": [ - { - "denom": "hard", - "multipliers": [ - { - "name": "small", - "months_lockup": "1", - "factor": "0.2" - }, - { - "name": "large", - "months_lockup": "12", - "factor": "1.0" - } - ] - }, - { - "denom": "swp", - "multipliers": [ - { - "name": "small", - "months_lockup": "1", - "factor": "0.1" - }, - { - "name": "large", - "months_lockup": "12", - "factor": "1.0" - } - ] - } - ], - "claim_end": "2025-01-01T00:00:00Z" - }, - "delegator_reward_state": { - "accumulation_times": [ - { - "collateral_type": "ukava", - "previous_accumulation_time": "2021-11-05T21:13:12.85608847Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "ukava", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "0.078380843036861815" - }, - { - "collateral_type": "swp", - "reward_factor": "0.013629025935176301" - } - ] - } - ] - }, - "hard_borrow_reward_state": { - "accumulation_times": [ - { - "collateral_type": "btcb", - "previous_accumulation_time": "2021-11-05T21:13:12.85608847Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "btcb", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "88.582200355378048199" - } - ] - } - ] - }, - "hard_supply_reward_state": { - "accumulation_times": [ - { - "collateral_type": "bnb", - "previous_accumulation_time": "2021-11-05T21:13:12.85608847Z" - }, - { - "collateral_type": "hard", - "previous_accumulation_time": "2021-11-05T21:13:12.85608847Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "bnb", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "32.458112657412585027" - } - ] - }, - { - "collateral_type": "hard", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "35.000000000000000000" - } - ] - } - ] - }, - "swap_reward_state": { - "accumulation_times": [ - { - "collateral_type": "btcb-a", - "previous_accumulation_time": "2021-06-10T16:43:11.679705Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "btcb:usdx", - "reward_indexes": [ - { - "collateral_type": "swp", - "reward_factor": "6.145396761233172901" - } - ] - } - ] - }, - "usdx_reward_state": { - "accumulation_times": [ - { - "collateral_type": "bnb-a", - "previous_accumulation_time": "2021-06-10T16:43:11.679705Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "bnb-a", - "reward_indexes": [ - { - "collateral_type": "ukava", - "reward_factor": "0.043949244534927716" - } - ] - } - ] - }, - "delegator_claims": [ - { - "base_claim": { - "owner": "kava1qqqvdyv8w0xdu7gjdtt598q78gtgqyukct4yz2", - "reward": [] - }, - "reward_indexes": [ - { - "collateral_type": "ukava", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "0.000000000000000000" - }, - { - "collateral_type": "swp", - "reward_factor": "0.000000100000000000" - } - ] - } - ] - } - ], - "hard_liquidity_provider_claims": [ - { - "base_claim": { - "owner": "kava1qqqvdyv8w0xdu7gjdtt598q78gtgqyukct4yz2", - "reward": [ - { - "amount": "1747514", - "denom": "hard" - } - ] - }, - "borrow_reward_indexes": [ - { - "collateral_type": "btc", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "88.582200355378048199" - } - ] - } - ], - "supply_reward_indexes": [ - { - "collateral_type": "bnb", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "22.000000000000000000" - } - ] - }, - { - "collateral_type": "hard", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "30.000000000000000000" - } - ] - } - ] - }, - { - "base_claim": { - "owner": "kava1w2uj6rpejrma47vjx4rcghh3fndhmrvs6pmxph", - "reward": [ - { - "amount": "1747514", - "denom": "hard" - } - ] - }, - "borrow_reward_indexes": [], - "supply_reward_indexes": [] - } - ], - "usdx_minting_claims": [ - { - "base_claim": { - "owner": "kava1qptt5vu26cmxpmv0hf2tnnmf293x266pjcsjar", - "reward": { - "amount": "550", - "denom": "ukava" - } - }, - "reward_indexes": [ - { - "collateral_type": "bnb-a", - "reward_factor": "0.043949244534927716" - }, - { - "collateral_type": "btcb-a", - "reward_factor": "0.046551281526135881" - } - ] - } - ], - "swap_claims": [ - { - "base_claim": { - "owner": "kava1qzease8mre5adak7wcc2twh6ryh9evnxpr6caj", - "reward": [ - { - "amount": "1960368", - "denom": "swp" - } - ] - }, - "reward_indexes": [ - { - "collateral_type": "busd:usdx", - "reward_indexes": [ - { - "collateral_type": "swp", - "reward_factor": "0.018083281889996318" - } - ] - } - ] - } - ] -} diff --git a/x/incentive/legacy/v0_16/testdata/v16-incentive.json b/x/incentive/legacy/v0_16/testdata/v16-incentive.json deleted file mode 100644 index 95da6e01..00000000 --- a/x/incentive/legacy/v0_16/testdata/v16-incentive.json +++ /dev/null @@ -1,337 +0,0 @@ -{ - "params": { - "usdx_minting_reward_periods": [ - { - "active": true, - "collateral_type": "bnb-a", - "start": "2021-07-20T14:00:00Z", - "end": "2024-10-16T14:00:00Z", - "rewards_per_second": { "denom": "ukava", "amount": "122354" } - }, - { - "active": true, - "collateral_type": "hard-a", - "start": "2021-07-20T14:00:00Z", - "end": "2024-10-16T14:00:00Z", - "rewards_per_second": { "denom": "ukava", "amount": "23809" } - } - ], - "hard_supply_reward_periods": [ - { - "active": true, - "collateral_type": "bnb", - "start": "2021-07-20T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [{ "denom": "hard", "amount": "123455" }] - }, - { - "active": true, - "collateral_type": "hard", - "start": "2021-07-20T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [{ "denom": "hard", "amount": "123455" }] - } - ], - "hard_borrow_reward_periods": [ - { - "active": true, - "collateral_type": "bnb", - "start": "2020-01-01T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [{ "denom": "hard", "amount": "12345" }] - }, - { - "active": true, - "collateral_type": "btcb", - "start": "2020-01-01T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [{ "denom": "hard", "amount": "12345" }] - } - ], - "delegator_reward_periods": [ - { - "active": true, - "collateral_type": "ukava", - "start": "2020-01-01T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { "denom": "hard", "amount": "316880" }, - { "denom": "swp", "amount": "316880" } - ] - } - ], - "swap_reward_periods": [ - { - "active": true, - "collateral_type": "ukava:usdx", - "start": "2021-07-14T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { "denom": "swp", "amount": "316880" }, - { "denom": "ukava", "amount": "31688" } - ] - }, - { - "active": true, - "collateral_type": "swp:usdx", - "start": "2021-07-14T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { "denom": "swp", "amount": "616880" }, - { "denom": "ukava", "amount": "31688" } - ] - } - ], - "savings_reward_periods": [], - "claim_multipliers": [ - { - "denom": "hard", - "multipliers": [ - { - "name": "small", - "months_lockup": "1", - "factor": "0.200000000000000000" - }, - { - "name": "large", - "months_lockup": "12", - "factor": "1.000000000000000000" - } - ] - }, - { - "denom": "swp", - "multipliers": [ - { - "name": "small", - "months_lockup": "1", - "factor": "0.100000000000000000" - }, - { - "name": "large", - "months_lockup": "12", - "factor": "1.000000000000000000" - } - ] - } - ], - "claim_end": "2025-01-01T00:00:00Z" - }, - "usdx_reward_state": { - "accumulation_times": [ - { - "collateral_type": "bnb-a", - "previous_accumulation_time": "2021-06-10T16:43:11.679705Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "bnb-a", - "reward_indexes": [ - { - "collateral_type": "ukava", - "reward_factor": "0.043949244534927716" - } - ] - } - ] - }, - "hard_supply_reward_state": { - "accumulation_times": [ - { - "collateral_type": "bnb", - "previous_accumulation_time": "2021-11-05T21:13:12.856088470Z" - }, - { - "collateral_type": "hard", - "previous_accumulation_time": "2021-11-05T21:13:12.856088470Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "bnb", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "32.458112657412585027" - } - ] - }, - { - "collateral_type": "hard", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "35.000000000000000000" - } - ] - } - ] - }, - "hard_borrow_reward_state": { - "accumulation_times": [ - { - "collateral_type": "btcb", - "previous_accumulation_time": "2021-11-05T21:13:12.856088470Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "btcb", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "88.582200355378048199" - } - ] - } - ] - }, - "delegator_reward_state": { - "accumulation_times": [ - { - "collateral_type": "ukava", - "previous_accumulation_time": "2021-11-05T21:13:12.856088470Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "ukava", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "0.078380843036861815" - }, - { "collateral_type": "swp", "reward_factor": "0.013629025935176301" } - ] - } - ] - }, - "swap_reward_state": { - "accumulation_times": [ - { - "collateral_type": "btcb-a", - "previous_accumulation_time": "2021-06-10T16:43:11.679705Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "btcb:usdx", - "reward_indexes": [ - { "collateral_type": "swp", "reward_factor": "6.145396761233172901" } - ] - } - ] - }, - "savings_reward_state": { - "accumulation_times": [], - "multi_reward_indexes": [] - }, - "usdx_minting_claims": [ - { - "base_claim": { - "owner": "kava1qptt5vu26cmxpmv0hf2tnnmf293x266pjcsjar", - "reward": { "denom": "ukava", "amount": "550" } - }, - "reward_indexes": [ - { "collateral_type": "bnb-a", "reward_factor": "0.043949244534927716" }, - { "collateral_type": "btcb-a", "reward_factor": "0.046551281526135881" } - ] - } - ], - "hard_liquidity_provider_claims": [ - { - "base_claim": { - "owner": "kava1qqqvdyv8w0xdu7gjdtt598q78gtgqyukct4yz2", - "reward": [{ "denom": "hard", "amount": "1747514" }] - }, - "supply_reward_indexes": [ - { - "collateral_type": "bnb", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "22.000000000000000000" - } - ] - }, - { - "collateral_type": "hard", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "30.000000000000000000" - } - ] - } - ], - "borrow_reward_indexes": [ - { - "collateral_type": "btc", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "88.582200355378048199" - } - ] - } - ] - }, - { - "base_claim": { - "owner": "kava1w2uj6rpejrma47vjx4rcghh3fndhmrvs6pmxph", - "reward": [ - { - "amount": "1747514", - "denom": "hard" - } - ] - }, - "borrow_reward_indexes": [], - "supply_reward_indexes": [] - } - ], - "delegator_claims": [ - { - "base_claim": { - "owner": "kava1qqqvdyv8w0xdu7gjdtt598q78gtgqyukct4yz2", - "reward": [] - }, - "reward_indexes": [ - { - "collateral_type": "ukava", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "0.000000000000000000" - }, - { - "collateral_type": "swp", - "reward_factor": "0.000000100000000000" - } - ] - } - ] - } - ], - "swap_claims": [ - { - "base_claim": { - "owner": "kava1qzease8mre5adak7wcc2twh6ryh9evnxpr6caj", - "reward": [{ "denom": "swp", "amount": "1960368" }] - }, - "reward_indexes": [ - { - "collateral_type": "busd:usdx", - "reward_indexes": [ - { - "collateral_type": "swp", - "reward_factor": "0.018083281889996318" - } - ] - } - ] - } - ], - "savings_claims": [] -} diff --git a/x/incentive/module.go b/x/incentive/module.go deleted file mode 100644 index f3a9dfc6..00000000 --- a/x/incentive/module.go +++ /dev/null @@ -1,143 +0,0 @@ -package incentive - -import ( - "context" - "encoding/json" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/kava-labs/kava/x/incentive/client/cli" - "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic defines the basic application module used by the incentive module. -type AppModuleBasic struct{} - -// Name returns the incentive module's name. -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis returns default genesis state as raw bytes for the incentive -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - gs := types.DefaultGenesisState() - return cdc.MustMarshalJSON(&gs) -} - -// ValidateGenesis performs genesis state validation for the incentive module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - if err := cdc.UnmarshalJSON(bz, &gs); err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the incentive module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// GetTxCmd returns the root tx command for the incentive module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the incentive module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -// AppModule implements the sdk.AppModule interface. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - cdpKeeper types.CdpKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, ak types.AccountKeeper, bk types.BankKeeper, ck types.CdpKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: ak, - bankKeeper: bk, - cdpKeeper: ck, - } -} - -// Name returns the incentive module's name. -func (AppModule) Name() string { - return types.ModuleName -} - -// RegisterInvariants registers the incentive module invariants. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) -} - -// InitGenesis performs genesis initialization for the incentive module. 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, am.accountKeeper, am.bankKeeper, am.cdpKeeper, genState) - return []abci.ValidatorUpdate{} -} - -// ExportGenesis returns the exported genesis state as raw bytes for the incentive module -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(&gs) -} - -// BeginBlock returns the begin blocker for the incentive module. -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { - BeginBlocker(ctx, am.keeper) -} - -// EndBlock returns the end blocker for the incentive module. It returns no validator updates. -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/incentive/spec/01_concepts.md b/x/incentive/spec/01_concepts.md deleted file mode 100644 index efc8678c..00000000 --- a/x/incentive/spec/01_concepts.md +++ /dev/null @@ -1,110 +0,0 @@ - - -# Concepts - -This module implements governance controlled user incentives. When users take a certain action, for example opening a CDP, they become eligible for rewards. Rewards are **opt in** meaning that users must submit a message before the claim deadline to claim their rewards. The goals and background of this module were subject of a previous Kava governance proposal, which can be found [here](https://ipfs.io/ipfs/QmSYedssC3nyQacDJmNcREtgmTPyaMx2JX7RNkMdAVkdkr/user-growth-fund-proposal.pdf) - -## General Reward Distribution - -Rewards target various user activity. For example, usdx borrowed from bnb CDPs, btcb supplied to the hard money market, or shares owned in a swap kava/usdx pool. - -Each second, the rewards accumulate at a rate set in the params, eg 100 ukava per second. These are then distributed to all users ratably based on their percentage involvement in the rewarded activity. For example if a user holds 1% of all funds deposited to the kava/usdx swap pool. They will receive 1% of the total rewards each second. - -The quantity tracking a user's involvement is referred to as "source shares". And the total across all users the "total source shares". The quotient then gives their percentage involvement, eg if a user borrowed 10,000 usdx, and there is 100,000 usdx borrowed by all users, then they will get 10% of rewards. - -## Efficiency - -Paying out rewards to every user every block would be slow and lead to long block times. Instead rewards are calculated lazily only when needed. - -First, every block, the amount of rewards to be distributed in that block are divided by the total source shares to get the rewards per share. This is added to a global total (named "global indexes"). This is repeated every block such that the global indexes represents the total rewards a user should be owed per source share if they had held a deposit from when the rewards were created. - -Then, if a user has deposited (say into a CDP) at the very start of the chain (and never changed their deposit), their current reward balance can be calculated at any time $t$ as - -$$ -\texttt{rewards}_ t = \texttt{globalIndexes}_ t \cdot \texttt{sourceShares}_ t -$$ - -If a user modifies their source shares (at say time $t-10$) we can still calculate their total rewards: - -$$ -\texttt{rewards}_ t= \text{rewards accrued up to time t-10} + \text{rewards accrued from time t-10 to time t} -$$ - -$$ -\texttt{rewards}_ t = \texttt{globalIndexes}_ {t-10} \cdot \texttt{sourceShares}_ {t-10} + (\texttt{globalIndexes}_ t - \texttt{globalIndexes}_ {t-10}) \cdot \texttt{sourceShares}_ t -$$ - -This generalizes to any number of source share modifications. - -In code, to avoid storing the entire history of a user's source shares and global index values, rewards are calculated on every source shares change and added to a reward balance: - -$$ -\texttt{rewards}_ t = \texttt{rewardBalance}_ {t -10} + (\texttt{globalIndexes}_ t - \texttt{globalIndexes}_ {t-10}) \cdot \texttt{sourceShares}_ t -$$ - -Old values of $\texttt{rewardBalance}$ and $\texttt{globalIndexes}$ ares stored in a `Claim` object for each user as `rewardBalance` and `rewardIndexes` respectively. - -Listeners on external modules fire to update these values when source shares change. For example, when a user deposits to hard, a method in incentive is called. This fundamental operation is called "sync". It calculates the rewards accrued since last time the `sourceShares` changed, adds it to the claim, and stores the current `globalIndexes` in the `rewardIndexes`. Sync must be called whenever source shares change, otherwise incorrect rewards will be distributed. - -Enumeration of 'sync' input states: -- `sourceShares`, `globalIndexes`, or `rewardIndexes` should never be negative -- `globalIndexes` >= `rewardIndexes` (global indexes must never decrease) -- `globalIndexes` and `rewardIndexes` can be positive or 0, where not existing in the store is counted as 0 - -- `sourceShares` are the value before the update (eg before a hard deposit) - - | `globalIndexes` | `rewardIndexes` | `sourceShares` | description | - |------------------|-----------------|-----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| - | positive | positive | positive | normal sync | - | positive | positive | 0 | normal (can happen when a user is creating a deposit (so shares are increasing from 0)) | - | positive | 0 | positive | The claim doesn't hold indexes, so the global indexes must have been added since last sync (eg a new denom was added to reward params). This is indistinguishable from a claim accidentally being deleted, where it will accrue a large amount of rewards. | - | positive | 0 | 0 | User is creating source shares. | - | 0 | positive | positive | global indexes < claim indexes - fatal error, otherwise the new rewards will be negative | - | 0 | positive | 0 | global indexes < claim indexes - fatal error | - | 0 | 0 | positive | Source has no rewards yet. User is updating their shares. | - | 0 | 0 | 0 | Source has no rewards yet. User is creating source shares. | - -It is important that: -- claim indexes are not deleted - - Otherwise when sync is called, it will fill them in with 0 values and perform sync as if the user had deposit since the beginning of the rewards (usually accumulating a lot of rewards). -- global indexes are not deleted - - Otherwise claims cannot be synced. Problematic if a sync happens in a begin blocker and it panics. -- hooks are called any time source shares change - - If source shares can be updated without a sync, it can be possible to accumulate far too much rewards. For example, a user who holds a small deposit for a long time could deposit a large amount and skip the sync, then trigger a sync which will calculate rewards as if the large deposit was there for a long time. - -The code is further complicated by: -- Claim objects contain indexes for several source shares. -- Rewards for hard borrows and hard deposits use the same claim object. -- Savings and hard hooks trigger any time one in a group of source shares change, but don't identify which changed. -- The hard `BeforeXModified` hooks don't show source shares that have increased from zero (eg when a new denom is deposited to an existing deposit). So there is an additional `AfterXModified` hook, and the claim indexes double up as a copy of the borrow/deposit denoms. -- The sync operation is split between two methods to try to protect against indexes being deleted. - - `InitXRewards` performs a sync assuming source shares are 0, it mostly fires in cases where `sourceShares` = 0 above (except for hard and supply) - - `SyncXRewards` performs a sync, but skips it if `globalIndexes` are not found or `rewardIndexes` are not found (only when claim object not found) -- Usdx rewards do not support multiple reward denoms. - -## HARD Token distribution - -The incentive module also distributes the HARD token on the Kava blockchain. HARD tokens are distributed to two types of ecosystem participants: - -1. Kava stakers - any address that stakes (delegates) KAVA tokens will be eligible to claim HARD tokens. For each delegator, HARD tokens are accumulated ratably based on the total number of kava tokens staked. For example, if a user stakes 1 million KAVA tokens and there are 100 million staked KAVA, that user will accumulate 1% of HARD tokens earmarked for stakers during the distribution period. Distribution periods are defined by a start date, an end date, and a number of HARD tokens that are distributed per second. -2. Depositors/Borrows - any address that deposits and/or borrows eligible tokens to the hard module will be eligible to claim HARD tokens. For each depositor, HARD tokens are accumulated ratably based on the total number of tokens staked of that denomination. For example, if a user deposits 1 million "xyz" tokens and there are 100 million xyz deposited, that user will accumulate 1% of HARD tokens earmarked for depositors of that denomination during the distribution period. Distribution periods are defined by a start date, an end date, and a number of HARD tokens that are distributed per second. - -Users are not air-dropped tokens, rather they accumulate `Claim` objects that they may submit a transaction in order to claim. In order to better align long term incentives, when users claim HARD tokens, they have options, called 'multipliers', for how tokens are distributed. - -The exact multipliers will be voted by governance and can be changed via a governance vote. An example multiplier schedule would be: - -- Short-term locked - 20% multiplier and 1 month transfer restriction. Users receive 20% as many tokens as users who choose long-term locked tokens. -- Long-term locked - 100% multiplier and 1 year transfer restriction. Users receive 5x as many tokens as users who choose short-term locked tokens. - -## USDX Minting Rewards - -The incentive module is responsible for distribution of KAVA tokens to users who mint USDX. When governance adds a collateral type to be eligible for rewards, they set the rate (coins/second) at which rewards are given to users, the length of each reward period, the length of each claim period, and the amount of time reward coins must vest before users who claim them can transfer them. For the duration of a reward period, any user that has minted USDX using an eligible collateral type will ratably accumulate rewards in a `USDXMintingClaim` object. For example, if a user has minted 10% of all USDX for the duration of the reward period, they will earn 10% of all rewards for that period. When the reward period ends, the claim period begins immediately, at which point users can submit a message to claim their rewards. Rewards are time-locked, meaning that when a user claims rewards they will receive them as a vesting balance on their account. Vesting balances can be used to stake coins, but cannot be transferred until the vesting period ends. In addition to vesting, rewards can have multipliers that vary the number of tokens received. For example, a reward with a vesting period of 1 month may have a multiplier of 0.25, meaning that the user will receive 25% of the reward balance if they choose that vesting schedule. - -## SWP Token Distribution - -The incentive module distributes the SWP token on the Kava blockchain. SWP tokens are distributed to two types of ecosystem participants: - -1. Kava stakers - any address that stakes (delegates) KAVA tokens will be eligible to claim SWP tokens. For each delegator, SWP tokens are accumulated ratably based on the total number of kava tokens staked. For example, if a user stakes 1 million KAVA tokens and there are 100 million staked KAVA, that user will accumulate 1% of SWP tokens earmarked for stakers during the distribution period. Distribution periods are defined by a start date, an end date, and a number of SWP tokens that are distributed per second. -2. Liquidity providers - any address that provides liquidity to eligible Swap protocol pools will be eligible to claim SWP tokens. For each liquidity provider, SWP tokens are accumulated ratably based on the total amount of pool shares. For example, if a liquidity provider deposits "xyz" and "abc" tokens into the "abc:xyz" pool to receive 10 shares and the pool has 50 total shares, then that user will accumulate 20% of SWP tokens earmarked for liquidity providers of that pool during the distribution period. Distribution periods are defined by a start date, an end date, and a number of SWP tokens that are distributed per second. diff --git a/x/incentive/spec/02_state.md b/x/incentive/spec/02_state.md deleted file mode 100644 index d76bfd9d..00000000 --- a/x/incentive/spec/02_state.md +++ /dev/null @@ -1,141 +0,0 @@ - - -# State - -## Parameters and Genesis State - -`Parameters` define the types of incentives that are available and the rewards that are available for each incentive. - -```go -// Params governance parameters for the incentive module -type Params struct { - USDXMintingRewardPeriods RewardPeriods `json:"usdx_minting_reward_periods" yaml:"usdx_minting_reward_periods"` - HardSupplyRewardPeriods MultiRewardPeriods `json:"hard_supply_reward_periods" yaml:"hard_supply_reward_periods"` - HardBorrowRewardPeriods MultiRewardPeriods `json:"hard_borrow_reward_periods" yaml:"hard_borrow_reward_periods"` - DelegatorRewardPeriods MultiRewardPeriods `json:"delegator_reward_periods" yaml:"delegator_reward_periods"` - SwapRewardPeriods MultiRewardPeriods `json:"swap_reward_periods" yaml:"swap_reward_periods"` - ClaimMultipliers Multipliers `json:"claim_multipliers" yaml:"claim_multipliers"` - ClaimEnd time.Time `json:"claim_end" yaml:"claim_end"` -} - -``` - -Each `RewardPeriod` defines a particular collateral for which rewards are eligible and the amount of rewards available. - -```go -// RewardPeriod stores the state of an ongoing reward -type RewardPeriod struct { - Active bool `json:"active" yaml:"active"` // if the reward is active - CollateralType string `json:"collateral_type" yaml:"collateral_type"` // the collateral type for which rewards apply - Start time.Time `json:"start" yaml:"start"` // when the rewards start - End time.Time `json:"end" yaml:"end"` // when the rewards end - RewardsPerSecond sdk.Coin `json:"rewards_per_second" yaml:"rewards_per_second"` // per second reward payouts -} -``` - -Each `MultiRewardPeriod` defines a particular collateral for which one or more reward tokens are eligible and the amount of rewards available - -```go -// MultiRewardPeriod supports multiple reward types -type MultiRewardPeriod struct { - Active bool `json:"active" yaml:"active"` - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - Start time.Time `json:"start" yaml:"start"` - End time.Time `json:"end" yaml:"end"` - RewardsPerSecond sdk.Coins `json:"rewards_per_second" yaml:"rewards_per_second"` // per second reward payouts -} -``` - -`GenesisState` defines the state that must be persisted when the blockchain stops/restarts in order for normal function of the incentive module to resume. - -```go -// GenesisState is the state that must be provided at genesis. -type GenesisState struct { - Params Params `json:"params" yaml:"params"` - - USDXRewardState GenesisRewardState `json:"usdx_reward_state" yaml:"usdx_reward_state"` - HardSupplyRewardState GenesisRewardState `json:"hard_supply_reward_state" yaml:"hard_supply_reward_state"` - HardBorrowRewardState GenesisRewardState `json:"hard_borrow_reward_state" yaml:"hard_borrow_reward_state"` - DelegatorRewardState GenesisRewardState `json:"delegator_reward_state" yaml:"delegator_reward_state"` - SwapRewardState GenesisRewardState `json:"swap_reward_state" yaml:"swap_reward_state"` - - USDXMintingClaims USDXMintingClaims `json:"usdx_minting_claims" yaml:"usdx_minting_claims"` - HardLiquidityProviderClaims HardLiquidityProviderClaims `json:"hard_liquidity_provider_claims" yaml:"hard_liquidity_provider_claims"` - DelegatorClaims DelegatorClaims `json:"delegator_claims" yaml:"delegator_claims"` - SwapClaims SwapClaims `json:"swap_claims" yaml:"swap_claims"` -} -``` - -## Store - -For complete details for how items are stored, see [keys.go](../types/keys.go). - -### Claim Creation - -When users take incentivized actions, the `incentive` module will create or update a `Claim` object in the store, which represents the amount of rewards that the user is eligible to claim. Each `Claim` object contains one or several RewardIndexes, which are used to calculate the amount of rewards a user can claim. There are four defined claim objects: - -- `USDXMintingClaim` -- `HardLiquidityProviderClaim` -- `DelegatorClaim` -- `SwapClaim` - -```go - -// Claim is an interface for handling common claim actions -type Claim interface { - GetOwner() sdk.AccAddress - GetReward() sdk.Coin - GetType() string -} - -// BaseClaim is a common type shared by all Claims -type BaseClaim struct { - Owner sdk.AccAddress `json:"owner" yaml:"owner"` - Reward sdk.Coin `json:"reward" yaml:"reward"` -} - -// BaseMultiClaim is a common type shared by all Claims with multiple reward denoms -type BaseMultiClaim struct { - Owner sdk.AccAddress `json:"owner" yaml:"owner"` - Reward sdk.Coins `json:"reward" yaml:"reward"` -} - -// RewardIndex stores reward accumulation information -type RewardIndex struct { - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - RewardFactor sdk.Dec `json:"reward_factor" yaml:"reward_factor"` -} - -// MultiRewardIndex stores reward accumulation information on multiple reward types -type MultiRewardIndex struct { - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - RewardIndexes RewardIndexes `json:"reward_indexes" yaml:"reward_indexes"` -} - -// USDXMintingClaim is for USDX minting rewards -type USDXMintingClaim struct { - BaseClaim `json:"base_claim" yaml:"base_claim"` - RewardIndexes RewardIndexes `json:"reward_indexes" yaml:"reward_indexes"` -} - -// HardLiquidityProviderClaim stores the hard liquidity provider rewards that can be claimed by owner -type HardLiquidityProviderClaim struct { - BaseMultiClaim `json:"base_claim" yaml:"base_claim"` - SupplyRewardIndexes MultiRewardIndexes `json:"supply_reward_indexes" yaml:"supply_reward_indexes"` - BorrowRewardIndexes MultiRewardIndexes `json:"borrow_reward_indexes" yaml:"borrow_reward_indexes"` -} - -// DelegatorClaim stores delegation rewards that can be claimed by owner -type DelegatorClaim struct { - BaseMultiClaim `json:"base_claim" yaml:"base_claim"` - RewardIndexes MultiRewardIndexes `json:"reward_indexes" yaml:"reward_indexes"` -} - -// SwapClaim stores the swap rewards that can be claimed by owner -type SwapClaim struct { - BaseMultiClaim `json:"base_claim" yaml:"base_claim"` - RewardIndexes MultiRewardIndexes `json:"reward_indexes" yaml:"reward_indexes"` -} -``` diff --git a/x/incentive/spec/03_messages.md b/x/incentive/spec/03_messages.md deleted file mode 100644 index 8cc3a4da..00000000 --- a/x/incentive/spec/03_messages.md +++ /dev/null @@ -1,42 +0,0 @@ - - -# Messages - -Users claim rewards using messages that correspond to each claim type. - -```go -// MsgClaimUSDXMintingReward message type used to claim USDX minting rewards -type MsgClaimUSDXMintingReward struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - MultiplierName string `json:"multiplier_name" yaml:"multiplier_name"` -} - -// MsgClaimHardReward message type used to claim Hard liquidity provider rewards -type MsgClaimHardReward struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - MultiplierName string `json:"multiplier_name" yaml:"multiplier_name"` - DenomsToClaim []string `json:"denoms_to_claim" yaml:"denoms_to_claim"` -} - -// MsgClaimDelegatorReward message type used to claim delegator rewards -type MsgClaimDelegatorReward struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - MultiplierName string `json:"multiplier_name" yaml:"multiplier_name"` - DenomsToClaim []string `json:"denoms_to_claim" yaml:"denoms_to_claim"` -} - -// MsgClaimSwapReward message type used to claim delegator rewards -type MsgClaimSwapReward struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - MultiplierName string `json:"multiplier_name" yaml:"multiplier_name"` - DenomsToClaim []string `json:"denoms_to_claim" yaml:"denoms_to_claim"` -} -``` - -## State Modifications - -- Accumulated rewards for active claims are transferred from the `kavadist` module account to the users account as vesting coins -- The number of coins transferred is determined by the multiplier in the message. For example, the multiplier equals 1.0, 100% of the claim's reward value is transferred. If the multiplier equals 0.5, 50% of the claim's reward value is transferred. -- The corresponding claim object is reset to zero in the store diff --git a/x/incentive/spec/04_events.md b/x/incentive/spec/04_events.md deleted file mode 100644 index 8901b93d..00000000 --- a/x/incentive/spec/04_events.md +++ /dev/null @@ -1,17 +0,0 @@ - - -# Events - -The `x/incentive` module emits the following events: - -## ClaimReward - -| Type | Attribute Key | Attribute Value | -| ------------ | ------------- | -------------------- | -| claim_reward | claimed_by | `{claiming address}' | -| claim_reward | claim_amount | `{amount claimed}' | -| claim_reward | claim_type | `{amount claimed}' | -| message | module | incentive | -| message | sender | claim_reward | diff --git a/x/incentive/spec/05_params.md b/x/incentive/spec/05_params.md deleted file mode 100644 index f9debed4..00000000 --- a/x/incentive/spec/05_params.md +++ /dev/null @@ -1,45 +0,0 @@ - - -# Parameters - -The incentive module contains the following parameters: - -| Key | Type | Example | Description | -| ------------------------ | ------------------ | ---------------------- | -------------------------------------------- | -| USDXMintingRewardPeriods | RewardPeriods | [{see below}] | USDX minting reward periods | -| HardSupplyRewardPeriods | MultiRewardPeriods | [{see below}] | Hard supply reward periods | -| HardBorrowRewardPeriods | MultiRewardPeriods | [{see below}] | Hard borrow reward periods | -| DelegatorRewardPeriods | MultiRewardPeriods | [{see below}] | Delegator reward periods | -| SwapRewardPeriods | MultiRewardPeriods | [{see below}] | Swap reward periods | -| ClaimMultipliers | Multipliers | [{see below}] | Multipliers applied when rewards are claimed | -| ClaimMultipliers | Time | "2025-12-02T14:00:00Z" | Time when reward claiming ends | - -Each `RewardPeriod` has the following parameters - -| Key | Type | Example | Description | -| ---------------- | ------------- | ---------------------------------- | ----------------------------------------------------- | -| Active | bool | "true | boolean for if rewards for this collateral are active | -| CollateralType | string | "bnb-a" | the collateral for which rewards are eligible | -| Start | Time | "2020-12-02T14:00:00Z" | the time at which rewards start | -| End | Time | "2023-12-02T14:00:00Z" | the time at which rewards end | -| AvailableRewards | object (coin) | `{"denom":"hard","amount":"1000"}` | the rewards available per reward period | - -Each `MultiRewardPeriod` has the following parameters - -| Key | Type | Example | Description | -| ---------------- | ------------- | ----------------------------------------------------------------------- | ----------------------------------------------------- | -| Active | bool | "true | boolean for if rewards for this collateral are active | -| CollateralType | string | "bnb-a" | the collateral for which rewards are eligible | -| Start | Time | "2020-12-02T14:00:00Z" | the time at which rewards start | -| End | Time | "2023-12-02T14:00:00Z" | the time at which rewards end | -| AvailableRewards | array (coins) | `[{"denom":"hard","amount":"1000"}, {"denom":"ukava","amount":"1000"}]` | the rewards available per reward period | - -Each `Multiplier` has the following parameters: - -| Key | Type | Example | Description | -| ------------ | ------ | ------- | ---------------------------------------------------------- | -| Name | string | "large" | the unique name of the reward multiplier | -| MonthsLockup | int | "6" | number of months tokens with this multiplier are locked | -| Factor | Dec | "0.5" | the scaling factor for tokens claimed with this multiplier | diff --git a/x/incentive/spec/06_hooks.md b/x/incentive/spec/06_hooks.md deleted file mode 100644 index b532fa33..00000000 --- a/x/incentive/spec/06_hooks.md +++ /dev/null @@ -1,127 +0,0 @@ - - -# Hooks - -This module implements the `Hooks` interface for the following modules: - -- cdp -- hard -- swap -- staking (defined in cosmos-sdk) - -CDP module hooks manage the creation and synchronization of USDX minting incentives. - -```go -// ------------------- Cdp Module Hooks ------------------- - -// AfterCDPCreated function that runs after a cdp is created -func (h Hooks) AfterCDPCreated(ctx sdk.Context, cdp cdptypes.CDP) { - h.k.InitializeUSDXMintingClaim(ctx, cdp) -} - -// BeforeCDPModified function that runs before a cdp is modified -// note that this is called immediately after interest is synchronized, and so could potentially -// be called AfterCDPInterestUpdated or something like that, if we we're to expand the scope of cdp hooks -func (h Hooks) BeforeCDPModified(ctx sdk.Context, cdp cdptypes.CDP) { - h.k.SynchronizeUSDXMintingReward(ctx, cdp) -} -``` - -Hard module hooks manage the creation and synchronization of hard supply and borrow rewards. - -```go -// ------------------- Hard Module Hooks ------------------- - -// AfterDepositCreated function that runs after a deposit is created -func (h Hooks) AfterDepositCreated(ctx sdk.Context, deposit hardtypes.Deposit) { - h.k.InitializeHardSupplyReward(ctx, deposit) -} - -// BeforeDepositModified function that runs before a deposit is modified -func (h Hooks) BeforeDepositModified(ctx sdk.Context, deposit hardtypes.Deposit) { - h.k.SynchronizeHardSupplyReward(ctx, deposit) -} - -// AfterDepositModified function that runs after a deposit is modified -func (h Hooks) AfterDepositModified(ctx sdk.Context, deposit hardtypes.Deposit) { - h.k.UpdateHardSupplyIndexDenoms(ctx, deposit) -} - -// AfterBorrowCreated function that runs after a borrow is created -func (h Hooks) AfterBorrowCreated(ctx sdk.Context, borrow hardtypes.Borrow) { - h.k.InitializeHardBorrowReward(ctx, borrow) -} - -// BeforeBorrowModified function that runs before a borrow is modified -func (h Hooks) BeforeBorrowModified(ctx sdk.Context, borrow hardtypes.Borrow) { - h.k.SynchronizeHardBorrowReward(ctx, borrow) -} - -// AfterBorrowModified function that runs after a borrow is modified -func (h Hooks) AfterBorrowModified(ctx sdk.Context, borrow hardtypes.Borrow) { - h.k.UpdateHardBorrowIndexDenoms(ctx, borrow) -} -``` - -Staking module hooks manage the creation and synchronization of hard delegator rewards. - -```go -// ------------------- Staking Module Hooks ------------------- - -// BeforeDelegationCreated runs before a delegation is created -func (h Hooks) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.k.InitializeHardDelegatorReward(ctx, delAddr) -} - -// BeforeDelegationSharesModified runs before an existing delegation is modified -func (h Hooks) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.k.SynchronizeHardDelegatorRewards(ctx, delAddr) -} - -// NOTE: following hooks are just implemented to ensure StakingHooks interface compliance - -// BeforeValidatorSlashed is called before a validator is slashed -func (h Hooks) BeforeValidatorSlashed(ctx sdk.Context, valAddr sdk.ValAddress, fraction sdk.Dec) {} - -// AfterValidatorBeginUnbonding is called after a validator begins unbonding -func (h Hooks) AfterValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { -} - -// AfterValidatorBonded is called after a validator is bonded -func (h Hooks) AfterValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { -} - -// AfterDelegationModified runs after a delegation is modified -func (h Hooks) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { -} - -// BeforeDelegationRemoved runs directly before a delegation is deleted -func (h Hooks) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { -} - -// AfterValidatorCreated runs after a validator is created -func (h Hooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) {} - -// BeforeValidatorModified runs before a validator is modified -func (h Hooks) BeforeValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) {} - -// AfterValidatorRemoved runs after a validator is removed -func (h Hooks) AfterValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { -} -``` - -Swap module hooks manage the creation and synchronization of Swap protocol liquidity provider rewards. - -```go -// ------------------- Swap Module Hooks ------------------- - -func (h Hooks) AfterPoolDepositCreated(ctx sdk.Context, poolID string, depositor sdk.AccAddress, _ sdkmath.Int) { - h.k.InitializeSwapReward(ctx, poolID, depositor) -} - -func (h Hooks) BeforePoolDepositModified(ctx sdk.Context, poolID string, depositor sdk.AccAddress, sharesOwned sdkmath.Int) { - h.k.SynchronizeSwapReward(ctx, poolID, depositor, sharesOwned) -} -``` diff --git a/x/incentive/spec/07_begin_block.md b/x/incentive/spec/07_begin_block.md deleted file mode 100644 index b66af81b..00000000 --- a/x/incentive/spec/07_begin_block.md +++ /dev/null @@ -1,31 +0,0 @@ - - -# Begin Block - -At the start of each block, rewards are accumulated for each reward time. Accumulation refers to computing the total amount of rewards that have accumulated since the previous block and updating a global accumulator value such that whenever a `Claim` object is accessed, it is synchronized with the latest global state. This ensures that all rewards are accurately accounted for without having to iterate over each claim object in the begin blocker. - -```go -// BeginBlocker runs at the start of every block -func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { - - params := k.GetParams(ctx) - - for _, rp := range params.USDXMintingRewardPeriods { - k.AccumulateUSDXMintingRewards(ctx, rp) - } - for _, rp := range params.HardSupplyRewardPeriods { - k.AccumulateHardSupplyRewards(ctx, rp) - } - for _, rp := range params.HardBorrowRewardPeriods { - k.AccumulateHardBorrowRewards(ctx, rp) - } - for _, rp := range params.DelegatorRewardPeriods { - k.AccumulateDelegatorRewards(ctx, rp) - } - for _, rp := range params.SwapRewardPeriods { - k.AccumulateSwapRewards(ctx, rp) - } -} -``` diff --git a/x/incentive/spec/README.md b/x/incentive/spec/README.md deleted file mode 100644 index 0c1a5bb2..00000000 --- a/x/incentive/spec/README.md +++ /dev/null @@ -1,25 +0,0 @@ - - -# `incentive` - - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** -5. **[Params](05_params.md)** -6. **[Hooks](06_hooks.md)** -7. **[BeginBlock](07_begin_block.md)** - -## Abstract - -`x/incentive` is an implementation of a Cosmos SDK Module that allows for governance controlled user incentives for users who take certain actions, such as opening a collateralized debt position (CDP). Governance proposes an array of rewards, with each item representing a collateral type that will be eligible for rewards. Each collateral reward specifies the number of coins awarded per second, the length of rewards periods. Governance can alter the collateral rewards using parameter change proposals as well as adding or removing collateral types. All changes to parameters would take place in the _next_ period. User rewards are __opt in__, ie. users must claim rewards in order to receive them. If users fail to claim rewards before the claim period expiry, they are no longer eligible for rewards. - -### Dependencies - -This module uses hooks to update user rewards. Currently, `incentive` implements hooks from the `cdp`, `hard`, `swap`, and `staking` (comsos-sdk) modules. All rewards are paid out from the `kavadist` module account. diff --git a/x/incentive/testutil/builder.go b/x/incentive/testutil/builder.go deleted file mode 100644 index e6ff5789..00000000 --- a/x/incentive/testutil/builder.go +++ /dev/null @@ -1,343 +0,0 @@ -package testutil - -import ( - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - hardtypes "github.com/kava-labs/kava/x/hard/types" - "github.com/kava-labs/kava/x/incentive/types" - savingstypes "github.com/kava-labs/kava/x/savings/types" -) - -const ( - oneYear time.Duration = time.Hour * 24 * 365 -) - -type GenesisBuilder interface { - BuildMarshalled(cdc codec.JSONCodec) app.GenesisState -} - -// IncentiveGenesisBuilder is a tool for creating an incentive genesis state. -// Helper methods add values onto a default genesis state. -// All methods are immutable and return updated copies of the builder. -type IncentiveGenesisBuilder struct { - types.GenesisState - genesisTime time.Time -} - -func NewIncentiveGenesisBuilder() IncentiveGenesisBuilder { - return IncentiveGenesisBuilder{ - GenesisState: types.DefaultGenesisState(), - genesisTime: time.Time{}, - } -} - -func (builder IncentiveGenesisBuilder) Build() types.GenesisState { - return builder.GenesisState -} - -func (builder IncentiveGenesisBuilder) BuildMarshalled(cdc codec.JSONCodec) app.GenesisState { - built := builder.Build() - - return app.GenesisState{ - types.ModuleName: cdc.MustMarshalJSON(&built), - } -} - -func (builder IncentiveGenesisBuilder) WithGenesisTime(time time.Time) IncentiveGenesisBuilder { - builder.genesisTime = time - builder.Params.ClaimEnd = time.Add(5 * oneYear) - return builder -} - -// WithInitializedBorrowRewardPeriod sets the genesis time as the previous accumulation time for the specified period. -// This can be helpful in tests. With no prev time set, the first block accrues no rewards as it just sets the prev time to the current. -func (builder IncentiveGenesisBuilder) WithInitializedBorrowRewardPeriod(period types.MultiRewardPeriod) IncentiveGenesisBuilder { - builder.Params.HardBorrowRewardPeriods = append(builder.Params.HardBorrowRewardPeriods, period) - - accumulationTimeForPeriod := types.NewAccumulationTime(period.CollateralType, builder.genesisTime) - builder.HardBorrowRewardState.AccumulationTimes = append( - builder.HardBorrowRewardState.AccumulationTimes, - accumulationTimeForPeriod, - ) - - // TODO remove to better reflect real states - builder.HardBorrowRewardState.MultiRewardIndexes = builder.HardBorrowRewardState.MultiRewardIndexes.With( - period.CollateralType, - newZeroRewardIndexesFromCoins(period.RewardsPerSecond...), - ) - - return builder -} - -func (builder IncentiveGenesisBuilder) WithSimpleBorrowRewardPeriod(ctype string, rewardsPerSecond sdk.Coins) IncentiveGenesisBuilder { - return builder.WithInitializedBorrowRewardPeriod(builder.simpleRewardPeriod(ctype, rewardsPerSecond)) -} - -// WithInitializedSupplyRewardPeriod sets the genesis time as the previous accumulation time for the specified period. -// This can be helpful in tests. With no prev time set, the first block accrues no rewards as it just sets the prev time to the current. -func (builder IncentiveGenesisBuilder) WithInitializedSupplyRewardPeriod(period types.MultiRewardPeriod) IncentiveGenesisBuilder { - builder.Params.HardSupplyRewardPeriods = append(builder.Params.HardSupplyRewardPeriods, period) - - accumulationTimeForPeriod := types.NewAccumulationTime(period.CollateralType, builder.genesisTime) - builder.HardSupplyRewardState.AccumulationTimes = append( - builder.HardSupplyRewardState.AccumulationTimes, - accumulationTimeForPeriod, - ) - - // TODO remove to better reflect real states - builder.HardSupplyRewardState.MultiRewardIndexes = builder.HardSupplyRewardState.MultiRewardIndexes.With( - period.CollateralType, - newZeroRewardIndexesFromCoins(period.RewardsPerSecond...), - ) - - return builder -} - -func (builder IncentiveGenesisBuilder) WithSimpleSupplyRewardPeriod(ctype string, rewardsPerSecond sdk.Coins) IncentiveGenesisBuilder { - return builder.WithInitializedSupplyRewardPeriod(builder.simpleRewardPeriod(ctype, rewardsPerSecond)) -} - -// WithInitializedDelegatorRewardPeriod sets the genesis time as the previous accumulation time for the specified period. -// This can be helpful in tests. With no prev time set, the first block accrues no rewards as it just sets the prev time to the current. -func (builder IncentiveGenesisBuilder) WithInitializedDelegatorRewardPeriod(period types.MultiRewardPeriod) IncentiveGenesisBuilder { - builder.Params.DelegatorRewardPeriods = append(builder.Params.DelegatorRewardPeriods, period) - - accumulationTimeForPeriod := types.NewAccumulationTime(period.CollateralType, builder.genesisTime) - builder.DelegatorRewardState.AccumulationTimes = append( - builder.DelegatorRewardState.AccumulationTimes, - accumulationTimeForPeriod, - ) - - // TODO remove to better reflect real states - builder.DelegatorRewardState.MultiRewardIndexes = builder.DelegatorRewardState.MultiRewardIndexes.With( - period.CollateralType, - newZeroRewardIndexesFromCoins(period.RewardsPerSecond...), - ) - - return builder -} - -func (builder IncentiveGenesisBuilder) WithSimpleDelegatorRewardPeriod(ctype string, rewardsPerSecond sdk.Coins) IncentiveGenesisBuilder { - return builder.WithInitializedDelegatorRewardPeriod(builder.simpleRewardPeriod(ctype, rewardsPerSecond)) -} - -// WithInitializedSwapRewardPeriod sets the genesis time as the previous accumulation time for the specified period. -// This can be helpful in tests. With no prev time set, the first block accrues no rewards as it just sets the prev time to the current. -func (builder IncentiveGenesisBuilder) WithInitializedSwapRewardPeriod(period types.MultiRewardPeriod) IncentiveGenesisBuilder { - builder.Params.SwapRewardPeriods = append(builder.Params.SwapRewardPeriods, period) - - accumulationTimeForPeriod := types.NewAccumulationTime(period.CollateralType, builder.genesisTime) - builder.SwapRewardState.AccumulationTimes = append( - builder.SwapRewardState.AccumulationTimes, - accumulationTimeForPeriod, - ) - - return builder -} - -func (builder IncentiveGenesisBuilder) WithSimpleSwapRewardPeriod(poolID string, rewardsPerSecond sdk.Coins) IncentiveGenesisBuilder { - return builder.WithInitializedSwapRewardPeriod(builder.simpleRewardPeriod(poolID, rewardsPerSecond)) -} - -// WithInitializedUSDXRewardPeriod sets the genesis time as the previous accumulation time for the specified period. -// This can be helpful in tests. With no prev time set, the first block accrues no rewards as it just sets the prev time to the current. -func (builder IncentiveGenesisBuilder) WithInitializedUSDXRewardPeriod(period types.RewardPeriod) IncentiveGenesisBuilder { - builder.Params.USDXMintingRewardPeriods = append(builder.Params.USDXMintingRewardPeriods, period) - - accumulationTimeForPeriod := types.NewAccumulationTime(period.CollateralType, builder.genesisTime) - builder.USDXRewardState.AccumulationTimes = append( - builder.USDXRewardState.AccumulationTimes, - accumulationTimeForPeriod, - ) - - // TODO remove to better reflect real states - builder.USDXRewardState.MultiRewardIndexes = builder.USDXRewardState.MultiRewardIndexes.With( - period.CollateralType, - newZeroRewardIndexesFromCoins(period.RewardsPerSecond), - ) - - return builder -} - -func (builder IncentiveGenesisBuilder) WithSimpleUSDXRewardPeriod(ctype string, rewardsPerSecond sdk.Coin) IncentiveGenesisBuilder { - return builder.WithInitializedUSDXRewardPeriod(types.NewRewardPeriod( - true, - ctype, - builder.genesisTime, - builder.genesisTime.Add(4*oneYear), - rewardsPerSecond, - )) -} - -// WithInitializedEarnRewardPeriod sets the genesis time as the previous accumulation time for the specified period. -// This can be helpful in tests. With no prev time set, the first block accrues no rewards as it just sets the prev time to the current. -func (builder IncentiveGenesisBuilder) WithInitializedEarnRewardPeriod(period types.MultiRewardPeriod) IncentiveGenesisBuilder { - builder.Params.EarnRewardPeriods = append(builder.Params.EarnRewardPeriods, period) - - accumulationTimeForPeriod := types.NewAccumulationTime(period.CollateralType, builder.genesisTime) - builder.EarnRewardState.AccumulationTimes = append( - builder.EarnRewardState.AccumulationTimes, - accumulationTimeForPeriod, - ) - - return builder -} - -func (builder IncentiveGenesisBuilder) WithSimpleEarnRewardPeriod(ctype string, rewardsPerSecond sdk.Coins) IncentiveGenesisBuilder { - return builder.WithInitializedEarnRewardPeriod(builder.simpleRewardPeriod(ctype, rewardsPerSecond)) -} - -func (builder IncentiveGenesisBuilder) WithMultipliers(multipliers types.MultipliersPerDenoms) IncentiveGenesisBuilder { - builder.Params.ClaimMultipliers = multipliers - - return builder -} - -func (builder IncentiveGenesisBuilder) simpleRewardPeriod(ctype string, rewardsPerSecond sdk.Coins) types.MultiRewardPeriod { - return types.NewMultiRewardPeriod( - true, - ctype, - builder.genesisTime, - builder.genesisTime.Add(4*oneYear), - rewardsPerSecond, - ) -} - -func newZeroRewardIndexesFromCoins(coins ...sdk.Coin) types.RewardIndexes { - var ri types.RewardIndexes - for _, coin := range coins { - ri = ri.With(coin.Denom, sdk.ZeroDec()) - } - return ri -} - -// HardGenesisBuilder is a tool for creating a hard genesis state. -// Helper methods add values onto a default genesis state. -// All methods are immutable and return updated copies of the builder. -type HardGenesisBuilder struct { - hardtypes.GenesisState - genesisTime time.Time -} - -func NewHardGenesisBuilder() HardGenesisBuilder { - return HardGenesisBuilder{ - GenesisState: hardtypes.DefaultGenesisState(), - } -} - -func (builder HardGenesisBuilder) Build() hardtypes.GenesisState { - return builder.GenesisState -} - -func (builder HardGenesisBuilder) BuildMarshalled(cdc codec.JSONCodec) app.GenesisState { - built := builder.Build() - - return app.GenesisState{ - hardtypes.ModuleName: cdc.MustMarshalJSON(&built), - } -} - -func (builder HardGenesisBuilder) WithGenesisTime(genTime time.Time) HardGenesisBuilder { - builder.genesisTime = genTime - return builder -} - -func (builder HardGenesisBuilder) WithInitializedMoneyMarket(market hardtypes.MoneyMarket) HardGenesisBuilder { - builder.Params.MoneyMarkets = append(builder.Params.MoneyMarkets, market) - - builder.PreviousAccumulationTimes = append( - builder.PreviousAccumulationTimes, - hardtypes.NewGenesisAccumulationTime(market.Denom, builder.genesisTime, sdk.OneDec(), sdk.OneDec()), - ) - return builder -} - -func (builder HardGenesisBuilder) WithMinBorrow(minUSDValue sdk.Dec) HardGenesisBuilder { - builder.Params.MinimumBorrowUSDValue = minUSDValue - return builder -} - -func NewStandardMoneyMarket(denom string) hardtypes.MoneyMarket { - return hardtypes.NewMoneyMarket( - denom, - hardtypes.NewBorrowLimit( - false, - sdk.NewDec(1e15), - sdk.MustNewDecFromStr("0.6"), - ), - denom+":usd", - sdkmath.NewInt(1e6), - hardtypes.NewInterestRateModel( - sdk.MustNewDecFromStr("0.05"), - sdk.MustNewDecFromStr("2"), - sdk.MustNewDecFromStr("0.8"), - sdk.MustNewDecFromStr("10"), - ), - sdk.MustNewDecFromStr("0.05"), - sdk.ZeroDec(), - ) -} - -// WithInitializedSavingsRewardPeriod sets the genesis time as the previous accumulation time for the specified period. -// This can be helpful in tests. With no prev time set, the first block accrues no rewards as it just sets the prev time to the current. -func (builder IncentiveGenesisBuilder) WithInitializedSavingsRewardPeriod(period types.MultiRewardPeriod) IncentiveGenesisBuilder { - builder.Params.SavingsRewardPeriods = append(builder.Params.SavingsRewardPeriods, period) - - accumulationTimeForPeriod := types.NewAccumulationTime(period.CollateralType, builder.genesisTime) - builder.SavingsRewardState.AccumulationTimes = append( - builder.SavingsRewardState.AccumulationTimes, - accumulationTimeForPeriod, - ) - - builder.SavingsRewardState.MultiRewardIndexes = builder.SavingsRewardState.MultiRewardIndexes.With( - period.CollateralType, - newZeroRewardIndexesFromCoins(period.RewardsPerSecond...), - ) - - return builder -} - -func (builder IncentiveGenesisBuilder) WithSimpleSavingsRewardPeriod(ctype string, rewardsPerSecond sdk.Coins) IncentiveGenesisBuilder { - return builder.WithInitializedSavingsRewardPeriod(builder.simpleRewardPeriod(ctype, rewardsPerSecond)) -} - -// SavingsGenesisBuilder is a tool for creating a savings genesis state. -// Helper methods add values onto a default genesis state. -// All methods are immutable and return updated copies of the builder. -type SavingsGenesisBuilder struct { - savingstypes.GenesisState - genesisTime time.Time -} - -func NewSavingsGenesisBuilder() SavingsGenesisBuilder { - return SavingsGenesisBuilder{ - GenesisState: savingstypes.DefaultGenesisState(), - } -} - -func (builder SavingsGenesisBuilder) Build() savingstypes.GenesisState { - return builder.GenesisState -} - -func (builder SavingsGenesisBuilder) BuildMarshalled(cdc codec.JSONCodec) app.GenesisState { - built := builder.Build() - - return app.GenesisState{ - savingstypes.ModuleName: cdc.MustMarshalJSON(&built), - } -} - -func (builder SavingsGenesisBuilder) WithGenesisTime(genTime time.Time) SavingsGenesisBuilder { - builder.genesisTime = genTime - return builder -} - -func (builder SavingsGenesisBuilder) WithSupportedDenoms(denoms ...string) SavingsGenesisBuilder { - builder.Params.SupportedDenoms = append(builder.Params.SupportedDenoms, denoms...) - return builder -} diff --git a/x/incentive/testutil/earn_builder.go b/x/incentive/testutil/earn_builder.go deleted file mode 100644 index 010ab057..00000000 --- a/x/incentive/testutil/earn_builder.go +++ /dev/null @@ -1,40 +0,0 @@ -package testutil - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/kava-labs/kava/app" - - earntypes "github.com/kava-labs/kava/x/earn/types" -) - -// EarnGenesisBuilder is a tool for creating a earn genesis state. -// Helper methods add values onto a default genesis state. -// All methods are immutable and return updated copies of the builder. -type EarnGenesisBuilder struct { - earntypes.GenesisState -} - -var _ GenesisBuilder = (*EarnGenesisBuilder)(nil) - -func NewEarnGenesisBuilder() EarnGenesisBuilder { - return EarnGenesisBuilder{ - GenesisState: earntypes.DefaultGenesisState(), - } -} - -func (builder EarnGenesisBuilder) Build() earntypes.GenesisState { - return builder.GenesisState -} - -func (builder EarnGenesisBuilder) BuildMarshalled(cdc codec.JSONCodec) app.GenesisState { - built := builder.Build() - - return app.GenesisState{ - earntypes.ModuleName: cdc.MustMarshalJSON(&built), - } -} - -func (builder EarnGenesisBuilder) WithAllowedVaults(vault ...earntypes.AllowedVault) EarnGenesisBuilder { - builder.Params.AllowedVaults = append(builder.Params.AllowedVaults, vault...) - return builder -} diff --git a/x/incentive/testutil/integration.go b/x/incentive/testutil/integration.go deleted file mode 100644 index 549a2105..00000000 --- a/x/incentive/testutil/integration.go +++ /dev/null @@ -1,602 +0,0 @@ -package testutil - -import ( - "errors" - "fmt" - "time" - - sdkmath "cosmossdk.io/math" - abcitypes "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - proposaltypes "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - cdpkeeper "github.com/kava-labs/kava/x/cdp/keeper" - cdptypes "github.com/kava-labs/kava/x/cdp/types" - committeekeeper "github.com/kava-labs/kava/x/committee/keeper" - committeetypes "github.com/kava-labs/kava/x/committee/types" - earnkeeper "github.com/kava-labs/kava/x/earn/keeper" - earntypes "github.com/kava-labs/kava/x/earn/types" - hardkeeper "github.com/kava-labs/kava/x/hard/keeper" - hardtypes "github.com/kava-labs/kava/x/hard/types" - incentivekeeper "github.com/kava-labs/kava/x/incentive/keeper" - "github.com/kava-labs/kava/x/incentive/types" - liquidkeeper "github.com/kava-labs/kava/x/liquid/keeper" - liquidtypes "github.com/kava-labs/kava/x/liquid/types" - routerkeeper "github.com/kava-labs/kava/x/router/keeper" - routertypes "github.com/kava-labs/kava/x/router/types" - swapkeeper "github.com/kava-labs/kava/x/swap/keeper" - swaptypes "github.com/kava-labs/kava/x/swap/types" -) - -type IntegrationTester struct { - suite.Suite - App app.TestApp - Ctx sdk.Context - - GenesisTime time.Time -} - -func (suite *IntegrationTester) SetupSuite() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - // Default genesis time, can be overridden with WithGenesisTime - suite.GenesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *IntegrationTester) SetApp() { - suite.App = app.NewTestApp() -} - -func (suite *IntegrationTester) SetupTest() { - suite.SetApp() -} - -func (suite *IntegrationTester) WithGenesisTime(genesisTime time.Time) { - suite.GenesisTime = genesisTime -} - -func (suite *IntegrationTester) StartChainWithBuilders(builders ...GenesisBuilder) { - var builtGenStates []app.GenesisState - for _, builder := range builders { - builtGenStates = append(builtGenStates, builder.BuildMarshalled(suite.App.AppCodec())) - } - - suite.StartChain(builtGenStates...) -} - -func (suite *IntegrationTester) StartChain(genesisStates ...app.GenesisState) { - suite.App.InitializeFromGenesisStatesWithTimeAndChainID( - suite.GenesisTime, - app.TestChainId, - genesisStates..., - ) - - suite.Ctx = suite.App.NewContext(false, tmproto.Header{ - Height: 1, - Time: suite.GenesisTime, - ChainID: app.TestChainId, - }) -} - -func (suite *IntegrationTester) NextBlockAfter(blockDuration time.Duration) { - suite.NextBlockAfterWithReq( - blockDuration, - abcitypes.RequestEndBlock{}, - abcitypes.RequestBeginBlock{}, - ) -} - -func (suite *IntegrationTester) NextBlockAfterWithReq( - blockDuration time.Duration, - reqEnd abcitypes.RequestEndBlock, - reqBegin abcitypes.RequestBeginBlock, -) (abcitypes.ResponseEndBlock, abcitypes.ResponseBeginBlock) { - return suite.NextBlockAtWithRequest( - suite.Ctx.BlockTime().Add(blockDuration), - reqEnd, - reqBegin, - ) -} - -func (suite *IntegrationTester) NextBlockAt( - blockTime time.Time, -) (abcitypes.ResponseEndBlock, abcitypes.ResponseBeginBlock) { - return suite.NextBlockAtWithRequest( - blockTime, - abcitypes.RequestEndBlock{}, - abcitypes.RequestBeginBlock{}, - ) -} - -func (suite *IntegrationTester) NextBlockAtWithRequest( - blockTime time.Time, - reqEnd abcitypes.RequestEndBlock, - reqBegin abcitypes.RequestBeginBlock, -) (abcitypes.ResponseEndBlock, abcitypes.ResponseBeginBlock) { - if !suite.Ctx.BlockTime().Before(blockTime) { - panic(fmt.Sprintf("new block time %s must be after current %s", blockTime, suite.Ctx.BlockTime())) - } - blockHeight := suite.Ctx.BlockHeight() + 1 - - responseEndBlock := suite.App.EndBlocker(suite.Ctx, reqEnd) - suite.Ctx = suite.Ctx.WithBlockTime(blockTime).WithBlockHeight(blockHeight).WithChainID(app.TestChainId) - responseBeginBlock := suite.App.BeginBlocker(suite.Ctx, reqBegin) // height and time in RequestBeginBlock are ignored by module begin blockers - - return responseEndBlock, responseBeginBlock -} - -func (suite *IntegrationTester) DeliverIncentiveMsg(msg sdk.Msg) error { - msgServer := incentivekeeper.NewMsgServerImpl(suite.App.GetIncentiveKeeper()) - - var err error - - switch msg := msg.(type) { - case *types.MsgClaimHardReward: - _, err = msgServer.ClaimHardReward(sdk.WrapSDKContext(suite.Ctx), msg) - case *types.MsgClaimSwapReward: - _, err = msgServer.ClaimSwapReward(sdk.WrapSDKContext(suite.Ctx), msg) - case *types.MsgClaimUSDXMintingReward: - _, err = msgServer.ClaimUSDXMintingReward(sdk.WrapSDKContext(suite.Ctx), msg) - case *types.MsgClaimDelegatorReward: - _, err = msgServer.ClaimDelegatorReward(sdk.WrapSDKContext(suite.Ctx), msg) - case *types.MsgClaimEarnReward: - _, err = msgServer.ClaimEarnReward(sdk.WrapSDKContext(suite.Ctx), msg) - default: - panic("unhandled incentive msg") - } - - return err -} - -// MintLiquidAnyValAddr mints liquid tokens with the given validator address, -// creating the validator if it does not already exist. -// **Note:** This will increment the block height/time and run the End and Begin -// blockers! -func (suite *IntegrationTester) MintLiquidAnyValAddr( - owner sdk.AccAddress, - validator sdk.ValAddress, - amount sdk.Coin, -) (sdk.Coin, error) { - // Check if validator already created - _, found := suite.App.GetStakingKeeper().GetValidator(suite.Ctx, validator) - if !found { - // Create validator - if err := suite.DeliverMsgCreateValidator(validator, sdk.NewCoin("ukava", sdkmath.NewInt(1e9))); err != nil { - return sdk.Coin{}, err - } - - // new block required to bond validator - suite.NextBlockAfter(7 * time.Second) - } - - // Delegate and mint liquid tokens - return suite.DeliverMsgDelegateMint(owner, validator, amount) -} - -func (suite *IntegrationTester) GetAbciValidator(valAddr sdk.ValAddress) abcitypes.Validator { - sk := suite.App.GetStakingKeeper() - - val, found := sk.GetValidator(suite.Ctx, valAddr) - suite.Require().True(found) - - pk, err := val.ConsPubKey() - suite.Require().NoError(err) - - return abcitypes.Validator{ - Address: pk.Address(), - Power: val.GetConsensusPower(sk.PowerReduction(suite.Ctx)), - } -} - -func (suite *IntegrationTester) DeliverMsgCreateValidator(address sdk.ValAddress, selfDelegation sdk.Coin) error { - msg, err := stakingtypes.NewMsgCreateValidator( - address, - ed25519.GenPrivKey().PubKey(), - selfDelegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - sdkmath.NewInt(1_000_000), - ) - if err != nil { - return err - } - - msgServer := stakingkeeper.NewMsgServerImpl(suite.App.GetStakingKeeper()) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.Ctx), msg) - - return err -} - -func (suite *IntegrationTester) DeliverMsgDelegate(delegator sdk.AccAddress, validator sdk.ValAddress, amount sdk.Coin) error { - msg := stakingtypes.NewMsgDelegate( - delegator, - validator, - amount, - ) - msgServer := stakingkeeper.NewMsgServerImpl(suite.App.GetStakingKeeper()) - _, err := msgServer.Delegate(sdk.WrapSDKContext(suite.Ctx), msg) - return err -} - -func (suite *IntegrationTester) DeliverSwapMsgDeposit(depositor sdk.AccAddress, tokenA, tokenB sdk.Coin, slippage sdk.Dec) error { - msg := swaptypes.NewMsgDeposit( - depositor.String(), - tokenA, - tokenB, - slippage, - suite.Ctx.BlockTime().Add(time.Hour).Unix(), // ensure msg will not fail due to short deadline - ) - msgServer := swapkeeper.NewMsgServerImpl(suite.App.GetSwapKeeper()) - _, err := msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), msg) - - return err -} - -func (suite *IntegrationTester) DeliverHardMsgDeposit(owner sdk.AccAddress, deposit sdk.Coins) error { - msg := hardtypes.NewMsgDeposit(owner, deposit) - msgServer := hardkeeper.NewMsgServerImpl(suite.App.GetHardKeeper()) - - _, err := msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverHardMsgBorrow(owner sdk.AccAddress, borrow sdk.Coins) error { - msg := hardtypes.NewMsgBorrow(owner, borrow) - msgServer := hardkeeper.NewMsgServerImpl(suite.App.GetHardKeeper()) - - _, err := msgServer.Borrow(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverHardMsgRepay(owner sdk.AccAddress, repay sdk.Coins) error { - msg := hardtypes.NewMsgRepay(owner, owner, repay) - msgServer := hardkeeper.NewMsgServerImpl(suite.App.GetHardKeeper()) - - _, err := msgServer.Repay(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverHardMsgWithdraw(owner sdk.AccAddress, withdraw sdk.Coins) error { - msg := hardtypes.NewMsgWithdraw(owner, withdraw) - msgServer := hardkeeper.NewMsgServerImpl(suite.App.GetHardKeeper()) - - _, err := msgServer.Withdraw(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverMsgCreateCDP(owner sdk.AccAddress, collateral, principal sdk.Coin, collateralType string) error { - msg := cdptypes.NewMsgCreateCDP(owner, collateral, principal, collateralType) - msgServer := cdpkeeper.NewMsgServerImpl(suite.App.GetCDPKeeper()) - - _, err := msgServer.CreateCDP(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverCDPMsgRepay(owner sdk.AccAddress, collateralType string, payment sdk.Coin) error { - msg := cdptypes.NewMsgRepayDebt(owner, collateralType, payment) - msgServer := cdpkeeper.NewMsgServerImpl(suite.App.GetCDPKeeper()) - - _, err := msgServer.RepayDebt(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverCDPMsgBorrow(owner sdk.AccAddress, collateralType string, draw sdk.Coin) error { - msg := cdptypes.NewMsgDrawDebt(owner, collateralType, draw) - msgServer := cdpkeeper.NewMsgServerImpl(suite.App.GetCDPKeeper()) - - _, err := msgServer.DrawDebt(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverMsgMintDerivative( - sender sdk.AccAddress, - validator sdk.ValAddress, - amount sdk.Coin, -) (sdk.Coin, error) { - msg := liquidtypes.NewMsgMintDerivative(sender, validator, amount) - msgServer := liquidkeeper.NewMsgServerImpl(suite.App.GetLiquidKeeper()) - - res, err := msgServer.MintDerivative(sdk.WrapSDKContext(suite.Ctx), &msg) - if err != nil { - // Instead of returning res.Received, as res will be nil if there is an error - return sdk.Coin{}, err - } - - return res.Received, err -} - -func (suite *IntegrationTester) DeliverEarnMsgDeposit( - depositor sdk.AccAddress, - amount sdk.Coin, - strategy earntypes.StrategyType, -) error { - msg := earntypes.NewMsgDeposit(depositor.String(), amount, strategy) - msgServer := earnkeeper.NewMsgServerImpl(suite.App.GetEarnKeeper()) - - _, err := msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), msg) - return err -} - -func (suite *IntegrationTester) ProposeAndVoteOnNewParams(voter sdk.AccAddress, committeeID uint64, changes []proposaltypes.ParamChange) { - propose, err := committeetypes.NewMsgSubmitProposal( - proposaltypes.NewParameterChangeProposal( - "test title", - "test description", - changes, - ), - voter, - committeeID, - ) - suite.NoError(err) - - msgServer := committeekeeper.NewMsgServerImpl(suite.App.GetCommitteeKeeper()) - - res, err := msgServer.SubmitProposal(sdk.WrapSDKContext(suite.Ctx), propose) - suite.NoError(err) - - proposalID := res.ProposalID - vote := committeetypes.NewMsgVote(voter, proposalID, committeetypes.VOTE_TYPE_YES) - _, err = msgServer.Vote(sdk.WrapSDKContext(suite.Ctx), vote) - suite.NoError(err) -} - -func (suite *IntegrationTester) GetAccount(addr sdk.AccAddress) authtypes.AccountI { - ak := suite.App.GetAccountKeeper() - return ak.GetAccount(suite.Ctx, addr) -} - -func (suite *IntegrationTester) GetModuleAccount(name string) authtypes.ModuleAccountI { - ak := suite.App.GetAccountKeeper() - return ak.GetModuleAccount(suite.Ctx, name) -} - -func (suite *IntegrationTester) GetBalance(address sdk.AccAddress) sdk.Coins { - bk := suite.App.GetBankKeeper() - return bk.GetAllBalances(suite.Ctx, address) -} - -func (suite *IntegrationTester) ErrorIs(err, target error) bool { - return suite.Truef(errors.Is(err, target), "err didn't match: %s, it was: %s", target, err) -} - -func (suite *IntegrationTester) BalanceEquals(address sdk.AccAddress, expected sdk.Coins) { - bk := suite.App.GetBankKeeper() - suite.Equalf( - expected, - bk.GetAllBalances(suite.Ctx, address), - "expected account balance to equal coins %s, but got %s", - expected, - bk.GetAllBalances(suite.Ctx, address), - ) -} - -func (suite *IntegrationTester) BalanceInEpsilon(address sdk.AccAddress, expected sdk.Coins, epsilon float64) { - actual := suite.GetBalance(address) - - allDenoms := expected.Add(actual...) - for _, coin := range allDenoms { - suite.InEpsilonf( - expected.AmountOf(coin.Denom).Int64(), - actual.AmountOf(coin.Denom).Int64(), - epsilon, - "expected balance to be within %f%% of coins %s, but got %s", epsilon*100, expected, actual, - ) - } -} - -func (suite *IntegrationTester) VestingPeriodsEqual(address sdk.AccAddress, expectedPeriods []vestingtypes.Period) { - acc := suite.App.GetAccountKeeper().GetAccount(suite.Ctx, address) - suite.Require().NotNil(acc, "expected vesting account not to be nil") - vacc, ok := acc.(*vestingtypes.PeriodicVestingAccount) - suite.Require().True(ok, "expected vesting account to be type PeriodicVestingAccount") - suite.Equal(expectedPeriods, vacc.VestingPeriods) -} - -// ----------------------------------------------------------------------------- -// x/incentive - -func (suite *IntegrationTester) SwapRewardEquals(owner sdk.AccAddress, expected sdk.Coins) { - claim, found := suite.App.GetIncentiveKeeper().GetSwapClaim(suite.Ctx, owner) - suite.Require().Truef(found, "expected swap claim to be found for %s", owner) - suite.Equalf(expected, claim.Reward, "expected swap claim reward to be %s, but got %s", expected, claim.Reward) -} - -func (suite *IntegrationTester) DelegatorRewardEquals(owner sdk.AccAddress, expected sdk.Coins) { - claim, found := suite.App.GetIncentiveKeeper().GetDelegatorClaim(suite.Ctx, owner) - suite.Require().Truef(found, "expected delegator claim to be found for %s", owner) - suite.Equalf(expected, claim.Reward, "expected delegator claim reward to be %s, but got %s", expected, claim.Reward) -} - -func (suite *IntegrationTester) HardRewardEquals(owner sdk.AccAddress, expected sdk.Coins) { - claim, found := suite.App.GetIncentiveKeeper().GetHardLiquidityProviderClaim(suite.Ctx, owner) - suite.Require().Truef(found, "expected delegator claim to be found for %s", owner) - suite.Equalf(expected, claim.Reward, "expected delegator claim reward to be %s, but got %s", expected, claim.Reward) -} - -func (suite *IntegrationTester) USDXRewardEquals(owner sdk.AccAddress, expected sdk.Coin) { - claim, found := suite.App.GetIncentiveKeeper().GetUSDXMintingClaim(suite.Ctx, owner) - suite.Require().Truef(found, "expected delegator claim to be found for %s", owner) - suite.Equalf(expected, claim.Reward, "expected delegator claim reward to be %s, but got %s", expected, claim.Reward) -} - -func (suite *IntegrationTester) EarnRewardEquals(owner sdk.AccAddress, expected sdk.Coins) { - claim, found := suite.App.GetIncentiveKeeper().GetEarnClaim(suite.Ctx, owner) - suite.Require().Truef(found, "expected earn claim to be found for %s", owner) - suite.Truef(expected.IsEqual(claim.Reward), "expected earn claim reward to be %s, but got %s", expected, claim.Reward) -} - -// AddTestAddrsFromPubKeys adds the addresses into the SimApp providing only the public keys. -func (suite *IntegrationTester) AddTestAddrsFromPubKeys(ctx sdk.Context, pubKeys []cryptotypes.PubKey, accAmt sdkmath.Int) { - initCoins := sdk.NewCoins(sdk.NewCoin(suite.App.GetStakingKeeper().BondDenom(ctx), accAmt)) - - for _, pk := range pubKeys { - suite.App.FundAccount(ctx, sdk.AccAddress(pk.Address()), initCoins) - } -} - -func (suite *IntegrationTester) StoredEarnTimeEquals(denom string, expected time.Time) { - storedTime, found := suite.App.GetIncentiveKeeper().GetEarnRewardAccrualTime(suite.Ctx, denom) - suite.Equal(found, expected != time.Time{}, "expected time is %v but time found = %v", expected, found) - if found { - suite.Equal(expected, storedTime) - } else { - suite.Empty(storedTime) - } -} - -func (suite *IntegrationTester) StoredEarnIndexesEqual(denom string, expected types.RewardIndexes) { - storedIndexes, found := suite.App.GetIncentiveKeeper().GetEarnRewardIndexes(suite.Ctx, denom) - suite.Equal(found, expected != nil) - - if found { - suite.Equal(expected, storedIndexes) - } else { - // Can't compare Equal for types.RewardIndexes(nil) vs types.RewardIndexes{} - suite.Empty(storedIndexes) - } -} - -func (suite *IntegrationTester) AddIncentiveEarnMultiRewardPeriod(period types.MultiRewardPeriod) { - ik := suite.App.GetIncentiveKeeper() - params := ik.GetParams(suite.Ctx) - - for i, reward := range params.EarnRewardPeriods { - if reward.CollateralType == period.CollateralType { - // Replace existing reward period if the collateralType exists. - // Params are invalid if there are multiple reward periods for the - // same collateral type. - params.EarnRewardPeriods[i] = period - ik.SetParams(suite.Ctx, params) - return - } - } - - params.EarnRewardPeriods = append(params.EarnRewardPeriods, period) - - suite.NoError(params.Validate()) - ik.SetParams(suite.Ctx, params) -} - -// ----------------------------------------------------------------------------- -// x/router - -func (suite *IntegrationTester) DeliverRouterMsgDelegateMintDeposit( - depositor sdk.AccAddress, - validator sdk.ValAddress, - amount sdk.Coin, -) error { - msg := routertypes.MsgDelegateMintDeposit{ - Depositor: depositor.String(), - Validator: validator.String(), - Amount: amount, - } - msgServer := routerkeeper.NewMsgServerImpl(suite.App.GetRouterKeeper()) - - _, err := msgServer.DelegateMintDeposit(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverRouterMsgMintDeposit( - depositor sdk.AccAddress, - validator sdk.ValAddress, - amount sdk.Coin, -) error { - msg := routertypes.MsgMintDeposit{ - Depositor: depositor.String(), - Validator: validator.String(), - Amount: amount, - } - msgServer := routerkeeper.NewMsgServerImpl(suite.App.GetRouterKeeper()) - - _, err := msgServer.MintDeposit(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverMsgDelegateMint( - delegator sdk.AccAddress, - validator sdk.ValAddress, - amount sdk.Coin, -) (sdk.Coin, error) { - if err := suite.DeliverMsgDelegate(delegator, validator, amount); err != nil { - return sdk.Coin{}, err - } - - return suite.DeliverMsgMintDerivative(delegator, validator, amount) -} - -// ----------------------------------------------------------------------------- -// x/distribution - -func (suite *IntegrationTester) GetBeginBlockClaimedStakingRewards( - resBeginBlock abcitypes.ResponseBeginBlock, -) (validatorRewards map[string]sdk.Coins, totalRewards sdk.Coins) { - // Events emitted in BeginBlocker are in the ResponseBeginBlock, not in - // ctx.EventManager().Events() as BeginBlock is called with a NewEventManager() - // cosmos-sdk/types/module/module.go: func(m *Manager) BeginBlock(...) - - // We also need to parse the events to get the rewards as querying state will - // always contain 0 rewards -- rewards are always claimed right after - // mint+distribution in BeginBlocker which resets distribution state back to - // 0 for reward amounts - blockRewardsClaimed := make(map[string]sdk.Coins) - for _, event := range resBeginBlock.Events { - if event.Type != distributiontypes.EventTypeWithdrawRewards { - continue - } - - // Example event attributes, amount can be empty for no rewards - // - // Event: withdraw_rewards - // - amount: - // - validator: kavavaloper1em2mlkrkx0qsa6327tgvl3g0fh8a95hjnqvrwh - // Event: withdraw_rewards - // - amount: 523909ukava - // - validator: kavavaloper1nmgpgr8l4t8pw9zqx9cltuymvz85wmw9sy8kjy - attrsMap := attrsToMap(event.Attributes) - - validator, found := attrsMap[distributiontypes.AttributeKeyValidator] - suite.Require().Truef(found, "expected validator attribute to be found in event %s", event) - - amountStr, found := attrsMap[sdk.AttributeKeyAmount] - suite.Require().Truef(found, "expected amount attribute to be found in event %s", event) - - amount := sdk.NewCoins() - - // Only parse amount if it is not empty - if len(amountStr) > 0 { - parsedAmt, err := sdk.ParseCoinNormalized(amountStr) - suite.Require().NoError(err) - amount = amount.Add(parsedAmt) - } - - blockRewardsClaimed[validator] = amount - } - - totalClaimedRewards := sdk.NewCoins() - for _, amount := range blockRewardsClaimed { - totalClaimedRewards = totalClaimedRewards.Add(amount...) - } - - return blockRewardsClaimed, totalClaimedRewards -} - -func attrsToMap(attrs []abcitypes.EventAttribute) map[string]string { - out := make(map[string]string) - - for _, attr := range attrs { - out[string(attr.Key)] = string(attr.Value) - } - - return out -} diff --git a/x/incentive/testutil/mint_builder.go b/x/incentive/testutil/mint_builder.go deleted file mode 100644 index 9c7bde74..00000000 --- a/x/incentive/testutil/mint_builder.go +++ /dev/null @@ -1,68 +0,0 @@ -package testutil - -import ( - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/app" - - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" -) - -// MintGenesisBuilder is a tool for creating a mint genesis state. -// Helper methods add values onto a default genesis state. -// All methods are immutable and return updated copies of the builder. -type MintGenesisBuilder struct { - minttypes.GenesisState -} - -var _ GenesisBuilder = (*MintGenesisBuilder)(nil) - -func NewMintGenesisBuilder() MintGenesisBuilder { - gen := minttypes.DefaultGenesisState() - gen.Params.MintDenom = "ukava" - - return MintGenesisBuilder{ - GenesisState: *gen, - } -} - -func (builder MintGenesisBuilder) Build() minttypes.GenesisState { - return builder.GenesisState -} - -func (builder MintGenesisBuilder) BuildMarshalled(cdc codec.JSONCodec) app.GenesisState { - built := builder.Build() - - return app.GenesisState{ - minttypes.ModuleName: cdc.MustMarshalJSON(&built), - } -} - -func (builder MintGenesisBuilder) WithMinter( - inflation sdk.Dec, - annualProvisions sdk.Dec, -) MintGenesisBuilder { - builder.Minter = minttypes.NewMinter(inflation, annualProvisions) - return builder -} - -func (builder MintGenesisBuilder) WithInflationMax( - inflationMax sdk.Dec, -) MintGenesisBuilder { - builder.Params.InflationMax = inflationMax - return builder -} - -func (builder MintGenesisBuilder) WithInflationMin( - inflationMin sdk.Dec, -) MintGenesisBuilder { - builder.Params.InflationMin = inflationMin - return builder -} - -func (builder MintGenesisBuilder) WithMintDenom( - mintDenom string, -) MintGenesisBuilder { - builder.Params.MintDenom = mintDenom - return builder -} diff --git a/x/incentive/testutil/staking_builder.go b/x/incentive/testutil/staking_builder.go deleted file mode 100644 index 7282fff6..00000000 --- a/x/incentive/testutil/staking_builder.go +++ /dev/null @@ -1,38 +0,0 @@ -package testutil - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/kava-labs/kava/app" - - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// StakingGenesisBuilder is a tool for creating a staking genesis state. -// Helper methods add values onto a default genesis state. -// All methods are immutable and return updated copies of the builder. -type StakingGenesisBuilder struct { - stakingtypes.GenesisState -} - -var _ GenesisBuilder = (*StakingGenesisBuilder)(nil) - -func NewStakingGenesisBuilder() StakingGenesisBuilder { - gen := stakingtypes.DefaultGenesisState() - gen.Params.BondDenom = "ukava" - - return StakingGenesisBuilder{ - GenesisState: *gen, - } -} - -func (builder StakingGenesisBuilder) Build() stakingtypes.GenesisState { - return builder.GenesisState -} - -func (builder StakingGenesisBuilder) BuildMarshalled(cdc codec.JSONCodec) app.GenesisState { - built := builder.Build() - - return app.GenesisState{ - stakingtypes.ModuleName: cdc.MustMarshalJSON(&built), - } -} diff --git a/x/incentive/types/accumulator.go b/x/incentive/types/accumulator.go deleted file mode 100644 index e9937cc8..00000000 --- a/x/incentive/types/accumulator.go +++ /dev/null @@ -1,144 +0,0 @@ -package types - -import ( - "fmt" - "math" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// An Accumulator handles calculating and tracking global reward distributions. -type Accumulator struct { - PreviousAccumulationTime time.Time - Indexes RewardIndexes -} - -func NewAccumulator(previousAccrual time.Time, indexes RewardIndexes) *Accumulator { - return &Accumulator{ - PreviousAccumulationTime: previousAccrual, - Indexes: indexes, - } -} - -// Accumulate accrues rewards up to the current time. -// -// It calculates new rewards and adds them to the reward indexes for the period from PreviousAccumulationTime to currentTime. -// It stores the currentTime in PreviousAccumulationTime to be used for later accumulations. -// -// Rewards are not accrued for times outside of the start and end times of a reward period. -// If a period ends before currentTime, the PreviousAccrualTime is shortened to the end time. This allows accumulate to be called sequentially on consecutive reward periods. -// -// totalSourceShares is the sum of all users' source shares. For example:total btcb supplied to hard, total usdx borrowed from all bnb CDPs, or total shares in a swap pool. -func (acc *Accumulator) Accumulate(period MultiRewardPeriod, totalSourceShares sdk.Dec, currentTime time.Time) { - acc.AccumulateDecCoins( - period.Start, - period.End, - sdk.NewDecCoinsFromCoins(period.RewardsPerSecond...), - totalSourceShares, - currentTime, - ) -} - -// AccumulateDecCoins -func (acc *Accumulator) AccumulateDecCoins( - periodStart time.Time, - periodEnd time.Time, - periodRewardsPerSecond sdk.DecCoins, - totalSourceShares sdk.Dec, - currentTime time.Time, -) { - accumulationDuration := acc.getTimeElapsedWithinLimits(acc.PreviousAccumulationTime, currentTime, periodStart, periodEnd) - - indexesIncrement := acc.calculateNewRewards(periodRewardsPerSecond, totalSourceShares, accumulationDuration) - - acc.Indexes = acc.Indexes.Add(indexesIncrement) - acc.PreviousAccumulationTime = minTime(periodEnd, currentTime) -} - -// getTimeElapsedWithinLimits returns the duration between start and end times, capped by min and max times. -// If the start and end range is outside the min to max time range then zero duration is returned. -func (*Accumulator) getTimeElapsedWithinLimits(start, end, limitMin, limitMax time.Time) time.Duration { - if start.After(end) { - panic(fmt.Sprintf("start time (%s) cannot be after end time (%s)", start, end)) - } - if limitMin.After(limitMax) { - panic(fmt.Sprintf("minimum limit time (%s) cannot be after maximum limit time (%s)", limitMin, limitMax)) - } - if start.After(limitMax) || end.Before(limitMin) { - // no intersection between the start-end and limitMin-limitMax time ranges - return 0 - } - return minTime(end, limitMax).Sub(maxTime(start, limitMin)) -} - -// calculateNewRewards calculates the amount to increase the global reward indexes by, for a given reward rate, duration, and number of source shares. -// The total rewards to distribute in this block are given by reward rate * duration. This value divided by the sum of all source shares to give -// total rewards per source share, which is what the indexes store. -// Note, duration is rounded to the nearest second to keep rewards calculation consistent with kava-7. -func (*Accumulator) calculateNewRewards(rewardsPerSecond sdk.DecCoins, totalSourceShares sdk.Dec, duration time.Duration) RewardIndexes { - if totalSourceShares.LTE(sdk.ZeroDec()) { - // When there is zero source shares, there is no users with deposits/borrows/delegations to pay out the current block's rewards to. - // So drop the rewards and pay out nothing. - return nil - } - durationSeconds := int64(math.RoundToEven(duration.Seconds())) - if durationSeconds <= 0 { - // If the duration is zero, there will be no increment. - // So return an empty increment instead of one full of zeros. - return nil - } - increment := NewRewardIndexesFromCoins(rewardsPerSecond) - increment = increment.Mul(sdk.NewDec(durationSeconds)).Quo(totalSourceShares) - return increment -} - -// minTime returns the earliest of two times. -func minTime(t1, t2 time.Time) time.Time { - if t2.Before(t1) { - return t2 - } - return t1 -} - -// maxTime returns the latest of two times. -func maxTime(t1, t2 time.Time) time.Time { - if t2.After(t1) { - return t2 - } - return t1 -} - -// NewRewardIndexesFromCoins is a helper function to initialize a RewardIndexes slice with the values from a Coins slice. -func NewRewardIndexesFromCoins(coins sdk.DecCoins) RewardIndexes { - var indexes RewardIndexes - for _, coin := range coins { - indexes = append(indexes, NewRewardIndex(coin.Denom, coin.Amount)) - } - return indexes -} - -func CalculatePerSecondRewards( - periodStart time.Time, - periodEnd time.Time, - periodRewardsPerSecond sdk.DecCoins, - previousTime, currentTime time.Time, -) (sdk.DecCoins, time.Time) { - duration := (&Accumulator{}).getTimeElapsedWithinLimits( - previousTime, - currentTime, - periodStart, - periodEnd, - ) - - upTo := minTime(periodEnd, currentTime) - - durationSeconds := int64(math.RoundToEven(duration.Seconds())) - if durationSeconds <= 0 { - // If the duration is zero, there will be no increment. - // So return an empty increment instead of one full of zeros. - return nil, upTo // TODO - } - - return periodRewardsPerSecond.MulDec(sdk.NewDec(durationSeconds)), upTo -} diff --git a/x/incentive/types/accumulator_test.go b/x/incentive/types/accumulator_test.go deleted file mode 100644 index f1792847..00000000 --- a/x/incentive/types/accumulator_test.go +++ /dev/null @@ -1,413 +0,0 @@ -package types - -import ( - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestAccumulator(t *testing.T) { - t.Run("getTimeElapsedWithinLimits", func(t *testing.T) { - type args struct { - start, end time.Time - limitMin, limitMax time.Time - } - testcases := []struct { - name string - args args - expected time.Duration - }{ - { - name: "given time range is before limits and is non zero, return 0 duration", - args: args{ - start: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - end: time.Date(1998, 1, 1, 0, 0, 1, 0, time.UTC), - limitMin: time.Date(2098, 1, 1, 0, 0, 0, 0, time.UTC), - limitMax: time.Date(2098, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: 0, - }, - { - name: "given time range is after limits and is non zero, return 0 duration", - args: args{ - start: time.Date(2098, 1, 1, 0, 0, 0, 0, time.UTC), - end: time.Date(2098, 1, 1, 0, 0, 1, 0, time.UTC), - limitMin: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - limitMax: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: 0, - }, - { - name: "given time range is within limits and is non zero, return duration", - args: args{ - start: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - end: time.Date(1998, 1, 1, 0, 0, 1, 0, time.UTC), - limitMin: time.Date(1990, 1, 1, 0, 0, 0, 0, time.UTC), - limitMax: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: time.Second, - }, - { - name: "given time range is within limits and is zero, return 0 duration", - args: args{ - start: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - end: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - limitMin: time.Date(1990, 1, 1, 0, 0, 0, 0, time.UTC), - limitMax: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: 0, - }, - { - name: "given time range overlaps limitMax and is non zero, return capped duration", - args: args{ - start: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - end: time.Date(1998, 1, 1, 0, 0, 2, 0, time.UTC), - limitMin: time.Date(1990, 1, 1, 0, 0, 0, 0, time.UTC), - limitMax: time.Date(1998, 1, 1, 0, 0, 1, 0, time.UTC), - }, - expected: time.Second, - }, - { - name: "given time range overlaps limitMin and is non zero, return capped duration", - args: args{ - start: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - end: time.Date(1998, 1, 1, 0, 0, 2, 0, time.UTC), - limitMin: time.Date(1998, 1, 1, 0, 0, 1, 0, time.UTC), - limitMax: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: time.Second, - }, - { - name: "given time range is larger than limits, return capped duration", - args: args{ - start: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - end: time.Date(1998, 1, 1, 0, 0, 10, 0, time.UTC), - limitMin: time.Date(1998, 1, 1, 0, 0, 1, 0, time.UTC), - limitMax: time.Date(1998, 1, 1, 0, 0, 9, 0, time.UTC), - }, - expected: 8 * time.Second, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - acc := &Accumulator{} - duration := acc.getTimeElapsedWithinLimits(tc.args.start, tc.args.end, tc.args.limitMin, tc.args.limitMax) - - require.Equal(t, tc.expected, duration) - }) - } - }) - t.Run("calculateNewRewards", func(t *testing.T) { - type args struct { - rewardsPerSecond sdk.Coins - duration time.Duration - totalSourceShares sdk.Dec - } - testcases := []struct { - name string - args args - expected RewardIndexes - }{ - { - name: "rewards calculated normally", - args: args{ - rewardsPerSecond: cs(c("hard", 1000), c("swap", 100)), - duration: 10 * time.Second, - totalSourceShares: d("1000"), - }, - expected: RewardIndexes{ - {CollateralType: "hard", RewardFactor: d("10")}, - {CollateralType: "swap", RewardFactor: d("1")}, - }, - }, - { - name: "duration is rounded to nearest even second", - args: args{ - rewardsPerSecond: cs(c("hard", 1000)), - duration: 10*time.Second + 500*time.Millisecond, - totalSourceShares: d("1000"), - }, - expected: RewardIndexes{ - {CollateralType: "hard", RewardFactor: d("10")}, - }, - }, - { - name: "reward indexes have enough precision for extreme params", - args: args{ - rewardsPerSecond: cs(c("anydenom", 1)), // minimum possible rewards - duration: 1 * time.Second, // minimum possible duration (beyond zero as it's rounded) - totalSourceShares: d("100000000000000000"), // approximate shares in a $1B pool of 10^8 precision assets - }, - expected: RewardIndexes{ - // smallest reward amount over smallest accumulation duration does not go past 10^-18 decimal precision - {CollateralType: "anydenom", RewardFactor: d("0.000000000000000010")}, - }, - }, - { - name: "when duration is zero there is no rewards", - args: args{ - rewardsPerSecond: cs(c("hard", 1000)), - duration: 0, - totalSourceShares: d("1000"), - }, - expected: nil, - }, - { - name: "when rewards per second are nil there is no rewards", - args: args{ - rewardsPerSecond: cs(), - duration: 10 * time.Second, - totalSourceShares: d("1000"), - }, - expected: nil, - }, - { - name: "when the source total is zero there is no rewards", - args: args{ - rewardsPerSecond: cs(c("hard", 1000)), - duration: 10 * time.Second, - totalSourceShares: d("0"), - }, - expected: nil, - }, - { - name: "when all args are zero there is no rewards", - args: args{ - rewardsPerSecond: cs(), - duration: 0, - totalSourceShares: d("0"), - }, - expected: nil, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - acc := &Accumulator{} - indexes := acc.calculateNewRewards( - sdk.NewDecCoinsFromCoins(tc.args.rewardsPerSecond...), - tc.args.totalSourceShares, - tc.args.duration, - ) - - require.Equal(t, tc.expected, indexes) - }) - } - }) - t.Run("Accumulate", func(t *testing.T) { - type args struct { - accumulator Accumulator - period MultiRewardPeriod - totalSourceShares sdk.Dec - currentTime time.Time - } - testcases := []struct { - name string - args args - expected Accumulator - }{ - { - name: "normal", - args: args{ - accumulator: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - Indexes: RewardIndexes{ - {CollateralType: "hard", RewardFactor: d("0.1")}, - {CollateralType: "swap", RewardFactor: d("0.2")}, - }, - }, - period: MultiRewardPeriod{ - Start: time.Date(1990, 1, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: cs(c("hard", 1000)), - }, - totalSourceShares: d("1000"), - currentTime: time.Date(1998, 1, 1, 0, 0, 5, 0, time.UTC), - }, - expected: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 5, 0, time.UTC), - Indexes: RewardIndexes{ - {CollateralType: "hard", RewardFactor: d("5.1")}, - {CollateralType: "swap", RewardFactor: d("0.2")}, - }, - }, - }, - { - name: "empty reward indexes are added to correctly", - args: args{ - accumulator: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - Indexes: RewardIndexes{}, - }, - period: MultiRewardPeriod{ - Start: time.Date(1990, 1, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: cs(c("hard", 1000)), - }, - totalSourceShares: d("1000"), - currentTime: time.Date(1998, 1, 1, 0, 0, 5, 0, time.UTC), - }, - expected: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 5, 0, time.UTC), - Indexes: RewardIndexes{{CollateralType: "hard", RewardFactor: d("5.0")}}, - }, - }, - { - name: "empty reward indexes are unchanged when there's no rewards", - args: args{ - accumulator: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - Indexes: RewardIndexes{}, - }, - period: MultiRewardPeriod{ - Start: time.Date(1990, 1, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: cs(), - }, - totalSourceShares: d("1000"), - currentTime: time.Date(1998, 1, 1, 0, 0, 5, 0, time.UTC), - }, - expected: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 5, 0, time.UTC), - Indexes: RewardIndexes{}, - }, - }, - { - name: "when a period is enclosed within block the accumulation time is set to the period end time", - args: args{ - accumulator: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - Indexes: RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.1")}}, - }, - period: MultiRewardPeriod{ - Start: time.Date(1998, 1, 1, 0, 0, 5, 0, time.UTC), - End: time.Date(1998, 1, 1, 0, 0, 7, 0, time.UTC), - RewardsPerSecond: cs(c("hard", 1000)), - }, - totalSourceShares: d("1000"), - currentTime: time.Date(1998, 1, 1, 0, 0, 10, 0, time.UTC), - }, - expected: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 7, 0, time.UTC), - Indexes: RewardIndexes{{CollateralType: "hard", RewardFactor: d("2.1")}}, - }, - }, - { - name: "accumulation duration is capped at param start when previous stored time is in the distant past", - // This could happend in the default time value time.Time{} was accidentally stored, or if a reward period was - // removed from the params, then added back a long time later. - args: args{ - accumulator: Accumulator{ - PreviousAccumulationTime: time.Time{}, - Indexes: RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.1")}}, - }, - period: MultiRewardPeriod{ - Start: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: cs(c("hard", 1000)), - }, - totalSourceShares: d("1000"), - currentTime: time.Date(1998, 1, 1, 0, 0, 10, 0, time.UTC), - }, - expected: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 10, 0, time.UTC), - Indexes: RewardIndexes{{CollateralType: "hard", RewardFactor: d("10.1")}}, - }, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - tc.args.accumulator.Accumulate(tc.args.period, tc.args.totalSourceShares, tc.args.currentTime) - require.Equal(t, tc.expected, tc.args.accumulator) - }) - } - }) -} - -func TestMinTime(t *testing.T) { - type args struct { - t1, t2 time.Time - } - testcases := []struct { - name string - args args - expected time.Time - }{ - { - name: "last arg greater than first", - args: args{ - t1: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - t2: time.Date(1998, 1, 1, 0, 0, 0, 1, time.UTC), - }, - expected: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - { - name: "first arg greater than last", - args: args{ - t2: time.Date(1998, 1, 1, 0, 0, 0, 1, time.UTC), - t1: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - { - name: "first and last args equal", - args: args{ - t2: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - t1: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - require.Equal(t, tc.expected, minTime(tc.args.t1, tc.args.t2)) - }) - } -} - -func TestMaxTime(t *testing.T) { - type args struct { - t1, t2 time.Time - } - testcases := []struct { - name string - args args - expected time.Time - }{ - { - name: "last arg greater than first", - args: args{ - t1: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - t2: time.Date(1998, 1, 1, 0, 0, 0, 1, time.UTC), - }, - expected: time.Date(1998, 1, 1, 0, 0, 0, 1, time.UTC), - }, - { - name: "first arg greater than last", - args: args{ - t2: time.Date(1998, 1, 1, 0, 0, 0, 1, time.UTC), - t1: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: time.Date(1998, 1, 1, 0, 0, 0, 1, time.UTC), - }, - { - name: "first and last args equal", - args: args{ - t2: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - t1: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - require.Equal(t, tc.expected, maxTime(tc.args.t1, tc.args.t2)) - }) - } -} diff --git a/x/incentive/types/apy.go b/x/incentive/types/apy.go deleted file mode 100644 index d7e54462..00000000 --- a/x/incentive/types/apy.go +++ /dev/null @@ -1,14 +0,0 @@ -package types - -import sdk "github.com/cosmos/cosmos-sdk/types" - -// NewAPY returns a new instance of APY -func NewAPY(collateralType string, apy sdk.Dec) Apy { - return Apy{ - CollateralType: collateralType, - Apy: apy, - } -} - -// APYs is a slice of APY -type APYs []Apy diff --git a/x/incentive/types/apy.pb.go b/x/incentive/types/apy.pb.go deleted file mode 100644 index ecf4ca3b..00000000 --- a/x/incentive/types/apy.pb.go +++ /dev/null @@ -1,372 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/incentive/v1beta1/apy.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// Apy contains the calculated APY for a given collateral type at a specific -// instant in time. -type Apy struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Apy github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=apy,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"apy"` -} - -func (m *Apy) Reset() { *m = Apy{} } -func (m *Apy) String() string { return proto.CompactTextString(m) } -func (*Apy) ProtoMessage() {} -func (*Apy) Descriptor() ([]byte, []int) { - return fileDescriptor_b2c1ad571f25cae9, []int{0} -} -func (m *Apy) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Apy) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Apy.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 *Apy) XXX_Merge(src proto.Message) { - xxx_messageInfo_Apy.Merge(m, src) -} -func (m *Apy) XXX_Size() int { - return m.Size() -} -func (m *Apy) XXX_DiscardUnknown() { - xxx_messageInfo_Apy.DiscardUnknown(m) -} - -var xxx_messageInfo_Apy proto.InternalMessageInfo - -func (m *Apy) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func init() { - proto.RegisterType((*Apy)(nil), "kava.incentive.v1beta1.Apy") -} - -func init() { proto.RegisterFile("kava/incentive/v1beta1/apy.proto", fileDescriptor_b2c1ad571f25cae9) } - -var fileDescriptor_b2c1ad571f25cae9 = []byte{ - // 248 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xc8, 0x4e, 0x2c, 0x4b, - 0xd4, 0xcf, 0xcc, 0x4b, 0x4e, 0xcd, 0x2b, 0xc9, 0x2c, 0x4b, 0xd5, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, - 0x49, 0x34, 0xd4, 0x4f, 0x2c, 0xa8, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x03, 0xa9, - 0xd0, 0x83, 0xab, 0xd0, 0x83, 0xaa, 0x90, 0x92, 0x4c, 0xce, 0x2f, 0xce, 0xcd, 0x2f, 0x8e, 0x07, - 0xab, 0xd2, 0x87, 0x70, 0x20, 0x5a, 0xa4, 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0x21, 0xe2, 0x20, 0x16, - 0x44, 0x54, 0xa9, 0x8e, 0x8b, 0xd9, 0xb1, 0xa0, 0x52, 0x48, 0x9d, 0x8b, 0x3f, 0x39, 0x3f, 0x27, - 0x27, 0xb1, 0x24, 0xb5, 0x28, 0x31, 0x27, 0xbe, 0xa4, 0xb2, 0x20, 0x55, 0x82, 0x51, 0x81, 0x51, - 0x83, 0x33, 0x88, 0x0f, 0x21, 0x1c, 0x52, 0x59, 0x90, 0x2a, 0xe4, 0xc7, 0xc5, 0x9c, 0x58, 0x50, - 0x29, 0xc1, 0x04, 0x92, 0x74, 0xb2, 0x39, 0x71, 0x4f, 0x9e, 0xe1, 0xd6, 0x3d, 0x79, 0xb5, 0xf4, - 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0xa8, 0x9d, 0x50, 0x4a, 0xb7, 0x38, 0x25, - 0x5b, 0x1f, 0x64, 0x5a, 0xb1, 0x9e, 0x4b, 0x6a, 0xf2, 0xa5, 0x2d, 0xba, 0x5c, 0x50, 0x27, 0xb9, - 0xa4, 0x26, 0x07, 0x81, 0x0c, 0x72, 0x72, 0x3d, 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, 0x6d, 0x24, 0x43, 0x41, 0xbe, 0xd5, 0xcd, 0x49, 0x4c, 0x2a, 0x06, 0xb3, 0xf4, 0x2b, - 0x90, 0xc2, 0x06, 0x6c, 0x7a, 0x12, 0x1b, 0xd8, 0x37, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, - 0x95, 0x59, 0xa8, 0x77, 0x3a, 0x01, 0x00, 0x00, -} - -func (m *Apy) 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 *Apy) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Apy) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Apy.Size() - i -= size - if _, err := m.Apy.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintApy(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintApy(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintApy(dAtA []byte, offset int, v uint64) int { - offset -= sovApy(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Apy) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovApy(uint64(l)) - } - l = m.Apy.Size() - n += 1 + l + sovApy(uint64(l)) - return n -} - -func sovApy(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozApy(x uint64) (n int) { - return sovApy(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Apy) 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 ErrIntOverflowApy - } - 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: Apy: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Apy: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowApy - } - 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 ErrInvalidLengthApy - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthApy - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Apy", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowApy - } - 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 ErrInvalidLengthApy - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthApy - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Apy.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipApy(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthApy - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipApy(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, ErrIntOverflowApy - } - 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, ErrIntOverflowApy - } - 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, ErrIntOverflowApy - } - 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, ErrInvalidLengthApy - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupApy - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthApy - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthApy = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowApy = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupApy = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/incentive/types/claims.go b/x/incentive/types/claims.go deleted file mode 100644 index ac7bc5f6..00000000 --- a/x/incentive/types/claims.go +++ /dev/null @@ -1,636 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - USDXMintingClaimType = "usdx_minting" - HardLiquidityProviderClaimType = "hard_liquidity_provider" - DelegatorClaimType = "delegator_claim" - SwapClaimType = "swap" - SavingsClaimType = "savings" - EarnClaimType = "earn" -) - -// GetOwner is a getter for Claim Owner -func (c BaseClaim) GetOwner() sdk.AccAddress { return c.Owner } - -// GetReward is a getter for Claim Reward -func (c BaseClaim) GetReward() sdk.Coin { return c.Reward } - -// GetType returns the claim type, used to identify auctions in event attributes -func (c BaseClaim) GetType() string { return "base" } - -// Validate performs a basic check of a BaseClaim fields -func (c BaseClaim) Validate() error { - if c.Owner.Empty() { - return errors.New("claim owner cannot be empty") - } - if !c.Reward.IsValid() { - return fmt.Errorf("invalid reward amount: %s", c.Reward) - } - return nil -} - -// GetOwner is a getter for Claim Owner -func (c BaseMultiClaim) GetOwner() sdk.AccAddress { return c.Owner } - -// GetReward is a getter for Claim Reward -func (c BaseMultiClaim) GetReward() sdk.Coins { return c.Reward } - -// GetType returns the claim type, used to identify auctions in event attributes -func (c BaseMultiClaim) GetType() string { return "base" } - -// Validate performs a basic check of a BaseClaim fields -func (c BaseMultiClaim) Validate() error { - if c.Owner.Empty() { - return errors.New("claim owner cannot be empty") - } - if !c.Reward.IsValid() { - return fmt.Errorf("invalid reward amount: %s", c.Reward) - } - return nil -} - -// NewUSDXMintingClaim returns a new USDXMintingClaim -func NewUSDXMintingClaim(owner sdk.AccAddress, reward sdk.Coin, rewardIndexes RewardIndexes) USDXMintingClaim { - return USDXMintingClaim{ - BaseClaim: BaseClaim{ - Owner: owner, - Reward: reward, - }, - RewardIndexes: rewardIndexes, - } -} - -// GetType returns the claim's type -func (c USDXMintingClaim) GetType() string { return USDXMintingClaimType } - -// GetReward returns the claim's reward coin -func (c USDXMintingClaim) GetReward() sdk.Coin { return c.Reward } - -// GetOwner returns the claim's owner -func (c USDXMintingClaim) GetOwner() sdk.AccAddress { return c.Owner } - -// Validate performs a basic check of a Claim fields -func (c USDXMintingClaim) Validate() error { - if err := c.RewardIndexes.Validate(); err != nil { - return err - } - - return c.BaseClaim.Validate() -} - -// HasRewardIndex check if a claim has a reward index for the input collateral type -func (c USDXMintingClaim) HasRewardIndex(collateralType string) (int64, bool) { - for index, ri := range c.RewardIndexes { - if ri.CollateralType == collateralType { - return int64(index), true - } - } - return 0, false -} - -// USDXMintingClaims slice of USDXMintingClaim -type USDXMintingClaims []USDXMintingClaim - -// Validate checks if all the claims are valid and there are no duplicated -// entries. -func (cs USDXMintingClaims) Validate() error { - for _, c := range cs { - if err := c.Validate(); err != nil { - return err - } - } - - return nil -} - -// NewHardLiquidityProviderClaim returns a new HardLiquidityProviderClaim -func NewHardLiquidityProviderClaim(owner sdk.AccAddress, rewards sdk.Coins, - supplyRewardIndexes, borrowRewardIndexes MultiRewardIndexes, -) HardLiquidityProviderClaim { - return HardLiquidityProviderClaim{ - BaseMultiClaim: BaseMultiClaim{ - Owner: owner, - Reward: rewards, - }, - SupplyRewardIndexes: supplyRewardIndexes, - BorrowRewardIndexes: borrowRewardIndexes, - } -} - -// GetType returns the claim's type -func (c HardLiquidityProviderClaim) GetType() string { return HardLiquidityProviderClaimType } - -// GetReward returns the claim's reward coin -func (c HardLiquidityProviderClaim) GetReward() sdk.Coins { return c.Reward } - -// GetOwner returns the claim's owner -func (c HardLiquidityProviderClaim) GetOwner() sdk.AccAddress { return c.Owner } - -// Validate performs a basic check of a HardLiquidityProviderClaim fields -func (c HardLiquidityProviderClaim) Validate() error { - if err := c.SupplyRewardIndexes.Validate(); err != nil { - return err - } - - if err := c.BorrowRewardIndexes.Validate(); err != nil { - return err - } - - return c.BaseMultiClaim.Validate() -} - -// HasSupplyRewardIndex check if a claim has a supply reward index for the input collateral type -func (c HardLiquidityProviderClaim) HasSupplyRewardIndex(denom string) (int64, bool) { - for index, ri := range c.SupplyRewardIndexes { - if ri.CollateralType == denom { - return int64(index), true - } - } - return 0, false -} - -// HasBorrowRewardIndex check if a claim has a borrow reward index for the input collateral type -func (c HardLiquidityProviderClaim) HasBorrowRewardIndex(denom string) (int64, bool) { - for index, ri := range c.BorrowRewardIndexes { - if ri.CollateralType == denom { - return int64(index), true - } - } - return 0, false -} - -// HardLiquidityProviderClaims slice of HardLiquidityProviderClaim -type HardLiquidityProviderClaims []HardLiquidityProviderClaim - -// Validate checks if all the claims are valid and there are no duplicated -// entries. -func (cs HardLiquidityProviderClaims) Validate() error { - for _, c := range cs { - if err := c.Validate(); err != nil { - return err - } - } - - return nil -} - -// NewDelegatorClaim returns a new DelegatorClaim -func NewDelegatorClaim(owner sdk.AccAddress, rewards sdk.Coins, rewardIndexes MultiRewardIndexes) DelegatorClaim { - return DelegatorClaim{ - BaseMultiClaim: BaseMultiClaim{ - Owner: owner, - Reward: rewards, - }, - RewardIndexes: rewardIndexes, - } -} - -// GetType returns the claim's type -func (c DelegatorClaim) GetType() string { return DelegatorClaimType } - -// GetReward returns the claim's reward coin -func (c DelegatorClaim) GetReward() sdk.Coins { return c.Reward } - -// GetOwner returns the claim's owner -func (c DelegatorClaim) GetOwner() sdk.AccAddress { return c.Owner } - -// Validate performs a basic check of a DelegatorClaim fields -func (c DelegatorClaim) Validate() error { - if err := c.RewardIndexes.Validate(); err != nil { - return err - } - - return c.BaseMultiClaim.Validate() -} - -// HasRewardIndex checks if a DelegatorClaim has a reward index for the input collateral type -func (c DelegatorClaim) HasRewardIndex(collateralType string) (int64, bool) { - for index, ri := range c.RewardIndexes { - if ri.CollateralType == collateralType { - return int64(index), true - } - } - return 0, false -} - -// DelegatorClaim slice of DelegatorClaim -type DelegatorClaims []DelegatorClaim - -// Validate checks if all the claims are valid and there are no duplicated -// entries. -func (cs DelegatorClaims) Validate() error { - for _, c := range cs { - if err := c.Validate(); err != nil { - return err - } - } - - return nil -} - -// NewSwapClaim returns a new SwapClaim -func NewSwapClaim(owner sdk.AccAddress, rewards sdk.Coins, rewardIndexes MultiRewardIndexes) SwapClaim { - return SwapClaim{ - BaseMultiClaim: BaseMultiClaim{ - Owner: owner, - Reward: rewards, - }, - RewardIndexes: rewardIndexes, - } -} - -// GetType returns the claim's type -func (c SwapClaim) GetType() string { return SwapClaimType } - -// GetReward returns the claim's reward coin -func (c SwapClaim) GetReward() sdk.Coins { return c.Reward } - -// GetOwner returns the claim's owner -func (c SwapClaim) GetOwner() sdk.AccAddress { return c.Owner } - -// Validate performs a basic check of a SwapClaim fields -func (c SwapClaim) Validate() error { - if err := c.RewardIndexes.Validate(); err != nil { - return err - } - return c.BaseMultiClaim.Validate() -} - -// HasRewardIndex check if a claim has a reward index for the input pool ID. -func (c SwapClaim) HasRewardIndex(poolID string) (int64, bool) { - for index, ri := range c.RewardIndexes { - if ri.CollateralType == poolID { - return int64(index), true - } - } - return 0, false -} - -// SwapClaims slice of SwapClaim -type SwapClaims []SwapClaim - -// Validate checks if all the claims are valid. -func (cs SwapClaims) Validate() error { - for _, c := range cs { - if err := c.Validate(); err != nil { - return err - } - } - - return nil -} - -// NewSavingsClaim returns a new SavingsClaim -func NewSavingsClaim(owner sdk.AccAddress, rewards sdk.Coins, rewardIndexes MultiRewardIndexes) SavingsClaim { - return SavingsClaim{ - BaseMultiClaim: BaseMultiClaim{ - Owner: owner, - Reward: rewards, - }, - RewardIndexes: rewardIndexes, - } -} - -// GetType returns the claim's type -func (c SavingsClaim) GetType() string { return SavingsClaimType } - -// GetReward returns the claim's reward coin -func (c SavingsClaim) GetReward() sdk.Coins { return c.Reward } - -// GetOwner returns the claim's owner -func (c SavingsClaim) GetOwner() sdk.AccAddress { return c.Owner } - -// Validate performs a basic check of a SavingsClaim fields -func (c SavingsClaim) Validate() error { - if err := c.RewardIndexes.Validate(); err != nil { - return err - } - return c.BaseMultiClaim.Validate() -} - -// HasRewardIndex check if a claim has a reward index for the input denom -func (c SavingsClaim) HasRewardIndex(denom string) (int64, bool) { - for index, ri := range c.RewardIndexes { - if ri.CollateralType == denom { - return int64(index), true - } - } - return 0, false -} - -// SavingsClaims slice of SavingsClaim -type SavingsClaims []SavingsClaim - -// Validate checks if all the claims are valid. -func (cs SavingsClaims) Validate() error { - for _, c := range cs { - if err := c.Validate(); err != nil { - return err - } - } - - return nil -} - -// NewEarnClaim returns a new EarnClaim -func NewEarnClaim(owner sdk.AccAddress, rewards sdk.Coins, rewardIndexes MultiRewardIndexes) EarnClaim { - return EarnClaim{ - BaseMultiClaim: BaseMultiClaim{ - Owner: owner, - Reward: rewards, - }, - RewardIndexes: rewardIndexes, - } -} - -// GetType returns the claim's type -func (c EarnClaim) GetType() string { return EarnClaimType } - -// GetReward returns the claim's reward coin -func (c EarnClaim) GetReward() sdk.Coins { return c.Reward } - -// GetOwner returns the claim's owner -func (c EarnClaim) GetOwner() sdk.AccAddress { return c.Owner } - -// Validate performs a basic check of a SwapClaim fields -func (c EarnClaim) Validate() error { - if err := c.RewardIndexes.Validate(); err != nil { - return err - } - return c.BaseMultiClaim.Validate() -} - -// HasRewardIndex check if a claim has a reward index for the input pool ID. -func (c EarnClaim) HasRewardIndex(poolID string) (int64, bool) { - for index, ri := range c.RewardIndexes { - if ri.CollateralType == poolID { - return int64(index), true - } - } - return 0, false -} - -// EarnClaims slice of EarnClaim -type EarnClaims []EarnClaim - -// Validate checks if all the claims are valid. -func (cs EarnClaims) Validate() error { - for _, c := range cs { - if err := c.Validate(); err != nil { - return err - } - } - - return nil -} - -// ---------------------- Reward indexes are used internally in the store ---------------------- - -// NewRewardIndex returns a new RewardIndex -func NewRewardIndex(collateralType string, factor sdk.Dec) RewardIndex { - return RewardIndex{ - CollateralType: collateralType, - RewardFactor: factor, - } -} - -// Validate validates reward index -func (ri RewardIndex) Validate() error { - if ri.RewardFactor.IsNegative() { - return fmt.Errorf("reward factor value should be positive, is %s for %s", ri.RewardFactor, ri.CollateralType) - } - if strings.TrimSpace(ri.CollateralType) == "" { - return fmt.Errorf("collateral type should not be empty") - } - return nil -} - -// RewardIndexes slice of RewardIndex -type RewardIndexes []RewardIndex - -// GetRewardIndex fetches a RewardIndex by its denom -func (ris RewardIndexes) GetRewardIndex(denom string) (RewardIndex, bool) { - for _, ri := range ris { - if ri.CollateralType == denom { - return ri, true - } - } - return RewardIndex{}, false -} - -// Get fetches a RewardFactor by it's denom -func (ris RewardIndexes) Get(denom string) (sdk.Dec, bool) { - for _, ri := range ris { - if ri.CollateralType == denom { - return ri.RewardFactor, true - } - } - return sdk.Dec{}, false -} - -// With returns a copy of the indexes with a new reward factor added -func (ris RewardIndexes) With(denom string, factor sdk.Dec) RewardIndexes { - newIndexes := ris.copy() - - for i, ri := range newIndexes { - if ri.CollateralType == denom { - newIndexes[i].RewardFactor = factor - return newIndexes - } - } - return append(newIndexes, NewRewardIndex(denom, factor)) -} - -// GetFactorIndex gets the index of a specific reward index inside the array by its index -func (ris RewardIndexes) GetFactorIndex(denom string) (int, bool) { - for i, ri := range ris { - if ri.CollateralType == denom { - return i, true - } - } - return -1, false -} - -// Validate validation for reward indexes -func (ris RewardIndexes) Validate() error { - for _, ri := range ris { - if err := ri.Validate(); err != nil { - return err - } - } - return nil -} - -// Mul returns a copy of RewardIndexes with all factors multiplied by a single value. -func (ris RewardIndexes) Mul(multiplier sdk.Dec) RewardIndexes { - newIndexes := ris.copy() - - for i := range newIndexes { - newIndexes[i].RewardFactor = newIndexes[i].RewardFactor.Mul(multiplier) - } - return newIndexes -} - -// Quo returns a copy of RewardIndexes with all factors divided by a single value. -// It uses sdk.Dec.Quo for the division. -func (ris RewardIndexes) Quo(divisor sdk.Dec) RewardIndexes { - newIndexes := ris.copy() - - for i := range newIndexes { - newIndexes[i].RewardFactor = newIndexes[i].RewardFactor.Quo(divisor) - } - return newIndexes -} - -// Add combines two reward indexes by adding together factors with the same CollateralType. -// Any CollateralTypes unique to either reward indexes are included in the output as is. -func (ris RewardIndexes) Add(addend RewardIndexes) RewardIndexes { - newIndexes := ris.copy() - - for _, addRi := range addend { - found := false - for i, origRi := range newIndexes { - if origRi.CollateralType == addRi.CollateralType { - found = true - newIndexes[i].RewardFactor = newIndexes[i].RewardFactor.Add(addRi.RewardFactor) - } - } - if !found { - newIndexes = append(newIndexes, addRi) - } - } - return newIndexes -} - -// copy returns a copy of the reward indexes slice and underlying array -func (ris RewardIndexes) copy() RewardIndexes { - if ris == nil { // return nil rather than empty slice when ris is nil - return nil - } - newIndexes := make(RewardIndexes, len(ris)) - copy(newIndexes, ris) - return newIndexes -} - -// NewMultiRewardIndex returns a new MultiRewardIndex -func NewMultiRewardIndex(collateralType string, indexes RewardIndexes) MultiRewardIndex { - return MultiRewardIndex{ - CollateralType: collateralType, - RewardIndexes: indexes, - } -} - -// GetFactorIndex gets the index of a specific reward index inside the array by its index -func (mri MultiRewardIndex) GetFactorIndex(denom string) (int, bool) { - for i, ri := range mri.RewardIndexes { - if ri.CollateralType == denom { - return i, true - } - } - return -1, false -} - -// Validate validates multi-reward index -func (mri MultiRewardIndex) Validate() error { - for _, rf := range mri.RewardIndexes { - if rf.RewardFactor.IsNegative() { - return fmt.Errorf("reward index's factor value cannot be negative: %s", rf) - } - } - if strings.TrimSpace(mri.CollateralType) == "" { - return fmt.Errorf("collateral type should not be empty") - } - return nil -} - -// MultiRewardIndexes slice of MultiRewardIndex -type MultiRewardIndexes []MultiRewardIndex - -// GetRewardIndex fetches a RewardIndex from a MultiRewardIndex by its denom -func (mris MultiRewardIndexes) GetRewardIndex(denom string) (MultiRewardIndex, bool) { - for _, ri := range mris { - if ri.CollateralType == denom { - return ri, true - } - } - return MultiRewardIndex{}, false -} - -// Get fetches a RewardIndexes by it's denom -func (mris MultiRewardIndexes) Get(denom string) (RewardIndexes, bool) { - for _, mri := range mris { - if mri.CollateralType == denom { - return mri.RewardIndexes, true - } - } - return nil, false -} - -// GetRewardIndexIndex fetches a specific reward index inside the array by its denom -func (mris MultiRewardIndexes) GetRewardIndexIndex(denom string) (int, bool) { - for i, ri := range mris { - if ri.CollateralType == denom { - return i, true - } - } - return -1, false -} - -// With returns a copy of the indexes with a new RewardIndexes added -func (mris MultiRewardIndexes) With(denom string, indexes RewardIndexes) MultiRewardIndexes { - newIndexes := mris.copy() - - for i, mri := range newIndexes { - if mri.CollateralType == denom { - newIndexes[i].RewardIndexes = indexes - return newIndexes - } - } - return append(newIndexes, NewMultiRewardIndex(denom, indexes)) -} - -// GetCollateralTypes returns a slice of containing all collateral types -func (mris MultiRewardIndexes) GetCollateralTypes() []string { - var collateralTypes []string - for _, ri := range mris { - collateralTypes = append(collateralTypes, ri.CollateralType) - } - return collateralTypes -} - -// RemoveRewardIndex removes a denom's reward interest factor value -func (mris MultiRewardIndexes) RemoveRewardIndex(denom string) MultiRewardIndexes { - for i, ri := range mris { - if ri.CollateralType == denom { - // copy the slice and underlying array to avoid altering the original - copy := mris.copy() - return append(copy[:i], copy[i+1:]...) - } - } - return mris -} - -// Validate validation for reward indexes -func (mris MultiRewardIndexes) Validate() error { - for _, mri := range mris { - if err := mri.Validate(); err != nil { - return err - } - } - return nil -} - -// copy returns a copy of the slice and underlying array -func (mris MultiRewardIndexes) copy() MultiRewardIndexes { - newIndexes := make(MultiRewardIndexes, len(mris)) - copy(newIndexes, mris) - return newIndexes -} diff --git a/x/incentive/types/claims.pb.go b/x/incentive/types/claims.pb.go deleted file mode 100644 index 8f098c55..00000000 --- a/x/incentive/types/claims.pb.go +++ /dev/null @@ -1,2777 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/incentive/v1beta1/claims.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" - 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 - -// BaseClaim is a claim with a single reward coin types -type BaseClaim struct { - Owner github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=owner,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"owner,omitempty"` - Reward types.Coin `protobuf:"bytes,2,opt,name=reward,proto3" json:"reward"` -} - -func (m *BaseClaim) Reset() { *m = BaseClaim{} } -func (m *BaseClaim) String() string { return proto.CompactTextString(m) } -func (*BaseClaim) ProtoMessage() {} -func (*BaseClaim) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{0} -} -func (m *BaseClaim) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BaseClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BaseClaim.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 *BaseClaim) XXX_Merge(src proto.Message) { - xxx_messageInfo_BaseClaim.Merge(m, src) -} -func (m *BaseClaim) XXX_Size() int { - return m.Size() -} -func (m *BaseClaim) XXX_DiscardUnknown() { - xxx_messageInfo_BaseClaim.DiscardUnknown(m) -} - -var xxx_messageInfo_BaseClaim proto.InternalMessageInfo - -// BaseMultiClaim is a claim with multiple reward coin types -type BaseMultiClaim struct { - Owner github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=owner,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"owner,omitempty"` - Reward github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=reward,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"reward"` -} - -func (m *BaseMultiClaim) Reset() { *m = BaseMultiClaim{} } -func (m *BaseMultiClaim) String() string { return proto.CompactTextString(m) } -func (*BaseMultiClaim) ProtoMessage() {} -func (*BaseMultiClaim) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{1} -} -func (m *BaseMultiClaim) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BaseMultiClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BaseMultiClaim.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 *BaseMultiClaim) XXX_Merge(src proto.Message) { - xxx_messageInfo_BaseMultiClaim.Merge(m, src) -} -func (m *BaseMultiClaim) XXX_Size() int { - return m.Size() -} -func (m *BaseMultiClaim) XXX_DiscardUnknown() { - xxx_messageInfo_BaseMultiClaim.DiscardUnknown(m) -} - -var xxx_messageInfo_BaseMultiClaim proto.InternalMessageInfo - -// RewardIndex stores reward accumulation information -type RewardIndex struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - RewardFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=reward_factor,json=rewardFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"reward_factor"` -} - -func (m *RewardIndex) Reset() { *m = RewardIndex{} } -func (m *RewardIndex) String() string { return proto.CompactTextString(m) } -func (*RewardIndex) ProtoMessage() {} -func (*RewardIndex) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{2} -} -func (m *RewardIndex) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *RewardIndex) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_RewardIndex.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 *RewardIndex) XXX_Merge(src proto.Message) { - xxx_messageInfo_RewardIndex.Merge(m, src) -} -func (m *RewardIndex) XXX_Size() int { - return m.Size() -} -func (m *RewardIndex) XXX_DiscardUnknown() { - xxx_messageInfo_RewardIndex.DiscardUnknown(m) -} - -var xxx_messageInfo_RewardIndex proto.InternalMessageInfo - -// RewardIndexesProto defines a Protobuf wrapper around a RewardIndexes slice -type RewardIndexesProto struct { - RewardIndexes RewardIndexes `protobuf:"bytes,1,rep,name=reward_indexes,json=rewardIndexes,proto3,castrepeated=RewardIndexes" json:"reward_indexes"` -} - -func (m *RewardIndexesProto) Reset() { *m = RewardIndexesProto{} } -func (m *RewardIndexesProto) String() string { return proto.CompactTextString(m) } -func (*RewardIndexesProto) ProtoMessage() {} -func (*RewardIndexesProto) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{3} -} -func (m *RewardIndexesProto) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *RewardIndexesProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_RewardIndexesProto.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 *RewardIndexesProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_RewardIndexesProto.Merge(m, src) -} -func (m *RewardIndexesProto) XXX_Size() int { - return m.Size() -} -func (m *RewardIndexesProto) XXX_DiscardUnknown() { - xxx_messageInfo_RewardIndexesProto.DiscardUnknown(m) -} - -var xxx_messageInfo_RewardIndexesProto proto.InternalMessageInfo - -// MultiRewardIndex stores reward accumulation information on multiple reward types -type MultiRewardIndex struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - RewardIndexes RewardIndexes `protobuf:"bytes,2,rep,name=reward_indexes,json=rewardIndexes,proto3,castrepeated=RewardIndexes" json:"reward_indexes"` -} - -func (m *MultiRewardIndex) Reset() { *m = MultiRewardIndex{} } -func (m *MultiRewardIndex) String() string { return proto.CompactTextString(m) } -func (*MultiRewardIndex) ProtoMessage() {} -func (*MultiRewardIndex) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{4} -} -func (m *MultiRewardIndex) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MultiRewardIndex) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MultiRewardIndex.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 *MultiRewardIndex) XXX_Merge(src proto.Message) { - xxx_messageInfo_MultiRewardIndex.Merge(m, src) -} -func (m *MultiRewardIndex) XXX_Size() int { - return m.Size() -} -func (m *MultiRewardIndex) XXX_DiscardUnknown() { - xxx_messageInfo_MultiRewardIndex.DiscardUnknown(m) -} - -var xxx_messageInfo_MultiRewardIndex proto.InternalMessageInfo - -// MultiRewardIndexesProto defines a Protobuf wrapper around a MultiRewardIndexes slice -type MultiRewardIndexesProto struct { - MultiRewardIndexes MultiRewardIndexes `protobuf:"bytes,1,rep,name=multi_reward_indexes,json=multiRewardIndexes,proto3,castrepeated=MultiRewardIndexes" json:"multi_reward_indexes"` -} - -func (m *MultiRewardIndexesProto) Reset() { *m = MultiRewardIndexesProto{} } -func (m *MultiRewardIndexesProto) String() string { return proto.CompactTextString(m) } -func (*MultiRewardIndexesProto) ProtoMessage() {} -func (*MultiRewardIndexesProto) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{5} -} -func (m *MultiRewardIndexesProto) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MultiRewardIndexesProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MultiRewardIndexesProto.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 *MultiRewardIndexesProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_MultiRewardIndexesProto.Merge(m, src) -} -func (m *MultiRewardIndexesProto) XXX_Size() int { - return m.Size() -} -func (m *MultiRewardIndexesProto) XXX_DiscardUnknown() { - xxx_messageInfo_MultiRewardIndexesProto.DiscardUnknown(m) -} - -var xxx_messageInfo_MultiRewardIndexesProto proto.InternalMessageInfo - -// USDXMintingClaim is for USDX minting rewards -type USDXMintingClaim struct { - BaseClaim `protobuf:"bytes,1,opt,name=base_claim,json=baseClaim,proto3,embedded=base_claim" json:"base_claim"` - RewardIndexes RewardIndexes `protobuf:"bytes,2,rep,name=reward_indexes,json=rewardIndexes,proto3,castrepeated=RewardIndexes" json:"reward_indexes"` -} - -func (m *USDXMintingClaim) Reset() { *m = USDXMintingClaim{} } -func (m *USDXMintingClaim) String() string { return proto.CompactTextString(m) } -func (*USDXMintingClaim) ProtoMessage() {} -func (*USDXMintingClaim) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{6} -} -func (m *USDXMintingClaim) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *USDXMintingClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_USDXMintingClaim.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 *USDXMintingClaim) XXX_Merge(src proto.Message) { - xxx_messageInfo_USDXMintingClaim.Merge(m, src) -} -func (m *USDXMintingClaim) XXX_Size() int { - return m.Size() -} -func (m *USDXMintingClaim) XXX_DiscardUnknown() { - xxx_messageInfo_USDXMintingClaim.DiscardUnknown(m) -} - -var xxx_messageInfo_USDXMintingClaim proto.InternalMessageInfo - -// HardLiquidityProviderClaim stores the hard liquidity provider rewards that can be claimed by owner -type HardLiquidityProviderClaim struct { - BaseMultiClaim `protobuf:"bytes,1,opt,name=base_claim,json=baseClaim,proto3,embedded=base_claim" json:"base_claim"` - SupplyRewardIndexes MultiRewardIndexes `protobuf:"bytes,2,rep,name=supply_reward_indexes,json=supplyRewardIndexes,proto3,castrepeated=MultiRewardIndexes" json:"supply_reward_indexes"` - BorrowRewardIndexes MultiRewardIndexes `protobuf:"bytes,3,rep,name=borrow_reward_indexes,json=borrowRewardIndexes,proto3,castrepeated=MultiRewardIndexes" json:"borrow_reward_indexes"` -} - -func (m *HardLiquidityProviderClaim) Reset() { *m = HardLiquidityProviderClaim{} } -func (m *HardLiquidityProviderClaim) String() string { return proto.CompactTextString(m) } -func (*HardLiquidityProviderClaim) ProtoMessage() {} -func (*HardLiquidityProviderClaim) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{7} -} -func (m *HardLiquidityProviderClaim) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *HardLiquidityProviderClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_HardLiquidityProviderClaim.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 *HardLiquidityProviderClaim) XXX_Merge(src proto.Message) { - xxx_messageInfo_HardLiquidityProviderClaim.Merge(m, src) -} -func (m *HardLiquidityProviderClaim) XXX_Size() int { - return m.Size() -} -func (m *HardLiquidityProviderClaim) XXX_DiscardUnknown() { - xxx_messageInfo_HardLiquidityProviderClaim.DiscardUnknown(m) -} - -var xxx_messageInfo_HardLiquidityProviderClaim proto.InternalMessageInfo - -// DelegatorClaim stores delegation rewards that can be claimed by owner -type DelegatorClaim struct { - BaseMultiClaim `protobuf:"bytes,1,opt,name=base_claim,json=baseClaim,proto3,embedded=base_claim" json:"base_claim"` - RewardIndexes MultiRewardIndexes `protobuf:"bytes,2,rep,name=reward_indexes,json=rewardIndexes,proto3,castrepeated=MultiRewardIndexes" json:"reward_indexes"` -} - -func (m *DelegatorClaim) Reset() { *m = DelegatorClaim{} } -func (m *DelegatorClaim) String() string { return proto.CompactTextString(m) } -func (*DelegatorClaim) ProtoMessage() {} -func (*DelegatorClaim) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{8} -} -func (m *DelegatorClaim) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DelegatorClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DelegatorClaim.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 *DelegatorClaim) XXX_Merge(src proto.Message) { - xxx_messageInfo_DelegatorClaim.Merge(m, src) -} -func (m *DelegatorClaim) XXX_Size() int { - return m.Size() -} -func (m *DelegatorClaim) XXX_DiscardUnknown() { - xxx_messageInfo_DelegatorClaim.DiscardUnknown(m) -} - -var xxx_messageInfo_DelegatorClaim proto.InternalMessageInfo - -// SwapClaim stores the swap rewards that can be claimed by owner -type SwapClaim struct { - BaseMultiClaim `protobuf:"bytes,1,opt,name=base_claim,json=baseClaim,proto3,embedded=base_claim" json:"base_claim"` - RewardIndexes MultiRewardIndexes `protobuf:"bytes,2,rep,name=reward_indexes,json=rewardIndexes,proto3,castrepeated=MultiRewardIndexes" json:"reward_indexes"` -} - -func (m *SwapClaim) Reset() { *m = SwapClaim{} } -func (m *SwapClaim) String() string { return proto.CompactTextString(m) } -func (*SwapClaim) ProtoMessage() {} -func (*SwapClaim) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{9} -} -func (m *SwapClaim) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SwapClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SwapClaim.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 *SwapClaim) XXX_Merge(src proto.Message) { - xxx_messageInfo_SwapClaim.Merge(m, src) -} -func (m *SwapClaim) XXX_Size() int { - return m.Size() -} -func (m *SwapClaim) XXX_DiscardUnknown() { - xxx_messageInfo_SwapClaim.DiscardUnknown(m) -} - -var xxx_messageInfo_SwapClaim proto.InternalMessageInfo - -// SavingsClaim stores the savings rewards that can be claimed by owner -type SavingsClaim struct { - BaseMultiClaim `protobuf:"bytes,1,opt,name=base_claim,json=baseClaim,proto3,embedded=base_claim" json:"base_claim"` - RewardIndexes MultiRewardIndexes `protobuf:"bytes,2,rep,name=reward_indexes,json=rewardIndexes,proto3,castrepeated=MultiRewardIndexes" json:"reward_indexes"` -} - -func (m *SavingsClaim) Reset() { *m = SavingsClaim{} } -func (m *SavingsClaim) String() string { return proto.CompactTextString(m) } -func (*SavingsClaim) ProtoMessage() {} -func (*SavingsClaim) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{10} -} -func (m *SavingsClaim) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SavingsClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SavingsClaim.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 *SavingsClaim) XXX_Merge(src proto.Message) { - xxx_messageInfo_SavingsClaim.Merge(m, src) -} -func (m *SavingsClaim) XXX_Size() int { - return m.Size() -} -func (m *SavingsClaim) XXX_DiscardUnknown() { - xxx_messageInfo_SavingsClaim.DiscardUnknown(m) -} - -var xxx_messageInfo_SavingsClaim proto.InternalMessageInfo - -// EarnClaim stores the earn rewards that can be claimed by owner -type EarnClaim struct { - BaseMultiClaim `protobuf:"bytes,1,opt,name=base_claim,json=baseClaim,proto3,embedded=base_claim" json:"base_claim"` - RewardIndexes MultiRewardIndexes `protobuf:"bytes,2,rep,name=reward_indexes,json=rewardIndexes,proto3,castrepeated=MultiRewardIndexes" json:"reward_indexes"` -} - -func (m *EarnClaim) Reset() { *m = EarnClaim{} } -func (m *EarnClaim) String() string { return proto.CompactTextString(m) } -func (*EarnClaim) ProtoMessage() {} -func (*EarnClaim) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{11} -} -func (m *EarnClaim) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *EarnClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_EarnClaim.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 *EarnClaim) XXX_Merge(src proto.Message) { - xxx_messageInfo_EarnClaim.Merge(m, src) -} -func (m *EarnClaim) XXX_Size() int { - return m.Size() -} -func (m *EarnClaim) XXX_DiscardUnknown() { - xxx_messageInfo_EarnClaim.DiscardUnknown(m) -} - -var xxx_messageInfo_EarnClaim proto.InternalMessageInfo - -func init() { - proto.RegisterType((*BaseClaim)(nil), "kava.incentive.v1beta1.BaseClaim") - proto.RegisterType((*BaseMultiClaim)(nil), "kava.incentive.v1beta1.BaseMultiClaim") - proto.RegisterType((*RewardIndex)(nil), "kava.incentive.v1beta1.RewardIndex") - proto.RegisterType((*RewardIndexesProto)(nil), "kava.incentive.v1beta1.RewardIndexesProto") - proto.RegisterType((*MultiRewardIndex)(nil), "kava.incentive.v1beta1.MultiRewardIndex") - proto.RegisterType((*MultiRewardIndexesProto)(nil), "kava.incentive.v1beta1.MultiRewardIndexesProto") - proto.RegisterType((*USDXMintingClaim)(nil), "kava.incentive.v1beta1.USDXMintingClaim") - proto.RegisterType((*HardLiquidityProviderClaim)(nil), "kava.incentive.v1beta1.HardLiquidityProviderClaim") - proto.RegisterType((*DelegatorClaim)(nil), "kava.incentive.v1beta1.DelegatorClaim") - proto.RegisterType((*SwapClaim)(nil), "kava.incentive.v1beta1.SwapClaim") - proto.RegisterType((*SavingsClaim)(nil), "kava.incentive.v1beta1.SavingsClaim") - proto.RegisterType((*EarnClaim)(nil), "kava.incentive.v1beta1.EarnClaim") -} - -func init() { - proto.RegisterFile("kava/incentive/v1beta1/claims.proto", fileDescriptor_5f7515029623a895) -} - -var fileDescriptor_5f7515029623a895 = []byte{ - // 691 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xdc, 0x56, 0x4f, 0x4f, 0x13, 0x4d, - 0x18, 0xef, 0xc0, 0x0b, 0x79, 0x3b, 0x94, 0xbe, 0x64, 0x81, 0x57, 0xe8, 0x61, 0x8b, 0x25, 0xc1, - 0x26, 0xa6, 0xbb, 0x82, 0x07, 0x13, 0x6f, 0x2c, 0x68, 0xc0, 0x48, 0x24, 0x5b, 0x4d, 0x8c, 0x07, - 0x9b, 0xd9, 0xdd, 0xb1, 0x4e, 0xd8, 0xee, 0xd4, 0x99, 0x6d, 0x4b, 0x3f, 0x83, 0x17, 0xfd, 0x02, - 0x7e, 0x00, 0x2f, 0x5e, 0xf8, 0x10, 0xc4, 0x78, 0x20, 0xc6, 0xc4, 0x3f, 0x87, 0x8a, 0x70, 0xf5, - 0x13, 0x78, 0x32, 0xf3, 0x07, 0x58, 0xa0, 0x25, 0xc4, 0x14, 0x0f, 0x9c, 0x76, 0xe7, 0x99, 0x67, - 0x9e, 0xdf, 0x9f, 0x79, 0x76, 0x76, 0xe0, 0xec, 0x06, 0x6a, 0x22, 0x9b, 0x44, 0x3e, 0x8e, 0x62, - 0xd2, 0xc4, 0x76, 0x73, 0xde, 0xc3, 0x31, 0x9a, 0xb7, 0xfd, 0x10, 0x91, 0x1a, 0xb7, 0xea, 0x8c, - 0xc6, 0xd4, 0xf8, 0x5f, 0x24, 0x59, 0x87, 0x49, 0x96, 0x4e, 0xca, 0x99, 0x3e, 0xe5, 0x35, 0xca, - 0x6d, 0x0f, 0xf1, 0xc4, 0x4a, 0x4a, 0x22, 0xb5, 0x2e, 0x37, 0xad, 0xe6, 0x2b, 0x72, 0x64, 0xab, - 0x81, 0x9e, 0x9a, 0xa8, 0xd2, 0x2a, 0x55, 0x71, 0xf1, 0xa6, 0xa2, 0x85, 0x77, 0x00, 0xa6, 0x1d, - 0xc4, 0xf1, 0x92, 0x40, 0x37, 0x9e, 0xc2, 0x21, 0xda, 0x8a, 0x30, 0x9b, 0x02, 0x33, 0xa0, 0x98, - 0x71, 0x56, 0x7e, 0x75, 0xf2, 0xa5, 0x2a, 0x89, 0x9f, 0x37, 0x3c, 0xcb, 0xa7, 0x35, 0x5d, 0x4f, - 0x3f, 0x4a, 0x3c, 0xd8, 0xb0, 0xe3, 0x76, 0x1d, 0x73, 0x6b, 0xd1, 0xf7, 0x17, 0x83, 0x80, 0x61, - 0xce, 0x3f, 0x6e, 0x95, 0xc6, 0x35, 0xaa, 0x8e, 0x38, 0xed, 0x18, 0x73, 0x57, 0x95, 0x35, 0x6e, - 0xc1, 0x61, 0x86, 0x5b, 0x88, 0x05, 0x53, 0x03, 0x33, 0xa0, 0x38, 0xb2, 0x30, 0x6d, 0xe9, 0x64, - 0xa1, 0xe7, 0x40, 0xa4, 0xb5, 0x44, 0x49, 0xe4, 0xfc, 0xb3, 0xdd, 0xc9, 0xa7, 0x5c, 0x9d, 0x7e, - 0x3b, 0xfd, 0x7e, 0xab, 0x34, 0x24, 0x39, 0x16, 0x76, 0x01, 0xcc, 0x0a, 0xc6, 0x6b, 0x8d, 0x30, - 0x26, 0x7f, 0x87, 0xb6, 0x9f, 0xa0, 0x3d, 0x78, 0x36, 0xed, 0x1b, 0x82, 0xf6, 0xdb, 0xef, 0xf9, - 0xe2, 0x39, 0xf0, 0xc5, 0x02, 0xde, 0x4d, 0xe2, 0x4b, 0x00, 0x47, 0x5c, 0x19, 0x5d, 0x8d, 0x02, - 0xbc, 0x69, 0x5c, 0x83, 0xff, 0xf9, 0x34, 0x0c, 0x51, 0x8c, 0x19, 0x0a, 0x2b, 0x62, 0xb1, 0x54, - 0x9a, 0x76, 0xb3, 0x47, 0xe1, 0x87, 0xed, 0x3a, 0x36, 0xca, 0x70, 0x54, 0x55, 0xab, 0x3c, 0x43, - 0x7e, 0x4c, 0x99, 0xb4, 0x39, 0xe3, 0x58, 0x82, 0xd4, 0xb7, 0x4e, 0x7e, 0xee, 0x1c, 0xa4, 0x96, - 0xb1, 0xef, 0x66, 0x54, 0x91, 0xbb, 0xb2, 0x46, 0xa1, 0x05, 0x8d, 0x04, 0x19, 0xcc, 0xd7, 0x65, - 0x87, 0x22, 0x98, 0xd5, 0x50, 0x44, 0x85, 0xa7, 0x80, 0xf4, 0x66, 0xd6, 0xea, 0xde, 0xba, 0x56, - 0xa2, 0x86, 0x33, 0xa9, 0x5d, 0x1a, 0x3d, 0x56, 0xd8, 0xd5, 0xe4, 0xf5, 0xb0, 0xf0, 0x06, 0xc0, - 0x31, 0xb9, 0xcb, 0x7f, 0xe4, 0xc5, 0x69, 0x82, 0x03, 0xfd, 0x26, 0xf8, 0x1a, 0xc0, 0x2b, 0x27, - 0x09, 0x1e, 0xf8, 0xd3, 0x84, 0x13, 0x35, 0x31, 0x55, 0xe9, 0xea, 0x52, 0xb1, 0x17, 0x89, 0x93, - 0xe5, 0x9c, 0x9c, 0x66, 0x62, 0x9c, 0x06, 0x72, 0x8d, 0xda, 0xa9, 0x58, 0xe1, 0x03, 0x80, 0x63, - 0x8f, 0xca, 0xcb, 0x8f, 0xd7, 0x48, 0x14, 0x93, 0xa8, 0xaa, 0x3e, 0x90, 0x7b, 0x10, 0x8a, 0x56, - 0xad, 0xc8, 0x33, 0x46, 0xfa, 0x35, 0xb2, 0x70, 0xb5, 0x17, 0x85, 0xc3, 0xe3, 0xc0, 0xf9, 0x57, - 0x60, 0xef, 0x74, 0xf2, 0xc0, 0x4d, 0x7b, 0x87, 0x67, 0xc4, 0xc5, 0xfb, 0x9a, 0xfc, 0x14, 0x7e, - 0x0e, 0xc0, 0xdc, 0x0a, 0x62, 0xc1, 0x7d, 0xf2, 0xa2, 0x41, 0x02, 0x12, 0xb7, 0xd7, 0x19, 0x6d, - 0x92, 0x00, 0x33, 0x45, 0xe6, 0x41, 0x17, 0x61, 0x73, 0x67, 0x09, 0x3b, 0x3a, 0x35, 0xba, 0xab, - 0xdb, 0x84, 0x93, 0xbc, 0x51, 0xaf, 0x87, 0xed, 0x4a, 0x57, 0x91, 0xfd, 0xd9, 0xb7, 0x71, 0x05, - 0x71, 0x2c, 0x28, 0x90, 0x3d, 0xca, 0x18, 0x6d, 0x9d, 0x44, 0x1e, 0xec, 0x27, 0xb2, 0x82, 0x70, - 0x7b, 0xd9, 0xfd, 0x15, 0xc0, 0xec, 0x32, 0x0e, 0x71, 0x15, 0xc5, 0xf4, 0xa2, 0x2c, 0xde, 0xe8, - 0xd1, 0x40, 0xfd, 0x51, 0xd8, 0xbb, 0x95, 0x3e, 0x01, 0x98, 0x2e, 0xb7, 0x50, 0xfd, 0x92, 0xc9, - 0xfa, 0x0c, 0x60, 0xa6, 0x8c, 0x9a, 0x24, 0xaa, 0xf2, 0x4b, 0xb8, 0x61, 0x77, 0x10, 0x8b, 0x2e, - 0x97, 0x2c, 0x67, 0x75, 0xfb, 0x87, 0x99, 0xda, 0xde, 0x33, 0xc1, 0xce, 0x9e, 0x09, 0x76, 0xf7, - 0x4c, 0xf0, 0x6a, 0xdf, 0x4c, 0xed, 0xec, 0x9b, 0xa9, 0x2f, 0xfb, 0x66, 0xea, 0xc9, 0xf5, 0xc4, - 0x3f, 0x5a, 0xf0, 0x28, 0x85, 0xc8, 0xe3, 0xf2, 0xcd, 0xde, 0x4c, 0xdc, 0x1a, 0xe5, 0xcf, 0xda, - 0x1b, 0x96, 0x97, 0xb8, 0x9b, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0x88, 0xd7, 0x8a, 0x4f, 0x54, - 0x0a, 0x00, 0x00, -} - -func (m *BaseClaim) 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 *BaseClaim) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *BaseClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Reward.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintClaims(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *BaseMultiClaim) 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 *BaseMultiClaim) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *BaseMultiClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Reward) > 0 { - for iNdEx := len(m.Reward) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Reward[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintClaims(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *RewardIndex) 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 *RewardIndex) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *RewardIndex) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.RewardFactor.Size() - i -= size - if _, err := m.RewardFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintClaims(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *RewardIndexesProto) 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 *RewardIndexesProto) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *RewardIndexesProto) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RewardIndexes) > 0 { - for iNdEx := len(m.RewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *MultiRewardIndex) 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 *MultiRewardIndex) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MultiRewardIndex) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RewardIndexes) > 0 { - for iNdEx := len(m.RewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintClaims(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MultiRewardIndexesProto) 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 *MultiRewardIndexesProto) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MultiRewardIndexesProto) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.MultiRewardIndexes) > 0 { - for iNdEx := len(m.MultiRewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.MultiRewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *USDXMintingClaim) 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 *USDXMintingClaim) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *USDXMintingClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RewardIndexes) > 0 { - for iNdEx := len(m.RewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.BaseClaim.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *HardLiquidityProviderClaim) 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 *HardLiquidityProviderClaim) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *HardLiquidityProviderClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.BorrowRewardIndexes) > 0 { - for iNdEx := len(m.BorrowRewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.BorrowRewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.SupplyRewardIndexes) > 0 { - for iNdEx := len(m.SupplyRewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SupplyRewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.BaseMultiClaim.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *DelegatorClaim) 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 *DelegatorClaim) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DelegatorClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RewardIndexes) > 0 { - for iNdEx := len(m.RewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.BaseMultiClaim.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *SwapClaim) 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 *SwapClaim) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SwapClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RewardIndexes) > 0 { - for iNdEx := len(m.RewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.BaseMultiClaim.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *SavingsClaim) 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 *SavingsClaim) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SavingsClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RewardIndexes) > 0 { - for iNdEx := len(m.RewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.BaseMultiClaim.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *EarnClaim) 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 *EarnClaim) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *EarnClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RewardIndexes) > 0 { - for iNdEx := len(m.RewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.BaseMultiClaim.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintClaims(dAtA []byte, offset int, v uint64) int { - offset -= sovClaims(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *BaseClaim) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovClaims(uint64(l)) - } - l = m.Reward.Size() - n += 1 + l + sovClaims(uint64(l)) - return n -} - -func (m *BaseMultiClaim) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovClaims(uint64(l)) - } - if len(m.Reward) > 0 { - for _, e := range m.Reward { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *RewardIndex) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovClaims(uint64(l)) - } - l = m.RewardFactor.Size() - n += 1 + l + sovClaims(uint64(l)) - return n -} - -func (m *RewardIndexesProto) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.RewardIndexes) > 0 { - for _, e := range m.RewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *MultiRewardIndex) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovClaims(uint64(l)) - } - if len(m.RewardIndexes) > 0 { - for _, e := range m.RewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *MultiRewardIndexesProto) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.MultiRewardIndexes) > 0 { - for _, e := range m.MultiRewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *USDXMintingClaim) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseClaim.Size() - n += 1 + l + sovClaims(uint64(l)) - if len(m.RewardIndexes) > 0 { - for _, e := range m.RewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *HardLiquidityProviderClaim) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseMultiClaim.Size() - n += 1 + l + sovClaims(uint64(l)) - if len(m.SupplyRewardIndexes) > 0 { - for _, e := range m.SupplyRewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - if len(m.BorrowRewardIndexes) > 0 { - for _, e := range m.BorrowRewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *DelegatorClaim) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseMultiClaim.Size() - n += 1 + l + sovClaims(uint64(l)) - if len(m.RewardIndexes) > 0 { - for _, e := range m.RewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *SwapClaim) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseMultiClaim.Size() - n += 1 + l + sovClaims(uint64(l)) - if len(m.RewardIndexes) > 0 { - for _, e := range m.RewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *SavingsClaim) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseMultiClaim.Size() - n += 1 + l + sovClaims(uint64(l)) - if len(m.RewardIndexes) > 0 { - for _, e := range m.RewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *EarnClaim) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseMultiClaim.Size() - n += 1 + l + sovClaims(uint64(l)) - if len(m.RewardIndexes) > 0 { - for _, e := range m.RewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func sovClaims(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozClaims(x uint64) (n int) { - return sovClaims(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *BaseClaim) 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 ErrIntOverflowClaims - } - 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: BaseClaim: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BaseClaim: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = append(m.Owner[:0], dAtA[iNdEx:postIndex]...) - if m.Owner == nil { - m.Owner = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Reward", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Reward.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *BaseMultiClaim) 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 ErrIntOverflowClaims - } - 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: BaseMultiClaim: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BaseMultiClaim: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = append(m.Owner[:0], dAtA[iNdEx:postIndex]...) - if m.Owner == nil { - m.Owner = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Reward", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Reward = append(m.Reward, types.Coin{}) - if err := m.Reward[len(m.Reward)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *RewardIndex) 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 ErrIntOverflowClaims - } - 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: RewardIndex: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: RewardIndex: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - 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 ErrInvalidLengthClaims - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardFactor", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.RewardFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *RewardIndexesProto) 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 ErrIntOverflowClaims - } - 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: RewardIndexesProto: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: RewardIndexesProto: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardIndexes = append(m.RewardIndexes, RewardIndex{}) - if err := m.RewardIndexes[len(m.RewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MultiRewardIndex) 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 ErrIntOverflowClaims - } - 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: MultiRewardIndex: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MultiRewardIndex: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - 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 ErrInvalidLengthClaims - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardIndexes = append(m.RewardIndexes, RewardIndex{}) - if err := m.RewardIndexes[len(m.RewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MultiRewardIndexesProto) 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 ErrIntOverflowClaims - } - 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: MultiRewardIndexesProto: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MultiRewardIndexesProto: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MultiRewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MultiRewardIndexes = append(m.MultiRewardIndexes, MultiRewardIndex{}) - if err := m.MultiRewardIndexes[len(m.MultiRewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *USDXMintingClaim) 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 ErrIntOverflowClaims - } - 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: USDXMintingClaim: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: USDXMintingClaim: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseClaim.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardIndexes = append(m.RewardIndexes, RewardIndex{}) - if err := m.RewardIndexes[len(m.RewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *HardLiquidityProviderClaim) 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 ErrIntOverflowClaims - } - 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: HardLiquidityProviderClaim: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: HardLiquidityProviderClaim: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseMultiClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseMultiClaim.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SupplyRewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SupplyRewardIndexes = append(m.SupplyRewardIndexes, MultiRewardIndex{}) - if err := m.SupplyRewardIndexes[len(m.SupplyRewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BorrowRewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.BorrowRewardIndexes = append(m.BorrowRewardIndexes, MultiRewardIndex{}) - if err := m.BorrowRewardIndexes[len(m.BorrowRewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DelegatorClaim) 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 ErrIntOverflowClaims - } - 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: DelegatorClaim: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DelegatorClaim: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseMultiClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseMultiClaim.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardIndexes = append(m.RewardIndexes, MultiRewardIndex{}) - if err := m.RewardIndexes[len(m.RewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *SwapClaim) 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 ErrIntOverflowClaims - } - 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: SwapClaim: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SwapClaim: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseMultiClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseMultiClaim.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardIndexes = append(m.RewardIndexes, MultiRewardIndex{}) - if err := m.RewardIndexes[len(m.RewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *SavingsClaim) 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 ErrIntOverflowClaims - } - 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: SavingsClaim: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SavingsClaim: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseMultiClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseMultiClaim.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardIndexes = append(m.RewardIndexes, MultiRewardIndex{}) - if err := m.RewardIndexes[len(m.RewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *EarnClaim) 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 ErrIntOverflowClaims - } - 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: EarnClaim: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: EarnClaim: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseMultiClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseMultiClaim.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardIndexes = append(m.RewardIndexes, MultiRewardIndex{}) - if err := m.RewardIndexes[len(m.RewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipClaims(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, ErrIntOverflowClaims - } - 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, ErrIntOverflowClaims - } - 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, ErrIntOverflowClaims - } - 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, ErrInvalidLengthClaims - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupClaims - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthClaims - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthClaims = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowClaims = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupClaims = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/incentive/types/claims_test.go b/x/incentive/types/claims_test.go deleted file mode 100644 index 143b6f9d..00000000 --- a/x/incentive/types/claims_test.go +++ /dev/null @@ -1,794 +0,0 @@ -package types - -import ( - "fmt" - "testing" - - "github.com/cometbft/cometbft/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// d is a helper function for creating sdk.Dec values in tests -func d(str string) sdk.Dec { return sdk.MustNewDecFromStr(str) } - -// c is a helper function for created sdk.Coin types in tests -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } - -// c is a helper function for created sdk.Coins types in tests -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } - -func TestClaims_Validate(t *testing.T) { - owner := sdk.AccAddress(crypto.AddressHash([]byte("KavaTestUser1"))) - - t.Run("USDXMintingClaims", func(t *testing.T) { - testCases := []struct { - name string - claims USDXMintingClaims - expPass bool - }{ - { - "valid", - USDXMintingClaims{ - NewUSDXMintingClaim(owner, sdk.NewCoin("bnb", sdk.OneInt()), RewardIndexes{NewRewardIndex("bnb-a", sdk.ZeroDec())}), - }, - true, - }, - { - "invalid owner", - USDXMintingClaims{ - USDXMintingClaim{ - BaseClaim: BaseClaim{ - Owner: nil, - }, - }, - }, - false, - }, - { - "invalid reward", - USDXMintingClaims{ - { - BaseClaim: BaseClaim{ - Owner: owner, - Reward: sdk.Coin{Denom: "", Amount: sdk.ZeroInt()}, - }, - }, - }, - false, - }, - { - "invalid collateral type", - USDXMintingClaims{ - { - BaseClaim: BaseClaim{ - Owner: owner, - Reward: sdk.NewCoin("bnb", sdk.OneInt()), - }, - RewardIndexes: []RewardIndex{{"", sdk.ZeroDec()}}, - }, - }, - false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.claims.Validate() - if tc.expPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } - }) - t.Run("SwapClaims", func(t *testing.T) { - validRewardIndexes := RewardIndexes{}.With("swap", d("0.002")) - validMultiRewardIndexes := MultiRewardIndexes{}.With("btcb/usdx", validRewardIndexes) - invalidRewardIndexes := RewardIndexes{}.With("swap", d("-0.002")) - invalidMultiRewardIndexes := MultiRewardIndexes{}.With("btcb/usdx", invalidRewardIndexes) - - testCases := []struct { - name string - claims SwapClaims - expPass bool - }{ - { - name: "valid", - claims: SwapClaims{ - NewSwapClaim(owner, cs(c("bnb", 1)), validMultiRewardIndexes), - }, - expPass: true, - }, - { - name: "invalid owner", - claims: SwapClaims{ - NewSwapClaim(nil, cs(c("bnb", 1)), validMultiRewardIndexes), - }, - expPass: false, - }, - { - name: "invalid reward", - claims: SwapClaims{ - NewSwapClaim(owner, sdk.Coins{sdk.Coin{Denom: "invalid😫"}}, validMultiRewardIndexes), - }, - expPass: false, - }, - { - name: "invalid indexes", - claims: SwapClaims{ - NewSwapClaim(nil, cs(c("bnb", 1)), invalidMultiRewardIndexes), - }, - expPass: false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.claims.Validate() - if tc.expPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } - }) - - t.Run("SavingsClaims", func(t *testing.T) { - validRewardIndexes := RewardIndexes{}.With("ukava", d("0.002")) - validMultiRewardIndexes := MultiRewardIndexes{}.With("btcb/usdx", validRewardIndexes) - invalidRewardIndexes := RewardIndexes{}.With("ukava", d("-0.002")) - invalidMultiRewardIndexes := MultiRewardIndexes{}.With("btcb/usdx", invalidRewardIndexes) - - testCases := []struct { - name string - claims SavingsClaims - expPass bool - }{ - { - name: "valid", - claims: SavingsClaims{ - NewSavingsClaim(owner, cs(c("bnb", 1)), validMultiRewardIndexes), - }, - expPass: true, - }, - { - name: "invalid owner", - claims: SavingsClaims{ - NewSavingsClaim(nil, cs(c("bnb", 1)), validMultiRewardIndexes), - }, - expPass: false, - }, - { - name: "invalid reward", - claims: SavingsClaims{ - NewSavingsClaim(owner, sdk.Coins{sdk.Coin{Denom: "invalid😫"}}, validMultiRewardIndexes), - }, - expPass: false, - }, - { - name: "invalid indexes", - claims: SavingsClaims{ - NewSavingsClaim(nil, cs(c("bnb", 1)), invalidMultiRewardIndexes), - }, - expPass: false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.claims.Validate() - if tc.expPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } - }) -} - -func TestRewardIndexes(t *testing.T) { - t.Run("With", func(t *testing.T) { - arbitraryDec := sdk.MustNewDecFromStr("0.1") - - type args struct { - denom string - factor sdk.Dec - } - testcases := []struct { - name string - rewardIndexes RewardIndexes - args args - expected RewardIndexes - }{ - { - name: "when index is not present, it's added and original isn't overwritten", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", arbitraryDec), - }, - args: args{ - denom: "otherdenom", - factor: arbitraryDec, - }, - expected: RewardIndexes{ - NewRewardIndex("denom", arbitraryDec), - NewRewardIndex("otherdenom", arbitraryDec), - }, - }, - { - name: "when index is present, it's updated and original isn't overwritten", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", arbitraryDec), - }, - args: args{ - denom: "denom", - factor: arbitraryDec.MulInt64(2), - }, - expected: RewardIndexes{ - NewRewardIndex("denom", arbitraryDec.MulInt64(2)), - }, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - newIndexes := tc.rewardIndexes.With(tc.args.denom, tc.args.factor) - - require.Equal(t, tc.expected, newIndexes) - require.NotEqual(t, tc.rewardIndexes, newIndexes) // check original slice not modified - }) - } - }) - t.Run("Get", func(t *testing.T) { - arbitraryDec := sdk.MustNewDecFromStr("0.1") - - type expected struct { - factor sdk.Dec - found bool - } - testcases := []struct { - name string - rewardIndexes RewardIndexes - arg_denom string - expected expected - }{ - { - name: "when index is present, it is found and returned", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", arbitraryDec), - }, - arg_denom: "denom", - expected: expected{ - factor: arbitraryDec, - found: true, - }, - }, - { - name: "when index is not present, it is not found", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", arbitraryDec), - }, - arg_denom: "notpresent", - expected: expected{ - found: false, - }, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - factor, found := tc.rewardIndexes.Get(tc.arg_denom) - - require.Equal(t, tc.expected.found, found) - require.Equal(t, tc.expected.factor, factor) - }) - } - }) - t.Run("Mul", func(t *testing.T) { - testcases := []struct { - name string - rewardIndexes RewardIndexes - multiplier sdk.Dec - expected RewardIndexes - }{ - { - name: "non zero values are all multiplied", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - NewRewardIndex("denom2", d("0.2")), - }, - multiplier: d("2.0"), - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.2")), - NewRewardIndex("denom2", d("0.4")), - }, - }, - { - name: "multiplying by zero, zeros all values", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - NewRewardIndex("denom2", d("0.0")), - }, - multiplier: d("0.0"), - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.0")), - NewRewardIndex("denom2", d("0.0")), - }, - }, - { - name: "empty indexes are unchanged", - rewardIndexes: RewardIndexes{}, - multiplier: d("2.0"), - expected: RewardIndexes{}, - }, - { - name: "nil indexes are unchanged", - rewardIndexes: nil, - multiplier: d("2.0"), - expected: nil, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - actual := tc.rewardIndexes.Mul(tc.multiplier) - - if len(tc.expected) == 0 { - require.Equal(t, actual, tc.expected) - } else { - require.Len(t, actual, len(tc.expected)) - for i := range tc.expected { - assert.Equal(t, - actual[i].CollateralType, - tc.expected[i].CollateralType, - ) - assert.True(t, - actual[i].RewardFactor.Equal(tc.expected[i].RewardFactor), - ) - } - } - }) - } - }) - t.Run("Quo", func(t *testing.T) { - type expected struct { - indexes RewardIndexes - panics bool - } - testcases := []struct { - name string - rewardIndexes RewardIndexes - divisor sdk.Dec - expected expected - }{ - { - name: "non zero values are all divided", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.6")), - NewRewardIndex("denom2", d("0.2")), - }, - divisor: d("3.0"), - expected: expected{ - indexes: RewardIndexes{ - NewRewardIndex("denom", d("0.2")), - NewRewardIndex("denom2", d("0.066666666666666667")), - }, - }, - }, - { - name: "diving by zero panics when values are present", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - NewRewardIndex("denom2", d("0.0")), - }, - divisor: d("0.0"), - expected: expected{ - panics: true, - }, - }, - { - name: "empty indexes are unchanged", - rewardIndexes: RewardIndexes{}, - divisor: d("2.0"), - expected: expected{ - indexes: RewardIndexes{}, - }, - }, - { - name: "nil indexes are unchanged", - rewardIndexes: nil, - divisor: d("2.0"), - expected: expected{ - indexes: nil, - }, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - var actual RewardIndexes - quoFunc := func() { actual = tc.rewardIndexes.Quo(tc.divisor) } - if tc.expected.panics { - require.Panics(t, quoFunc) - return - } else { - require.NotPanics(t, quoFunc) - } - require.Equal(t, tc.expected.indexes, actual) - }) - } - }) - t.Run("Add", func(t *testing.T) { - testcases := []struct { - name string - rewardIndexes RewardIndexes - addend RewardIndexes - expected RewardIndexes - }{ - { - name: "same denoms are added", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - NewRewardIndex("denom2", d("0.2")), - }, - addend: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - NewRewardIndex("denom2", d("0.2")), - }, - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.2")), - NewRewardIndex("denom2", d("0.4")), - }, - }, - { - name: "new denoms are appended", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - addend: RewardIndexes{ - NewRewardIndex("denom", d("0.3")), - NewRewardIndex("denom2", d("0.2")), - }, - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.4")), - NewRewardIndex("denom2", d("0.2")), - }, - }, - { - name: "missing denoms are unchanged", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - NewRewardIndex("denom2", d("0.2")), - }, - addend: RewardIndexes{ - NewRewardIndex("denom2", d("0.2")), - }, - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - NewRewardIndex("denom2", d("0.4")), - }, - }, - { - name: "adding empty indexes does nothing", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - addend: RewardIndexes{}, - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - }, - { - name: "adding nil indexes does nothing", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - addend: nil, - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - }, - { - name: "denom can be added to empty indexes", - rewardIndexes: RewardIndexes{}, - addend: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - }, - { - name: "denom can be added to nil indexes", - rewardIndexes: nil, - addend: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - }, - { - name: "adding empty indexes to nil does nothing", - rewardIndexes: nil, - addend: RewardIndexes{}, - expected: nil, - }, - { - name: "adding nil to empty indexes does nothing", - rewardIndexes: RewardIndexes{}, - addend: nil, - expected: RewardIndexes{}, - }, - { - name: "adding nil to nil indexes does nothing", - rewardIndexes: nil, - addend: nil, - expected: nil, - }, - { - name: "adding empty indexes to empty indexes does nothing", - rewardIndexes: RewardIndexes{}, - addend: RewardIndexes{}, - expected: RewardIndexes{}, - }, - } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - sum := tc.rewardIndexes.Add(tc.addend) - require.Equal(t, tc.expected, sum) - }) - } - }) -} - -func TestMultiRewardIndexes(t *testing.T) { - arbitraryRewardIndexes := RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: sdk.MustNewDecFromStr("0.1"), - }, - } - - t.Run("Get", func(t *testing.T) { - type expected struct { - rewardIndexes RewardIndexes - found bool - } - testcases := []struct { - name string - multiRewardIndexes MultiRewardIndexes - arg_denom string - expected expected - }{ - { - name: "when indexes are present, they are found and returned", - multiRewardIndexes: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - arg_denom: "denom", - expected: expected{ - found: true, - rewardIndexes: arbitraryRewardIndexes, - }, - }, - { - name: "when indexes are not present, they are not found", - multiRewardIndexes: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - arg_denom: "notpresent", - expected: expected{ - found: false, - }, - }, - } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - rewardIndexes, found := tc.multiRewardIndexes.Get(tc.arg_denom) - - require.Equal(t, tc.expected.found, found) - require.Equal(t, tc.expected.rewardIndexes, rewardIndexes) - }) - } - }) - t.Run("With", func(t *testing.T) { - type args struct { - denom string - rewardIndexes RewardIndexes - } - testcases := []struct { - name string - multiRewardIndexes MultiRewardIndexes - args args - expected MultiRewardIndexes - }{ - { - name: "when indexes are not present, add them and do not update original", - multiRewardIndexes: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - args: args{ - denom: "otherdenom", - rewardIndexes: arbitraryRewardIndexes, - }, - expected: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: arbitraryRewardIndexes, - }, - { - CollateralType: "otherdenom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - }, - { - name: "when indexes are present, update them and do not update original", - multiRewardIndexes: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - args: args{ - denom: "denom", - rewardIndexes: appendUniqueRewardIndex(arbitraryRewardIndexes), - }, - expected: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: appendUniqueRewardIndex(arbitraryRewardIndexes), - }, - }, - }, - } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - oldIndexes := tc.multiRewardIndexes.copy() - - newIndexes := tc.multiRewardIndexes.With(tc.args.denom, tc.args.rewardIndexes) - - require.Equal(t, tc.expected, newIndexes) - require.Equal(t, oldIndexes, tc.multiRewardIndexes) - }) - } - }) - t.Run("RemoveRewardIndex", func(t *testing.T) { - testcases := []struct { - name string - multiRewardIndexes MultiRewardIndexes - arg_denom string - expected MultiRewardIndexes - }{ - { - name: "when indexes are not present, do nothing", - multiRewardIndexes: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - arg_denom: "notpresent", - expected: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - }, - { - name: "when indexes are present, remove them and do not update original", - multiRewardIndexes: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: arbitraryRewardIndexes, - }, - { - CollateralType: "otherdenom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - arg_denom: "denom", - expected: MultiRewardIndexes{ - { - CollateralType: "otherdenom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - }, - } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - oldIndexes := tc.multiRewardIndexes.copy() - - newIndexes := tc.multiRewardIndexes.RemoveRewardIndex(tc.arg_denom) - - require.Equal(t, tc.expected, newIndexes) - require.Equal(t, oldIndexes, tc.multiRewardIndexes) - }) - } - }) - t.Run("Validate", func(t *testing.T) { - testcases := []struct { - name string - multiRewardIndexes MultiRewardIndexes - wantErr bool - }{ - { - name: "normal case", - multiRewardIndexes: MultiRewardIndexes{ - {CollateralType: "btcb", RewardIndexes: normalRewardIndexes}, - {CollateralType: "bnb", RewardIndexes: normalRewardIndexes}, - }, - wantErr: false, - }, - { - name: "empty", - multiRewardIndexes: nil, - wantErr: false, - }, - { - name: "empty collateral type", - multiRewardIndexes: MultiRewardIndexes{ - {RewardIndexes: normalRewardIndexes}, - }, - wantErr: true, - }, - { - name: "invalid reward index", - multiRewardIndexes: MultiRewardIndexes{ - {CollateralType: "btcb", RewardIndexes: invalidRewardIndexes}, - }, - wantErr: true, - }, - } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - err := tc.multiRewardIndexes.Validate() - if tc.wantErr { - require.NotNil(t, err) - } else { - require.Nil(t, err) - } - }) - } - }) -} - -var normalRewardIndexes = RewardIndexes{ - NewRewardIndex("hard", sdk.MustNewDecFromStr("0.000001")), - NewRewardIndex("ukava", sdk.MustNewDecFromStr("0.1")), -} - -var invalidRewardIndexes = RewardIndexes{ - RewardIndex{"hard", sdk.MustNewDecFromStr("-0.01")}, -} - -func appendUniqueRewardIndex(indexes RewardIndexes) RewardIndexes { - const uniqueDenom = "uniquereward" - - for _, mri := range indexes { - if mri.CollateralType == uniqueDenom { - panic(fmt.Sprintf("tried to add unique reward index with denom '%s', but denom already existed", uniqueDenom)) - } - } - - return append( - indexes, - NewRewardIndex(uniqueDenom, sdk.MustNewDecFromStr("0.02")), - ) -} diff --git a/x/incentive/types/codec.go b/x/incentive/types/codec.go deleted file mode 100644 index ccf56005..00000000 --- a/x/incentive/types/codec.go +++ /dev/null @@ -1,49 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the -// governance module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgClaimUSDXMintingReward{}, "incentive/MsgClaimUSDXMintingReward", nil) - cdc.RegisterConcrete(&MsgClaimHardReward{}, "incentive/MsgClaimHardReward", nil) - cdc.RegisterConcrete(&MsgClaimDelegatorReward{}, "incentive/MsgClaimDelegatorReward", nil) - cdc.RegisterConcrete(&MsgClaimSwapReward{}, "incentive/MsgClaimSwapReward", nil) - cdc.RegisterConcrete(&MsgClaimSavingsReward{}, "incentive/MsgClaimSavingsReward", nil) - cdc.RegisterConcrete(&MsgClaimEarnReward{}, "incentive/MsgClaimEarnReward", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgClaimUSDXMintingReward{}, - &MsgClaimHardReward{}, - &MsgClaimDelegatorReward{}, - &MsgClaimSwapReward{}, - &MsgClaimSavingsReward{}, - &MsgClaimEarnReward{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/incentive/types/errors.go b/x/incentive/types/errors.go deleted file mode 100644 index f14f7e40..00000000 --- a/x/incentive/types/errors.go +++ /dev/null @@ -1,21 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// DONTCOVER - -// Incentive module errors -var ( - ErrClaimNotFound = errorsmod.Register(ModuleName, 2, "no claimable rewards found for user") - ErrRewardPeriodNotFound = errorsmod.Register(ModuleName, 3, "no reward period found for collateral type") - ErrInvalidAccountType = errorsmod.Register(ModuleName, 4, "account type not supported") - ErrNoClaimsFound = errorsmod.Register(ModuleName, 5, "no claimable rewards found") - ErrInsufficientModAccountBalance = errorsmod.Register(ModuleName, 6, "module account has insufficient balance to pay claim") - ErrAccountNotFound = errorsmod.Register(ModuleName, 7, "account not found") - ErrInvalidMultiplier = errorsmod.Register(ModuleName, 8, "invalid rewards multiplier") - ErrZeroClaim = errorsmod.Register(ModuleName, 9, "cannot claim - claim amount rounds to zero") - ErrClaimExpired = errorsmod.Register(ModuleName, 10, "claim has expired") - ErrInvalidClaimType = errorsmod.Register(ModuleName, 11, "invalid claim type") - ErrDecreasingRewardFactor = errorsmod.Register(ModuleName, 13, "found new reward factor less than an old reward factor") - ErrInvalidClaimDenoms = errorsmod.Register(ModuleName, 14, "invalid claim denoms") -) diff --git a/x/incentive/types/events.go b/x/incentive/types/events.go deleted file mode 100644 index 5255d1c4..00000000 --- a/x/incentive/types/events.go +++ /dev/null @@ -1,16 +0,0 @@ -package types - -// Events emitted by the incentive module -const ( - EventTypeClaim = "claim_reward" - EventTypeRewardPeriod = "new_reward_period" - EventTypeClaimPeriod = "new_claim_period" - EventTypeClaimPeriodExpiry = "claim_period_expiry" - - AttributeValueCategory = ModuleName - AttributeKeyClaimedBy = "claimed_by" - AttributeKeyClaimAmount = "claim_amount" - AttributeKeyClaimType = "claim_type" - AttributeKeyRewardPeriod = "reward_period" - AttributeKeyClaimPeriod = "claim_period" -) diff --git a/x/incentive/types/expected_keepers.go b/x/incentive/types/expected_keepers.go deleted file mode 100644 index caf27faa..00000000 --- a/x/incentive/types/expected_keepers.go +++ /dev/null @@ -1,127 +0,0 @@ -package types - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - cdptypes "github.com/kava-labs/kava/x/cdp/types" - earntypes "github.com/kava-labs/kava/x/earn/types" - hardtypes "github.com/kava-labs/kava/x/hard/types" - pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types" - savingstypes "github.com/kava-labs/kava/x/savings/types" -) - -// ParamSubspace defines the expected Subspace interfacace -type ParamSubspace interface { - GetParamSet(sdk.Context, paramtypes.ParamSet) - SetParamSet(sdk.Context, paramtypes.ParamSet) - WithKeyTable(paramtypes.KeyTable) paramtypes.Subspace - HasKeyTable() bool -} - -// BankKeeper defines the expected interface needed to send coins -type BankKeeper interface { - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - GetSupply(ctx sdk.Context, denom string) sdk.Coin -} - -// StakingKeeper defines the expected staking keeper for module accounts -type StakingKeeper interface { - GetDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress, maxRetrieve uint16) (delegations []stakingtypes.Delegation) - GetValidatorDelegations(ctx sdk.Context, valAddr sdk.ValAddress) (delegations []stakingtypes.Delegation) - GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool) - TotalBondedTokens(ctx sdk.Context) sdkmath.Int -} - -// CdpKeeper defines the expected cdp keeper for interacting with cdps -type CdpKeeper interface { - GetInterestFactor(ctx sdk.Context, collateralType string) (sdk.Dec, bool) - GetTotalPrincipal(ctx sdk.Context, collateralType string, principalDenom string) (total sdkmath.Int) - GetCdpByOwnerAndCollateralType(ctx sdk.Context, owner sdk.AccAddress, collateralType string) (cdptypes.CDP, bool) - GetCollateral(ctx sdk.Context, collateralType string) (cdptypes.CollateralParam, bool) -} - -// HardKeeper defines the expected hard keeper for interacting with Hard protocol -type HardKeeper interface { - GetDeposit(ctx sdk.Context, depositor sdk.AccAddress) (hardtypes.Deposit, bool) - GetBorrow(ctx sdk.Context, borrower sdk.AccAddress) (hardtypes.Borrow, bool) - - GetSupplyInterestFactor(ctx sdk.Context, denom string) (sdk.Dec, bool) - GetBorrowInterestFactor(ctx sdk.Context, denom string) (sdk.Dec, bool) - GetBorrowedCoins(ctx sdk.Context) (coins sdk.Coins, found bool) - GetSuppliedCoins(ctx sdk.Context) (coins sdk.Coins, found bool) -} - -// SwapKeeper defines the required methods needed by this modules keeper -type SwapKeeper interface { - GetPoolShares(ctx sdk.Context, poolID string) (shares sdkmath.Int, found bool) - GetDepositorSharesAmount(ctx sdk.Context, depositor sdk.AccAddress, poolID string) (shares sdkmath.Int, found bool) -} - -// SavingsKeeper defines the required methods needed by this module's keeper -type SavingsKeeper interface { - GetDeposit(ctx sdk.Context, depositor sdk.AccAddress) (savingstypes.Deposit, bool) - GetSavingsModuleAccountBalances(ctx sdk.Context) sdk.Coins -} - -// EarnKeeper defines the required methods needed by this modules keeper -type EarnKeeper interface { - GetVaultTotalShares(ctx sdk.Context, denom string) (shares earntypes.VaultShare, found bool) - GetVaultTotalValue(ctx sdk.Context, denom string) (sdk.Coin, error) - GetVaultAccountShares(ctx sdk.Context, acc sdk.AccAddress) (shares earntypes.VaultShares, found bool) - IterateVaultRecords(ctx sdk.Context, cb func(record earntypes.VaultRecord) (stop bool)) -} - -// LiquidKeeper defines the required methods needed by this modules keeper -type LiquidKeeper interface { - IsDerivativeDenom(ctx sdk.Context, denom string) bool - GetTotalDerivativeValue(ctx sdk.Context) (sdk.Coin, error) - GetDerivativeValue(ctx sdk.Context, denom string) (sdk.Coin, error) - CollectStakingRewardsByDenom( - ctx sdk.Context, - derivativeDenom string, - destinationModAccount string, - ) (sdk.Coins, error) -} - -// AccountKeeper expected interface for the account keeper (noalias) -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI - SetAccount(ctx sdk.Context, acc authtypes.AccountI) - GetModuleAccount(ctx sdk.Context, name string) authtypes.ModuleAccountI -} - -// MintKeeper defines the required methods needed by this modules keeper -type MintKeeper interface { - GetMinter(ctx sdk.Context) (minter minttypes.Minter) -} - -// DistrKeeper defines the required methods needed by this modules keeper -type DistrKeeper interface { - GetCommunityTax(ctx sdk.Context) (percent sdk.Dec) -} - -// PricefeedKeeper defines the required methods needed by this modules keeper -type PricefeedKeeper interface { - GetCurrentPrice(ctx sdk.Context, marketID string) (pricefeedtypes.CurrentPrice, error) -} - -// CDPHooks event hooks for other keepers to run code in response to CDP modifications -type CDPHooks interface { - AfterCDPCreated(ctx sdk.Context, cdp cdptypes.CDP) - BeforeCDPModified(ctx sdk.Context, cdp cdptypes.CDP) -} - -// HARDHooks event hooks for other keepers to run code in response to HARD modifications -type HARDHooks interface { - AfterDepositCreated(ctx sdk.Context, deposit hardtypes.Deposit) - BeforeDepositModified(ctx sdk.Context, deposit hardtypes.Deposit) - AfterDepositModified(ctx sdk.Context, deposit hardtypes.Deposit) - AfterBorrowCreated(ctx sdk.Context, borrow hardtypes.Borrow) - BeforeBorrowModified(ctx sdk.Context, borrow hardtypes.Borrow) - AfterBorrowModified(ctx sdk.Context, deposit hardtypes.Deposit) -} diff --git a/x/incentive/types/genesis.go b/x/incentive/types/genesis.go deleted file mode 100644 index 1955617b..00000000 --- a/x/incentive/types/genesis.go +++ /dev/null @@ -1,160 +0,0 @@ -package types - -import ( - "fmt" - "time" -) - -var ( - DefaultUSDXClaims = USDXMintingClaims{} - DefaultHardClaims = HardLiquidityProviderClaims{} - DefaultDelegatorClaims = DelegatorClaims{} - DefaultSwapClaims = SwapClaims{} - DefaultSavingsClaims = SavingsClaims{} - DefaultGenesisRewardState = NewGenesisRewardState( - AccumulationTimes{}, - MultiRewardIndexes{}, - ) - DefaultEarnClaims = EarnClaims{} -) - -// NewGenesisState returns a new genesis state -func NewGenesisState( - params Params, - usdxState, hardSupplyState, hardBorrowState, delegatorState, swapState, savingsState, earnState GenesisRewardState, - c USDXMintingClaims, hc HardLiquidityProviderClaims, dc DelegatorClaims, sc SwapClaims, savingsc SavingsClaims, - earnc EarnClaims, -) GenesisState { - return GenesisState{ - Params: params, - - USDXRewardState: usdxState, - HardSupplyRewardState: hardSupplyState, - HardBorrowRewardState: hardBorrowState, - DelegatorRewardState: delegatorState, - SwapRewardState: swapState, - SavingsRewardState: savingsState, - EarnRewardState: earnState, - - USDXMintingClaims: c, - HardLiquidityProviderClaims: hc, - DelegatorClaims: dc, - SwapClaims: sc, - SavingsClaims: savingsc, - EarnClaims: earnc, - } -} - -// DefaultGenesisState returns a default genesis state -func DefaultGenesisState() GenesisState { - return GenesisState{ - Params: DefaultParams(), - USDXRewardState: DefaultGenesisRewardState, - HardSupplyRewardState: DefaultGenesisRewardState, - HardBorrowRewardState: DefaultGenesisRewardState, - DelegatorRewardState: DefaultGenesisRewardState, - SwapRewardState: DefaultGenesisRewardState, - SavingsRewardState: DefaultGenesisRewardState, - EarnRewardState: DefaultGenesisRewardState, - USDXMintingClaims: DefaultUSDXClaims, - HardLiquidityProviderClaims: DefaultHardClaims, - DelegatorClaims: DefaultDelegatorClaims, - SwapClaims: DefaultSwapClaims, - SavingsClaims: DefaultSavingsClaims, - EarnClaims: DefaultEarnClaims, - } -} - -// Validate performs basic validation of genesis data returning an -// error for any failed validation criteria. -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - - if err := gs.USDXRewardState.Validate(); err != nil { - return err - } - if err := gs.HardSupplyRewardState.Validate(); err != nil { - return err - } - if err := gs.HardBorrowRewardState.Validate(); err != nil { - return err - } - if err := gs.DelegatorRewardState.Validate(); err != nil { - return err - } - if err := gs.SwapRewardState.Validate(); err != nil { - return err - } - if err := gs.SavingsRewardState.Validate(); err != nil { - return err - } - if err := gs.EarnRewardState.Validate(); err != nil { - return err - } - - if err := gs.USDXMintingClaims.Validate(); err != nil { - return err - } - if err := gs.HardLiquidityProviderClaims.Validate(); err != nil { - return err - } - if err := gs.DelegatorClaims.Validate(); err != nil { - return err - } - if err := gs.SwapClaims.Validate(); err != nil { - return err - } - - if err := gs.SavingsClaims.Validate(); err != nil { - return err - } - - return gs.EarnClaims.Validate() -} - -// NewGenesisRewardState returns a new GenesisRewardState -func NewGenesisRewardState(accumTimes AccumulationTimes, indexes MultiRewardIndexes) GenesisRewardState { - return GenesisRewardState{ - AccumulationTimes: accumTimes, - MultiRewardIndexes: indexes, - } -} - -// Validate performs validation of a GenesisRewardState -func (grs GenesisRewardState) Validate() error { - if err := grs.AccumulationTimes.Validate(); err != nil { - return err - } - return grs.MultiRewardIndexes.Validate() -} - -// NewAccumulationTime returns a new GenesisAccumulationTime -func NewAccumulationTime(ctype string, prevTime time.Time) AccumulationTime { - return AccumulationTime{ - CollateralType: ctype, - PreviousAccumulationTime: prevTime, - } -} - -// Validate performs validation of GenesisAccumulationTime -func (gat AccumulationTime) Validate() error { - if len(gat.CollateralType) == 0 { - return fmt.Errorf("genesis accumulation time's collateral type must be defined") - } - return nil -} - -// AccumulationTimes slice of GenesisAccumulationTime -type AccumulationTimes []AccumulationTime - -// Validate performs validation of GenesisAccumulationTimes -func (gats AccumulationTimes) Validate() error { - for _, gat := range gats { - if err := gat.Validate(); err != nil { - return err - } - } - return nil -} diff --git a/x/incentive/types/genesis.pb.go b/x/incentive/types/genesis.pb.go deleted file mode 100644 index e4cadfa4..00000000 --- a/x/incentive/types/genesis.pb.go +++ /dev/null @@ -1,1447 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/incentive/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 - -// AccumulationTime stores the previous reward distribution time and its corresponding collateral type -type AccumulationTime struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - PreviousAccumulationTime time.Time `protobuf:"bytes,2,opt,name=previous_accumulation_time,json=previousAccumulationTime,proto3,stdtime" json:"previous_accumulation_time"` -} - -func (m *AccumulationTime) Reset() { *m = AccumulationTime{} } -func (m *AccumulationTime) String() string { return proto.CompactTextString(m) } -func (*AccumulationTime) ProtoMessage() {} -func (*AccumulationTime) Descriptor() ([]byte, []int) { - return fileDescriptor_8b76737885d05afd, []int{0} -} -func (m *AccumulationTime) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AccumulationTime) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AccumulationTime.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 *AccumulationTime) XXX_Merge(src proto.Message) { - xxx_messageInfo_AccumulationTime.Merge(m, src) -} -func (m *AccumulationTime) XXX_Size() int { - return m.Size() -} -func (m *AccumulationTime) XXX_DiscardUnknown() { - xxx_messageInfo_AccumulationTime.DiscardUnknown(m) -} - -var xxx_messageInfo_AccumulationTime proto.InternalMessageInfo - -// GenesisRewardState groups together the global state for a particular reward so it can be exported in genesis. -type GenesisRewardState struct { - AccumulationTimes AccumulationTimes `protobuf:"bytes,1,rep,name=accumulation_times,json=accumulationTimes,proto3,castrepeated=AccumulationTimes" json:"accumulation_times"` - MultiRewardIndexes MultiRewardIndexes `protobuf:"bytes,2,rep,name=multi_reward_indexes,json=multiRewardIndexes,proto3,castrepeated=MultiRewardIndexes" json:"multi_reward_indexes"` -} - -func (m *GenesisRewardState) Reset() { *m = GenesisRewardState{} } -func (m *GenesisRewardState) String() string { return proto.CompactTextString(m) } -func (*GenesisRewardState) ProtoMessage() {} -func (*GenesisRewardState) Descriptor() ([]byte, []int) { - return fileDescriptor_8b76737885d05afd, []int{1} -} -func (m *GenesisRewardState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisRewardState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisRewardState.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 *GenesisRewardState) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisRewardState.Merge(m, src) -} -func (m *GenesisRewardState) XXX_Size() int { - return m.Size() -} -func (m *GenesisRewardState) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisRewardState.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisRewardState proto.InternalMessageInfo - -// GenesisState is the state that must be provided at genesis. -type GenesisState struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - USDXRewardState GenesisRewardState `protobuf:"bytes,2,opt,name=usdx_reward_state,json=usdxRewardState,proto3" json:"usdx_reward_state"` - HardSupplyRewardState GenesisRewardState `protobuf:"bytes,3,opt,name=hard_supply_reward_state,json=hardSupplyRewardState,proto3" json:"hard_supply_reward_state"` - HardBorrowRewardState GenesisRewardState `protobuf:"bytes,4,opt,name=hard_borrow_reward_state,json=hardBorrowRewardState,proto3" json:"hard_borrow_reward_state"` - DelegatorRewardState GenesisRewardState `protobuf:"bytes,5,opt,name=delegator_reward_state,json=delegatorRewardState,proto3" json:"delegator_reward_state"` - SwapRewardState GenesisRewardState `protobuf:"bytes,6,opt,name=swap_reward_state,json=swapRewardState,proto3" json:"swap_reward_state"` - USDXMintingClaims USDXMintingClaims `protobuf:"bytes,7,rep,name=usdx_minting_claims,json=usdxMintingClaims,proto3,castrepeated=USDXMintingClaims" json:"usdx_minting_claims"` - HardLiquidityProviderClaims HardLiquidityProviderClaims `protobuf:"bytes,8,rep,name=hard_liquidity_provider_claims,json=hardLiquidityProviderClaims,proto3,castrepeated=HardLiquidityProviderClaims" json:"hard_liquidity_provider_claims"` - DelegatorClaims DelegatorClaims `protobuf:"bytes,9,rep,name=delegator_claims,json=delegatorClaims,proto3,castrepeated=DelegatorClaims" json:"delegator_claims"` - SwapClaims SwapClaims `protobuf:"bytes,10,rep,name=swap_claims,json=swapClaims,proto3,castrepeated=SwapClaims" json:"swap_claims"` - SavingsRewardState GenesisRewardState `protobuf:"bytes,11,opt,name=savings_reward_state,json=savingsRewardState,proto3" json:"savings_reward_state"` - SavingsClaims SavingsClaims `protobuf:"bytes,12,rep,name=savings_claims,json=savingsClaims,proto3,castrepeated=SavingsClaims" json:"savings_claims"` - EarnRewardState GenesisRewardState `protobuf:"bytes,13,opt,name=earn_reward_state,json=earnRewardState,proto3" json:"earn_reward_state"` - EarnClaims EarnClaims `protobuf:"bytes,14,rep,name=earn_claims,json=earnClaims,proto3,castrepeated=EarnClaims" json:"earn_claims"` -} - -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_8b76737885d05afd, []int{2} -} -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 init() { - proto.RegisterType((*AccumulationTime)(nil), "kava.incentive.v1beta1.AccumulationTime") - proto.RegisterType((*GenesisRewardState)(nil), "kava.incentive.v1beta1.GenesisRewardState") - proto.RegisterType((*GenesisState)(nil), "kava.incentive.v1beta1.GenesisState") -} - -func init() { - proto.RegisterFile("kava/incentive/v1beta1/genesis.proto", fileDescriptor_8b76737885d05afd) -} - -var fileDescriptor_8b76737885d05afd = []byte{ - // 785 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x95, 0xcf, 0x4f, 0xdb, 0x48, - 0x14, 0xc7, 0x63, 0x60, 0x59, 0x98, 0x00, 0x21, 0xb3, 0x01, 0xb2, 0x41, 0x72, 0x58, 0x40, 0xbb, - 0xd1, 0x56, 0xb5, 0x45, 0x7a, 0xed, 0xa5, 0x2e, 0x55, 0x8b, 0x54, 0x24, 0xe4, 0x50, 0x54, 0x55, - 0x95, 0xa2, 0x71, 0x3c, 0x98, 0x69, 0xfd, 0xab, 0x1e, 0x3b, 0x21, 0xb7, 0x1e, 0x7b, 0xe4, 0x0f, - 0xa8, 0xd4, 0x7b, 0xff, 0x8f, 0x4a, 0x1c, 0x39, 0xf6, 0x04, 0x6d, 0xf8, 0x47, 0xaa, 0x19, 0x8f, - 0x83, 0x9d, 0x60, 0xaa, 0xa6, 0xb7, 0xc9, 0x9b, 0x37, 0xdf, 0xcf, 0xf7, 0xcd, 0x7b, 0x13, 0x83, - 0xed, 0xb7, 0xa8, 0x8b, 0x54, 0xe2, 0x76, 0xb0, 0x1b, 0x92, 0x2e, 0x56, 0xbb, 0x3b, 0x06, 0x0e, - 0xd1, 0x8e, 0x6a, 0x61, 0x17, 0x53, 0x42, 0x15, 0x3f, 0xf0, 0x42, 0x0f, 0xae, 0xb2, 0x2c, 0x65, - 0x98, 0xa5, 0x88, 0xac, 0x5a, 0xc5, 0xf2, 0x2c, 0x8f, 0xa7, 0xa8, 0x6c, 0x15, 0x67, 0xd7, 0xea, - 0x96, 0xe7, 0x59, 0x36, 0x56, 0xf9, 0x2f, 0x23, 0x3a, 0x56, 0x43, 0xe2, 0x60, 0x1a, 0x22, 0xc7, - 0x17, 0x09, 0x5b, 0x39, 0xd0, 0x8e, 0x8d, 0x88, 0x43, 0x7f, 0x92, 0xe4, 0xa3, 0x00, 0x25, 0x49, - 0x9b, 0x9f, 0x24, 0xb0, 0xfc, 0xa8, 0xd3, 0x89, 0x9c, 0xc8, 0x46, 0x21, 0xf1, 0xdc, 0x43, 0xe2, - 0x60, 0xf8, 0x1f, 0x28, 0x75, 0x3c, 0xdb, 0x46, 0x21, 0x0e, 0x90, 0xdd, 0x0e, 0xfb, 0x3e, 0xae, - 0x4a, 0x1b, 0x52, 0x63, 0x5e, 0x5f, 0xba, 0x09, 0x1f, 0xf6, 0x7d, 0x0c, 0x0d, 0x50, 0xf3, 0x03, - 0xdc, 0x25, 0x5e, 0x44, 0xdb, 0x28, 0xa5, 0xd2, 0x66, 0x86, 0xab, 0x53, 0x1b, 0x52, 0xa3, 0xd8, - 0xac, 0x29, 0x71, 0x35, 0x4a, 0x52, 0x8d, 0x72, 0x98, 0x54, 0xa3, 0xcd, 0x9d, 0x5f, 0xd6, 0x0b, - 0x67, 0x57, 0x75, 0x49, 0xaf, 0x26, 0x3a, 0xa3, 0x66, 0x36, 0xdf, 0x4f, 0x01, 0xf8, 0x34, 0xbe, - 0x4c, 0x1d, 0xf7, 0x50, 0x60, 0xb6, 0x42, 0x14, 0x62, 0x18, 0x00, 0x38, 0x46, 0xa4, 0x55, 0x69, - 0x63, 0xba, 0x51, 0x6c, 0x36, 0x94, 0xdb, 0xaf, 0x5b, 0x19, 0x15, 0xd7, 0xfe, 0x66, 0x06, 0x3e, - 0x5f, 0xd5, 0xcb, 0xa3, 0x3b, 0x54, 0x2f, 0xa3, 0xd1, 0x10, 0xec, 0x82, 0x8a, 0x13, 0xd9, 0x21, - 0x69, 0x07, 0xdc, 0x48, 0x9b, 0xb8, 0x26, 0x3e, 0xc5, 0xb4, 0x3a, 0x75, 0x37, 0x75, 0x9f, 0x9d, - 0x89, 0xbd, 0xef, 0xb1, 0x13, 0x5a, 0x4d, 0x50, 0xe1, 0xe8, 0x0e, 0xa6, 0x3a, 0x74, 0xc6, 0x62, - 0x9b, 0x5f, 0x8a, 0x60, 0x41, 0x5c, 0x41, 0x5c, 0xfc, 0x43, 0x30, 0x1b, 0x77, 0x91, 0xf7, 0xa5, - 0xd8, 0x94, 0xf3, 0xd0, 0x07, 0x3c, 0x4b, 0x9b, 0x61, 0x40, 0x5d, 0x9c, 0x81, 0x1e, 0x28, 0x47, - 0xd4, 0x3c, 0x4d, 0xaa, 0xa0, 0x4c, 0x52, 0x34, 0xeb, 0xff, 0x3c, 0xa1, 0xf1, 0x0e, 0x68, 0x6b, - 0x4c, 0x74, 0x70, 0x59, 0x2f, 0xbd, 0x68, 0xed, 0xbe, 0x4c, 0x6d, 0xe8, 0x25, 0xa6, 0x9e, 0xee, - 0x15, 0x01, 0xd5, 0x13, 0x4e, 0x8a, 0x7c, 0xdf, 0xee, 0x67, 0xb9, 0xd3, 0xbf, 0xcc, 0x8d, 0x8b, - 0x59, 0x61, 0x8a, 0x2d, 0x2e, 0x78, 0x1b, 0xca, 0xf0, 0x82, 0xc0, 0xeb, 0x65, 0x51, 0x33, 0xbf, - 0x83, 0xd2, 0xb8, 0x60, 0x1a, 0x75, 0x0c, 0x56, 0x4d, 0x6c, 0x63, 0x0b, 0x85, 0x5e, 0x90, 0x05, - 0xfd, 0x31, 0x21, 0xa8, 0x32, 0xd4, 0x4b, 0x73, 0x5e, 0x83, 0x32, 0xed, 0x21, 0x3f, 0x8b, 0x98, - 0x9d, 0x10, 0x51, 0x62, 0x52, 0x69, 0xf5, 0x0f, 0x12, 0xf8, 0x8b, 0x4f, 0x83, 0x43, 0xdc, 0x90, - 0xb8, 0x56, 0x3b, 0xfe, 0x0f, 0xa9, 0xfe, 0x79, 0xf7, 0x4c, 0xb3, 0x9e, 0xef, 0xc7, 0x27, 0x1e, - 0xb3, 0x03, 0x9a, 0x22, 0xa6, 0xa1, 0x3c, 0xba, 0x43, 0xd9, 0xf3, 0x1a, 0x0b, 0xea, 0x7c, 0x04, - 0x33, 0x21, 0xf8, 0x51, 0x02, 0x32, 0x6f, 0x9e, 0x4d, 0xde, 0x45, 0xc4, 0x24, 0x61, 0xbf, 0xed, - 0x07, 0x5e, 0x97, 0x98, 0x38, 0x48, 0x5c, 0xcd, 0x71, 0x57, 0xcd, 0x3c, 0x57, 0xcf, 0x50, 0x60, - 0x3e, 0x4f, 0x0e, 0x1f, 0x88, 0xb3, 0xb1, 0xbf, 0x2d, 0xf1, 0xe6, 0xd6, 0xf3, 0x73, 0xa8, 0xbe, - 0x7e, 0x92, 0xbf, 0x09, 0xdf, 0x80, 0xe5, 0x9b, 0x7e, 0x0b, 0x3f, 0xf3, 0xdc, 0xcf, 0xbf, 0x79, - 0x7e, 0x76, 0x93, 0xfc, 0xd8, 0xc3, 0x9a, 0xf0, 0x50, 0xca, 0xc6, 0xa9, 0x5e, 0x32, 0xb3, 0x01, - 0x78, 0x04, 0x8a, 0xbc, 0xe7, 0x02, 0x03, 0x38, 0xe6, 0x9f, 0x3c, 0x4c, 0xab, 0x87, 0xfc, 0x98, - 0x00, 0x05, 0x01, 0x0c, 0x43, 0x54, 0x07, 0x74, 0xb8, 0x86, 0x06, 0xa8, 0x50, 0xd4, 0x25, 0xae, - 0x45, 0xb3, 0xe3, 0x54, 0x9c, 0x70, 0x9c, 0xa0, 0x50, 0x4b, 0x4f, 0x94, 0x01, 0x96, 0x12, 0x86, - 0xb0, 0xbf, 0xc0, 0xed, 0x6f, 0xe7, 0xda, 0x8f, 0xb3, 0xe3, 0x0a, 0x56, 0x44, 0x05, 0x8b, 0xe9, - 0x28, 0xd5, 0x17, 0x69, 0xfa, 0x27, 0x7b, 0x13, 0x18, 0x05, 0x6e, 0xb6, 0x88, 0xc5, 0x49, 0xdf, - 0x04, 0x93, 0x4a, 0x57, 0x70, 0x04, 0x8a, 0x5c, 0x5d, 0xd8, 0x5f, 0xba, 0xfb, 0xf6, 0x9f, 0xa0, - 0xc0, 0x1d, 0xb9, 0xfd, 0x61, 0x88, 0xea, 0x00, 0x0f, 0xd7, 0xda, 0xde, 0xf9, 0x77, 0xb9, 0x70, - 0x3e, 0x90, 0xa5, 0x8b, 0x81, 0x2c, 0x7d, 0x1b, 0xc8, 0xd2, 0xd9, 0xb5, 0x5c, 0xb8, 0xb8, 0x96, - 0x0b, 0x5f, 0xaf, 0xe5, 0xc2, 0xab, 0x7b, 0x16, 0x09, 0x4f, 0x22, 0x43, 0xe9, 0x78, 0x8e, 0xca, - 0x50, 0xf7, 0x6d, 0x64, 0x50, 0xbe, 0x52, 0x4f, 0x53, 0x9f, 0x71, 0xf6, 0x39, 0xa6, 0xc6, 0x2c, - 0xff, 0x9a, 0x3e, 0xf8, 0x11, 0x00, 0x00, 0xff, 0xff, 0xbc, 0xa8, 0x1c, 0xb0, 0x7f, 0x08, 0x00, - 0x00, -} - -func (m *AccumulationTime) 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 *AccumulationTime) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AccumulationTime) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.PreviousAccumulationTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousAccumulationTime):]) - if err1 != nil { - return 0, err1 - } - i -= n1 - i = encodeVarintGenesis(dAtA, i, uint64(n1)) - i-- - dAtA[i] = 0x12 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *GenesisRewardState) 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 *GenesisRewardState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisRewardState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.MultiRewardIndexes) > 0 { - for iNdEx := len(m.MultiRewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.MultiRewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.AccumulationTimes) > 0 { - for iNdEx := len(m.AccumulationTimes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.AccumulationTimes[iNdEx].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 (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.EarnClaims) > 0 { - for iNdEx := len(m.EarnClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.EarnClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x72 - } - } - { - size, err := m.EarnRewardState.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x6a - if len(m.SavingsClaims) > 0 { - for iNdEx := len(m.SavingsClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SavingsClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x62 - } - } - { - size, err := m.SavingsRewardState.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x5a - if len(m.SwapClaims) > 0 { - for iNdEx := len(m.SwapClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SwapClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x52 - } - } - if len(m.DelegatorClaims) > 0 { - for iNdEx := len(m.DelegatorClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DelegatorClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - } - } - if len(m.HardLiquidityProviderClaims) > 0 { - for iNdEx := len(m.HardLiquidityProviderClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.HardLiquidityProviderClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - } - } - if len(m.USDXMintingClaims) > 0 { - for iNdEx := len(m.USDXMintingClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.USDXMintingClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - } - { - size, err := m.SwapRewardState.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.DelegatorRewardState.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.HardBorrowRewardState.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.HardSupplyRewardState.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.USDXRewardState.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 *AccumulationTime) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousAccumulationTime) - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *GenesisRewardState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.AccumulationTimes) > 0 { - for _, e := range m.AccumulationTimes { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.MultiRewardIndexes) > 0 { - for _, e := range m.MultiRewardIndexes { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -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)) - l = m.USDXRewardState.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.HardSupplyRewardState.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.HardBorrowRewardState.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.DelegatorRewardState.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.SwapRewardState.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.USDXMintingClaims) > 0 { - for _, e := range m.USDXMintingClaims { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.HardLiquidityProviderClaims) > 0 { - for _, e := range m.HardLiquidityProviderClaims { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.DelegatorClaims) > 0 { - for _, e := range m.DelegatorClaims { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.SwapClaims) > 0 { - for _, e := range m.SwapClaims { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - l = m.SavingsRewardState.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.SavingsClaims) > 0 { - for _, e := range m.SavingsClaims { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - l = m.EarnRewardState.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.EarnClaims) > 0 { - for _, e := range m.EarnClaims { - 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 *AccumulationTime) 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: AccumulationTime: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AccumulationTime: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - 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 ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PreviousAccumulationTime", 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 := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.PreviousAccumulationTime, 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 (m *GenesisRewardState) 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: GenesisRewardState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisRewardState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AccumulationTimes", 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.AccumulationTimes = append(m.AccumulationTimes, AccumulationTime{}) - if err := m.AccumulationTimes[len(m.AccumulationTimes)-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 MultiRewardIndexes", 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.MultiRewardIndexes = append(m.MultiRewardIndexes, MultiRewardIndex{}) - if err := m.MultiRewardIndexes[len(m.MultiRewardIndexes)-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 (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 USDXRewardState", 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.USDXRewardState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HardSupplyRewardState", 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.HardSupplyRewardState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HardBorrowRewardState", 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.HardBorrowRewardState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorRewardState", 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.DelegatorRewardState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SwapRewardState", 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.SwapRewardState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field USDXMintingClaims", 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.USDXMintingClaims = append(m.USDXMintingClaims, USDXMintingClaim{}) - if err := m.USDXMintingClaims[len(m.USDXMintingClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HardLiquidityProviderClaims", 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.HardLiquidityProviderClaims = append(m.HardLiquidityProviderClaims, HardLiquidityProviderClaim{}) - if err := m.HardLiquidityProviderClaims[len(m.HardLiquidityProviderClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorClaims", 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.DelegatorClaims = append(m.DelegatorClaims, DelegatorClaim{}) - if err := m.DelegatorClaims[len(m.DelegatorClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SwapClaims", 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.SwapClaims = append(m.SwapClaims, SwapClaim{}) - if err := m.SwapClaims[len(m.SwapClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 11: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SavingsRewardState", 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.SavingsRewardState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 12: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SavingsClaims", 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.SavingsClaims = append(m.SavingsClaims, SavingsClaim{}) - if err := m.SavingsClaims[len(m.SavingsClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 13: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EarnRewardState", 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.EarnRewardState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 14: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EarnClaims", 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.EarnClaims = append(m.EarnClaims, EarnClaim{}) - if err := m.EarnClaims[len(m.EarnClaims)-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/incentive/types/genesis_test.go b/x/incentive/types/genesis_test.go deleted file mode 100644 index 4cf95d2a..00000000 --- a/x/incentive/types/genesis_test.go +++ /dev/null @@ -1,191 +0,0 @@ -package types - -import ( - "strings" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestGenesisState_Validate(t *testing.T) { - type errArgs struct { - expectPass bool - contains string - } - - testCases := []struct { - name string - genesis GenesisState - errArgs errArgs - }{ - { - name: "default", - genesis: DefaultGenesisState(), - errArgs: errArgs{ - expectPass: true, - }, - }, - { - name: "valid", - genesis: GenesisState{ - Params: NewParams( - RewardPeriods{ - NewRewardPeriod( - true, - "bnb-a", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.NewCoin("ukava", sdkmath.NewInt(25000)), - ), - }, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - MultipliersPerDenoms{ - { - Denom: "ukava", - Multipliers: Multipliers{ - NewMultiplier("small", 1, sdk.MustNewDecFromStr("0.33")), - NewMultiplier("large", 12, sdk.MustNewDecFromStr("1.00")), - }, - }, - }, - time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - ), - USDXRewardState: GenesisRewardState{ - AccumulationTimes: AccumulationTimes{{ - CollateralType: "bnb-a", - PreviousAccumulationTime: time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - }}, - MultiRewardIndexes: MultiRewardIndexes{{ - CollateralType: "bnb-a", - RewardIndexes: normalRewardIndexes, - }}, - }, - USDXMintingClaims: USDXMintingClaims{ - { - BaseClaim: BaseClaim{ - Owner: sdk.AccAddress(crypto.AddressHash([]byte("KavaTestUser1"))), - Reward: sdk.NewCoin("ukava", sdkmath.NewInt(100000000)), - }, - RewardIndexes: []RewardIndex{ - { - CollateralType: "bnb-a", - RewardFactor: sdk.ZeroDec(), - }, - }, - }, - }, - }, - errArgs: errArgs{ - expectPass: true, - }, - }, - { - name: "invalid genesis accumulation time", - genesis: GenesisState{ - Params: DefaultParams(), - USDXRewardState: GenesisRewardState{ - AccumulationTimes: AccumulationTimes{{ - CollateralType: "", - PreviousAccumulationTime: time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - }}, - MultiRewardIndexes: MultiRewardIndexes{{ - CollateralType: "bnb-a", - RewardIndexes: normalRewardIndexes, - }}, - }, - USDXMintingClaims: DefaultUSDXClaims, - }, - errArgs: errArgs{ - expectPass: false, - contains: "collateral type must be defined", - }, - }, - { - name: "invalid claim", - genesis: GenesisState{ - Params: DefaultParams(), - USDXRewardState: DefaultGenesisRewardState, - USDXMintingClaims: USDXMintingClaims{ - { - BaseClaim: BaseClaim{ - Owner: nil, // invalid address - Reward: sdk.NewCoin("ukava", sdkmath.NewInt(100000000)), - }, - RewardIndexes: []RewardIndex{ - { - CollateralType: "bnb-a", - RewardFactor: sdk.ZeroDec(), - }, - }, - }, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "claim owner cannot be empty", - }, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.genesis.Validate() - if tc.errArgs.expectPass { - require.NoError(t, err, tc.name) - } else { - require.Error(t, err, tc.name) - require.True(t, strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func TestGenesisAccumulationTimes_Validate(t *testing.T) { - testCases := []struct { - name string - gats AccumulationTimes - wantErr bool - }{ - { - name: "normal", - gats: AccumulationTimes{ - {CollateralType: "btcb", PreviousAccumulationTime: normalAccumulationtime}, - {CollateralType: "bnb", PreviousAccumulationTime: normalAccumulationtime}, - }, - wantErr: false, - }, - { - name: "empty", - gats: nil, - wantErr: false, - }, - { - name: "empty collateral type", - gats: AccumulationTimes{ - {PreviousAccumulationTime: normalAccumulationtime}, - }, - wantErr: true, - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.gats.Validate() - if tc.wantErr { - require.NotNil(t, err) - } else { - require.Nil(t, err) - } - }) - } -} - -var normalAccumulationtime = time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) diff --git a/x/incentive/types/keys.go b/x/incentive/types/keys.go deleted file mode 100644 index 803a8e18..00000000 --- a/x/incentive/types/keys.go +++ /dev/null @@ -1,39 +0,0 @@ -package types - -const ( - // ModuleName The name that will be used throughout the module - ModuleName = "incentive" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default name for parameter store - DefaultParamspace = ModuleName -) - -// Key Prefixes -var ( - USDXMintingClaimKeyPrefix = []byte{0x01} // prefix for keys that store USDX minting claims - USDXMintingRewardFactorKeyPrefix = []byte{0x02} // prefix for key that stores USDX minting reward factors - PreviousUSDXMintingRewardAccrualTimeKeyPrefix = []byte{0x03} // prefix for key that stores the blocktime - HardLiquidityClaimKeyPrefix = []byte{0x04} // prefix for keys that store Hard liquidity claims - HardSupplyRewardIndexesKeyPrefix = []byte{0x05} // prefix for key that stores Hard supply reward indexes - PreviousHardSupplyRewardAccrualTimeKeyPrefix = []byte{0x06} // prefix for key that stores the previous time Hard supply rewards accrued - HardBorrowRewardIndexesKeyPrefix = []byte{0x07} // prefix for key that stores Hard borrow reward indexes - PreviousHardBorrowRewardAccrualTimeKeyPrefix = []byte{0x08} // prefix for key that stores the previous time Hard borrow rewards accrued - DelegatorClaimKeyPrefix = []byte{0x09} // prefix for keys that store delegator claims - DelegatorRewardIndexesKeyPrefix = []byte{0x10} // prefix for key that stores delegator reward indexes - PreviousDelegatorRewardAccrualTimeKeyPrefix = []byte{0x11} // prefix for key that stores the previous time delegator rewards accrued - SwapClaimKeyPrefix = []byte{0x12} // prefix for keys that store swap claims - SwapRewardIndexesKeyPrefix = []byte{0x13} // prefix for key that stores swap reward indexes - PreviousSwapRewardAccrualTimeKeyPrefix = []byte{0x14} // prefix for key that stores the previous time swap rewards accrued - SavingsClaimKeyPrefix = []byte{0x15} // prefix for keys that store savings claims - SavingsRewardIndexesKeyPrefix = []byte{0x16} // prefix for key that stores savings reward indexes - PreviousSavingsRewardAccrualTimeKeyPrefix = []byte{0x17} // prefix for key that stores the previous time savings rewards accrued - EarnClaimKeyPrefix = []byte{0x18} // prefix for keys that store earn claims - EarnRewardIndexesKeyPrefix = []byte{0x19} // prefix for key that stores earn reward indexes - PreviousEarnRewardAccrualTimeKeyPrefix = []byte{0x20} // prefix for key that stores the previous time earn rewards accrued -) diff --git a/x/incentive/types/msg.go b/x/incentive/types/msg.go deleted file mode 100644 index c4ef901f..00000000 --- a/x/incentive/types/msg.go +++ /dev/null @@ -1,292 +0,0 @@ -package types - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" -) - -const MaxDenomsToClaim = 1000 - -// ensure Msg interface compliance at compile time -var ( - _ sdk.Msg = &MsgClaimUSDXMintingReward{} - _ sdk.Msg = &MsgClaimHardReward{} - _ sdk.Msg = &MsgClaimDelegatorReward{} - _ sdk.Msg = &MsgClaimSwapReward{} - _ sdk.Msg = &MsgClaimSavingsReward{} - _ sdk.Msg = &MsgClaimEarnReward{} - - _ legacytx.LegacyMsg = &MsgClaimUSDXMintingReward{} - _ legacytx.LegacyMsg = &MsgClaimHardReward{} - _ legacytx.LegacyMsg = &MsgClaimDelegatorReward{} - _ legacytx.LegacyMsg = &MsgClaimSwapReward{} - _ legacytx.LegacyMsg = &MsgClaimSavingsReward{} - _ legacytx.LegacyMsg = &MsgClaimEarnReward{} -) - -const ( - TypeMsgClaimUSDXMintingReward = "claim_usdx_minting_reward" - TypeMsgClaimHardReward = "claim_hard_reward" - TypeMsgClaimDelegatorReward = "claim_delegator_reward" - TypeMsgClaimSwapReward = "claim_swap_reward" - TypeMsgClaimSavingsReward = "claim_savings_reward" - TypeMsgClaimEarnReward = "claim_earn_reward" -) - -// NewMsgClaimUSDXMintingReward returns a new MsgClaimUSDXMintingReward. -func NewMsgClaimUSDXMintingReward(sender string, multiplierName string) MsgClaimUSDXMintingReward { - return MsgClaimUSDXMintingReward{ - Sender: sender, - MultiplierName: multiplierName, - } -} - -// Route return the message type used for routing the message. -func (msg MsgClaimUSDXMintingReward) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgClaimUSDXMintingReward) Type() string { return TypeMsgClaimUSDXMintingReward } - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgClaimUSDXMintingReward) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty or invalid") - } - if msg.MultiplierName == "" { - return errorsmod.Wrap(ErrInvalidMultiplier, "multiplier name cannot be empty") - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgClaimUSDXMintingReward) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgClaimUSDXMintingReward) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgClaimHardReward returns a new MsgClaimHardReward. -func NewMsgClaimHardReward(sender string, denomsToClaim Selections) MsgClaimHardReward { - return MsgClaimHardReward{ - Sender: sender, - DenomsToClaim: denomsToClaim, - } -} - -// Route return the message type used for routing the message. -func (msg MsgClaimHardReward) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgClaimHardReward) Type() string { - return TypeMsgClaimHardReward -} - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgClaimHardReward) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty or invalid") - } - if err := msg.DenomsToClaim.Validate(); err != nil { - return err - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgClaimHardReward) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgClaimHardReward) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgClaimDelegatorReward returns a new MsgClaimDelegatorReward. -func NewMsgClaimDelegatorReward(sender string, denomsToClaim Selections) MsgClaimDelegatorReward { - return MsgClaimDelegatorReward{ - Sender: sender, - DenomsToClaim: denomsToClaim, - } -} - -// Route return the message type used for routing the message. -func (msg MsgClaimDelegatorReward) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgClaimDelegatorReward) Type() string { - return TypeMsgClaimDelegatorReward -} - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgClaimDelegatorReward) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty or invalid") - } - if err := msg.DenomsToClaim.Validate(); err != nil { - return err - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgClaimDelegatorReward) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgClaimDelegatorReward) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgClaimSwapReward returns a new MsgClaimSwapReward. -func NewMsgClaimSwapReward(sender string, denomsToClaim Selections) MsgClaimSwapReward { - return MsgClaimSwapReward{ - Sender: sender, - DenomsToClaim: denomsToClaim, - } -} - -// Route return the message type used for routing the message. -func (msg MsgClaimSwapReward) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgClaimSwapReward) Type() string { - return TypeMsgClaimSwapReward -} - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgClaimSwapReward) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty or invalid") - } - if err := msg.DenomsToClaim.Validate(); err != nil { - return err - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgClaimSwapReward) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgClaimSwapReward) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgClaimSavingsReward returns a new MsgClaimSavingsReward. -func NewMsgClaimSavingsReward(sender string, denomsToClaim Selections) MsgClaimSavingsReward { - return MsgClaimSavingsReward{ - Sender: sender, - DenomsToClaim: denomsToClaim, - } -} - -// Route return the message type used for routing the message. -func (msg MsgClaimSavingsReward) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgClaimSavingsReward) Type() string { - return TypeMsgClaimSavingsReward -} - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgClaimSavingsReward) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty or invalid") - } - if err := msg.DenomsToClaim.Validate(); err != nil { - return err - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgClaimSavingsReward) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgClaimSavingsReward) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgClaimEarnReward returns a new MsgClaimEarnReward. -func NewMsgClaimEarnReward(sender string, denomsToClaim Selections) MsgClaimEarnReward { - return MsgClaimEarnReward{ - Sender: sender, - DenomsToClaim: denomsToClaim, - } -} - -// Route return the message type used for routing the message. -func (msg MsgClaimEarnReward) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgClaimEarnReward) Type() string { - return TypeMsgClaimEarnReward -} - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgClaimEarnReward) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty or invalid") - } - if err := msg.DenomsToClaim.Validate(); err != nil { - return err - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgClaimEarnReward) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgClaimEarnReward) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} diff --git a/x/incentive/types/msg_test.go b/x/incentive/types/msg_test.go deleted file mode 100644 index 9e9a1dae..00000000 --- a/x/incentive/types/msg_test.go +++ /dev/null @@ -1,233 +0,0 @@ -package types_test - -import ( - "errors" - "fmt" - "testing" - - "github.com/cometbft/cometbft/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/require" - - "github.com/kava-labs/kava/x/incentive/types" -) - -func TestMsgClaim_Validate(t *testing.T) { - validAddress := sdk.AccAddress(crypto.AddressHash([]byte("KavaTest1"))).String() - - type expectedErr struct { - wraps error - pass bool - } - type msgArgs struct { - sender string - denomsToClaim types.Selections - } - tests := []struct { - name string - msgArgs msgArgs - expect expectedErr - }{ - { - name: "normal multiplier is valid", - msgArgs: msgArgs{ - sender: validAddress, - denomsToClaim: types.Selections{ - { - Denom: "hard", - MultiplierName: "large", - }, - }, - }, - expect: expectedErr{ - pass: true, - }, - }, - { - name: "empty multiplier name is invalid", - msgArgs: msgArgs{ - sender: validAddress, - denomsToClaim: types.Selections{ - { - Denom: "hard", - MultiplierName: "", - }, - }, - }, - expect: expectedErr{ - wraps: types.ErrInvalidMultiplier, - }, - }, - { - name: "empty denoms to claim is not valid", - msgArgs: msgArgs{ - sender: validAddress, - denomsToClaim: types.Selections{}, - }, - expect: expectedErr{ - wraps: types.ErrInvalidClaimDenoms, - }, - }, - { - name: "nil denoms to claim is not valid", - msgArgs: msgArgs{ - sender: validAddress, - denomsToClaim: nil, - }, - expect: expectedErr{ - wraps: types.ErrInvalidClaimDenoms, - }, - }, - { - name: "invalid sender", - msgArgs: msgArgs{ - sender: "", - denomsToClaim: types.Selections{ - { - Denom: "hard", - MultiplierName: "medium", - }, - }, - }, - expect: expectedErr{ - wraps: sdkerrors.ErrInvalidAddress, - }, - }, - { - name: "invalid claim denom", - msgArgs: msgArgs{ - sender: validAddress, - denomsToClaim: types.Selections{ - { - Denom: "a denom string that is invalid because it is much too long", - MultiplierName: "medium", - }, - }, - }, - expect: expectedErr{ - wraps: types.ErrInvalidClaimDenoms, - }, - }, - { - name: "too many claim denoms", - msgArgs: msgArgs{ - sender: validAddress, - denomsToClaim: tooManySelections(), - }, - expect: expectedErr{ - wraps: types.ErrInvalidClaimDenoms, - }, - }, - { - name: "duplicated claim denoms", - msgArgs: msgArgs{ - sender: validAddress, - denomsToClaim: types.Selections{ - { - Denom: "hard", - MultiplierName: "medium", - }, - { - Denom: "hard", - MultiplierName: "large", - }, - }, - }, - expect: expectedErr{ - wraps: types.ErrInvalidClaimDenoms, - }, - }, - } - - for _, tc := range tests { - msgClaimHardReward := types.NewMsgClaimHardReward(tc.msgArgs.sender, tc.msgArgs.denomsToClaim) - msgClaimDelegatorReward := types.NewMsgClaimDelegatorReward(tc.msgArgs.sender, tc.msgArgs.denomsToClaim) - msgClaimSwapReward := types.NewMsgClaimSwapReward(tc.msgArgs.sender, tc.msgArgs.denomsToClaim) - msgClaimSavingsReward := types.NewMsgClaimSavingsReward(tc.msgArgs.sender, tc.msgArgs.denomsToClaim) - msgs := []sdk.Msg{&msgClaimHardReward, &msgClaimDelegatorReward, &msgClaimSwapReward, &msgClaimSavingsReward} - for _, msg := range msgs { - t.Run(tc.name, func(t *testing.T) { - err := msg.ValidateBasic() - if tc.expect.pass { - require.NoError(t, err) - } else { - require.Truef(t, errors.Is(err, tc.expect.wraps), "expected error '%s' was not actual '%s'", tc.expect.wraps, err) - } - }) - } - } -} - -func TestMsgClaimUSDXMintingReward_Validate(t *testing.T) { - validAddress := sdk.AccAddress(crypto.AddressHash([]byte("KavaTest1"))).String() - - type expectedErr struct { - wraps error - pass bool - } - type msgArgs struct { - sender string - multiplierName string - } - tests := []struct { - name string - msgArgs msgArgs - expect expectedErr - }{ - { - name: "normal multiplier is valid", - msgArgs: msgArgs{ - sender: validAddress, - multiplierName: "large", - }, - expect: expectedErr{ - pass: true, - }, - }, - { - name: "invalid sender", - msgArgs: msgArgs{ - sender: "", - multiplierName: "medium", - }, - expect: expectedErr{ - wraps: sdkerrors.ErrInvalidAddress, - }, - }, - { - name: "empty multiplier is invalid", - msgArgs: msgArgs{ - sender: validAddress, - multiplierName: "", - }, - expect: expectedErr{ - wraps: types.ErrInvalidMultiplier, - }, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - msg := types.NewMsgClaimUSDXMintingReward(tc.msgArgs.sender, tc.msgArgs.multiplierName) - - err := msg.ValidateBasic() - if tc.expect.pass { - require.NoError(t, err) - } else { - require.Truef(t, errors.Is(err, tc.expect.wraps), "expected error '%s' was not actual '%s'", tc.expect.wraps, err) - } - }) - } -} - -func tooManySelections() types.Selections { - selections := make(types.Selections, types.MaxDenomsToClaim+1) - for i := range selections { - selections[i] = types.Selection{ - Denom: fmt.Sprintf("denom%d", i), - MultiplierName: "large", - } - } - return selections -} diff --git a/x/incentive/types/multipliers.go b/x/incentive/types/multipliers.go deleted file mode 100644 index 689bea64..00000000 --- a/x/incentive/types/multipliers.go +++ /dev/null @@ -1,139 +0,0 @@ -package types - -import ( - "fmt" - "sort" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewMultiplier returns a new Multiplier -func NewMultiplier(name string, lockup int64, factor sdk.Dec) Multiplier { - return Multiplier{ - Name: name, - MonthsLockup: lockup, - Factor: factor, - } -} - -// Validate multiplier param -func (m Multiplier) Validate() error { - if m.Name == "" { - return fmt.Errorf("expected non empty name") - } - if m.MonthsLockup < 0 { - return fmt.Errorf("expected non-negative lockup, got %d", m.MonthsLockup) - } - if m.Factor.IsNegative() { - return fmt.Errorf("expected non-negative factor, got %s", m.Factor.String()) - } - - return nil -} - -// Multipliers is a slice of Multiplier -type Multipliers []Multiplier - -// Validate validates each multiplier -func (ms Multipliers) Validate() error { - for _, m := range ms { - if err := m.Validate(); err != nil { - return err - } - } - return nil -} - -// Get returns a multiplier with a matching name -func (ms Multipliers) Get(name string) (Multiplier, bool) { - for _, m := range ms { - if m.Name == name { - return m, true - } - } - return Multiplier{}, false -} - -// MultipliersPerDenoms is a slice of MultipliersPerDenom -type MultipliersPerDenoms []MultipliersPerDenom - -// Validate checks each denom and multipliers for invalid values. -func (mpd MultipliersPerDenoms) Validate() error { - foundDenoms := map[string]bool{} - - for _, item := range mpd { - if err := sdk.ValidateDenom(item.Denom); err != nil { - return err - } - if err := item.Multipliers.Validate(); err != nil { - return err - } - - if foundDenoms[item.Denom] { - return fmt.Errorf("duplicate denom %s", item.Denom) - } - foundDenoms[item.Denom] = true - } - return nil -} - -// NewSelection returns a new Selection -func NewSelection(denom, multiplierName string) Selection { - return Selection{ - Denom: denom, - MultiplierName: multiplierName, - } -} - -// Validate performs basic validation checks -func (s Selection) Validate() error { - if err := sdk.ValidateDenom(s.Denom); err != nil { - return errorsmod.Wrap(ErrInvalidClaimDenoms, err.Error()) - } - if s.MultiplierName == "" { - return errorsmod.Wrap(ErrInvalidMultiplier, "multiplier name cannot be empty") - } - return nil -} - -// Selections are a list of denom - multiplier pairs that specify what rewards to claim and with what lockups. -type Selections []Selection - -// NewSelectionsFromMap creates a new set of selections from a string to string map. -// It sorts the output before returning. -func NewSelectionsFromMap(selectionMap map[string]string) Selections { - var selections Selections - for k, v := range selectionMap { - selections = append(selections, NewSelection(k, v)) - } - // deterministically sort the slice to protect against the random range order causing consensus failures - sort.Slice(selections, func(i, j int) bool { - if selections[i].Denom != selections[j].Denom { - return selections[i].Denom < selections[j].Denom - } - return selections[i].MultiplierName < selections[j].MultiplierName - }) - return selections -} - -// Valdate performs basic validaton checks -func (ss Selections) Validate() error { - if len(ss) == 0 { - return errorsmod.Wrap(ErrInvalidClaimDenoms, "cannot claim 0 denoms") - } - if len(ss) >= MaxDenomsToClaim { - return errorsmod.Wrapf(ErrInvalidClaimDenoms, "cannot claim more than %d denoms", MaxDenomsToClaim) - } - foundDenoms := map[string]bool{} - for _, s := range ss { - if err := s.Validate(); err != nil { - return err - } - if foundDenoms[s.Denom] { - return errorsmod.Wrapf(ErrInvalidClaimDenoms, "cannot claim denom '%s' more than once", s.Denom) - } - foundDenoms[s.Denom] = true - } - return nil -} diff --git a/x/incentive/types/params.go b/x/incentive/types/params.go deleted file mode 100644 index 72184c6b..00000000 --- a/x/incentive/types/params.go +++ /dev/null @@ -1,315 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "strings" - "time" - - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - - kavadistTypes "github.com/kava-labs/kava/x/kavadist/types" -) - -// Parameter keys and default values -var ( - KeyUSDXMintingRewardPeriods = []byte("USDXMintingRewardPeriods") - KeyHardSupplyRewardPeriods = []byte("HardSupplyRewardPeriods") - KeyHardBorrowRewardPeriods = []byte("HardBorrowRewardPeriods") - KeyDelegatorRewardPeriods = []byte("DelegatorRewardPeriods") - KeySwapRewardPeriods = []byte("SwapRewardPeriods") - KeySavingsRewardPeriods = []byte("SavingsRewardPeriods") - KeyEarnRewardPeriods = []byte("EarnRewardPeriods") - KeyClaimEnd = []byte("ClaimEnd") - KeyMultipliers = []byte("ClaimMultipliers") - - DefaultActive = false - DefaultRewardPeriods = RewardPeriods{} - DefaultMultiRewardPeriods = MultiRewardPeriods{} - DefaultMultipliers = MultipliersPerDenoms{} - DefaultClaimEnd = tmtime.Canonical(time.Unix(1, 0)) - - BondDenom = "ukava" - USDXMintingRewardDenom = "ukava" - - IncentiveMacc = kavadistTypes.ModuleName -) - -// NewParams returns a new params object -func NewParams( - usdxMinting RewardPeriods, - // MultiRewardPeriods - hardSupply, hardBorrow, delegator, swap, savings, earn MultiRewardPeriods, - multipliers MultipliersPerDenoms, - claimEnd time.Time, -) Params { - return Params{ - USDXMintingRewardPeriods: usdxMinting, - HardSupplyRewardPeriods: hardSupply, - HardBorrowRewardPeriods: hardBorrow, - DelegatorRewardPeriods: delegator, - SwapRewardPeriods: swap, - SavingsRewardPeriods: savings, - ClaimMultipliers: multipliers, - ClaimEnd: claimEnd, - } -} - -// DefaultParams returns default params for incentive module -func DefaultParams() Params { - return NewParams( - DefaultRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultipliers, - DefaultClaimEnd, - ) -} - -// ParamKeyTable Key declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements the ParamSet interface and returns all the key/value pairs -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyUSDXMintingRewardPeriods, &p.USDXMintingRewardPeriods, validateRewardPeriodsParam), - paramtypes.NewParamSetPair(KeyHardSupplyRewardPeriods, &p.HardSupplyRewardPeriods, validateMultiRewardPeriodsParam), - paramtypes.NewParamSetPair(KeyHardBorrowRewardPeriods, &p.HardBorrowRewardPeriods, validateMultiRewardPeriodsParam), - paramtypes.NewParamSetPair(KeyDelegatorRewardPeriods, &p.DelegatorRewardPeriods, validateMultiRewardPeriodsParam), - paramtypes.NewParamSetPair(KeySwapRewardPeriods, &p.SwapRewardPeriods, validateMultiRewardPeriodsParam), - paramtypes.NewParamSetPair(KeySavingsRewardPeriods, &p.SavingsRewardPeriods, validateMultiRewardPeriodsParam), - paramtypes.NewParamSetPair(KeyEarnRewardPeriods, &p.EarnRewardPeriods, validateMultiRewardPeriodsParam), - paramtypes.NewParamSetPair(KeyMultipliers, &p.ClaimMultipliers, validateMultipliersPerDenomParam), - paramtypes.NewParamSetPair(KeyClaimEnd, &p.ClaimEnd, validateClaimEndParam), - } -} - -// Validate checks that the parameters have valid values. -func (p Params) Validate() error { - if err := validateMultipliersPerDenomParam(p.ClaimMultipliers); err != nil { - return err - } - - if err := validateRewardPeriodsParam(p.USDXMintingRewardPeriods); err != nil { - return err - } - - if err := validateMultiRewardPeriodsParam(p.HardSupplyRewardPeriods); err != nil { - return err - } - - if err := validateMultiRewardPeriodsParam(p.HardBorrowRewardPeriods); err != nil { - return err - } - - if err := validateMultiRewardPeriodsParam(p.DelegatorRewardPeriods); err != nil { - return err - } - - if err := validateMultiRewardPeriodsParam(p.SwapRewardPeriods); err != nil { - return err - } - - if err := validateMultiRewardPeriodsParam(p.SavingsRewardPeriods); err != nil { - return err - } - - if err := validateMultiRewardPeriodsParam(p.EarnRewardPeriods); err != nil { - return err - } - - return nil -} - -func validateRewardPeriodsParam(i interface{}) error { - rewards, ok := i.(RewardPeriods) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return rewards.Validate() -} - -func validateMultiRewardPeriodsParam(i interface{}) error { - rewards, ok := i.(MultiRewardPeriods) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return rewards.Validate() -} - -func validateMultipliersPerDenomParam(i interface{}) error { - multipliers, ok := i.(MultipliersPerDenoms) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - return multipliers.Validate() -} - -func validateClaimEndParam(i interface{}) error { - endTime, ok := i.(time.Time) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - if endTime.Unix() <= 0 { - return fmt.Errorf("end time should not be zero") - } - return nil -} - -// NewRewardPeriod returns a new RewardPeriod -func NewRewardPeriod(active bool, collateralType string, start time.Time, end time.Time, reward sdk.Coin) RewardPeriod { - return RewardPeriod{ - Active: active, - CollateralType: collateralType, - Start: start, - End: end, - RewardsPerSecond: reward, - } -} - -// NewMultiRewardPeriodFromRewardPeriod converts a RewardPeriod into a MultiRewardPeriod. -// It's useful for compatibility between single and multi denom rewards. -func NewMultiRewardPeriodFromRewardPeriod(period RewardPeriod) MultiRewardPeriod { - return NewMultiRewardPeriod( - period.Active, - period.CollateralType, - period.Start, - period.End, - sdk.NewCoins(period.RewardsPerSecond), - ) -} - -// Validate performs a basic check of a RewardPeriod fields. -func (rp RewardPeriod) Validate() error { - if rp.Start.Unix() <= 0 { - return errors.New("reward period start time cannot be 0") - } - if rp.End.Unix() <= 0 { - return errors.New("reward period end time cannot be 0") - } - if rp.Start.After(rp.End) { - // This is needed to ensure that the begin blocker accumulation does not panic. - return fmt.Errorf("end period time %s cannot be before start time %s", rp.End, rp.Start) - } - if rp.RewardsPerSecond.Denom != USDXMintingRewardDenom { - return fmt.Errorf("reward denom must be %s, got: %s", USDXMintingRewardDenom, rp.RewardsPerSecond.Denom) - } - if !rp.RewardsPerSecond.IsValid() { - return fmt.Errorf("invalid reward amount: %s", rp.RewardsPerSecond) - } - - if rp.RewardsPerSecond.Amount.IsZero() { - return fmt.Errorf("reward amount cannot be zero: %v", rp.RewardsPerSecond) - } - - if strings.TrimSpace(rp.CollateralType) == "" { - return fmt.Errorf("reward period collateral type cannot be blank: %v", rp) - } - return nil -} - -// RewardPeriods array of RewardPeriod -type RewardPeriods []RewardPeriod - -// Validate checks if all the RewardPeriods are valid and there are no duplicated -// entries. -func (rps RewardPeriods) Validate() error { - seenPeriods := make(map[string]bool) - for _, rp := range rps { - if seenPeriods[rp.CollateralType] { - return fmt.Errorf("duplicated reward period with collateral type %s", rp.CollateralType) - } - - if err := rp.Validate(); err != nil { - return err - } - seenPeriods[rp.CollateralType] = true - } - - return nil -} - -// NewMultiRewardPeriod returns a new MultiRewardPeriod -func NewMultiRewardPeriod(active bool, collateralType string, start time.Time, end time.Time, reward sdk.Coins) MultiRewardPeriod { - return MultiRewardPeriod{ - Active: active, - CollateralType: collateralType, - Start: start, - End: end, - RewardsPerSecond: reward, - } -} - -// Validate performs a basic check of a MultiRewardPeriod. -func (mrp MultiRewardPeriod) Validate() error { - if mrp.Start.IsZero() { - return errors.New("reward period start time cannot be 0") - } - if mrp.End.IsZero() { - return errors.New("reward period end time cannot be 0") - } - if mrp.Start.After(mrp.End) { - // This is needed to ensure that the begin blocker accumulation does not panic. - return fmt.Errorf("end period time %s cannot be before start time %s", mrp.End, mrp.Start) - } - - // This also ensures there are no 0 amount coins. - if !mrp.RewardsPerSecond.IsValid() { - return fmt.Errorf("invalid reward amount: %s", mrp.RewardsPerSecond) - } - if strings.TrimSpace(mrp.CollateralType) == "" { - return fmt.Errorf("reward period collateral type cannot be blank: %v", mrp) - } - return nil -} - -// MultiRewardPeriods array of MultiRewardPeriod -type MultiRewardPeriods []MultiRewardPeriod - -// GetMultiRewardPeriod fetches a MultiRewardPeriod from an array of MultiRewardPeriods by its denom -func (mrps MultiRewardPeriods) GetMultiRewardPeriod(denom string) (MultiRewardPeriod, bool) { - for _, rp := range mrps { - if rp.CollateralType == denom { - return rp, true - } - } - return MultiRewardPeriod{}, false -} - -// GetMultiRewardPeriodIndex returns the index of a MultiRewardPeriod inside array MultiRewardPeriods -func (mrps MultiRewardPeriods) GetMultiRewardPeriodIndex(denom string) (int, bool) { - for i, rp := range mrps { - if rp.CollateralType == denom { - return i, true - } - } - return -1, false -} - -// Validate checks if all the RewardPeriods are valid and there are no duplicated -// entries. -func (mrps MultiRewardPeriods) Validate() error { - seenPeriods := make(map[string]bool) - for _, rp := range mrps { - if seenPeriods[rp.CollateralType] { - return fmt.Errorf("duplicated reward period with collateral type %s", rp.CollateralType) - } - - if err := rp.Validate(); err != nil { - return err - } - seenPeriods[rp.CollateralType] = true - } - - return nil -} diff --git a/x/incentive/types/params.pb.go b/x/incentive/types/params.pb.go deleted file mode 100644 index 9656459b..00000000 --- a/x/incentive/types/params.pb.go +++ /dev/null @@ -1,1926 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/incentive/v1beta1/params.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" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 - -// RewardPeriod stores the state of an ongoing reward -type RewardPeriod struct { - Active bool `protobuf:"varint,1,opt,name=active,proto3" json:"active,omitempty"` - CollateralType string `protobuf:"bytes,2,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Start time.Time `protobuf:"bytes,3,opt,name=start,proto3,stdtime" json:"start"` - End time.Time `protobuf:"bytes,4,opt,name=end,proto3,stdtime" json:"end"` - RewardsPerSecond types.Coin `protobuf:"bytes,5,opt,name=rewards_per_second,json=rewardsPerSecond,proto3" json:"rewards_per_second"` -} - -func (m *RewardPeriod) Reset() { *m = RewardPeriod{} } -func (m *RewardPeriod) String() string { return proto.CompactTextString(m) } -func (*RewardPeriod) ProtoMessage() {} -func (*RewardPeriod) Descriptor() ([]byte, []int) { - return fileDescriptor_bb8833f5d745eac9, []int{0} -} -func (m *RewardPeriod) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *RewardPeriod) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_RewardPeriod.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 *RewardPeriod) XXX_Merge(src proto.Message) { - xxx_messageInfo_RewardPeriod.Merge(m, src) -} -func (m *RewardPeriod) XXX_Size() int { - return m.Size() -} -func (m *RewardPeriod) XXX_DiscardUnknown() { - xxx_messageInfo_RewardPeriod.DiscardUnknown(m) -} - -var xxx_messageInfo_RewardPeriod proto.InternalMessageInfo - -// MultiRewardPeriod supports multiple reward types -type MultiRewardPeriod struct { - Active bool `protobuf:"varint,1,opt,name=active,proto3" json:"active,omitempty"` - CollateralType string `protobuf:"bytes,2,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Start time.Time `protobuf:"bytes,3,opt,name=start,proto3,stdtime" json:"start"` - End time.Time `protobuf:"bytes,4,opt,name=end,proto3,stdtime" json:"end"` - RewardsPerSecond github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,5,rep,name=rewards_per_second,json=rewardsPerSecond,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"rewards_per_second"` -} - -func (m *MultiRewardPeriod) Reset() { *m = MultiRewardPeriod{} } -func (m *MultiRewardPeriod) String() string { return proto.CompactTextString(m) } -func (*MultiRewardPeriod) ProtoMessage() {} -func (*MultiRewardPeriod) Descriptor() ([]byte, []int) { - return fileDescriptor_bb8833f5d745eac9, []int{1} -} -func (m *MultiRewardPeriod) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MultiRewardPeriod) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MultiRewardPeriod.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 *MultiRewardPeriod) XXX_Merge(src proto.Message) { - xxx_messageInfo_MultiRewardPeriod.Merge(m, src) -} -func (m *MultiRewardPeriod) XXX_Size() int { - return m.Size() -} -func (m *MultiRewardPeriod) XXX_DiscardUnknown() { - xxx_messageInfo_MultiRewardPeriod.DiscardUnknown(m) -} - -var xxx_messageInfo_MultiRewardPeriod proto.InternalMessageInfo - -// Multiplier amount the claim rewards get increased by, along with how long the claim rewards are locked -type Multiplier struct { - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - MonthsLockup int64 `protobuf:"varint,2,opt,name=months_lockup,json=monthsLockup,proto3" json:"months_lockup,omitempty"` - Factor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=factor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"factor"` -} - -func (m *Multiplier) Reset() { *m = Multiplier{} } -func (m *Multiplier) String() string { return proto.CompactTextString(m) } -func (*Multiplier) ProtoMessage() {} -func (*Multiplier) Descriptor() ([]byte, []int) { - return fileDescriptor_bb8833f5d745eac9, []int{2} -} -func (m *Multiplier) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Multiplier) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Multiplier.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 *Multiplier) XXX_Merge(src proto.Message) { - xxx_messageInfo_Multiplier.Merge(m, src) -} -func (m *Multiplier) XXX_Size() int { - return m.Size() -} -func (m *Multiplier) XXX_DiscardUnknown() { - xxx_messageInfo_Multiplier.DiscardUnknown(m) -} - -var xxx_messageInfo_Multiplier proto.InternalMessageInfo - -// MultipliersPerDenom is a map of denoms to a set of multipliers -type MultipliersPerDenom struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Multipliers Multipliers `protobuf:"bytes,2,rep,name=multipliers,proto3,castrepeated=Multipliers" json:"multipliers"` -} - -func (m *MultipliersPerDenom) Reset() { *m = MultipliersPerDenom{} } -func (m *MultipliersPerDenom) String() string { return proto.CompactTextString(m) } -func (*MultipliersPerDenom) ProtoMessage() {} -func (*MultipliersPerDenom) Descriptor() ([]byte, []int) { - return fileDescriptor_bb8833f5d745eac9, []int{3} -} -func (m *MultipliersPerDenom) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MultipliersPerDenom) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MultipliersPerDenom.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 *MultipliersPerDenom) XXX_Merge(src proto.Message) { - xxx_messageInfo_MultipliersPerDenom.Merge(m, src) -} -func (m *MultipliersPerDenom) XXX_Size() int { - return m.Size() -} -func (m *MultipliersPerDenom) XXX_DiscardUnknown() { - xxx_messageInfo_MultipliersPerDenom.DiscardUnknown(m) -} - -var xxx_messageInfo_MultipliersPerDenom proto.InternalMessageInfo - -// Params -type Params struct { - USDXMintingRewardPeriods RewardPeriods `protobuf:"bytes,1,rep,name=usdx_minting_reward_periods,json=usdxMintingRewardPeriods,proto3,castrepeated=RewardPeriods" json:"usdx_minting_reward_periods"` - HardSupplyRewardPeriods MultiRewardPeriods `protobuf:"bytes,2,rep,name=hard_supply_reward_periods,json=hardSupplyRewardPeriods,proto3,castrepeated=MultiRewardPeriods" json:"hard_supply_reward_periods"` - HardBorrowRewardPeriods MultiRewardPeriods `protobuf:"bytes,3,rep,name=hard_borrow_reward_periods,json=hardBorrowRewardPeriods,proto3,castrepeated=MultiRewardPeriods" json:"hard_borrow_reward_periods"` - DelegatorRewardPeriods MultiRewardPeriods `protobuf:"bytes,4,rep,name=delegator_reward_periods,json=delegatorRewardPeriods,proto3,castrepeated=MultiRewardPeriods" json:"delegator_reward_periods"` - SwapRewardPeriods MultiRewardPeriods `protobuf:"bytes,5,rep,name=swap_reward_periods,json=swapRewardPeriods,proto3,castrepeated=MultiRewardPeriods" json:"swap_reward_periods"` - ClaimMultipliers MultipliersPerDenoms `protobuf:"bytes,6,rep,name=claim_multipliers,json=claimMultipliers,proto3,castrepeated=MultipliersPerDenoms" json:"claim_multipliers"` - ClaimEnd time.Time `protobuf:"bytes,7,opt,name=claim_end,json=claimEnd,proto3,stdtime" json:"claim_end"` - SavingsRewardPeriods MultiRewardPeriods `protobuf:"bytes,8,rep,name=savings_reward_periods,json=savingsRewardPeriods,proto3,castrepeated=MultiRewardPeriods" json:"savings_reward_periods"` - EarnRewardPeriods MultiRewardPeriods `protobuf:"bytes,9,rep,name=earn_reward_periods,json=earnRewardPeriods,proto3,castrepeated=MultiRewardPeriods" json:"earn_reward_periods"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_bb8833f5d745eac9, []int{4} -} -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((*RewardPeriod)(nil), "kava.incentive.v1beta1.RewardPeriod") - proto.RegisterType((*MultiRewardPeriod)(nil), "kava.incentive.v1beta1.MultiRewardPeriod") - proto.RegisterType((*Multiplier)(nil), "kava.incentive.v1beta1.Multiplier") - proto.RegisterType((*MultipliersPerDenom)(nil), "kava.incentive.v1beta1.MultipliersPerDenom") - proto.RegisterType((*Params)(nil), "kava.incentive.v1beta1.Params") -} - -func init() { - proto.RegisterFile("kava/incentive/v1beta1/params.proto", fileDescriptor_bb8833f5d745eac9) -} - -var fileDescriptor_bb8833f5d745eac9 = []byte{ - // 774 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x96, 0xcf, 0x6e, 0xd3, 0x4a, - 0x14, 0xc6, 0xe3, 0xfc, 0xbb, 0xc9, 0xb4, 0xbd, 0xb7, 0x9d, 0x46, 0xb9, 0xbe, 0xb9, 0xc8, 0xa9, - 0x52, 0x04, 0x41, 0x55, 0x6d, 0x0a, 0x12, 0x0b, 0x76, 0x98, 0x82, 0x84, 0x44, 0xa5, 0xca, 0x2d, - 0x12, 0xb0, 0x89, 0x26, 0xf6, 0xd4, 0xb5, 0x6a, 0x7b, 0xac, 0x99, 0x49, 0xda, 0x88, 0x05, 0x12, - 0x0b, 0x76, 0x48, 0x15, 0x0b, 0x1e, 0xa2, 0xaf, 0xc1, 0xa6, 0xcb, 0x8a, 0x15, 0x62, 0xd1, 0x42, - 0xfa, 0x22, 0x68, 0xc6, 0x6e, 0xe3, 0xa4, 0x69, 0xa1, 0x52, 0x36, 0xac, 0x32, 0x3e, 0x73, 0xce, - 0xf9, 0x7d, 0xfe, 0xc6, 0x67, 0x14, 0xb0, 0xb8, 0x83, 0xba, 0xc8, 0xf0, 0x42, 0x1b, 0x87, 0xdc, - 0xeb, 0x62, 0xa3, 0xbb, 0xd2, 0xc6, 0x1c, 0xad, 0x18, 0x11, 0xa2, 0x28, 0x60, 0x7a, 0x44, 0x09, - 0x27, 0xb0, 0x2a, 0x92, 0xf4, 0xf3, 0x24, 0x3d, 0x49, 0xaa, 0x69, 0x36, 0x61, 0x01, 0x61, 0x46, - 0x1b, 0xb1, 0x41, 0xa5, 0x4d, 0xbc, 0x30, 0xae, 0xab, 0x55, 0x5c, 0xe2, 0x12, 0xb9, 0x34, 0xc4, - 0x2a, 0x89, 0xd6, 0x5d, 0x42, 0x5c, 0x1f, 0x1b, 0xf2, 0xa9, 0xdd, 0xd9, 0x32, 0xb8, 0x17, 0x60, - 0xc6, 0x51, 0x10, 0xc5, 0x09, 0x8d, 0x8f, 0x59, 0x30, 0x6d, 0xe1, 0x5d, 0x44, 0x9d, 0x75, 0x4c, - 0x3d, 0xe2, 0xc0, 0x2a, 0x28, 0x22, 0x5b, 0x90, 0x55, 0x65, 0x41, 0x69, 0x96, 0xac, 0xe4, 0x09, - 0xde, 0x06, 0xff, 0xd8, 0xc4, 0xf7, 0x11, 0xc7, 0x14, 0xf9, 0x2d, 0xde, 0x8b, 0xb0, 0x9a, 0x5d, - 0x50, 0x9a, 0x65, 0xeb, 0xef, 0x41, 0x78, 0xb3, 0x17, 0x61, 0xf8, 0x10, 0x14, 0x18, 0x47, 0x94, - 0xab, 0xb9, 0x05, 0xa5, 0x39, 0x75, 0xaf, 0xa6, 0xc7, 0x12, 0xf4, 0x33, 0x09, 0xfa, 0xe6, 0x99, - 0x04, 0xb3, 0x74, 0x78, 0x5c, 0xcf, 0xec, 0x9f, 0xd4, 0x15, 0x2b, 0x2e, 0x81, 0x0f, 0x40, 0x0e, - 0x87, 0x8e, 0x9a, 0xbf, 0x46, 0xa5, 0x28, 0x80, 0x6b, 0x00, 0x52, 0xf9, 0x12, 0xac, 0x15, 0x61, - 0xda, 0x62, 0xd8, 0x26, 0xa1, 0xa3, 0x16, 0x64, 0x9b, 0xff, 0xf4, 0xd8, 0x39, 0x5d, 0x38, 0x77, - 0x66, 0xa7, 0xfe, 0x98, 0x78, 0xa1, 0x99, 0x17, 0x5d, 0xac, 0xd9, 0xa4, 0x74, 0x1d, 0xd3, 0x0d, - 0x59, 0xd8, 0xf8, 0x9c, 0x05, 0x73, 0x6b, 0x1d, 0x9f, 0x7b, 0x7f, 0xbe, 0x33, 0xbd, 0x4b, 0x9c, - 0xc9, 0x5d, 0xed, 0xcc, 0x5d, 0xd1, 0xe5, 0xe0, 0xa4, 0xde, 0x74, 0x3d, 0xbe, 0xdd, 0x69, 0xeb, - 0x36, 0x09, 0x8c, 0xe4, 0x03, 0x8c, 0x7f, 0x96, 0x99, 0xb3, 0x63, 0x88, 0x77, 0x65, 0xb2, 0x80, - 0x8d, 0x71, 0xf1, 0x83, 0x02, 0x80, 0x74, 0x31, 0xf2, 0x3d, 0x4c, 0x21, 0x04, 0xf9, 0x10, 0x05, - 0xb1, 0x79, 0x65, 0x4b, 0xae, 0xe1, 0x22, 0x98, 0x09, 0x48, 0xc8, 0xb7, 0x59, 0xcb, 0x27, 0xf6, - 0x4e, 0x27, 0x92, 0xc6, 0xe5, 0xac, 0xe9, 0x38, 0xf8, 0x5c, 0xc6, 0xe0, 0x53, 0x50, 0xdc, 0x42, - 0x36, 0x27, 0x54, 0xfa, 0x36, 0x6d, 0xea, 0x42, 0xdb, 0xb7, 0xe3, 0xfa, 0xad, 0xdf, 0xd0, 0xb6, - 0x8a, 0x6d, 0x2b, 0xa9, 0x6e, 0xbc, 0x57, 0xc0, 0xfc, 0x40, 0x8f, 0x10, 0xba, 0x8a, 0x43, 0x12, - 0xc0, 0x0a, 0x28, 0x38, 0x62, 0x91, 0x28, 0x8b, 0x1f, 0xe0, 0x2b, 0x30, 0x15, 0x0c, 0x92, 0xd5, - 0xac, 0x74, 0xac, 0xa1, 0x8f, 0x9f, 0x4e, 0x7d, 0xd0, 0xd7, 0x9c, 0x4f, 0xac, 0x9b, 0x4a, 0xb1, - 0xac, 0x74, 0xaf, 0xc6, 0x97, 0x12, 0x28, 0xae, 0xcb, 0x99, 0x87, 0x9f, 0x14, 0xf0, 0x7f, 0x87, - 0x39, 0x7b, 0xad, 0xc0, 0x0b, 0xb9, 0x17, 0xba, 0xad, 0xd8, 0x45, 0x71, 0x56, 0x1e, 0x71, 0x98, - 0xaa, 0x48, 0xec, 0xcd, 0xcb, 0xb0, 0xe9, 0xef, 0xd3, 0x5c, 0x11, 0xe0, 0xfe, 0x71, 0x5d, 0x7d, - 0xb1, 0xb1, 0xfa, 0x72, 0x2d, 0xee, 0x97, 0x4e, 0x60, 0x07, 0x27, 0xf5, 0x99, 0xa1, 0x80, 0xa5, - 0x0a, 0xf6, 0xb8, 0x54, 0xf8, 0x4e, 0x01, 0xb5, 0x6d, 0xa1, 0x84, 0x75, 0xa2, 0xc8, 0xef, 0x8d, - 0xea, 0x8a, 0xed, 0xb8, 0x73, 0xa5, 0x1d, 0x43, 0xe2, 0x6a, 0x89, 0x2b, 0xf0, 0xc2, 0x16, 0xb3, - 0xfe, 0x15, 0xa0, 0x0d, 0xc9, 0xb9, 0x44, 0x44, 0x9b, 0x50, 0x4a, 0x76, 0x47, 0x45, 0xe4, 0x26, - 0x2e, 0xc2, 0x94, 0x9c, 0x61, 0x11, 0x6f, 0x81, 0xea, 0x60, 0x1f, 0xbb, 0x88, 0x13, 0x3a, 0xaa, - 0x20, 0x3f, 0x49, 0x05, 0xd5, 0x73, 0xcc, 0xb0, 0x80, 0x0e, 0x98, 0x67, 0xbb, 0x28, 0x1a, 0x65, - 0x17, 0x26, 0xc9, 0x9e, 0x13, 0x84, 0x61, 0x6c, 0x17, 0xcc, 0xd9, 0x3e, 0xf2, 0x82, 0x56, 0x7a, - 0x0c, 0x8a, 0x12, 0xba, 0xf4, 0xeb, 0x31, 0x38, 0x1f, 0x2f, 0xf3, 0x46, 0x82, 0xad, 0x8c, 0xd9, - 0x64, 0xd6, 0xac, 0x64, 0xa4, 0xb6, 0xe0, 0x23, 0x50, 0x8e, 0xb9, 0xe2, 0xbe, 0xfb, 0xeb, 0x1a, - 0xf7, 0x5d, 0x49, 0x96, 0x3d, 0x09, 0x1d, 0xf8, 0x06, 0x54, 0x19, 0xea, 0x7a, 0xa1, 0xcb, 0x46, - 0x4d, 0x2b, 0x4d, 0xd2, 0xb4, 0x4a, 0x02, 0xb9, 0x70, 0x5c, 0x18, 0xd1, 0x70, 0x94, 0x5c, 0x9e, - 0xe8, 0x71, 0x09, 0xc2, 0x50, 0xc8, 0x7c, 0x76, 0xf8, 0x43, 0xcb, 0x1c, 0xf6, 0x35, 0xe5, 0xa8, - 0xaf, 0x29, 0xdf, 0xfb, 0x9a, 0xb2, 0x7f, 0xaa, 0x65, 0x8e, 0x4e, 0xb5, 0xcc, 0xd7, 0x53, 0x2d, - 0xf3, 0x7a, 0x29, 0x75, 0x57, 0x0a, 0x05, 0xcb, 0x3e, 0x6a, 0x33, 0xb9, 0x32, 0xf6, 0x52, 0xff, - 0x48, 0xe4, 0xa5, 0xd9, 0x2e, 0x4a, 0x9b, 0xef, 0xff, 0x0c, 0x00, 0x00, 0xff, 0xff, 0xca, 0x77, - 0xf8, 0x09, 0xb0, 0x08, 0x00, 0x00, -} - -func (m *RewardPeriod) 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 *RewardPeriod) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *RewardPeriod) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.RewardsPerSecond.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - n2, err2 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.End, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.End):]) - if err2 != nil { - return 0, err2 - } - i -= n2 - i = encodeVarintParams(dAtA, i, uint64(n2)) - i-- - dAtA[i] = 0x22 - n3, err3 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Start, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Start):]) - if err3 != nil { - return 0, err3 - } - i -= n3 - i = encodeVarintParams(dAtA, i, uint64(n3)) - i-- - dAtA[i] = 0x1a - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintParams(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x12 - } - if m.Active { - i-- - if m.Active { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *MultiRewardPeriod) 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 *MultiRewardPeriod) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MultiRewardPeriod) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RewardsPerSecond) > 0 { - for iNdEx := len(m.RewardsPerSecond) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RewardsPerSecond[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - } - n4, err4 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.End, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.End):]) - if err4 != nil { - return 0, err4 - } - i -= n4 - i = encodeVarintParams(dAtA, i, uint64(n4)) - i-- - dAtA[i] = 0x22 - n5, err5 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Start, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Start):]) - if err5 != nil { - return 0, err5 - } - i -= n5 - i = encodeVarintParams(dAtA, i, uint64(n5)) - i-- - dAtA[i] = 0x1a - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintParams(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x12 - } - if m.Active { - i-- - if m.Active { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *Multiplier) 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 *Multiplier) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Multiplier) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Factor.Size() - i -= size - if _, err := m.Factor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if m.MonthsLockup != 0 { - i = encodeVarintParams(dAtA, i, uint64(m.MonthsLockup)) - i-- - dAtA[i] = 0x10 - } - if len(m.Name) > 0 { - i -= len(m.Name) - copy(dAtA[i:], m.Name) - i = encodeVarintParams(dAtA, i, uint64(len(m.Name))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MultipliersPerDenom) 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 *MultipliersPerDenom) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MultipliersPerDenom) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Multipliers) > 0 { - for iNdEx := len(m.Multipliers) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Multipliers[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintParams(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -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 - if len(m.EarnRewardPeriods) > 0 { - for iNdEx := len(m.EarnRewardPeriods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.EarnRewardPeriods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - } - } - if len(m.SavingsRewardPeriods) > 0 { - for iNdEx := len(m.SavingsRewardPeriods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SavingsRewardPeriods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - } - } - n6, err6 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.ClaimEnd, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.ClaimEnd):]) - if err6 != nil { - return 0, err6 - } - i -= n6 - i = encodeVarintParams(dAtA, i, uint64(n6)) - i-- - dAtA[i] = 0x3a - if len(m.ClaimMultipliers) > 0 { - for iNdEx := len(m.ClaimMultipliers) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ClaimMultipliers[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - } - if len(m.SwapRewardPeriods) > 0 { - for iNdEx := len(m.SwapRewardPeriods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SwapRewardPeriods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - } - if len(m.DelegatorRewardPeriods) > 0 { - for iNdEx := len(m.DelegatorRewardPeriods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DelegatorRewardPeriods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.HardBorrowRewardPeriods) > 0 { - for iNdEx := len(m.HardBorrowRewardPeriods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.HardBorrowRewardPeriods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.HardSupplyRewardPeriods) > 0 { - for iNdEx := len(m.HardSupplyRewardPeriods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.HardSupplyRewardPeriods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.USDXMintingRewardPeriods) > 0 { - for iNdEx := len(m.USDXMintingRewardPeriods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.USDXMintingRewardPeriods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - 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 *RewardPeriod) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Active { - n += 2 - } - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovParams(uint64(l)) - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Start) - n += 1 + l + sovParams(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.End) - n += 1 + l + sovParams(uint64(l)) - l = m.RewardsPerSecond.Size() - n += 1 + l + sovParams(uint64(l)) - return n -} - -func (m *MultiRewardPeriod) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Active { - n += 2 - } - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovParams(uint64(l)) - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Start) - n += 1 + l + sovParams(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.End) - n += 1 + l + sovParams(uint64(l)) - if len(m.RewardsPerSecond) > 0 { - for _, e := range m.RewardsPerSecond { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - return n -} - -func (m *Multiplier) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Name) - if l > 0 { - n += 1 + l + sovParams(uint64(l)) - } - if m.MonthsLockup != 0 { - n += 1 + sovParams(uint64(m.MonthsLockup)) - } - l = m.Factor.Size() - n += 1 + l + sovParams(uint64(l)) - return n -} - -func (m *MultipliersPerDenom) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovParams(uint64(l)) - } - if len(m.Multipliers) > 0 { - for _, e := range m.Multipliers { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - return n -} - -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.USDXMintingRewardPeriods) > 0 { - for _, e := range m.USDXMintingRewardPeriods { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - if len(m.HardSupplyRewardPeriods) > 0 { - for _, e := range m.HardSupplyRewardPeriods { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - if len(m.HardBorrowRewardPeriods) > 0 { - for _, e := range m.HardBorrowRewardPeriods { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - if len(m.DelegatorRewardPeriods) > 0 { - for _, e := range m.DelegatorRewardPeriods { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - if len(m.SwapRewardPeriods) > 0 { - for _, e := range m.SwapRewardPeriods { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - if len(m.ClaimMultipliers) > 0 { - for _, e := range m.ClaimMultipliers { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.ClaimEnd) - n += 1 + l + sovParams(uint64(l)) - if len(m.SavingsRewardPeriods) > 0 { - for _, e := range m.SavingsRewardPeriods { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - if len(m.EarnRewardPeriods) > 0 { - for _, e := range m.EarnRewardPeriods { - l = e.Size() - n += 1 + l + sovParams(uint64(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 *RewardPeriod) 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: RewardPeriod: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: RewardPeriod: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Active", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Active = bool(v != 0) - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", 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.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Start", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Start, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field End", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.End, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardsPerSecond", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.RewardsPerSecond.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - 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 (m *MultiRewardPeriod) 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: MultiRewardPeriod: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MultiRewardPeriod: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Active", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Active = bool(v != 0) - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", 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.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Start", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Start, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field End", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.End, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardsPerSecond", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardsPerSecond = append(m.RewardsPerSecond, types.Coin{}) - if err := m.RewardsPerSecond[len(m.RewardsPerSecond)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - 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 (m *Multiplier) 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: Multiplier: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Multiplier: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", 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.Name = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field MonthsLockup", wireType) - } - m.MonthsLockup = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.MonthsLockup |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Factor", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Factor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - 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 (m *MultipliersPerDenom) 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: MultipliersPerDenom: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MultipliersPerDenom: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", 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.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Multipliers", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Multipliers = append(m.Multipliers, Multiplier{}) - if err := m.Multipliers[len(m.Multipliers)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - 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 (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 { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field USDXMintingRewardPeriods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.USDXMintingRewardPeriods = append(m.USDXMintingRewardPeriods, RewardPeriod{}) - if err := m.USDXMintingRewardPeriods[len(m.USDXMintingRewardPeriods)-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 HardSupplyRewardPeriods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.HardSupplyRewardPeriods = append(m.HardSupplyRewardPeriods, MultiRewardPeriod{}) - if err := m.HardSupplyRewardPeriods[len(m.HardSupplyRewardPeriods)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HardBorrowRewardPeriods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.HardBorrowRewardPeriods = append(m.HardBorrowRewardPeriods, MultiRewardPeriod{}) - if err := m.HardBorrowRewardPeriods[len(m.HardBorrowRewardPeriods)-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 DelegatorRewardPeriods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DelegatorRewardPeriods = append(m.DelegatorRewardPeriods, MultiRewardPeriod{}) - if err := m.DelegatorRewardPeriods[len(m.DelegatorRewardPeriods)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SwapRewardPeriods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SwapRewardPeriods = append(m.SwapRewardPeriods, MultiRewardPeriod{}) - if err := m.SwapRewardPeriods[len(m.SwapRewardPeriods)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClaimMultipliers", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ClaimMultipliers = append(m.ClaimMultipliers, MultipliersPerDenom{}) - if err := m.ClaimMultipliers[len(m.ClaimMultipliers)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClaimEnd", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.ClaimEnd, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SavingsRewardPeriods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SavingsRewardPeriods = append(m.SavingsRewardPeriods, MultiRewardPeriod{}) - if err := m.SavingsRewardPeriods[len(m.SavingsRewardPeriods)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EarnRewardPeriods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.EarnRewardPeriods = append(m.EarnRewardPeriods, MultiRewardPeriod{}) - if err := m.EarnRewardPeriods[len(m.EarnRewardPeriods)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - 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/incentive/types/params_test.go b/x/incentive/types/params_test.go deleted file mode 100644 index 2716d095..00000000 --- a/x/incentive/types/params_test.go +++ /dev/null @@ -1,407 +0,0 @@ -package types_test - -import ( - "fmt" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/incentive/types" -) - -type ParamTestSuite struct { - suite.Suite -} - -func (suite *ParamTestSuite) SetupTest() {} - -var rewardPeriodWithInvalidRewardsPerSecond = types.NewRewardPeriod( - true, - "bnb", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.Coin{Denom: "INVALID!@#😫", Amount: sdk.ZeroInt()}, -) - -var rewardPeriodWithZeroRewardsPerSecond = types.NewRewardPeriod( - true, - "bnb", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.Coin{Denom: "ukava", Amount: sdk.ZeroInt()}, -) - -var rewardMultiPeriodWithInvalidRewardsPerSecond = types.NewMultiRewardPeriod( - true, - "bnb", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.Coins{sdk.Coin{Denom: "INVALID!@#😫", Amount: sdk.ZeroInt()}}, -) - -var rewardMultiPeriodWithZeroRewardsPerSecond = types.NewMultiRewardPeriod( - true, - "bnb", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.Coins{sdk.Coin{Denom: "zero", Amount: sdk.ZeroInt()}}, -) - -var validMultiRewardPeriod = types.NewMultiRewardPeriod( - true, - "bnb", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.NewCoins(sdk.NewInt64Coin("swap", 1e9)), -) - -var validRewardPeriod = types.NewRewardPeriod( - true, - "bnb-a", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.NewInt64Coin(types.USDXMintingRewardDenom, 1e9), -) - -func (suite *ParamTestSuite) TestParamValidation() { - type errArgs struct { - expectPass bool - contains string - } - type test struct { - name string - params types.Params - errArgs errArgs - } - - testCases := []test{ - { - "default is valid", - types.DefaultParams(), - errArgs{ - expectPass: true, - }, - }, - { - "valid", - types.Params{ - USDXMintingRewardPeriods: types.RewardPeriods{ - types.NewRewardPeriod( - true, - "bnb-a", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.NewCoin(types.USDXMintingRewardDenom, sdkmath.NewInt(122354)), - ), - }, - HardSupplyRewardPeriods: types.DefaultMultiRewardPeriods, - HardBorrowRewardPeriods: types.DefaultMultiRewardPeriods, - DelegatorRewardPeriods: types.DefaultMultiRewardPeriods, - SwapRewardPeriods: types.DefaultMultiRewardPeriods, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.MultipliersPerDenoms{ - { - Denom: "hard", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, sdk.MustNewDecFromStr("0.25")), - types.NewMultiplier("large", 12, sdk.MustNewDecFromStr("1.0")), - }, - }, - { - Denom: "ukava", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, sdk.MustNewDecFromStr("0.2")), - types.NewMultiplier("large", 12, sdk.MustNewDecFromStr("1.0")), - }, - }, - }, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: true, - }, - }, - { - "invalid usdx minting period makes params invalid", - types.Params{ - USDXMintingRewardPeriods: types.RewardPeriods{rewardPeriodWithInvalidRewardsPerSecond}, - HardSupplyRewardPeriods: types.DefaultMultiRewardPeriods, - HardBorrowRewardPeriods: types.DefaultMultiRewardPeriods, - DelegatorRewardPeriods: types.DefaultMultiRewardPeriods, - SwapRewardPeriods: types.DefaultMultiRewardPeriods, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.DefaultMultipliers, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: false, - contains: fmt.Sprintf("reward denom must be %s", types.USDXMintingRewardDenom), - }, - }, - { - "invalid hard supply periods makes params invalid", - types.Params{ - USDXMintingRewardPeriods: types.DefaultRewardPeriods, - HardSupplyRewardPeriods: types.MultiRewardPeriods{rewardMultiPeriodWithInvalidRewardsPerSecond}, - HardBorrowRewardPeriods: types.DefaultMultiRewardPeriods, - DelegatorRewardPeriods: types.DefaultMultiRewardPeriods, - SwapRewardPeriods: types.DefaultMultiRewardPeriods, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.DefaultMultipliers, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: false, - contains: "invalid reward amount", - }, - }, - { - "invalid hard borrow periods makes params invalid", - types.Params{ - USDXMintingRewardPeriods: types.DefaultRewardPeriods, - HardSupplyRewardPeriods: types.DefaultMultiRewardPeriods, - HardBorrowRewardPeriods: types.MultiRewardPeriods{rewardMultiPeriodWithInvalidRewardsPerSecond}, - DelegatorRewardPeriods: types.DefaultMultiRewardPeriods, - SwapRewardPeriods: types.DefaultMultiRewardPeriods, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.DefaultMultipliers, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: false, - contains: "invalid reward amount", - }, - }, - { - "invalid delegator periods makes params invalid", - types.Params{ - USDXMintingRewardPeriods: types.DefaultRewardPeriods, - HardSupplyRewardPeriods: types.DefaultMultiRewardPeriods, - HardBorrowRewardPeriods: types.DefaultMultiRewardPeriods, - DelegatorRewardPeriods: types.MultiRewardPeriods{rewardMultiPeriodWithInvalidRewardsPerSecond}, - SwapRewardPeriods: types.DefaultMultiRewardPeriods, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.DefaultMultipliers, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: false, - contains: "invalid reward amount", - }, - }, - { - "invalid swap periods makes params invalid", - types.Params{ - USDXMintingRewardPeriods: types.DefaultRewardPeriods, - HardSupplyRewardPeriods: types.DefaultMultiRewardPeriods, - HardBorrowRewardPeriods: types.DefaultMultiRewardPeriods, - DelegatorRewardPeriods: types.DefaultMultiRewardPeriods, - SwapRewardPeriods: types.MultiRewardPeriods{rewardMultiPeriodWithInvalidRewardsPerSecond}, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.DefaultMultipliers, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: false, - contains: "invalid reward amount", - }, - }, - { - "invalid multipliers makes params invalid", - types.Params{ - USDXMintingRewardPeriods: types.DefaultRewardPeriods, - HardSupplyRewardPeriods: types.DefaultMultiRewardPeriods, - HardBorrowRewardPeriods: types.DefaultMultiRewardPeriods, - DelegatorRewardPeriods: types.DefaultMultiRewardPeriods, - SwapRewardPeriods: types.DefaultMultiRewardPeriods, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.MultipliersPerDenoms{ - { - Denom: "hard", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", -9999, sdk.MustNewDecFromStr("0.25")), - }, - }, - }, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: false, - contains: "expected non-negative lockup", - }, - }, - { - "invalid zero amount multi rewards per second", - types.Params{ - USDXMintingRewardPeriods: types.DefaultRewardPeriods, - HardSupplyRewardPeriods: types.MultiRewardPeriods{ - rewardMultiPeriodWithZeroRewardsPerSecond, - }, - HardBorrowRewardPeriods: types.DefaultMultiRewardPeriods, - DelegatorRewardPeriods: types.DefaultMultiRewardPeriods, - SwapRewardPeriods: types.DefaultMultiRewardPeriods, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.DefaultMultipliers, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: false, - contains: "invalid reward amount: 0zero", - }, - }, - { - "invalid zero amount single rewards per second", - types.Params{ - USDXMintingRewardPeriods: types.RewardPeriods{ - rewardPeriodWithZeroRewardsPerSecond, - }, - HardSupplyRewardPeriods: types.DefaultMultiRewardPeriods, - HardBorrowRewardPeriods: types.DefaultMultiRewardPeriods, - DelegatorRewardPeriods: types.DefaultMultiRewardPeriods, - SwapRewardPeriods: types.DefaultMultiRewardPeriods, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.DefaultMultipliers, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: false, - contains: "reward amount cannot be zero: 0ukava", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - err := tc.params.Validate() - - if tc.errArgs.expectPass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Require().Contains(err.Error(), tc.errArgs.contains) - } - }) - } -} - -func (suite *ParamTestSuite) TestRewardPeriods() { - suite.Run("Validate", func() { - type err struct { - pass bool - contains string - } - testCases := []struct { - name string - periods types.RewardPeriods - expect err - }{ - { - name: "single period is valid", - periods: types.RewardPeriods{ - validRewardPeriod, - }, - expect: err{ - pass: true, - }, - }, - { - name: "duplicated reward period is invalid", - periods: types.RewardPeriods{ - validRewardPeriod, - validRewardPeriod, - }, - expect: err{ - contains: "duplicated reward period", - }, - }, - { - name: "invalid reward denom is invalid", - periods: types.RewardPeriods{ - types.NewRewardPeriod( - true, - "bnb-a", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.NewInt64Coin("hard", 1e9), - ), - }, - expect: err{ - contains: fmt.Sprintf("reward denom must be %s", types.USDXMintingRewardDenom), - }, - }, - } - for _, tc := range testCases { - - err := tc.periods.Validate() - - if tc.expect.pass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Contains(err.Error(), tc.expect.contains) - } - } - }) -} - -func (suite *ParamTestSuite) TestMultiRewardPeriods() { - suite.Run("Validate", func() { - type err struct { - pass bool - contains string - } - testCases := []struct { - name string - periods types.MultiRewardPeriods - expect err - }{ - { - name: "single period is valid", - periods: types.MultiRewardPeriods{ - validMultiRewardPeriod, - }, - expect: err{ - pass: true, - }, - }, - { - name: "duplicated reward period is invalid", - periods: types.MultiRewardPeriods{ - validMultiRewardPeriod, - validMultiRewardPeriod, - }, - expect: err{ - contains: "duplicated reward period", - }, - }, - { - name: "invalid reward period is invalid", - periods: types.MultiRewardPeriods{ - rewardMultiPeriodWithInvalidRewardsPerSecond, - }, - expect: err{ - contains: "invalid reward amount", - }, - }, - } - for _, tc := range testCases { - - err := tc.periods.Validate() - - if tc.expect.pass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Contains(err.Error(), tc.expect.contains) - } - } - }) -} - -func TestParamTestSuite(t *testing.T) { - suite.Run(t, new(ParamTestSuite)) -} diff --git a/x/incentive/types/query.pb.go b/x/incentive/types/query.pb.go deleted file mode 100644 index d639bf69..00000000 --- a/x/incentive/types/query.pb.go +++ /dev/null @@ -1,2425 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/incentive/v1beta1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "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 the 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_a78d71d0cbe5e95a, []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 the response type for the Query/Params RPC method. -type QueryParamsResponse struct { - 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_a78d71d0cbe5e95a, []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{} -} - -// QueryRewardsRequest is the request type for the Query/Rewards RPC method. -type QueryRewardsRequest struct { - // owner is the address of the user to query rewards for. - Owner string `protobuf:"bytes,1,opt,name=owner,proto3" json:"owner,omitempty"` - // reward_type is the type of reward to query rewards for, e.g. hard, earn, - // swap. - RewardType string `protobuf:"bytes,2,opt,name=reward_type,json=rewardType,proto3" json:"reward_type,omitempty"` - // unsynchronized is a flag to query rewards that are not simulated for reward - // synchronized for the current block. - Unsynchronized bool `protobuf:"varint,3,opt,name=unsynchronized,proto3" json:"unsynchronized,omitempty"` -} - -func (m *QueryRewardsRequest) Reset() { *m = QueryRewardsRequest{} } -func (m *QueryRewardsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRewardsRequest) ProtoMessage() {} -func (*QueryRewardsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_a78d71d0cbe5e95a, []int{2} -} -func (m *QueryRewardsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRewardsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRewardsRequest.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 *QueryRewardsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRewardsRequest.Merge(m, src) -} -func (m *QueryRewardsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryRewardsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRewardsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRewardsRequest proto.InternalMessageInfo - -func (m *QueryRewardsRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *QueryRewardsRequest) GetRewardType() string { - if m != nil { - return m.RewardType - } - return "" -} - -func (m *QueryRewardsRequest) GetUnsynchronized() bool { - if m != nil { - return m.Unsynchronized - } - return false -} - -// QueryRewardsResponse is the response type for the Query/Rewards RPC method. -type QueryRewardsResponse struct { - USDXMintingClaims USDXMintingClaims `protobuf:"bytes,1,rep,name=usdx_minting_claims,json=usdxMintingClaims,proto3,castrepeated=USDXMintingClaims" json:"usdx_minting_claims"` - HardLiquidityProviderClaims HardLiquidityProviderClaims `protobuf:"bytes,2,rep,name=hard_liquidity_provider_claims,json=hardLiquidityProviderClaims,proto3,castrepeated=HardLiquidityProviderClaims" json:"hard_liquidity_provider_claims"` - DelegatorClaims DelegatorClaims `protobuf:"bytes,3,rep,name=delegator_claims,json=delegatorClaims,proto3,castrepeated=DelegatorClaims" json:"delegator_claims"` - SwapClaims SwapClaims `protobuf:"bytes,4,rep,name=swap_claims,json=swapClaims,proto3,castrepeated=SwapClaims" json:"swap_claims"` - SavingsClaims SavingsClaims `protobuf:"bytes,5,rep,name=savings_claims,json=savingsClaims,proto3,castrepeated=SavingsClaims" json:"savings_claims"` - EarnClaims EarnClaims `protobuf:"bytes,6,rep,name=earn_claims,json=earnClaims,proto3,castrepeated=EarnClaims" json:"earn_claims"` -} - -func (m *QueryRewardsResponse) Reset() { *m = QueryRewardsResponse{} } -func (m *QueryRewardsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryRewardsResponse) ProtoMessage() {} -func (*QueryRewardsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_a78d71d0cbe5e95a, []int{3} -} -func (m *QueryRewardsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRewardsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRewardsResponse.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 *QueryRewardsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRewardsResponse.Merge(m, src) -} -func (m *QueryRewardsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryRewardsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRewardsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRewardsResponse proto.InternalMessageInfo - -func (m *QueryRewardsResponse) GetUSDXMintingClaims() USDXMintingClaims { - if m != nil { - return m.USDXMintingClaims - } - return nil -} - -func (m *QueryRewardsResponse) GetHardLiquidityProviderClaims() HardLiquidityProviderClaims { - if m != nil { - return m.HardLiquidityProviderClaims - } - return nil -} - -func (m *QueryRewardsResponse) GetDelegatorClaims() DelegatorClaims { - if m != nil { - return m.DelegatorClaims - } - return nil -} - -func (m *QueryRewardsResponse) GetSwapClaims() SwapClaims { - if m != nil { - return m.SwapClaims - } - return nil -} - -func (m *QueryRewardsResponse) GetSavingsClaims() SavingsClaims { - if m != nil { - return m.SavingsClaims - } - return nil -} - -func (m *QueryRewardsResponse) GetEarnClaims() EarnClaims { - if m != nil { - return m.EarnClaims - } - return nil -} - -// QueryRewardFactorsRequest is the request type for the Query/RewardFactors RPC method. -type QueryRewardFactorsRequest struct { -} - -func (m *QueryRewardFactorsRequest) Reset() { *m = QueryRewardFactorsRequest{} } -func (m *QueryRewardFactorsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRewardFactorsRequest) ProtoMessage() {} -func (*QueryRewardFactorsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_a78d71d0cbe5e95a, []int{4} -} -func (m *QueryRewardFactorsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRewardFactorsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRewardFactorsRequest.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 *QueryRewardFactorsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRewardFactorsRequest.Merge(m, src) -} -func (m *QueryRewardFactorsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryRewardFactorsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRewardFactorsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRewardFactorsRequest proto.InternalMessageInfo - -// QueryRewardFactorsResponse is the response type for the Query/RewardFactors RPC method. -type QueryRewardFactorsResponse struct { - UsdxMintingRewardFactors RewardIndexes `protobuf:"bytes,1,rep,name=usdx_minting_reward_factors,json=usdxMintingRewardFactors,proto3,castrepeated=RewardIndexes" json:"usdx_minting_reward_factors"` - HardSupplyRewardFactors MultiRewardIndexes `protobuf:"bytes,2,rep,name=hard_supply_reward_factors,json=hardSupplyRewardFactors,proto3,castrepeated=MultiRewardIndexes" json:"hard_supply_reward_factors"` - HardBorrowRewardFactors MultiRewardIndexes `protobuf:"bytes,3,rep,name=hard_borrow_reward_factors,json=hardBorrowRewardFactors,proto3,castrepeated=MultiRewardIndexes" json:"hard_borrow_reward_factors"` - DelegatorRewardFactors MultiRewardIndexes `protobuf:"bytes,4,rep,name=delegator_reward_factors,json=delegatorRewardFactors,proto3,castrepeated=MultiRewardIndexes" json:"delegator_reward_factors"` - SwapRewardFactors MultiRewardIndexes `protobuf:"bytes,5,rep,name=swap_reward_factors,json=swapRewardFactors,proto3,castrepeated=MultiRewardIndexes" json:"swap_reward_factors"` - SavingsRewardFactors MultiRewardIndexes `protobuf:"bytes,6,rep,name=savings_reward_factors,json=savingsRewardFactors,proto3,castrepeated=MultiRewardIndexes" json:"savings_reward_factors"` - EarnRewardFactors MultiRewardIndexes `protobuf:"bytes,7,rep,name=earn_reward_factors,json=earnRewardFactors,proto3,castrepeated=MultiRewardIndexes" json:"earn_reward_factors"` -} - -func (m *QueryRewardFactorsResponse) Reset() { *m = QueryRewardFactorsResponse{} } -func (m *QueryRewardFactorsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryRewardFactorsResponse) ProtoMessage() {} -func (*QueryRewardFactorsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_a78d71d0cbe5e95a, []int{5} -} -func (m *QueryRewardFactorsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRewardFactorsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRewardFactorsResponse.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 *QueryRewardFactorsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRewardFactorsResponse.Merge(m, src) -} -func (m *QueryRewardFactorsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryRewardFactorsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRewardFactorsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRewardFactorsResponse proto.InternalMessageInfo - -func (m *QueryRewardFactorsResponse) GetUsdxMintingRewardFactors() RewardIndexes { - if m != nil { - return m.UsdxMintingRewardFactors - } - return nil -} - -func (m *QueryRewardFactorsResponse) GetHardSupplyRewardFactors() MultiRewardIndexes { - if m != nil { - return m.HardSupplyRewardFactors - } - return nil -} - -func (m *QueryRewardFactorsResponse) GetHardBorrowRewardFactors() MultiRewardIndexes { - if m != nil { - return m.HardBorrowRewardFactors - } - return nil -} - -func (m *QueryRewardFactorsResponse) GetDelegatorRewardFactors() MultiRewardIndexes { - if m != nil { - return m.DelegatorRewardFactors - } - return nil -} - -func (m *QueryRewardFactorsResponse) GetSwapRewardFactors() MultiRewardIndexes { - if m != nil { - return m.SwapRewardFactors - } - return nil -} - -func (m *QueryRewardFactorsResponse) GetSavingsRewardFactors() MultiRewardIndexes { - if m != nil { - return m.SavingsRewardFactors - } - return nil -} - -func (m *QueryRewardFactorsResponse) GetEarnRewardFactors() MultiRewardIndexes { - if m != nil { - return m.EarnRewardFactors - } - return nil -} - -// QueryApysRequest is the request type for the Query/Apys RPC method. -type QueryApyRequest struct { -} - -func (m *QueryApyRequest) Reset() { *m = QueryApyRequest{} } -func (m *QueryApyRequest) String() string { return proto.CompactTextString(m) } -func (*QueryApyRequest) ProtoMessage() {} -func (*QueryApyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_a78d71d0cbe5e95a, []int{6} -} -func (m *QueryApyRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryApyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryApyRequest.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 *QueryApyRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryApyRequest.Merge(m, src) -} -func (m *QueryApyRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryApyRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryApyRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryApyRequest proto.InternalMessageInfo - -// QueryApysResponse is the response type for the Query/Apys RPC method. -type QueryApyResponse struct { - Earn []Apy `protobuf:"bytes,1,rep,name=earn,proto3" json:"earn"` -} - -func (m *QueryApyResponse) Reset() { *m = QueryApyResponse{} } -func (m *QueryApyResponse) String() string { return proto.CompactTextString(m) } -func (*QueryApyResponse) ProtoMessage() {} -func (*QueryApyResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_a78d71d0cbe5e95a, []int{7} -} -func (m *QueryApyResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryApyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryApyResponse.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 *QueryApyResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryApyResponse.Merge(m, src) -} -func (m *QueryApyResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryApyResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryApyResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryApyResponse proto.InternalMessageInfo - -func (m *QueryApyResponse) GetEarn() []Apy { - if m != nil { - return m.Earn - } - return nil -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.incentive.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.incentive.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryRewardsRequest)(nil), "kava.incentive.v1beta1.QueryRewardsRequest") - proto.RegisterType((*QueryRewardsResponse)(nil), "kava.incentive.v1beta1.QueryRewardsResponse") - proto.RegisterType((*QueryRewardFactorsRequest)(nil), "kava.incentive.v1beta1.QueryRewardFactorsRequest") - proto.RegisterType((*QueryRewardFactorsResponse)(nil), "kava.incentive.v1beta1.QueryRewardFactorsResponse") - proto.RegisterType((*QueryApyRequest)(nil), "kava.incentive.v1beta1.QueryApyRequest") - proto.RegisterType((*QueryApyResponse)(nil), "kava.incentive.v1beta1.QueryApyResponse") -} - -func init() { - proto.RegisterFile("kava/incentive/v1beta1/query.proto", fileDescriptor_a78d71d0cbe5e95a) -} - -var fileDescriptor_a78d71d0cbe5e95a = []byte{ - // 904 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x96, 0xcf, 0x6f, 0xe3, 0x44, - 0x14, 0xc7, 0xeb, 0xe6, 0x47, 0xe1, 0x55, 0xdd, 0x6e, 0xa7, 0xa1, 0x1b, 0x1c, 0x70, 0xb2, 0x29, - 0xea, 0x46, 0x2c, 0xc4, 0x6a, 0x10, 0x37, 0x2e, 0x2d, 0xbb, 0x88, 0x95, 0x58, 0x69, 0x71, 0x01, - 0x21, 0x2e, 0xd5, 0x24, 0x1e, 0x5c, 0x43, 0x3a, 0xe3, 0xce, 0xd8, 0x49, 0xbd, 0x12, 0x48, 0x70, - 0x01, 0x0e, 0x48, 0x48, 0x5c, 0x39, 0x73, 0xd8, 0xbf, 0x82, 0xe3, 0x4a, 0x5c, 0x56, 0xe2, 0xc2, - 0x69, 0x17, 0xb5, 0xfc, 0x21, 0xc8, 0x33, 0x63, 0x37, 0xf6, 0xd6, 0xd9, 0x22, 0xe5, 0xe6, 0xbc, - 0xf9, 0xbe, 0xf7, 0xfd, 0x3c, 0xeb, 0xbd, 0x8c, 0xa1, 0xfb, 0x35, 0x9e, 0x60, 0xdb, 0xa7, 0x23, - 0x42, 0x43, 0x7f, 0x42, 0xec, 0xc9, 0xee, 0x90, 0x84, 0x78, 0xd7, 0x3e, 0x89, 0x08, 0x8f, 0xfb, - 0x01, 0x67, 0x21, 0x43, 0x5b, 0x89, 0xa6, 0x9f, 0x69, 0xfa, 0x5a, 0x63, 0x36, 0x3c, 0xe6, 0x31, - 0x29, 0xb1, 0x93, 0x27, 0xa5, 0x36, 0x5f, 0xf3, 0x18, 0xf3, 0xc6, 0xc4, 0xc6, 0x81, 0x6f, 0x63, - 0x4a, 0x59, 0x88, 0x43, 0x9f, 0x51, 0xa1, 0x4f, 0x3b, 0x25, 0x7e, 0x38, 0xd0, 0x6e, 0xe6, 0x76, - 0x89, 0x62, 0x34, 0xc6, 0xfe, 0xb1, 0x78, 0x81, 0x28, 0xc0, 0x1c, 0xa7, 0xa2, 0x6e, 0x03, 0xd0, - 0xc7, 0x49, 0x1b, 0x0f, 0x64, 0xd0, 0x21, 0x27, 0x11, 0x11, 0x61, 0xf7, 0x00, 0x36, 0x73, 0x51, - 0x11, 0x30, 0x2a, 0x08, 0x7a, 0x0f, 0xea, 0x2a, 0xb9, 0x69, 0x74, 0x8c, 0xde, 0xea, 0xc0, 0xea, - 0x5f, 0xde, 0x75, 0x5f, 0xe5, 0xed, 0x57, 0x1f, 0x3f, 0x6d, 0x2f, 0x39, 0x3a, 0xa7, 0x1b, 0xea, - 0xa2, 0x0e, 0x99, 0x62, 0xee, 0xa6, 0x5e, 0xa8, 0x01, 0x35, 0x36, 0xa5, 0x84, 0xcb, 0x9a, 0x2f, - 0x3b, 0xea, 0x07, 0x6a, 0xc3, 0x2a, 0x97, 0xba, 0xc3, 0x30, 0x0e, 0x48, 0x73, 0x59, 0x9e, 0x81, - 0x0a, 0x7d, 0x12, 0x07, 0x04, 0xed, 0xc0, 0xb5, 0x88, 0x8a, 0x98, 0x8e, 0x8e, 0x38, 0xa3, 0xfe, - 0x43, 0xe2, 0x36, 0x2b, 0x1d, 0xa3, 0xf7, 0x92, 0x53, 0x88, 0x76, 0xff, 0xa8, 0x41, 0x23, 0x6f, - 0xab, 0x9b, 0xf9, 0xd1, 0x80, 0xcd, 0x48, 0xb8, 0xa7, 0x87, 0xc7, 0x3e, 0x0d, 0x7d, 0xea, 0x1d, - 0xaa, 0x97, 0xd7, 0x34, 0x3a, 0x95, 0xde, 0xea, 0xa0, 0x57, 0xd6, 0xda, 0xa7, 0x07, 0x77, 0x3e, - 0xbf, 0xaf, 0x32, 0xde, 0x4f, 0x12, 0xf6, 0xfb, 0x49, 0x93, 0x67, 0x4f, 0xdb, 0x1b, 0xc5, 0x13, - 0xf1, 0xe8, 0xd9, 0x25, 0x41, 0x67, 0x23, 0x31, 0xcd, 0x85, 0xd0, 0x6f, 0x06, 0x58, 0x47, 0x49, - 0xaf, 0x63, 0xff, 0x24, 0xf2, 0x5d, 0x3f, 0x8c, 0x0f, 0x03, 0xce, 0x26, 0xbe, 0x4b, 0x78, 0x4a, - 0xb5, 0x2c, 0xa9, 0x06, 0x65, 0x54, 0x1f, 0x62, 0xee, 0x7e, 0x94, 0x26, 0x3f, 0xd0, 0xb9, 0x8a, - 0x6f, 0x3b, 0xe1, 0x7b, 0xf4, 0xac, 0xdd, 0x2a, 0xd7, 0x08, 0xa7, 0x75, 0x54, 0x7e, 0x88, 0xbe, - 0x82, 0xeb, 0x2e, 0x19, 0x13, 0x0f, 0x87, 0x2c, 0xe3, 0xa9, 0x48, 0x9e, 0x9d, 0x32, 0x9e, 0x3b, - 0xa9, 0x5e, 0x31, 0xdc, 0xd0, 0x0c, 0xeb, 0xf9, 0xb8, 0x70, 0xd6, 0xdd, 0x7c, 0x00, 0x7d, 0x06, - 0xab, 0x62, 0x8a, 0x83, 0xd4, 0xa6, 0x2a, 0x6d, 0x6e, 0x96, 0xd9, 0x1c, 0x4c, 0x71, 0xa0, 0x1c, - 0x90, 0x76, 0x80, 0x2c, 0x24, 0x1c, 0x10, 0xd9, 0x33, 0x1a, 0xc2, 0x35, 0x81, 0x27, 0x3e, 0xf5, - 0x44, 0x5a, 0xba, 0x26, 0x4b, 0xbf, 0x51, 0x5a, 0x5a, 0xa9, 0x55, 0xf5, 0x57, 0x74, 0xf5, 0xb5, - 0xd9, 0xa8, 0x70, 0xd6, 0xc4, 0xec, 0xcf, 0x84, 0x9d, 0x60, 0x4e, 0x53, 0x83, 0xfa, 0x7c, 0xf6, - 0xbb, 0x98, 0xd3, 0x02, 0x7b, 0x16, 0x12, 0x0e, 0x90, 0xec, 0xb9, 0xdb, 0x82, 0x57, 0x67, 0x26, - 0xf8, 0x03, 0x3c, 0x0a, 0x19, 0xcf, 0x56, 0xf5, 0x87, 0x15, 0x30, 0x2f, 0x3b, 0xd5, 0x53, 0x1e, - 0x43, 0x2b, 0x37, 0xe4, 0x7a, 0xa9, 0xbe, 0x54, 0x32, 0x3d, 0xec, 0xdb, 0x65, 0x8c, 0xaa, 0xe6, - 0x3d, 0xea, 0x92, 0xd3, 0x8b, 0x77, 0x30, 0x13, 0x24, 0xc2, 0x69, 0xce, 0x8c, 0x73, 0x0e, 0x01, - 0x7d, 0x67, 0x80, 0x29, 0xa7, 0x5a, 0x44, 0x41, 0x30, 0x8e, 0x8b, 0xd6, 0xcb, 0xf3, 0xf7, 0xec, - 0x7e, 0x34, 0x0e, 0xfd, 0x59, 0x7f, 0x53, 0xfb, 0xa3, 0xe2, 0x09, 0x11, 0xce, 0x8d, 0xc4, 0xe7, - 0x40, 0xda, 0x94, 0x30, 0x0c, 0x19, 0xe7, 0x6c, 0x5a, 0x64, 0xa8, 0x2c, 0x9a, 0x61, 0x5f, 0xda, - 0xe4, 0x19, 0xbe, 0x85, 0xe6, 0xc5, 0xfa, 0x14, 0x00, 0xaa, 0x0b, 0x04, 0xd8, 0xca, 0x5c, 0xf2, - 0xfe, 0x21, 0x6c, 0xca, 0x95, 0x2a, 0x58, 0xd7, 0x16, 0x68, 0xbd, 0x91, 0x18, 0xe4, 0x5d, 0x1f, - 0xc2, 0x56, 0xba, 0x70, 0x05, 0xe3, 0xfa, 0x02, 0x8d, 0x1b, 0xda, 0xe3, 0xb9, 0x8e, 0xe5, 0x22, - 0x16, 0x8c, 0x57, 0x16, 0xd9, 0x71, 0x62, 0x90, 0x73, 0xed, 0x6e, 0xc0, 0xba, 0x5c, 0xc4, 0xbd, - 0x20, 0x4e, 0x97, 0xf3, 0x1e, 0x5c, 0xbf, 0x08, 0xe9, 0x8d, 0x7c, 0x17, 0xaa, 0x49, 0xae, 0x5e, - 0xbd, 0x56, 0x19, 0xcd, 0x5e, 0x10, 0xeb, 0xfb, 0x53, 0xca, 0x07, 0x7f, 0x56, 0xa1, 0x26, 0x6b, - 0xa1, 0x9f, 0x0c, 0xa8, 0xab, 0x0b, 0x16, 0xbd, 0x59, 0x96, 0xfd, 0xfc, 0x9d, 0x6e, 0xde, 0xbe, - 0x92, 0x56, 0x41, 0x76, 0x77, 0xbe, 0xff, 0xeb, 0xdf, 0x5f, 0x97, 0x3b, 0xc8, 0xb2, 0xe7, 0x7e, - 0x44, 0xa0, 0x9f, 0x0d, 0x58, 0xd1, 0x17, 0x2b, 0x9a, 0x6f, 0x90, 0xbf, 0xf5, 0xcd, 0xb7, 0xae, - 0x26, 0xd6, 0x38, 0xb7, 0x24, 0xce, 0x4d, 0xd4, 0x2e, 0xc3, 0xe1, 0x9a, 0xe1, 0x77, 0x03, 0xd6, - 0xf2, 0xb3, 0xb0, 0x7b, 0x05, 0xa3, 0xfc, 0x5f, 0xaa, 0x39, 0xf8, 0x3f, 0x29, 0x9a, 0xb0, 0x2f, - 0x09, 0x7b, 0x68, 0x67, 0x3e, 0x61, 0x3a, 0x8b, 0xe8, 0x1b, 0xa8, 0xec, 0x05, 0x31, 0xba, 0x35, - 0xd7, 0xea, 0x62, 0x92, 0xcc, 0xde, 0x8b, 0x85, 0x9a, 0x64, 0x5b, 0x92, 0xbc, 0x8e, 0x5a, 0x76, - 0xf9, 0x67, 0xe4, 0xfe, 0xdd, 0xc7, 0x67, 0x96, 0xf1, 0xe4, 0xcc, 0x32, 0xfe, 0x39, 0xb3, 0x8c, - 0x5f, 0xce, 0xad, 0xa5, 0x27, 0xe7, 0xd6, 0xd2, 0xdf, 0xe7, 0xd6, 0xd2, 0x17, 0xb7, 0x3d, 0x3f, - 0x3c, 0x8a, 0x86, 0xfd, 0x11, 0x3b, 0x96, 0x05, 0xde, 0x1e, 0xe3, 0xa1, 0x50, 0xa5, 0x4e, 0x67, - 0x8a, 0x25, 0x5f, 0x65, 0x62, 0x58, 0x97, 0x1f, 0x91, 0xef, 0xfc, 0x17, 0x00, 0x00, 0xff, 0xff, - 0x8e, 0xce, 0x8c, 0x23, 0x22, 0x0b, 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 { - // Params queries module params. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Rewards queries reward information for a given user. - Rewards(ctx context.Context, in *QueryRewardsRequest, opts ...grpc.CallOption) (*QueryRewardsResponse, error) - // Rewards queries the reward factors. - RewardFactors(ctx context.Context, in *QueryRewardFactorsRequest, opts ...grpc.CallOption) (*QueryRewardFactorsResponse, error) - // Apy queries incentive reward apy for a reward. - Apy(ctx context.Context, in *QueryApyRequest, opts ...grpc.CallOption) (*QueryApyResponse, 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, "/kava.incentive.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Rewards(ctx context.Context, in *QueryRewardsRequest, opts ...grpc.CallOption) (*QueryRewardsResponse, error) { - out := new(QueryRewardsResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Query/Rewards", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) RewardFactors(ctx context.Context, in *QueryRewardFactorsRequest, opts ...grpc.CallOption) (*QueryRewardFactorsResponse, error) { - out := new(QueryRewardFactorsResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Query/RewardFactors", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Apy(ctx context.Context, in *QueryApyRequest, opts ...grpc.CallOption) (*QueryApyResponse, error) { - out := new(QueryApyResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Query/Apy", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries module params. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Rewards queries reward information for a given user. - Rewards(context.Context, *QueryRewardsRequest) (*QueryRewardsResponse, error) - // Rewards queries the reward factors. - RewardFactors(context.Context, *QueryRewardFactorsRequest) (*QueryRewardFactorsResponse, error) - // Apy queries incentive reward apy for a reward. - Apy(context.Context, *QueryApyRequest) (*QueryApyResponse, 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) Rewards(ctx context.Context, req *QueryRewardsRequest) (*QueryRewardsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Rewards not implemented") -} -func (*UnimplementedQueryServer) RewardFactors(ctx context.Context, req *QueryRewardFactorsRequest) (*QueryRewardFactorsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RewardFactors not implemented") -} -func (*UnimplementedQueryServer) Apy(ctx context.Context, req *QueryApyRequest) (*QueryApyResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Apy 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: "/kava.incentive.v1beta1.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_Rewards_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRewardsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Rewards(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Query/Rewards", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Rewards(ctx, req.(*QueryRewardsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_RewardFactors_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRewardFactorsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).RewardFactors(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Query/RewardFactors", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).RewardFactors(ctx, req.(*QueryRewardFactorsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Apy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryApyRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Apy(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Query/Apy", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Apy(ctx, req.(*QueryApyRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.incentive.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Rewards", - Handler: _Query_Rewards_Handler, - }, - { - MethodName: "RewardFactors", - Handler: _Query_RewardFactors_Handler, - }, - { - MethodName: "Apy", - Handler: _Query_Apy_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/incentive/v1beta1/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 *QueryRewardsRequest) 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 *QueryRewardsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRewardsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Unsynchronized { - i-- - if m.Unsynchronized { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x18 - } - if len(m.RewardType) > 0 { - i -= len(m.RewardType) - copy(dAtA[i:], m.RewardType) - i = encodeVarintQuery(dAtA, i, uint64(len(m.RewardType))) - i-- - dAtA[i] = 0x12 - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryRewardsResponse) 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 *QueryRewardsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRewardsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.EarnClaims) > 0 { - for iNdEx := len(m.EarnClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.EarnClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - } - if len(m.SavingsClaims) > 0 { - for iNdEx := len(m.SavingsClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SavingsClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - } - if len(m.SwapClaims) > 0 { - for iNdEx := len(m.SwapClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SwapClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.DelegatorClaims) > 0 { - for iNdEx := len(m.DelegatorClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DelegatorClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.HardLiquidityProviderClaims) > 0 { - for iNdEx := len(m.HardLiquidityProviderClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.HardLiquidityProviderClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.USDXMintingClaims) > 0 { - for iNdEx := len(m.USDXMintingClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.USDXMintingClaims[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 (m *QueryRewardFactorsRequest) 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 *QueryRewardFactorsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRewardFactorsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryRewardFactorsResponse) 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 *QueryRewardFactorsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRewardFactorsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.EarnRewardFactors) > 0 { - for iNdEx := len(m.EarnRewardFactors) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.EarnRewardFactors[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - } - if len(m.SavingsRewardFactors) > 0 { - for iNdEx := len(m.SavingsRewardFactors) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SavingsRewardFactors[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - } - if len(m.SwapRewardFactors) > 0 { - for iNdEx := len(m.SwapRewardFactors) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SwapRewardFactors[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - } - if len(m.DelegatorRewardFactors) > 0 { - for iNdEx := len(m.DelegatorRewardFactors) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DelegatorRewardFactors[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.HardBorrowRewardFactors) > 0 { - for iNdEx := len(m.HardBorrowRewardFactors) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.HardBorrowRewardFactors[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.HardSupplyRewardFactors) > 0 { - for iNdEx := len(m.HardSupplyRewardFactors) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.HardSupplyRewardFactors[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.UsdxMintingRewardFactors) > 0 { - for iNdEx := len(m.UsdxMintingRewardFactors) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.UsdxMintingRewardFactors[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 (m *QueryApyRequest) 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 *QueryApyRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryApyRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryApyResponse) 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 *QueryApyResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryApyResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Earn) > 0 { - for iNdEx := len(m.Earn) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Earn[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 *QueryRewardsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.RewardType) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Unsynchronized { - n += 2 - } - return n -} - -func (m *QueryRewardsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.USDXMintingClaims) > 0 { - for _, e := range m.USDXMintingClaims { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.HardLiquidityProviderClaims) > 0 { - for _, e := range m.HardLiquidityProviderClaims { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.DelegatorClaims) > 0 { - for _, e := range m.DelegatorClaims { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.SwapClaims) > 0 { - for _, e := range m.SwapClaims { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.SavingsClaims) > 0 { - for _, e := range m.SavingsClaims { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.EarnClaims) > 0 { - for _, e := range m.EarnClaims { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryRewardFactorsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryRewardFactorsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.UsdxMintingRewardFactors) > 0 { - for _, e := range m.UsdxMintingRewardFactors { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.HardSupplyRewardFactors) > 0 { - for _, e := range m.HardSupplyRewardFactors { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.HardBorrowRewardFactors) > 0 { - for _, e := range m.HardBorrowRewardFactors { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.DelegatorRewardFactors) > 0 { - for _, e := range m.DelegatorRewardFactors { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.SwapRewardFactors) > 0 { - for _, e := range m.SwapRewardFactors { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.SavingsRewardFactors) > 0 { - for _, e := range m.SavingsRewardFactors { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.EarnRewardFactors) > 0 { - for _, e := range m.EarnRewardFactors { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryApyRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryApyResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Earn) > 0 { - for _, e := range m.Earn { - l = e.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 *QueryRewardsRequest) 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: QueryRewardsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRewardsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Unsynchronized", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Unsynchronized = bool(v != 0) - 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 *QueryRewardsResponse) 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: QueryRewardsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRewardsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field USDXMintingClaims", 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.USDXMintingClaims = append(m.USDXMintingClaims, USDXMintingClaim{}) - if err := m.USDXMintingClaims[len(m.USDXMintingClaims)-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 HardLiquidityProviderClaims", 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.HardLiquidityProviderClaims = append(m.HardLiquidityProviderClaims, HardLiquidityProviderClaim{}) - if err := m.HardLiquidityProviderClaims[len(m.HardLiquidityProviderClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorClaims", 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.DelegatorClaims = append(m.DelegatorClaims, DelegatorClaim{}) - if err := m.DelegatorClaims[len(m.DelegatorClaims)-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 SwapClaims", 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.SwapClaims = append(m.SwapClaims, SwapClaim{}) - if err := m.SwapClaims[len(m.SwapClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SavingsClaims", 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.SavingsClaims = append(m.SavingsClaims, SavingsClaim{}) - if err := m.SavingsClaims[len(m.SavingsClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EarnClaims", 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.EarnClaims = append(m.EarnClaims, EarnClaim{}) - if err := m.EarnClaims[len(m.EarnClaims)-1].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 *QueryRewardFactorsRequest) 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: QueryRewardFactorsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRewardFactorsRequest: 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 *QueryRewardFactorsResponse) 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: QueryRewardFactorsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRewardFactorsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UsdxMintingRewardFactors", 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.UsdxMintingRewardFactors = append(m.UsdxMintingRewardFactors, RewardIndex{}) - if err := m.UsdxMintingRewardFactors[len(m.UsdxMintingRewardFactors)-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 HardSupplyRewardFactors", 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.HardSupplyRewardFactors = append(m.HardSupplyRewardFactors, MultiRewardIndex{}) - if err := m.HardSupplyRewardFactors[len(m.HardSupplyRewardFactors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HardBorrowRewardFactors", 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.HardBorrowRewardFactors = append(m.HardBorrowRewardFactors, MultiRewardIndex{}) - if err := m.HardBorrowRewardFactors[len(m.HardBorrowRewardFactors)-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 DelegatorRewardFactors", 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.DelegatorRewardFactors = append(m.DelegatorRewardFactors, MultiRewardIndex{}) - if err := m.DelegatorRewardFactors[len(m.DelegatorRewardFactors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SwapRewardFactors", 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.SwapRewardFactors = append(m.SwapRewardFactors, MultiRewardIndex{}) - if err := m.SwapRewardFactors[len(m.SwapRewardFactors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SavingsRewardFactors", 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.SavingsRewardFactors = append(m.SavingsRewardFactors, MultiRewardIndex{}) - if err := m.SavingsRewardFactors[len(m.SavingsRewardFactors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EarnRewardFactors", 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.EarnRewardFactors = append(m.EarnRewardFactors, MultiRewardIndex{}) - if err := m.EarnRewardFactors[len(m.EarnRewardFactors)-1].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 *QueryApyRequest) 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: QueryApyRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryApyRequest: 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 *QueryApyResponse) 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: QueryApyResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryApyResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Earn", 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.Earn = append(m.Earn, Apy{}) - if err := m.Earn[len(m.Earn)-1].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/incentive/types/query.pb.gw.go b/x/incentive/types/query.pb.gw.go deleted file mode 100644 index ffc69a87..00000000 --- a/x/incentive/types/query.pb.gw.go +++ /dev/null @@ -1,366 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/incentive/v1beta1/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 - -} - -var ( - filter_Query_Rewards_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Rewards_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRewardsRequest - 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_Rewards_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Rewards(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Rewards_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRewardsRequest - 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_Rewards_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Rewards(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_RewardFactors_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRewardFactorsRequest - var metadata runtime.ServerMetadata - - msg, err := client.RewardFactors(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_RewardFactors_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRewardFactorsRequest - var metadata runtime.ServerMetadata - - msg, err := server.RewardFactors(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Apy_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryApyRequest - var metadata runtime.ServerMetadata - - msg, err := client.Apy(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Apy_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryApyRequest - var metadata runtime.ServerMetadata - - msg, err := server.Apy(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_Rewards_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_Rewards_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_Rewards_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_RewardFactors_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_RewardFactors_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_RewardFactors_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Apy_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_Apy_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_Apy_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_Rewards_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_Rewards_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_Rewards_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_RewardFactors_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_RewardFactors_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_RewardFactors_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Apy_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_Apy_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_Apy_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{"kava", "incentive", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Rewards_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "incentive", "v1beta1", "rewards"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_RewardFactors_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "incentive", "v1beta1", "reward_factors"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Apy_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "incentive", "v1beta1", "apy"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Rewards_0 = runtime.ForwardResponseMessage - - forward_Query_RewardFactors_0 = runtime.ForwardResponseMessage - - forward_Query_Apy_0 = runtime.ForwardResponseMessage -) diff --git a/x/incentive/types/sdk.go b/x/incentive/types/sdk.go deleted file mode 100644 index 10787a99..00000000 --- a/x/incentive/types/sdk.go +++ /dev/null @@ -1,20 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" -) - -// NewPeriod returns a new vesting period -func NewPeriod(amount sdk.Coins, length int64) vestingtypes.Period { - return vestingtypes.Period{Amount: amount, Length: length} -} - -// GetTotalVestingPeriodLength returns the summed length of all vesting periods -func GetTotalVestingPeriodLength(periods vestingtypes.Periods) int64 { - length := int64(0) - for _, period := range periods { - length += period.Length - } - return length -} diff --git a/x/incentive/types/sdk_test.go b/x/incentive/types/sdk_test.go deleted file mode 100644 index 6e74f1b8..00000000 --- a/x/incentive/types/sdk_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - - "github.com/kava-labs/kava/x/incentive/types" -) - -func TestGetTotalVestingPeriodLength(t *testing.T) { - testCases := []struct { - name string - periods vestingtypes.Periods - expectedVal int64 - }{ - { - name: "two period lengths are added together", - periods: vestingtypes.Periods{ - { - Length: 100, - }, - { - Length: 200, - }, - }, - expectedVal: 300, - }, - { - name: "no periods returns zero", - periods: nil, - expectedVal: 0, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - length := types.GetTotalVestingPeriodLength(tc.periods) - require.Equal(t, tc.expectedVal, length) - }) - } -} diff --git a/x/incentive/types/tx.pb.go b/x/incentive/types/tx.pb.go deleted file mode 100644 index 30dd8bec..00000000 --- a/x/incentive/types/tx.pb.go +++ /dev/null @@ -1,2677 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/incentive/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - 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 - -// Selection is a pair of denom and multiplier name. It holds the choice of multiplier a user makes when they claim a -// denom. -type Selection struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - MultiplierName string `protobuf:"bytes,2,opt,name=multiplier_name,json=multiplierName,proto3" json:"multiplier_name,omitempty"` -} - -func (m *Selection) Reset() { *m = Selection{} } -func (m *Selection) String() string { return proto.CompactTextString(m) } -func (*Selection) ProtoMessage() {} -func (*Selection) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{0} -} -func (m *Selection) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Selection) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Selection.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 *Selection) XXX_Merge(src proto.Message) { - xxx_messageInfo_Selection.Merge(m, src) -} -func (m *Selection) XXX_Size() int { - return m.Size() -} -func (m *Selection) XXX_DiscardUnknown() { - xxx_messageInfo_Selection.DiscardUnknown(m) -} - -var xxx_messageInfo_Selection proto.InternalMessageInfo - -// MsgClaimUSDXMintingReward message type used to claim USDX minting rewards -type MsgClaimUSDXMintingReward struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - MultiplierName string `protobuf:"bytes,2,opt,name=multiplier_name,json=multiplierName,proto3" json:"multiplier_name,omitempty"` -} - -func (m *MsgClaimUSDXMintingReward) Reset() { *m = MsgClaimUSDXMintingReward{} } -func (m *MsgClaimUSDXMintingReward) String() string { return proto.CompactTextString(m) } -func (*MsgClaimUSDXMintingReward) ProtoMessage() {} -func (*MsgClaimUSDXMintingReward) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{1} -} -func (m *MsgClaimUSDXMintingReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimUSDXMintingReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimUSDXMintingReward.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 *MsgClaimUSDXMintingReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimUSDXMintingReward.Merge(m, src) -} -func (m *MsgClaimUSDXMintingReward) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimUSDXMintingReward) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimUSDXMintingReward.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimUSDXMintingReward proto.InternalMessageInfo - -// MsgClaimUSDXMintingRewardResponse defines the Msg/ClaimUSDXMintingReward response type. -type MsgClaimUSDXMintingRewardResponse struct { -} - -func (m *MsgClaimUSDXMintingRewardResponse) Reset() { *m = MsgClaimUSDXMintingRewardResponse{} } -func (m *MsgClaimUSDXMintingRewardResponse) String() string { return proto.CompactTextString(m) } -func (*MsgClaimUSDXMintingRewardResponse) ProtoMessage() {} -func (*MsgClaimUSDXMintingRewardResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{2} -} -func (m *MsgClaimUSDXMintingRewardResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimUSDXMintingRewardResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimUSDXMintingRewardResponse.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 *MsgClaimUSDXMintingRewardResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimUSDXMintingRewardResponse.Merge(m, src) -} -func (m *MsgClaimUSDXMintingRewardResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimUSDXMintingRewardResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimUSDXMintingRewardResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimUSDXMintingRewardResponse proto.InternalMessageInfo - -// MsgClaimHardReward message type used to claim Hard liquidity provider rewards -type MsgClaimHardReward struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - DenomsToClaim Selections `protobuf:"bytes,2,rep,name=denoms_to_claim,json=denomsToClaim,proto3,castrepeated=Selections" json:"denoms_to_claim"` -} - -func (m *MsgClaimHardReward) Reset() { *m = MsgClaimHardReward{} } -func (m *MsgClaimHardReward) String() string { return proto.CompactTextString(m) } -func (*MsgClaimHardReward) ProtoMessage() {} -func (*MsgClaimHardReward) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{3} -} -func (m *MsgClaimHardReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimHardReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimHardReward.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 *MsgClaimHardReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimHardReward.Merge(m, src) -} -func (m *MsgClaimHardReward) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimHardReward) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimHardReward.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimHardReward proto.InternalMessageInfo - -// MsgClaimHardRewardResponse defines the Msg/ClaimHardReward response type. -type MsgClaimHardRewardResponse struct { -} - -func (m *MsgClaimHardRewardResponse) Reset() { *m = MsgClaimHardRewardResponse{} } -func (m *MsgClaimHardRewardResponse) String() string { return proto.CompactTextString(m) } -func (*MsgClaimHardRewardResponse) ProtoMessage() {} -func (*MsgClaimHardRewardResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{4} -} -func (m *MsgClaimHardRewardResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimHardRewardResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimHardRewardResponse.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 *MsgClaimHardRewardResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimHardRewardResponse.Merge(m, src) -} -func (m *MsgClaimHardRewardResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimHardRewardResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimHardRewardResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimHardRewardResponse proto.InternalMessageInfo - -// MsgClaimDelegatorReward message type used to claim delegator rewards -type MsgClaimDelegatorReward struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - DenomsToClaim Selections `protobuf:"bytes,2,rep,name=denoms_to_claim,json=denomsToClaim,proto3,castrepeated=Selections" json:"denoms_to_claim"` -} - -func (m *MsgClaimDelegatorReward) Reset() { *m = MsgClaimDelegatorReward{} } -func (m *MsgClaimDelegatorReward) String() string { return proto.CompactTextString(m) } -func (*MsgClaimDelegatorReward) ProtoMessage() {} -func (*MsgClaimDelegatorReward) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{5} -} -func (m *MsgClaimDelegatorReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimDelegatorReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimDelegatorReward.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 *MsgClaimDelegatorReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimDelegatorReward.Merge(m, src) -} -func (m *MsgClaimDelegatorReward) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimDelegatorReward) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimDelegatorReward.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimDelegatorReward proto.InternalMessageInfo - -// MsgClaimDelegatorRewardResponse defines the Msg/ClaimDelegatorReward response type. -type MsgClaimDelegatorRewardResponse struct { -} - -func (m *MsgClaimDelegatorRewardResponse) Reset() { *m = MsgClaimDelegatorRewardResponse{} } -func (m *MsgClaimDelegatorRewardResponse) String() string { return proto.CompactTextString(m) } -func (*MsgClaimDelegatorRewardResponse) ProtoMessage() {} -func (*MsgClaimDelegatorRewardResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{6} -} -func (m *MsgClaimDelegatorRewardResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimDelegatorRewardResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimDelegatorRewardResponse.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 *MsgClaimDelegatorRewardResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimDelegatorRewardResponse.Merge(m, src) -} -func (m *MsgClaimDelegatorRewardResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimDelegatorRewardResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimDelegatorRewardResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimDelegatorRewardResponse proto.InternalMessageInfo - -// MsgClaimSwapReward message type used to claim delegator rewards -type MsgClaimSwapReward struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - DenomsToClaim Selections `protobuf:"bytes,2,rep,name=denoms_to_claim,json=denomsToClaim,proto3,castrepeated=Selections" json:"denoms_to_claim"` -} - -func (m *MsgClaimSwapReward) Reset() { *m = MsgClaimSwapReward{} } -func (m *MsgClaimSwapReward) String() string { return proto.CompactTextString(m) } -func (*MsgClaimSwapReward) ProtoMessage() {} -func (*MsgClaimSwapReward) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{7} -} -func (m *MsgClaimSwapReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimSwapReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimSwapReward.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 *MsgClaimSwapReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimSwapReward.Merge(m, src) -} -func (m *MsgClaimSwapReward) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimSwapReward) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimSwapReward.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimSwapReward proto.InternalMessageInfo - -// MsgClaimSwapRewardResponse defines the Msg/ClaimSwapReward response type. -type MsgClaimSwapRewardResponse struct { -} - -func (m *MsgClaimSwapRewardResponse) Reset() { *m = MsgClaimSwapRewardResponse{} } -func (m *MsgClaimSwapRewardResponse) String() string { return proto.CompactTextString(m) } -func (*MsgClaimSwapRewardResponse) ProtoMessage() {} -func (*MsgClaimSwapRewardResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{8} -} -func (m *MsgClaimSwapRewardResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimSwapRewardResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimSwapRewardResponse.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 *MsgClaimSwapRewardResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimSwapRewardResponse.Merge(m, src) -} -func (m *MsgClaimSwapRewardResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimSwapRewardResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimSwapRewardResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimSwapRewardResponse proto.InternalMessageInfo - -// MsgClaimSavingsReward message type used to claim savings rewards -type MsgClaimSavingsReward struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - DenomsToClaim Selections `protobuf:"bytes,2,rep,name=denoms_to_claim,json=denomsToClaim,proto3,castrepeated=Selections" json:"denoms_to_claim"` -} - -func (m *MsgClaimSavingsReward) Reset() { *m = MsgClaimSavingsReward{} } -func (m *MsgClaimSavingsReward) String() string { return proto.CompactTextString(m) } -func (*MsgClaimSavingsReward) ProtoMessage() {} -func (*MsgClaimSavingsReward) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{9} -} -func (m *MsgClaimSavingsReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimSavingsReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimSavingsReward.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 *MsgClaimSavingsReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimSavingsReward.Merge(m, src) -} -func (m *MsgClaimSavingsReward) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimSavingsReward) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimSavingsReward.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimSavingsReward proto.InternalMessageInfo - -// MsgClaimSavingsRewardResponse defines the Msg/ClaimSavingsReward response type. -type MsgClaimSavingsRewardResponse struct { -} - -func (m *MsgClaimSavingsRewardResponse) Reset() { *m = MsgClaimSavingsRewardResponse{} } -func (m *MsgClaimSavingsRewardResponse) String() string { return proto.CompactTextString(m) } -func (*MsgClaimSavingsRewardResponse) ProtoMessage() {} -func (*MsgClaimSavingsRewardResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{10} -} -func (m *MsgClaimSavingsRewardResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimSavingsRewardResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimSavingsRewardResponse.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 *MsgClaimSavingsRewardResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimSavingsRewardResponse.Merge(m, src) -} -func (m *MsgClaimSavingsRewardResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimSavingsRewardResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimSavingsRewardResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimSavingsRewardResponse proto.InternalMessageInfo - -// MsgClaimEarnReward message type used to claim earn rewards -type MsgClaimEarnReward struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - DenomsToClaim Selections `protobuf:"bytes,2,rep,name=denoms_to_claim,json=denomsToClaim,proto3,castrepeated=Selections" json:"denoms_to_claim"` -} - -func (m *MsgClaimEarnReward) Reset() { *m = MsgClaimEarnReward{} } -func (m *MsgClaimEarnReward) String() string { return proto.CompactTextString(m) } -func (*MsgClaimEarnReward) ProtoMessage() {} -func (*MsgClaimEarnReward) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{11} -} -func (m *MsgClaimEarnReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimEarnReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimEarnReward.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 *MsgClaimEarnReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimEarnReward.Merge(m, src) -} -func (m *MsgClaimEarnReward) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimEarnReward) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimEarnReward.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimEarnReward proto.InternalMessageInfo - -// MsgClaimEarnRewardResponse defines the Msg/ClaimEarnReward response type. -type MsgClaimEarnRewardResponse struct { -} - -func (m *MsgClaimEarnRewardResponse) Reset() { *m = MsgClaimEarnRewardResponse{} } -func (m *MsgClaimEarnRewardResponse) String() string { return proto.CompactTextString(m) } -func (*MsgClaimEarnRewardResponse) ProtoMessage() {} -func (*MsgClaimEarnRewardResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{12} -} -func (m *MsgClaimEarnRewardResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimEarnRewardResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimEarnRewardResponse.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 *MsgClaimEarnRewardResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimEarnRewardResponse.Merge(m, src) -} -func (m *MsgClaimEarnRewardResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimEarnRewardResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimEarnRewardResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimEarnRewardResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Selection)(nil), "kava.incentive.v1beta1.Selection") - proto.RegisterType((*MsgClaimUSDXMintingReward)(nil), "kava.incentive.v1beta1.MsgClaimUSDXMintingReward") - proto.RegisterType((*MsgClaimUSDXMintingRewardResponse)(nil), "kava.incentive.v1beta1.MsgClaimUSDXMintingRewardResponse") - proto.RegisterType((*MsgClaimHardReward)(nil), "kava.incentive.v1beta1.MsgClaimHardReward") - proto.RegisterType((*MsgClaimHardRewardResponse)(nil), "kava.incentive.v1beta1.MsgClaimHardRewardResponse") - proto.RegisterType((*MsgClaimDelegatorReward)(nil), "kava.incentive.v1beta1.MsgClaimDelegatorReward") - proto.RegisterType((*MsgClaimDelegatorRewardResponse)(nil), "kava.incentive.v1beta1.MsgClaimDelegatorRewardResponse") - proto.RegisterType((*MsgClaimSwapReward)(nil), "kava.incentive.v1beta1.MsgClaimSwapReward") - proto.RegisterType((*MsgClaimSwapRewardResponse)(nil), "kava.incentive.v1beta1.MsgClaimSwapRewardResponse") - proto.RegisterType((*MsgClaimSavingsReward)(nil), "kava.incentive.v1beta1.MsgClaimSavingsReward") - proto.RegisterType((*MsgClaimSavingsRewardResponse)(nil), "kava.incentive.v1beta1.MsgClaimSavingsRewardResponse") - proto.RegisterType((*MsgClaimEarnReward)(nil), "kava.incentive.v1beta1.MsgClaimEarnReward") - proto.RegisterType((*MsgClaimEarnRewardResponse)(nil), "kava.incentive.v1beta1.MsgClaimEarnRewardResponse") -} - -func init() { proto.RegisterFile("kava/incentive/v1beta1/tx.proto", fileDescriptor_b1cec058e3ff75d5) } - -var fileDescriptor_b1cec058e3ff75d5 = []byte{ - // 525 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x95, 0x31, 0x6f, 0xd3, 0x40, - 0x14, 0xc7, 0x7d, 0xad, 0x5a, 0xd1, 0x87, 0x20, 0xd2, 0x29, 0x84, 0x60, 0x81, 0xdd, 0x84, 0x81, - 0x0a, 0x54, 0x5b, 0x09, 0x42, 0x08, 0xc6, 0xd2, 0x4a, 0x2c, 0x61, 0x48, 0x8a, 0x84, 0x90, 0x50, - 0x74, 0x49, 0x0e, 0x73, 0xc2, 0xbe, 0x33, 0xbe, 0x6b, 0x5a, 0x98, 0x98, 0x10, 0x23, 0x0b, 0x12, - 0x62, 0xea, 0xcc, 0x27, 0xe9, 0xd8, 0x91, 0x09, 0x50, 0x22, 0x21, 0x3e, 0x06, 0x8a, 0x93, 0xd8, - 0x56, 0x6d, 0x63, 0xd2, 0x29, 0x9b, 0xed, 0xf7, 0x7f, 0xef, 0xfd, 0xfe, 0x4f, 0x7e, 0x77, 0x60, - 0xbe, 0x26, 0x43, 0x62, 0x33, 0xde, 0xa7, 0x5c, 0xb1, 0x21, 0xb5, 0x87, 0x8d, 0x1e, 0x55, 0xa4, - 0x61, 0xab, 0x23, 0xcb, 0x0f, 0x84, 0x12, 0xb8, 0x32, 0x11, 0x58, 0x91, 0xc0, 0x9a, 0x09, 0xf4, - 0xb2, 0x23, 0x1c, 0x11, 0x4a, 0xec, 0xc9, 0xd3, 0x54, 0x5d, 0xdf, 0x87, 0x8d, 0x0e, 0x75, 0x69, - 0x5f, 0x31, 0xc1, 0x71, 0x19, 0xd6, 0x06, 0x94, 0x0b, 0xaf, 0x8a, 0x36, 0xd1, 0xd6, 0x46, 0x7b, - 0xfa, 0x82, 0x6f, 0x41, 0xc9, 0x3b, 0x70, 0x15, 0xf3, 0x5d, 0x46, 0x83, 0x2e, 0x27, 0x1e, 0xad, - 0xae, 0x84, 0xf1, 0xcb, 0xf1, 0xe7, 0x27, 0xc4, 0xa3, 0x0f, 0x2f, 0x7c, 0x3c, 0x36, 0xb5, 0x3f, - 0xc7, 0xa6, 0x56, 0x7f, 0x09, 0xd7, 0x5a, 0xd2, 0x79, 0xe4, 0x12, 0xe6, 0x3d, 0xed, 0xec, 0x3e, - 0x6b, 0x31, 0xae, 0x18, 0x77, 0xda, 0xf4, 0x90, 0x04, 0x03, 0x5c, 0x81, 0x75, 0x49, 0xf9, 0x80, - 0x06, 0xb3, 0x36, 0xb3, 0xb7, 0xf3, 0xf4, 0xb9, 0x09, 0xb5, 0xdc, 0x3e, 0x6d, 0x2a, 0x7d, 0xc1, - 0x25, 0xad, 0x7f, 0x46, 0x80, 0xe7, 0xaa, 0xc7, 0x61, 0xe0, 0x9f, 0x18, 0x2f, 0xa0, 0x14, 0xfa, - 0x96, 0x5d, 0x25, 0xba, 0xfd, 0x49, 0x52, 0x75, 0x65, 0x73, 0x75, 0xeb, 0x62, 0xb3, 0x66, 0x65, - 0x4f, 0xd6, 0x8a, 0x06, 0xb8, 0x83, 0x4f, 0x7e, 0x98, 0xda, 0xb7, 0x9f, 0x26, 0x44, 0x9f, 0x64, - 0xfb, 0xd2, 0xb4, 0xda, 0xbe, 0x08, 0x01, 0x12, 0xf0, 0xd7, 0x41, 0x4f, 0x63, 0x45, 0xd4, 0x5f, - 0x11, 0x5c, 0x9d, 0x87, 0x77, 0xa9, 0x4b, 0x1d, 0xa2, 0x44, 0xb0, 0x2c, 0xe8, 0x35, 0x30, 0x73, - 0xd8, 0x32, 0xa7, 0xde, 0x39, 0x24, 0xfe, 0x12, 0x4e, 0x3d, 0xc6, 0x8a, 0xa8, 0xbf, 0x20, 0xb8, - 0x12, 0x85, 0xc9, 0x90, 0x71, 0x47, 0x2e, 0x0b, 0xb8, 0x09, 0x37, 0x32, 0xc9, 0x32, 0x27, 0xbe, - 0x47, 0x02, 0xbe, 0x84, 0x13, 0x8f, 0xb1, 0xe6, 0xd4, 0xcd, 0xdf, 0x6b, 0xb0, 0xda, 0x92, 0x0e, - 0xfe, 0x80, 0xa0, 0x92, 0x73, 0x60, 0x34, 0xf2, 0x80, 0x72, 0x77, 0x5f, 0x7f, 0xb0, 0x70, 0xca, - 0x1c, 0x08, 0xbf, 0x81, 0xd2, 0xd9, 0xa3, 0xe2, 0x76, 0x51, 0xb5, 0x58, 0xab, 0x37, 0xff, 0x5f, - 0x1b, 0xb5, 0x7c, 0x8f, 0xa0, 0x9c, 0xb9, 0xe8, 0x76, 0x51, 0xb1, 0x33, 0x09, 0xfa, 0xfd, 0x05, - 0x13, 0x52, 0xae, 0x13, 0xab, 0x5a, 0xe8, 0x3a, 0xd6, 0x16, 0xbb, 0x4e, 0xef, 0x1a, 0x7e, 0x07, - 0x38, 0x63, 0xcf, 0xb6, 0x0b, 0x2b, 0x25, 0xe5, 0xfa, 0xbd, 0x85, 0xe4, 0x29, 0xbb, 0x89, 0x3d, - 0x29, 0xb4, 0x1b, 0x6b, 0x8b, 0xed, 0xa6, 0x7f, 0xf4, 0x9d, 0xbd, 0x93, 0x91, 0x81, 0x4e, 0x47, - 0x06, 0xfa, 0x35, 0x32, 0xd0, 0xa7, 0xb1, 0xa1, 0x9d, 0x8e, 0x0d, 0xed, 0xfb, 0xd8, 0xd0, 0x9e, - 0xdf, 0x71, 0x98, 0x7a, 0x75, 0xd0, 0xb3, 0xfa, 0xc2, 0xb3, 0x27, 0x75, 0xb7, 0x5d, 0xd2, 0x93, - 0xe1, 0x93, 0x7d, 0x94, 0xb8, 0xe9, 0xd5, 0x5b, 0x9f, 0xca, 0xde, 0x7a, 0x78, 0x6f, 0xdf, 0xfd, - 0x1b, 0x00, 0x00, 0xff, 0xff, 0x28, 0x8b, 0x70, 0xee, 0x08, 0x08, 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 { - // ClaimUSDXMintingReward is a message type used to claim USDX minting rewards - ClaimUSDXMintingReward(ctx context.Context, in *MsgClaimUSDXMintingReward, opts ...grpc.CallOption) (*MsgClaimUSDXMintingRewardResponse, error) - // ClaimHardReward is a message type used to claim Hard liquidity provider rewards - ClaimHardReward(ctx context.Context, in *MsgClaimHardReward, opts ...grpc.CallOption) (*MsgClaimHardRewardResponse, error) - // ClaimDelegatorReward is a message type used to claim delegator rewards - ClaimDelegatorReward(ctx context.Context, in *MsgClaimDelegatorReward, opts ...grpc.CallOption) (*MsgClaimDelegatorRewardResponse, error) - // ClaimSwapReward is a message type used to claim swap rewards - ClaimSwapReward(ctx context.Context, in *MsgClaimSwapReward, opts ...grpc.CallOption) (*MsgClaimSwapRewardResponse, error) - // ClaimSavingsReward is a message type used to claim savings rewards - ClaimSavingsReward(ctx context.Context, in *MsgClaimSavingsReward, opts ...grpc.CallOption) (*MsgClaimSavingsRewardResponse, error) - // ClaimEarnReward is a message type used to claim earn rewards - ClaimEarnReward(ctx context.Context, in *MsgClaimEarnReward, opts ...grpc.CallOption) (*MsgClaimEarnRewardResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) ClaimUSDXMintingReward(ctx context.Context, in *MsgClaimUSDXMintingReward, opts ...grpc.CallOption) (*MsgClaimUSDXMintingRewardResponse, error) { - out := new(MsgClaimUSDXMintingRewardResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Msg/ClaimUSDXMintingReward", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ClaimHardReward(ctx context.Context, in *MsgClaimHardReward, opts ...grpc.CallOption) (*MsgClaimHardRewardResponse, error) { - out := new(MsgClaimHardRewardResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Msg/ClaimHardReward", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ClaimDelegatorReward(ctx context.Context, in *MsgClaimDelegatorReward, opts ...grpc.CallOption) (*MsgClaimDelegatorRewardResponse, error) { - out := new(MsgClaimDelegatorRewardResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Msg/ClaimDelegatorReward", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ClaimSwapReward(ctx context.Context, in *MsgClaimSwapReward, opts ...grpc.CallOption) (*MsgClaimSwapRewardResponse, error) { - out := new(MsgClaimSwapRewardResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Msg/ClaimSwapReward", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ClaimSavingsReward(ctx context.Context, in *MsgClaimSavingsReward, opts ...grpc.CallOption) (*MsgClaimSavingsRewardResponse, error) { - out := new(MsgClaimSavingsRewardResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Msg/ClaimSavingsReward", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ClaimEarnReward(ctx context.Context, in *MsgClaimEarnReward, opts ...grpc.CallOption) (*MsgClaimEarnRewardResponse, error) { - out := new(MsgClaimEarnRewardResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Msg/ClaimEarnReward", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // ClaimUSDXMintingReward is a message type used to claim USDX minting rewards - ClaimUSDXMintingReward(context.Context, *MsgClaimUSDXMintingReward) (*MsgClaimUSDXMintingRewardResponse, error) - // ClaimHardReward is a message type used to claim Hard liquidity provider rewards - ClaimHardReward(context.Context, *MsgClaimHardReward) (*MsgClaimHardRewardResponse, error) - // ClaimDelegatorReward is a message type used to claim delegator rewards - ClaimDelegatorReward(context.Context, *MsgClaimDelegatorReward) (*MsgClaimDelegatorRewardResponse, error) - // ClaimSwapReward is a message type used to claim swap rewards - ClaimSwapReward(context.Context, *MsgClaimSwapReward) (*MsgClaimSwapRewardResponse, error) - // ClaimSavingsReward is a message type used to claim savings rewards - ClaimSavingsReward(context.Context, *MsgClaimSavingsReward) (*MsgClaimSavingsRewardResponse, error) - // ClaimEarnReward is a message type used to claim earn rewards - ClaimEarnReward(context.Context, *MsgClaimEarnReward) (*MsgClaimEarnRewardResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) ClaimUSDXMintingReward(ctx context.Context, req *MsgClaimUSDXMintingReward) (*MsgClaimUSDXMintingRewardResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ClaimUSDXMintingReward not implemented") -} -func (*UnimplementedMsgServer) ClaimHardReward(ctx context.Context, req *MsgClaimHardReward) (*MsgClaimHardRewardResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ClaimHardReward not implemented") -} -func (*UnimplementedMsgServer) ClaimDelegatorReward(ctx context.Context, req *MsgClaimDelegatorReward) (*MsgClaimDelegatorRewardResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ClaimDelegatorReward not implemented") -} -func (*UnimplementedMsgServer) ClaimSwapReward(ctx context.Context, req *MsgClaimSwapReward) (*MsgClaimSwapRewardResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ClaimSwapReward not implemented") -} -func (*UnimplementedMsgServer) ClaimSavingsReward(ctx context.Context, req *MsgClaimSavingsReward) (*MsgClaimSavingsRewardResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ClaimSavingsReward not implemented") -} -func (*UnimplementedMsgServer) ClaimEarnReward(ctx context.Context, req *MsgClaimEarnReward) (*MsgClaimEarnRewardResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ClaimEarnReward not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_ClaimUSDXMintingReward_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgClaimUSDXMintingReward) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ClaimUSDXMintingReward(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Msg/ClaimUSDXMintingReward", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ClaimUSDXMintingReward(ctx, req.(*MsgClaimUSDXMintingReward)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ClaimHardReward_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgClaimHardReward) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ClaimHardReward(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Msg/ClaimHardReward", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ClaimHardReward(ctx, req.(*MsgClaimHardReward)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ClaimDelegatorReward_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgClaimDelegatorReward) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ClaimDelegatorReward(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Msg/ClaimDelegatorReward", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ClaimDelegatorReward(ctx, req.(*MsgClaimDelegatorReward)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ClaimSwapReward_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgClaimSwapReward) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ClaimSwapReward(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Msg/ClaimSwapReward", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ClaimSwapReward(ctx, req.(*MsgClaimSwapReward)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ClaimSavingsReward_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgClaimSavingsReward) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ClaimSavingsReward(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Msg/ClaimSavingsReward", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ClaimSavingsReward(ctx, req.(*MsgClaimSavingsReward)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ClaimEarnReward_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgClaimEarnReward) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ClaimEarnReward(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Msg/ClaimEarnReward", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ClaimEarnReward(ctx, req.(*MsgClaimEarnReward)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.incentive.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "ClaimUSDXMintingReward", - Handler: _Msg_ClaimUSDXMintingReward_Handler, - }, - { - MethodName: "ClaimHardReward", - Handler: _Msg_ClaimHardReward_Handler, - }, - { - MethodName: "ClaimDelegatorReward", - Handler: _Msg_ClaimDelegatorReward_Handler, - }, - { - MethodName: "ClaimSwapReward", - Handler: _Msg_ClaimSwapReward_Handler, - }, - { - MethodName: "ClaimSavingsReward", - Handler: _Msg_ClaimSavingsReward_Handler, - }, - { - MethodName: "ClaimEarnReward", - Handler: _Msg_ClaimEarnReward_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/incentive/v1beta1/tx.proto", -} - -func (m *Selection) 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 *Selection) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Selection) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.MultiplierName) > 0 { - i -= len(m.MultiplierName) - copy(dAtA[i:], m.MultiplierName) - i = encodeVarintTx(dAtA, i, uint64(len(m.MultiplierName))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintTx(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClaimUSDXMintingReward) 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 *MsgClaimUSDXMintingReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimUSDXMintingReward) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.MultiplierName) > 0 { - i -= len(m.MultiplierName) - copy(dAtA[i:], m.MultiplierName) - i = encodeVarintTx(dAtA, i, uint64(len(m.MultiplierName))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClaimUSDXMintingRewardResponse) 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 *MsgClaimUSDXMintingRewardResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimUSDXMintingRewardResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgClaimHardReward) 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 *MsgClaimHardReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimHardReward) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.DenomsToClaim) > 0 { - for iNdEx := len(m.DenomsToClaim) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DenomsToClaim[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClaimHardRewardResponse) 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 *MsgClaimHardRewardResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimHardRewardResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgClaimDelegatorReward) 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 *MsgClaimDelegatorReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimDelegatorReward) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.DenomsToClaim) > 0 { - for iNdEx := len(m.DenomsToClaim) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DenomsToClaim[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClaimDelegatorRewardResponse) 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 *MsgClaimDelegatorRewardResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimDelegatorRewardResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgClaimSwapReward) 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 *MsgClaimSwapReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimSwapReward) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.DenomsToClaim) > 0 { - for iNdEx := len(m.DenomsToClaim) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DenomsToClaim[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClaimSwapRewardResponse) 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 *MsgClaimSwapRewardResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimSwapRewardResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgClaimSavingsReward) 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 *MsgClaimSavingsReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimSavingsReward) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.DenomsToClaim) > 0 { - for iNdEx := len(m.DenomsToClaim) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DenomsToClaim[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClaimSavingsRewardResponse) 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 *MsgClaimSavingsRewardResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimSavingsRewardResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgClaimEarnReward) 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 *MsgClaimEarnReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimEarnReward) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.DenomsToClaim) > 0 { - for iNdEx := len(m.DenomsToClaim) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DenomsToClaim[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClaimEarnRewardResponse) 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 *MsgClaimEarnRewardResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimEarnRewardResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Selection) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.MultiplierName) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgClaimUSDXMintingReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.MultiplierName) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgClaimUSDXMintingRewardResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgClaimHardReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.DenomsToClaim) > 0 { - for _, e := range m.DenomsToClaim { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgClaimHardRewardResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgClaimDelegatorReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.DenomsToClaim) > 0 { - for _, e := range m.DenomsToClaim { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgClaimDelegatorRewardResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgClaimSwapReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.DenomsToClaim) > 0 { - for _, e := range m.DenomsToClaim { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgClaimSwapRewardResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgClaimSavingsReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.DenomsToClaim) > 0 { - for _, e := range m.DenomsToClaim { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgClaimSavingsRewardResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgClaimEarnReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.DenomsToClaim) > 0 { - for _, e := range m.DenomsToClaim { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgClaimEarnRewardResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Selection) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Selection: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Selection: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MultiplierName", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MultiplierName = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimUSDXMintingReward) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimUSDXMintingReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimUSDXMintingReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MultiplierName", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MultiplierName = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimUSDXMintingRewardResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimUSDXMintingRewardResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimUSDXMintingRewardResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimHardReward) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimHardReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimHardReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DenomsToClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DenomsToClaim = append(m.DenomsToClaim, Selection{}) - if err := m.DenomsToClaim[len(m.DenomsToClaim)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimHardRewardResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimHardRewardResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimHardRewardResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimDelegatorReward) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimDelegatorReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimDelegatorReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DenomsToClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DenomsToClaim = append(m.DenomsToClaim, Selection{}) - if err := m.DenomsToClaim[len(m.DenomsToClaim)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimDelegatorRewardResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimDelegatorRewardResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimDelegatorRewardResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimSwapReward) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimSwapReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimSwapReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DenomsToClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DenomsToClaim = append(m.DenomsToClaim, Selection{}) - if err := m.DenomsToClaim[len(m.DenomsToClaim)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimSwapRewardResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimSwapRewardResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimSwapRewardResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimSavingsReward) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimSavingsReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimSavingsReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DenomsToClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DenomsToClaim = append(m.DenomsToClaim, Selection{}) - if err := m.DenomsToClaim[len(m.DenomsToClaim)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimSavingsRewardResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimSavingsRewardResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimSavingsRewardResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimEarnReward) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimEarnReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimEarnReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DenomsToClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DenomsToClaim = append(m.DenomsToClaim, Selection{}) - if err := m.DenomsToClaim[len(m.DenomsToClaim)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimEarnRewardResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimEarnRewardResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimEarnRewardResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/issuance/abci.go b/x/issuance/abci.go deleted file mode 100644 index cb6ddca7..00000000 --- a/x/issuance/abci.go +++ /dev/null @@ -1,22 +0,0 @@ -package issuance - -import ( - "time" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/issuance/keeper" - "github.com/kava-labs/kava/x/issuance/types" -) - -// BeginBlocker iterates over each asset and seizes coins from blocked addresses by returning them to the asset owner -func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - - err := k.SeizeCoinsForBlockableAssets(ctx) - if err != nil { - panic(err) - } - k.SynchronizeBlockList(ctx) - k.UpdateTimeBasedSupplyLimits(ctx) -} diff --git a/x/issuance/abci_test.go b/x/issuance/abci_test.go deleted file mode 100644 index 9805b9f4..00000000 --- a/x/issuance/abci_test.go +++ /dev/null @@ -1,114 +0,0 @@ -package issuance_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/issuance" - "github.com/kava-labs/kava/x/issuance/keeper" - "github.com/kava-labs/kava/x/issuance/types" -) - -// Test suite used for all keeper tests -type ABCITestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context - addrs []sdk.AccAddress - modAccount sdk.AccAddress - blockTime time.Time -} - -// The default state used by each test -func (suite *ABCITestSuite) SetupTest() { - tApp := app.NewTestApp() - blockTime := tmtime.Now() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: blockTime}) - tApp.InitializeFromGenesisStates() - _, addrs := app.GeneratePrivKeyAddressPairs(5) - keeper := tApp.GetIssuanceKeeper() - modAccount, err := sdk.AccAddressFromBech32("kava1cj7njkw2g9fqx4e768zc75dp9sks8u9znxrf0w") - suite.Require().NoError(err) - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - suite.addrs = addrs - suite.modAccount = modAccount - suite.blockTime = blockTime -} - -func (suite *ABCITestSuite) TestRateLimitingTimePassage() { - type args struct { - assets []types.Asset - supplies []types.AssetSupply - blockTimes []time.Duration - expectedSupply types.AssetSupply - } - testCases := []struct { - name string - args args - }{ - { - "time passage same period", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0].String(), "usdtoken", []string{suite.addrs[1].String()}, false, true, types.NewRateLimit(true, sdkmath.NewInt(10000000000), time.Hour*24)), - }, - supplies: []types.AssetSupply{ - types.NewAssetSupply(sdk.NewCoin("usdtoken", sdk.ZeroInt()), time.Hour), - }, - blockTimes: []time.Duration{time.Hour}, - expectedSupply: types.NewAssetSupply(sdk.NewCoin("usdtoken", sdk.ZeroInt()), time.Hour*2), - }, - }, - { - "time passage new period", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0].String(), "usdtoken", []string{suite.addrs[1].String()}, false, true, types.NewRateLimit(true, sdkmath.NewInt(10000000000), time.Hour*24)), - }, - supplies: []types.AssetSupply{ - types.NewAssetSupply(sdk.NewCoin("usdtoken", sdk.ZeroInt()), time.Hour), - }, - blockTimes: []time.Duration{time.Hour * 12, time.Hour * 12}, - expectedSupply: types.NewAssetSupply(sdk.NewCoin("usdtoken", sdk.ZeroInt()), time.Duration(0)), - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - params := types.NewParams(tc.args.assets) - suite.keeper.SetParams(suite.ctx, params) - for _, supply := range tc.args.supplies { - suite.keeper.SetAssetSupply(suite.ctx, supply, supply.GetDenom()) - } - suite.keeper.SetPreviousBlockTime(suite.ctx, suite.blockTime) - for _, bt := range tc.args.blockTimes { - nextBlockTime := suite.ctx.BlockTime().Add(bt) - suite.ctx = suite.ctx.WithBlockTime(nextBlockTime) - suite.Require().NotPanics(func() { - issuance.BeginBlocker(suite.ctx, suite.keeper) - }) - } - actualSupply, found := suite.keeper.GetAssetSupply(suite.ctx, tc.args.expectedSupply.GetDenom()) - suite.Require().True(found) - suite.Require().Equal(tc.args.expectedSupply, actualSupply) - }) - } -} - -func TestABCITestSuite(t *testing.T) { - suite.Run(t, new(ABCITestSuite)) -} diff --git a/x/issuance/client/cli/query.go b/x/issuance/client/cli/query.go deleted file mode 100644 index 8035de6e..00000000 --- a/x/issuance/client/cli/query.go +++ /dev/null @@ -1,58 +0,0 @@ -package cli - -import ( - "context" - "fmt" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - - "github.com/kava-labs/kava/x/issuance/types" -) - -// GetQueryCmd returns the cli query commands for the issuance module -func GetQueryCmd() *cobra.Command { - issuanceQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName), - } - - cmds := []*cobra.Command{ - GetCmdQueryParams(), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - issuanceQueryCmd.AddCommand(cmds...) - - return issuanceQueryCmd -} - -// GetCmdQueryParams queries the issuance module parameters -func GetCmdQueryParams() *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: fmt.Sprintf("get the %s module parameters", types.ModuleName), - Long: "Get the current issuance module parameters.", - 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(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } -} diff --git a/x/issuance/client/cli/tx.go b/x/issuance/client/cli/tx.go deleted file mode 100644 index b284b25f..00000000 --- a/x/issuance/client/cli/tx.go +++ /dev/null @@ -1,205 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/kava-labs/kava/x/issuance/types" -) - -// GetTxCmd returns the transaction cli commands for the issuance module -func GetTxCmd() *cobra.Command { - issuanceTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "transaction commands for the issuance module", - } - - cmds := []*cobra.Command{ - GetCmdIssueTokens(), - GetCmdRedeemTokens(), - GetCmdBlockAddress(), - GetCmdUnblockAddress(), - GetCmdPauseAsset(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - issuanceTxCmd.AddCommand(cmds...) - - return issuanceTxCmd -} - -func GetCmdIssueTokens() *cobra.Command { - return &cobra.Command{ - Use: "issue [tokens] [receiver]", - Short: "issue new tokens to the receiver address", - Long: "The asset owner issues new tokens that will be credited to the receiver address", - Example: fmt.Sprintf(`$ %s tx %s issue 20000000usdtoken kava15qdefkmwswysgg4qxgqpqr35k3m49pkx2jdfnw - `, version.AppName, types.ModuleName), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - tokens, err := sdk.ParseCoinNormalized(args[0]) - if err != nil { - return err - } - // We use the string later but here validate the acc address - receiver, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } - - msg := types.NewMsgIssueTokens(cliCtx.GetFromAddress().String(), tokens, receiver.String()) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), msg) - }, - } -} - -func GetCmdRedeemTokens() *cobra.Command { - return &cobra.Command{ - Use: "redeem [tokens]", - Short: "redeem tokens", - Long: "The asset owner redeems (burns) tokens, removing them from the circulating supply", - Example: fmt.Sprintf(`$ %s tx %s redeem 20000000usdtoken - `, version.AppName, types.ModuleName), - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - tokens, err := sdk.ParseCoinNormalized(args[0]) - if err != nil { - return err - } - - msg := types.NewMsgRedeemTokens(cliCtx.GetFromAddress().String(), tokens) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), msg) - }, - } -} - -func GetCmdBlockAddress() *cobra.Command { - return &cobra.Command{ - Use: "block [address] [denom]", - Short: "block an address for the input denom", - Long: "The asset owner blocks an address from holding coins of that denomination. Any tokens of the input denomination held by the address will be sent to the owner address", - Example: fmt.Sprintf(`$ %s tx %s block kava15qdefkmwswysgg4qxgqpqr35k3m49pkx2jdfnw usdtoken - `, version.AppName, types.ModuleName), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - address, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - err = sdk.ValidateDenom(args[1]) - if err != nil { - return err - } - msg := types.NewMsgBlockAddress(cliCtx.GetFromAddress().String(), args[1], address.String()) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), msg) - }, - } -} - -func GetCmdUnblockAddress() *cobra.Command { - return &cobra.Command{ - Use: "unblock [address] [denom]", - Short: "unblock an address for the input denom", - Long: "The asset owner unblocks an address from holding coins of that denomination.", - Example: fmt.Sprintf(`$ %s tx %s unblock kava15qdefkmwswysgg4qxgqpqr35k3m49pkx2jdfnw usdtoken - `, version.AppName, types.ModuleName), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - address, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - err = sdk.ValidateDenom(args[1]) - if err != nil { - return err - } - msg := types.NewMsgUnblockAddress(cliCtx.GetFromAddress().String(), args[1], address.String()) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), msg) - }, - } -} - -func GetCmdPauseAsset() *cobra.Command { - return &cobra.Command{ - Use: "set-pause-status [denom] [status]", - Short: "pause or unpause an asset", - Long: "The asset owner pauses or un-pauses the input asset, halting new issuance and redemption", - Example: fmt.Sprintf(`$ %s tx %s pause usdtoken true - `, version.AppName, types.ModuleName), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - err = sdk.ValidateDenom(args[0]) - if err != nil { - return err - } - var status bool - if args[1] == "true" { - status = true - } else if args[1] == "false" { - status = false - } else { - return fmt.Errorf(fmt.Sprintf("status must be true or false, got %s", args[1])) - } - - msg := types.NewMsgSetPauseStatus(cliCtx.GetFromAddress().String(), args[0], status) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), msg) - }, - } -} diff --git a/x/issuance/genesis.go b/x/issuance/genesis.go deleted file mode 100644 index 5681d8f3..00000000 --- a/x/issuance/genesis.go +++ /dev/null @@ -1,45 +0,0 @@ -package issuance - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/issuance/keeper" - "github.com/kava-labs/kava/x/issuance/types" -) - -// InitGenesis initializes the store state from a genesis state. -func InitGenesis(ctx sdk.Context, k keeper.Keeper, accountKeeper types.AccountKeeper, gs types.GenesisState) { - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - // check if the module account exists - moduleAcc := accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - if moduleAcc == nil { - panic(fmt.Sprintf("%s module account has not been set", types.ModuleAccountName)) - } - - k.SetParams(ctx, gs.Params) - - for _, supply := range gs.Supplies { - k.SetAssetSupply(ctx, supply, supply.GetDenom()) - } - - for _, asset := range gs.Params.Assets { - if asset.RateLimit.Active { - _, found := k.GetAssetSupply(ctx, asset.Denom) - if !found { - k.CreateNewAssetSupply(ctx, asset.Denom) - } - } - } -} - -// ExportGenesis export genesis state for issuance module -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { - params := k.GetParams(ctx) - supplies := k.GetAllAssetSupplies(ctx) - return types.NewGenesisState(params, supplies) -} diff --git a/x/issuance/keeper/gprc_query.go b/x/issuance/keeper/gprc_query.go deleted file mode 100644 index 9df2e533..00000000 --- a/x/issuance/keeper/gprc_query.go +++ /dev/null @@ -1,35 +0,0 @@ -package keeper - -import ( - "context" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/issuance/types" -) - -type queryServer struct { - keeper Keeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -var _ types.QueryServer = queryServer{} - -// Params implements the gRPC service handler for querying x/issuance parameters. -func (s queryServer) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - params := s.keeper.GetParams(sdkCtx) - - return &types.QueryParamsResponse{Params: params}, nil -} diff --git a/x/issuance/keeper/issuance.go b/x/issuance/keeper/issuance.go deleted file mode 100644 index 92c619fe..00000000 --- a/x/issuance/keeper/issuance.go +++ /dev/null @@ -1,253 +0,0 @@ -package keeper - -import ( - "fmt" - "strings" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/kava-labs/kava/x/issuance/types" -) - -// IssueTokens mints new tokens and sends them to the receiver address -func (k Keeper) IssueTokens(ctx sdk.Context, tokens sdk.Coin, owner, receiver sdk.AccAddress) error { - asset, found := k.GetAsset(ctx, tokens.Denom) - if !found { - return errorsmod.Wrapf(types.ErrAssetNotFound, "denom: %s", tokens.Denom) - } - if strings.Compare(owner.String(), asset.Owner) != 0 { - return errorsmod.Wrapf(types.ErrNotAuthorized, "owner: %s, address: %s", asset.Owner, owner) - } - if asset.Paused { - return errorsmod.Wrapf(types.ErrAssetPaused, "denom: %s", tokens.Denom) - } - if asset.Blockable { - blocked, _ := k.checkBlockedAddress(asset, receiver.String()) - if blocked { - return errorsmod.Wrapf(types.ErrAccountBlocked, "address: %s", receiver) - } - } - acc := k.accountKeeper.GetAccount(ctx, receiver) - _, ok := acc.(authtypes.ModuleAccountI) - if ok { - return errorsmod.Wrapf(types.ErrIssueToModuleAccount, "address: %s", receiver) - } - - // for rate-limited assets, check that the issuance isn't over the limit - if asset.RateLimit.Active { - err := k.IncrementCurrentAssetSupply(ctx, tokens) - if err != nil { - return err - } - } - - // mint new tokens - err := k.bankKeeper.MintCoins(ctx, types.ModuleAccountName, sdk.NewCoins(tokens)) - if err != nil { - return err - } - // send to receiver - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, receiver, sdk.NewCoins(tokens)) - if err != nil { - return err - } - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeIssue, - sdk.NewAttribute(types.AttributeKeyIssueAmount, tokens.String()), - ), - ) - return nil -} - -// RedeemTokens sends tokens from the owner address to the module account and burns them -func (k Keeper) RedeemTokens(ctx sdk.Context, tokens sdk.Coin, owner sdk.AccAddress) error { - asset, found := k.GetAsset(ctx, tokens.Denom) - if !found { - return errorsmod.Wrapf(types.ErrAssetNotFound, "denom: %s", tokens.Denom) - } - if strings.Compare(owner.String(), asset.Owner) != 0 { - return errorsmod.Wrapf(types.ErrNotAuthorized, "owner: %s, address: %s", asset.Owner, owner) - } - if asset.Paused { - return errorsmod.Wrapf(types.ErrAssetPaused, "denom: %s", tokens.Denom) - } - coins := sdk.NewCoins(tokens) - err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, owner, types.ModuleAccountName, coins) - if err != nil { - return err - } - err = k.bankKeeper.BurnCoins(ctx, types.ModuleAccountName, coins) - if err != nil { - return err - } - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeRedeem, - sdk.NewAttribute(types.AttributeKeyRedeemAmount, tokens.String()), - ), - ) - return nil -} - -// BlockAddress adds an address to the blocked list -func (k Keeper) BlockAddress(ctx sdk.Context, denom string, owner, blockedAddress sdk.AccAddress) error { - asset, found := k.GetAsset(ctx, denom) - if !found { - return errorsmod.Wrapf(types.ErrAssetNotFound, "denom: %s", denom) - } - if !asset.Blockable { - return errorsmod.Wrap(types.ErrAssetUnblockable, denom) - } - if strings.Compare(owner.String(), asset.Owner) != 0 { - return errorsmod.Wrapf(types.ErrNotAuthorized, "owner: %s, address: %s", asset.Owner, owner) - } - blocked, _ := k.checkBlockedAddress(asset, blockedAddress.String()) - if blocked { - return errorsmod.Wrapf(types.ErrAccountAlreadyBlocked, "address: %s", blockedAddress) - } - account := k.accountKeeper.GetAccount(ctx, blockedAddress) - if account == nil { - return errorsmod.Wrapf(types.ErrAccountNotFound, "address: %s", blockedAddress) - } - asset.BlockedAddresses = append(asset.BlockedAddresses, blockedAddress.String()) - k.SetAsset(ctx, asset) - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeBlock, - sdk.NewAttribute(types.AttributeKeyBlock, blockedAddress.String()), - sdk.NewAttribute(types.AttributeKeyDenom, asset.Denom), - ), - ) - return nil -} - -// UnblockAddress removes an address from the blocked list -func (k Keeper) UnblockAddress(ctx sdk.Context, denom string, owner, addr sdk.AccAddress) error { - asset, found := k.GetAsset(ctx, denom) - if !found { - return errorsmod.Wrapf(types.ErrAssetNotFound, "denom: %s", denom) - } - if !asset.Blockable { - return errorsmod.Wrap(types.ErrAssetUnblockable, denom) - } - if strings.Compare(owner.String(), asset.Owner) != 0 { - return errorsmod.Wrapf(types.ErrNotAuthorized, "owner: %s, address: %s", asset.Owner, owner) - } - blocked, i := k.checkBlockedAddress(asset, addr.String()) - if !blocked { - return errorsmod.Wrapf(types.ErrAccountAlreadyUnblocked, "address: %s", addr) - } - - blockedAddrs := k.removeBlockedAddress(asset.BlockedAddresses, i) - asset.BlockedAddresses = blockedAddrs - k.SetAsset(ctx, asset) - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeUnblock, - sdk.NewAttribute(types.AttributeKeyUnblock, addr.String()), - sdk.NewAttribute(types.AttributeKeyDenom, asset.Denom), - ), - ) - return nil -} - -// SetPauseStatus pauses/un-pauses an asset -func (k Keeper) SetPauseStatus(ctx sdk.Context, owner sdk.AccAddress, denom string, status bool) error { - asset, found := k.GetAsset(ctx, denom) - if !found { - return errorsmod.Wrapf(types.ErrAssetNotFound, "denom: %s", denom) - } - if strings.Compare(owner.String(), asset.Owner) != 0 { - return errorsmod.Wrapf(types.ErrNotAuthorized, "owner: %s, address: %s", asset.Owner, owner) - } - if asset.Paused == status { - return nil - } - asset.Paused = !asset.Paused - k.SetAsset(ctx, asset) - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypePause, - sdk.NewAttribute(types.AttributeKeyPauseStatus, fmt.Sprintf("%t", status)), - sdk.NewAttribute(types.AttributeKeyDenom, asset.Denom), - ), - ) - return nil -} - -// SeizeCoinsForBlockableAssets seizes coins from blocked addresses for assets that have blocking enabled -func (k Keeper) SeizeCoinsForBlockableAssets(ctx sdk.Context) error { - params := k.GetParams(ctx) - for _, asset := range params.Assets { - if asset.Blockable { - err := k.SeizeCoinsFromBlockedAddresses(ctx, asset.Denom) - if err != nil { - return err - } - } - } - return nil -} - -// SeizeCoinsFromBlockedAddresses checks blocked addresses for coins of the input denom and transfers them to the owner account -func (k Keeper) SeizeCoinsFromBlockedAddresses(ctx sdk.Context, denom string) error { - asset, found := k.GetAsset(ctx, denom) - if !found { - return errorsmod.Wrapf(types.ErrAssetNotFound, "denom: %s", denom) - } - for _, address := range asset.BlockedAddresses { - addrBech32, err := sdk.AccAddressFromBech32(address) - if err != nil { - return err - } - - account := k.accountKeeper.GetAccount(ctx, addrBech32) - if account == nil { - // avoids a potential panic - // this could happen if, for example, an account was pruned from state but remained in the block list, - continue - } - - coinsAmount := k.bankKeeper.GetAllBalances(ctx, addrBech32).AmountOf(denom) - if !coinsAmount.IsPositive() { - continue - } - coins := sdk.NewCoins(sdk.NewCoin(denom, coinsAmount)) - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, addrBech32, types.ModuleAccountName, coins) - if err != nil { - return err - } - ownerBech32, err := sdk.AccAddressFromBech32(asset.Owner) - if err != nil { - return err - } - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, ownerBech32, coins) - if err != nil { - return err - } - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeSeize, - sdk.NewAttribute(sdk.AttributeKeyAmount, coins.String()), - sdk.NewAttribute(types.AttributeKeyAddress, address), - ), - ) - } - return nil -} - -func (k Keeper) checkBlockedAddress(asset types.Asset, checkAddress string) (bool, int) { - for i, address := range asset.BlockedAddresses { - if strings.Compare(address, checkAddress) == 0 { - return true, i - } - } - return false, 0 -} - -func (k Keeper) removeBlockedAddress(blockedAddrs []string, i int) []string { - blockedAddrs[len(blockedAddrs)-1], blockedAddrs[i] = blockedAddrs[i], blockedAddrs[len(blockedAddrs)-1] - return blockedAddrs[:len(blockedAddrs)-1] -} diff --git a/x/issuance/keeper/issuance_test.go b/x/issuance/keeper/issuance_test.go deleted file mode 100644 index 03e9c9e8..00000000 --- a/x/issuance/keeper/issuance_test.go +++ /dev/null @@ -1,804 +0,0 @@ -package keeper_test - -import ( - "strings" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - - "github.com/cometbft/cometbft/crypto" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/issuance/keeper" - "github.com/kava-labs/kava/x/issuance/types" -) - -// Test suite used for all keeper tests -type KeeperTestSuite struct { - suite.Suite - - tApp app.TestApp - keeper keeper.Keeper - ctx sdk.Context - addrs []string - modAccount sdk.AccAddress -} - -// The default state used by each test -func (suite *KeeperTestSuite) SetupTest() { - tApp := app.NewTestApp() - - ctx := tApp.NewContext(true, tmprototypes.Header{Height: 1, Time: tmtime.Now()}) - tApp.InitializeFromGenesisStates() - _, addrs := app.GeneratePrivKeyAddressPairs(5) - var strAddrs []string - for _, addr := range addrs { - acc := tApp.GetAccountKeeper().NewAccountWithAddress(ctx, addr) - tApp.GetAccountKeeper().SetAccount(ctx, acc) - strAddrs = append(strAddrs, addr.String()) - } - - keeper := tApp.GetIssuanceKeeper() - modAccount, err := sdk.AccAddressFromBech32("kava1cj7njkw2g9fqx4e768zc75dp9sks8u9znxrf0w") - suite.Require().NoError(err) - - suite.tApp = tApp - suite.ctx = ctx - suite.keeper = keeper - suite.addrs = strAddrs - suite.modAccount = modAccount -} - -func (suite *KeeperTestSuite) getAccount(addr sdk.AccAddress) authtypes.AccountI { - ak := suite.tApp.GetAccountKeeper() - return ak.GetAccount(suite.ctx, addr) -} - -func (suite *KeeperTestSuite) getBalance(addr sdk.AccAddress, denom string) sdk.Coin { - bk := suite.tApp.GetBankKeeper() - return bk.GetBalance(suite.ctx, addr, denom) -} - -func (suite *KeeperTestSuite) getModuleAccount(name string) authtypes.ModuleAccountI { - sk := suite.tApp.GetAccountKeeper() - return sk.GetModuleAccount(suite.ctx, name) -} - -func (suite *KeeperTestSuite) TestGetSetParams() { - params := suite.keeper.GetParams(suite.ctx) - suite.Require().Equal(types.Params{Assets: []types.Asset(nil)}, params) - asset := types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))) - params = types.NewParams([]types.Asset{asset}) - suite.keeper.SetParams(suite.ctx, params) - newParams := suite.keeper.GetParams(suite.ctx) - suite.Require().Equal(params, newParams) -} - -func (suite *KeeperTestSuite) TestIssueTokens() { - type args struct { - assets []types.Asset - sender string - tokens sdk.Coin - receiver string - } - type errArgs struct { - expectPass bool - contains string - } - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - "valid issuance", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - tokens: sdk.NewCoin("usdtoken", sdkmath.NewInt(100000)), - receiver: suite.addrs[2], - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "non-owner issuance", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[2], - tokens: sdk.NewCoin("usdtoken", sdkmath.NewInt(100000)), - receiver: suite.addrs[3], - }, - errArgs{ - expectPass: false, - contains: "account not authorized", - }, - }, - { - "invalid denom", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - tokens: sdk.NewCoin("othertoken", sdkmath.NewInt(100000)), - receiver: suite.addrs[2], - }, - errArgs{ - expectPass: false, - contains: "no asset with input denom found", - }, - }, - { - "issue to blocked address", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - tokens: sdk.NewCoin("usdtoken", sdkmath.NewInt(100000)), - receiver: suite.addrs[1], - }, - errArgs{ - expectPass: false, - contains: "account is blocked", - }, - }, - { - "issue to module account", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - tokens: sdk.NewCoin("usdtoken", sdkmath.NewInt(100000)), - receiver: suite.modAccount.String(), - }, - errArgs{ - expectPass: false, - contains: "cannot issue tokens to module account", - }, - }, - { - "paused issuance", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, true, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - tokens: sdk.NewCoin("usdtoken", sdkmath.NewInt(100000)), - receiver: suite.addrs[1], - }, - errArgs{ - expectPass: false, - contains: "asset is paused", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - params := types.NewParams(tc.args.assets) - suite.keeper.SetParams(suite.ctx, params) - sender, _ := sdk.AccAddressFromBech32(tc.args.sender) - receiver, _ := sdk.AccAddressFromBech32(tc.args.receiver) - err := suite.keeper.IssueTokens(suite.ctx, tc.args.tokens, sender, receiver) - if tc.errArgs.expectPass { - suite.Require().NoError(err, tc.name) - suite.Require().Equal(sdk.NewCoins(tc.args.tokens), sdk.NewCoins(suite.getBalance(receiver, tc.args.tokens.Denom))) - } else { - suite.Require().Error(err, tc.name) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *KeeperTestSuite) TestIssueTokensRateLimited() { - type args struct { - assets []types.Asset - supplies []types.AssetSupply - sender string - tokens sdk.Coin - receiver string - blockTime time.Time - } - type errArgs struct { - expectPass bool - contains string - } - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - "valid issuance", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(true, sdkmath.NewInt(10000000000), time.Hour*24)), - }, - supplies: []types.AssetSupply{ - types.NewAssetSupply(sdk.NewCoin("usdtoken", sdk.ZeroInt()), time.Hour), - }, - sender: suite.addrs[0], - tokens: sdk.NewCoin("usdtoken", sdkmath.NewInt(100000)), - receiver: suite.addrs[2], - blockTime: suite.ctx.BlockTime().Add(time.Hour), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "over-limit issuance", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(true, sdkmath.NewInt(10000000000), time.Hour*24)), - }, - supplies: []types.AssetSupply{ - types.NewAssetSupply(sdk.NewCoin("usdtoken", sdk.ZeroInt()), time.Hour), - }, - sender: suite.addrs[0], - tokens: sdk.NewCoin("usdtoken", sdkmath.NewInt(10000000001)), - receiver: suite.addrs[2], - blockTime: suite.ctx.BlockTime().Add(time.Hour), - }, - errArgs{ - expectPass: false, - contains: "asset supply over limit", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - params := types.NewParams(tc.args.assets) - suite.keeper.SetParams(suite.ctx, params) - for _, supply := range tc.args.supplies { - suite.keeper.SetAssetSupply(suite.ctx, supply, supply.GetDenom()) - } - suite.ctx = suite.ctx.WithBlockTime(tc.args.blockTime) - sender, _ := sdk.AccAddressFromBech32(tc.args.sender) - receiver, _ := sdk.AccAddressFromBech32(tc.args.receiver) - err := suite.keeper.IssueTokens(suite.ctx, tc.args.tokens, sender, receiver) - if tc.errArgs.expectPass { - suite.Require().NoError(err, tc.name) - suite.Require().Equal(sdk.NewCoins(tc.args.tokens), sdk.NewCoins(suite.getBalance(receiver, tc.args.tokens.Denom))) - } else { - suite.Require().Error(err, tc.name) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *KeeperTestSuite) TestRedeemTokens() { - type args struct { - assets []types.Asset - sender string - initialTokens sdk.Coin - redeemTokens sdk.Coin - } - type errArgs struct { - expectPass bool - contains string - } - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - "valid redemption", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - initialTokens: sdk.NewCoin("usdtoken", sdkmath.NewInt(100000)), - redeemTokens: sdk.NewCoin("usdtoken", sdkmath.NewInt(100000)), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid denom redemption", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - initialTokens: sdk.NewCoin("usdtoken", sdkmath.NewInt(100000)), - redeemTokens: sdk.NewCoin("othertoken", sdkmath.NewInt(100000)), - }, - errArgs{ - expectPass: false, - contains: "", - }, - }, - { - "non-owner redemption", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[2], - initialTokens: sdk.NewCoin("usdtoken", sdkmath.NewInt(100000)), - redeemTokens: sdk.NewCoin("usdtoken", sdkmath.NewInt(100000)), - }, - errArgs{ - expectPass: false, - contains: "account not authorized", - }, - }, - { - "paused redemption", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, true, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - initialTokens: sdk.NewCoin("usdtoken", sdkmath.NewInt(100000)), - redeemTokens: sdk.NewCoin("usdtoken", sdkmath.NewInt(100000)), - }, - errArgs{ - expectPass: false, - contains: "asset is paused", - }, - }, - { - "redeem amount greater than balance", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - initialTokens: sdk.NewCoin("usdtoken", sdkmath.NewInt(100000)), - redeemTokens: sdk.NewCoin("usdtoken", sdkmath.NewInt(200000)), - }, - errArgs{ - expectPass: false, - contains: "insufficient funds", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - params := types.NewParams(tc.args.assets) - suite.keeper.SetParams(suite.ctx, params) - sk := suite.tApp.GetBankKeeper() - err := sk.MintCoins(suite.ctx, types.ModuleAccountName, sdk.NewCoins(tc.args.initialTokens)) - suite.Require().NoError(err) - sender, _ := sdk.AccAddressFromBech32(tc.args.sender) - err = sk.SendCoinsFromModuleToAccount(suite.ctx, types.ModuleAccountName, sender, sdk.NewCoins(tc.args.initialTokens)) - suite.Require().NoError(err) - - err = suite.keeper.RedeemTokens(suite.ctx, tc.args.redeemTokens, sender) - - if tc.errArgs.expectPass { - suite.Require().NoError(err) - initialSupply := sdk.NewCoins(tc.args.redeemTokens) - moduleAccount := suite.getModuleAccount(types.ModuleAccountName) - suite.Require().Equal(sdk.NewCoins(initialSupply.Sub(tc.args.redeemTokens)...), sdk.NewCoins(suite.getBalance(moduleAccount.GetAddress(), tc.args.redeemTokens.Denom))) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *KeeperTestSuite) TestBlockAddress() { - type args struct { - assets []types.Asset - sender string - blockedAddr string - denom string - } - type errArgs struct { - expectPass bool - contains string - } - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - "valid block", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - blockedAddr: suite.addrs[1], - denom: "usdtoken", - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "unblockable token", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{}, false, false, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - blockedAddr: suite.addrs[1], - denom: "usdtoken", - }, - errArgs{ - expectPass: false, - contains: "asset does not support block/unblock functionality", - }, - }, - { - "non-owner block", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[2], - blockedAddr: suite.addrs[1], - denom: "usdtoken", - }, - errArgs{ - expectPass: false, - contains: "account not authorized", - }, - }, - { - "invalid denom block", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - blockedAddr: suite.addrs[1], - denom: "othertoken", - }, - errArgs{ - expectPass: false, - contains: "no asset with input denom found", - }, - }, - { - "block non-existing account", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - blockedAddr: sdk.AccAddress(crypto.AddressHash([]byte("RandomAddr"))).String(), - denom: "usdtoken", - }, - errArgs{ - expectPass: false, - contains: "cannot block account that does not exist in state", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - params := types.NewParams(tc.args.assets) - suite.keeper.SetParams(suite.ctx, params) - sender, _ := sdk.AccAddressFromBech32(tc.args.sender) - blockedAddr, _ := sdk.AccAddressFromBech32(tc.args.blockedAddr) - err := suite.keeper.BlockAddress(suite.ctx, tc.args.denom, sender, blockedAddr) - if tc.errArgs.expectPass { - suite.Require().NoError(err, tc.name) - asset, found := suite.keeper.GetAsset(suite.ctx, tc.args.denom) - blocked := false - suite.Require().True(found) - for _, blockedAddr := range asset.BlockedAddresses { - if blockedAddr == tc.args.blockedAddr { - blocked = true - } - } - suite.Require().True(blocked) - } else { - suite.Require().Error(err, tc.name) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *KeeperTestSuite) TestUnblockAddress() { - type args struct { - assets []types.Asset - sender string - blockedAddr string - denom string - } - type errArgs struct { - expectPass bool - contains string - } - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - "valid unblock", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - blockedAddr: suite.addrs[1], - denom: "usdtoken", - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "non-owner unblock", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[2], - blockedAddr: suite.addrs[1], - denom: "usdtoken", - }, - errArgs{ - expectPass: false, - contains: "account not authorized", - }, - }, - { - "invalid denom block", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - blockedAddr: suite.addrs[1], - denom: "othertoken", - }, - errArgs{ - expectPass: false, - contains: "no asset with input denom found", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - params := types.NewParams(tc.args.assets) - suite.keeper.SetParams(suite.ctx, params) - sender, _ := sdk.AccAddressFromBech32(tc.args.sender) - blockedAddr, _ := sdk.AccAddressFromBech32(tc.args.blockedAddr) - err := suite.keeper.UnblockAddress(suite.ctx, tc.args.denom, sender, blockedAddr) - if tc.errArgs.expectPass { - suite.Require().NoError(err, tc.name) - asset, found := suite.keeper.GetAsset(suite.ctx, tc.args.denom) - blocked := false - suite.Require().True(found) - for _, blockedAddr := range asset.BlockedAddresses { - if blockedAddr == tc.args.blockedAddr { - blocked = true - } - } - suite.Require().False(blocked) - } else { - suite.Require().Error(err, tc.name) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *KeeperTestSuite) TestChangePauseStatus() { - type args struct { - assets []types.Asset - sender string - startStatus bool - endStatus bool - denom string - } - type errArgs struct { - expectPass bool - contains string - } - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - "valid pause", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - startStatus: false, - endStatus: true, - denom: "usdtoken", - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid unpause", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{}, true, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - startStatus: true, - endStatus: false, - denom: "usdtoken", - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "non-owner pause", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[2], - startStatus: false, - endStatus: true, - denom: "usdtoken", - }, - errArgs{ - expectPass: false, - contains: "account not authorized", - }, - }, - { - "invalid denom pause", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - sender: suite.addrs[0], - startStatus: true, - endStatus: false, - denom: "othertoken", - }, - errArgs{ - expectPass: false, - contains: "no asset with input denom found", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - params := types.NewParams(tc.args.assets) - suite.keeper.SetParams(suite.ctx, params) - - sender, _ := sdk.AccAddressFromBech32(tc.args.sender) - err := suite.keeper.SetPauseStatus(suite.ctx, sender, tc.args.denom, tc.args.endStatus) - if tc.errArgs.expectPass { - suite.Require().NoError(err, tc.name) - asset, found := suite.keeper.GetAsset(suite.ctx, tc.args.denom) - suite.Require().True(found) - suite.Require().Equal(tc.args.endStatus, asset.Paused) - } else { - suite.Require().Error(err, tc.name) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *KeeperTestSuite) TestSeizeCoinsFromBlockedAddress() { - type args struct { - assets []types.Asset - initialCoins sdk.Coin - blockedAddrs []string - denom string - } - type errArgs struct { - expectPass bool - contains string - } - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - "valid seize", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - initialCoins: sdk.NewCoin("usdtoken", sdkmath.NewInt(100000000)), - denom: "usdtoken", - blockedAddrs: []string{suite.addrs[1], suite.addrs[2]}, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid denom seize", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - initialCoins: sdk.NewCoin("usdtoken", sdkmath.NewInt(100000000)), - denom: "othertoken", - blockedAddrs: []string{suite.addrs[1], suite.addrs[2]}, - }, - errArgs{ - expectPass: false, - contains: "no asset with input denom found", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - assetsWithBlockedAddrs := []types.Asset{} - for _, asset := range tc.args.assets { - asset.BlockedAddresses = tc.args.blockedAddrs - assetsWithBlockedAddrs = append(assetsWithBlockedAddrs, asset) - } - params := types.NewParams(assetsWithBlockedAddrs) - suite.keeper.SetParams(suite.ctx, params) - sk := suite.tApp.GetBankKeeper() - for _, addrStr := range tc.args.blockedAddrs { - addr, _ := sdk.AccAddressFromBech32(addrStr) - err := sk.MintCoins(suite.ctx, types.ModuleAccountName, sdk.NewCoins(tc.args.initialCoins)) - suite.Require().NoError(err) - err = sk.SendCoinsFromModuleToAccount(suite.ctx, types.ModuleAccountName, addr, sdk.NewCoins(tc.args.initialCoins)) - } - - err := suite.keeper.SeizeCoinsFromBlockedAddresses(suite.ctx, tc.args.denom) - if tc.errArgs.expectPass { - suite.Require().NoError(err, tc.name) - asset, found := suite.keeper.GetAsset(suite.ctx, tc.args.denom) - suite.Require().True(found) - owner, _ := sdk.AccAddressFromBech32(asset.Owner) - ownerCoinAmount := tc.args.initialCoins.Amount.Mul(sdkmath.NewInt(int64(len(tc.args.blockedAddrs)))) - suite.Require().Equal(sdk.NewCoins(sdk.NewCoin(tc.args.denom, ownerCoinAmount)), sdk.NewCoins(suite.getBalance(owner, tc.args.initialCoins.Denom))) - } else { - suite.Require().Error(err, tc.name) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} diff --git a/x/issuance/keeper/keeper.go b/x/issuance/keeper/keeper.go deleted file mode 100644 index c4680db9..00000000 --- a/x/issuance/keeper/keeper.go +++ /dev/null @@ -1,101 +0,0 @@ -package keeper - -import ( - "time" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store/prefix" - 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/kava-labs/kava/x/issuance/types" -) - -// Keeper keeper for the issuance module -type Keeper struct { - key storetypes.StoreKey - cdc codec.Codec - paramSubspace paramtypes.Subspace - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper -} - -// NewKeeper returns a new keeper -func NewKeeper(cdc codec.Codec, key storetypes.StoreKey, paramstore paramtypes.Subspace, ak types.AccountKeeper, bk types.BankKeeper) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - key: key, - cdc: cdc, - paramSubspace: paramstore, - accountKeeper: ak, - bankKeeper: bk, - } -} - -// GetAssetSupply gets an asset's current supply from the store. -func (k Keeper) GetAssetSupply(ctx sdk.Context, denom string) (types.AssetSupply, bool) { - var assetSupply types.AssetSupply - store := prefix.NewStore(ctx.KVStore(k.key), types.AssetSupplyPrefix) - bz := store.Get([]byte(denom)) - if bz == nil { - return types.AssetSupply{}, false - } - k.cdc.MustUnmarshal(bz, &assetSupply) - return assetSupply, true -} - -// SetAssetSupply updates an asset's supply -func (k Keeper) SetAssetSupply(ctx sdk.Context, supply types.AssetSupply, denom string) { - store := prefix.NewStore(ctx.KVStore(k.key), types.AssetSupplyPrefix) - store.Set([]byte(denom), k.cdc.MustMarshal(&supply)) -} - -// IterateAssetSupplies provides an iterator over all stored AssetSupplies. -func (k Keeper) IterateAssetSupplies(ctx sdk.Context, cb func(supply types.AssetSupply) (stop bool)) { - iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.key), types.AssetSupplyPrefix) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var supply types.AssetSupply - k.cdc.MustUnmarshal(iterator.Value(), &supply) - if cb(supply) { - break - } - } -} - -// GetAllAssetSupplies returns all asset supplies from the store -func (k Keeper) GetAllAssetSupplies(ctx sdk.Context) (supplies []types.AssetSupply) { - k.IterateAssetSupplies(ctx, func(supply types.AssetSupply) bool { - supplies = append(supplies, supply) - return false - }) - return -} - -// GetPreviousBlockTime get the blocktime for the previous block -func (k Keeper) GetPreviousBlockTime(ctx sdk.Context) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousBlockTimeKey) - b := store.Get(types.PreviousBlockTimeKey) - if b == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(b); err != nil { - panic(err) - } - return blockTime, true -} - -// SetPreviousBlockTime set the time of the previous block -func (k Keeper) SetPreviousBlockTime(ctx sdk.Context, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousBlockTimeKey) - b, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set(types.PreviousBlockTimeKey, b) -} diff --git a/x/issuance/keeper/msg_server.go b/x/issuance/keeper/msg_server.go deleted file mode 100644 index ebe536b5..00000000 --- a/x/issuance/keeper/msg_server.go +++ /dev/null @@ -1,146 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/issuance/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the issuance MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -func (k msgServer) IssueTokens(goCtx context.Context, msg *types.MsgIssueTokens) (*types.MsgIssueTokensResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - receiver, err := sdk.AccAddressFromBech32(msg.Receiver) - if err != nil { - return nil, err - } - - err = k.keeper.IssueTokens(ctx, msg.Tokens, sender, receiver) - if err != nil { - return nil, err - } - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - ), - ) - return &types.MsgIssueTokensResponse{}, nil -} - -func (k msgServer) RedeemTokens(goCtx context.Context, msg *types.MsgRedeemTokens) (*types.MsgRedeemTokensResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - err = k.keeper.RedeemTokens(ctx, msg.Tokens, sender) - if err != nil { - return nil, err - } - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - ), - ) - return &types.MsgRedeemTokensResponse{}, nil -} - -func (k msgServer) BlockAddress(goCtx context.Context, msg *types.MsgBlockAddress) (*types.MsgBlockAddressResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - blockedAddress, err := sdk.AccAddressFromBech32(msg.BlockedAddress) - if err != nil { - return nil, err - } - - err = k.keeper.BlockAddress(ctx, msg.Denom, sender, blockedAddress) - if err != nil { - return nil, err - } - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - ), - ) - return &types.MsgBlockAddressResponse{}, nil -} - -func (k msgServer) UnblockAddress(goCtx context.Context, msg *types.MsgUnblockAddress) (*types.MsgUnblockAddressResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - blockedAddress, err := sdk.AccAddressFromBech32(msg.BlockedAddress) - if err != nil { - return nil, err - } - - err = k.keeper.UnblockAddress(ctx, msg.Denom, sender, blockedAddress) - if err != nil { - return nil, err - } - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - ), - ) - return &types.MsgUnblockAddressResponse{}, nil -} - -func (k msgServer) SetPauseStatus(goCtx context.Context, msg *types.MsgSetPauseStatus) (*types.MsgSetPauseStatusResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - err = k.keeper.SetPauseStatus(ctx, sender, msg.Denom, msg.Status) - if err != nil { - return nil, err - } - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - ), - ) - return &types.MsgSetPauseStatusResponse{}, nil -} diff --git a/x/issuance/keeper/params.go b/x/issuance/keeper/params.go deleted file mode 100644 index 49e027c5..00000000 --- a/x/issuance/keeper/params.go +++ /dev/null @@ -1,62 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/issuance/types" -) - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - var p types.Params - k.paramSubspace.GetParamSet(ctx, &p) - return p -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} - -// GetAsset returns an asset from the params and a boolean for if it was found -func (k Keeper) GetAsset(ctx sdk.Context, denom string) (types.Asset, bool) { - params := k.GetParams(ctx) - for _, asset := range params.Assets { - if asset.Denom == denom { - return asset, true - } - } - return types.Asset{}, false -} - -// SetAsset sets an asset in the params -func (k Keeper) SetAsset(ctx sdk.Context, asset types.Asset) { - params := k.GetParams(ctx) - for i := range params.Assets { - if params.Assets[i].Denom == asset.Denom { - params.Assets[i] = asset - } - } - k.SetParams(ctx, params) -} - -// GetRateLimit returns the rete-limit parameters for the input denom -func (k Keeper) GetRateLimit(ctx sdk.Context, denom string) (types.RateLimit, error) { - asset, found := k.GetAsset(ctx, denom) - if !found { - errorsmod.Wrap(types.ErrAssetNotFound, denom) - } - return asset.RateLimit, nil -} - -// SynchronizeBlockList resets the block list to empty for any asset that is not blockable - could happen if this value is changed via governance -func (k Keeper) SynchronizeBlockList(ctx sdk.Context) { - params := k.GetParams(ctx) - for _, asset := range params.Assets { - if !asset.Blockable && len(asset.BlockedAddresses) > 0 { - asset.BlockedAddresses = []string{} - k.SetAsset(ctx, asset) - } - } -} diff --git a/x/issuance/keeper/supply.go b/x/issuance/keeper/supply.go deleted file mode 100644 index 0b624063..00000000 --- a/x/issuance/keeper/supply.go +++ /dev/null @@ -1,78 +0,0 @@ -package keeper - -import ( - "time" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/issuance/types" -) - -// CreateNewAssetSupply creates a new AssetSupply in the store for the input denom -func (k Keeper) CreateNewAssetSupply(ctx sdk.Context, denom string) types.AssetSupply { - supply := types.NewAssetSupply( - sdk.NewCoin(denom, sdk.ZeroInt()), time.Duration(0)) - k.SetAssetSupply(ctx, supply, denom) - return supply -} - -// IncrementCurrentAssetSupply increments an asset's supply by the coin -func (k Keeper) IncrementCurrentAssetSupply(ctx sdk.Context, coin sdk.Coin) error { - supply, found := k.GetAssetSupply(ctx, coin.Denom) - if !found { - return errorsmod.Wrap(types.ErrAssetNotFound, coin.Denom) - } - - limit, err := k.GetRateLimit(ctx, coin.Denom) - if err != nil { - return err - } - - if limit.Active { - supplyLimit := sdk.NewCoin(coin.Denom, limit.Limit) - // Resulting current supply must be under asset's limit - if supplyLimit.IsLT(supply.CurrentSupply.Add(coin)) { - return errorsmod.Wrapf(types.ErrExceedsSupplyLimit, "increase %s, asset supply %s, limit %s", coin, supply.CurrentSupply, supplyLimit) - } - supply.CurrentSupply = supply.CurrentSupply.Add(coin) - k.SetAssetSupply(ctx, supply, coin.Denom) - } - return nil -} - -// UpdateTimeBasedSupplyLimits updates the time based supply for each asset, resetting it if the current time window has elapsed. -func (k Keeper) UpdateTimeBasedSupplyLimits(ctx sdk.Context) { - params := k.GetParams(ctx) - previousBlockTime, found := k.GetPreviousBlockTime(ctx) - if !found { - previousBlockTime = ctx.BlockTime() - k.SetPreviousBlockTime(ctx, previousBlockTime) - } - timeElapsed := ctx.BlockTime().Sub(previousBlockTime) - for _, asset := range params.Assets { - supply, found := k.GetAssetSupply(ctx, asset.Denom) - // if a new asset has been added by governance, create a new asset supply for it in the store - if !found { - supply = k.CreateNewAssetSupply(ctx, asset.Denom) - } - if !asset.RateLimit.Active { - // rate limiting is not active, reset supply - supply.CurrentSupply = sdk.NewCoin(asset.Denom, sdk.ZeroInt()) - supply.TimeElapsed = time.Duration(0) - k.SetAssetSupply(ctx, supply, asset.Denom) - continue - } - if asset.RateLimit.TimePeriod > supply.TimeElapsed+timeElapsed { - // rate limiting is active, the rate-limiting period has not expired - supply.TimeElapsed = supply.TimeElapsed + timeElapsed - k.SetAssetSupply(ctx, supply, asset.Denom) - continue - } - // rate limiting is active, the rate-limiting period has expired, and is now reset - supply.TimeElapsed = time.Duration(0) - supply.CurrentSupply = sdk.NewCoin(asset.Denom, sdk.ZeroInt()) - k.SetAssetSupply(ctx, supply, asset.Denom) - } - k.SetPreviousBlockTime(ctx, ctx.BlockTime()) -} diff --git a/x/issuance/keeper/supply_test.go b/x/issuance/keeper/supply_test.go deleted file mode 100644 index fb7a1e28..00000000 --- a/x/issuance/keeper/supply_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package keeper_test - -import ( - "strings" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/issuance/types" -) - -func (suite *KeeperTestSuite) TestIncrementCurrentAssetSupply() { - type args struct { - assets []types.Asset - supplies []types.AssetSupply - coin sdk.Coin - } - type errArgs struct { - expectPass bool - contains string - } - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - "valid supply increase", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(true, sdkmath.NewInt(10000000000), time.Hour*24)), - }, - supplies: []types.AssetSupply{ - types.NewAssetSupply(sdk.NewCoin("usdtoken", sdk.ZeroInt()), time.Hour), - }, - coin: sdk.NewCoin("usdtoken", sdkmath.NewInt(100000)), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "over limit increase", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(true, sdkmath.NewInt(10000000000), time.Hour*24)), - }, - supplies: []types.AssetSupply{ - types.NewAssetSupply(sdk.NewCoin("usdtoken", sdk.ZeroInt()), time.Hour), - }, - coin: sdk.NewCoin("usdtoken", sdkmath.NewInt(10000000001)), - }, - errArgs{ - expectPass: false, - contains: "asset supply over limit", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - params := types.NewParams(tc.args.assets) - suite.keeper.SetParams(suite.ctx, params) - for _, supply := range tc.args.supplies { - suite.keeper.SetAssetSupply(suite.ctx, supply, supply.GetDenom()) - } - err := suite.keeper.IncrementCurrentAssetSupply(suite.ctx, tc.args.coin) - if tc.errArgs.expectPass { - suite.Require().NoError(err, tc.name) - for _, expectedSupply := range tc.args.supplies { - expectedSupply.CurrentSupply = expectedSupply.CurrentSupply.Add(tc.args.coin) - actualSupply, found := suite.keeper.GetAssetSupply(suite.ctx, expectedSupply.GetDenom()) - suite.Require().True(found) - suite.Require().Equal(expectedSupply, actualSupply, tc.name) - } - } else { - suite.Require().Error(err, tc.name) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} diff --git a/x/issuance/legacy/v0_15/types.go b/x/issuance/legacy/v0_15/types.go deleted file mode 100644 index f76a60c2..00000000 --- a/x/issuance/legacy/v0_15/types.go +++ /dev/null @@ -1,53 +0,0 @@ -package v0_15 - -import ( - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName The name that will be used throughout the module - ModuleName = "issuance" -) - -// GenesisState is the state that must be provided at genesis for the issuance module -type GenesisState struct { - Params Params `json:"params" yaml:"params"` - Supplies AssetSupplies `json:"supplies" yaml:"supplies"` -} - -// Params governance parameters for the issuance module -type Params struct { - Assets Assets `json:"assets" yaml:"assets"` -} - -// Assets slice of Asset -type Assets []Asset - -// Asset type for assets in the issuance module -type Asset struct { - Owner sdk.AccAddress `json:"owner" yaml:"owner"` - Denom string `json:"denom" yaml:"denom"` - BlockedAddresses []sdk.AccAddress `json:"blocked_addresses" yaml:"blocked_addresses"` - Paused bool `json:"paused" yaml:"paused"` - Blockable bool `json:"blockable" yaml:"blockable"` - RateLimit RateLimit `json:"rate_limit" yaml:"rate_limit"` -} - -// RateLimit parameters for rate-limiting the supply of an issued asset -type RateLimit struct { - Active bool `json:"active" yaml:"active"` - Limit sdkmath.Int `json:"limit" yaml:"limit"` - TimePeriod time.Duration `json:"time_period" yaml:"time_period"` -} - -// AssetSupplies is a slice of AssetSupply -type AssetSupplies []AssetSupply - -// AssetSupply contains information about an asset's rate-limited supply (the total supply of the asset is tracked in the top-level supply module) -type AssetSupply struct { - CurrentSupply sdk.Coin `json:"current_supply" yaml:"current_supply"` - TimeElapsed time.Duration `json:"time_elapsed" yaml:"time_elapsed"` -} diff --git a/x/issuance/legacy/v0_16/migrate.go b/x/issuance/legacy/v0_16/migrate.go deleted file mode 100644 index 0623407b..00000000 --- a/x/issuance/legacy/v0_16/migrate.go +++ /dev/null @@ -1,48 +0,0 @@ -package v0_16 - -import ( - v015issuance "github.com/kava-labs/kava/x/issuance/legacy/v0_15" - v016issuance "github.com/kava-labs/kava/x/issuance/types" -) - -func migrateParams(params v015issuance.Params) v016issuance.Params { - assets := make([]v016issuance.Asset, len(params.Assets)) - for i, asset := range params.Assets { - blockedAddresses := make([]string, len(asset.BlockedAddresses)) - for i, addr := range asset.BlockedAddresses { - blockedAddresses[i] = addr.String() - } - assets[i] = v016issuance.Asset{ - Owner: asset.Owner.String(), - Denom: asset.Denom, - BlockedAddresses: blockedAddresses, - Paused: asset.Paused, - Blockable: asset.Blockable, - RateLimit: v016issuance.RateLimit{ - Active: asset.RateLimit.Active, - Limit: asset.RateLimit.Limit, - TimePeriod: asset.RateLimit.TimePeriod, - }, - } - } - return v016issuance.Params{Assets: assets} -} - -func migrateSupplies(oldSupplies v015issuance.AssetSupplies) []v016issuance.AssetSupply { - supplies := make([]v016issuance.AssetSupply, len(oldSupplies)) - for i, supply := range oldSupplies { - supplies[i] = v016issuance.AssetSupply{ - CurrentSupply: supply.CurrentSupply, - TimeElapsed: supply.TimeElapsed, - } - } - return supplies -} - -// Migrate converts v0.15 issuance state and returns it in v0.16 format -func Migrate(oldState v015issuance.GenesisState) *v016issuance.GenesisState { - return &v016issuance.GenesisState{ - Params: migrateParams(oldState.Params), - Supplies: migrateSupplies(oldState.Supplies), - } -} diff --git a/x/issuance/legacy/v0_16/migrate_test.go b/x/issuance/legacy/v0_16/migrate_test.go deleted file mode 100644 index d5f49c86..00000000 --- a/x/issuance/legacy/v0_16/migrate_test.go +++ /dev/null @@ -1,176 +0,0 @@ -package v0_16 - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - app "github.com/kava-labs/kava/app" - v015issuance "github.com/kava-labs/kava/x/issuance/legacy/v0_15" - v016issuance "github.com/kava-labs/kava/x/issuance/types" -) - -type migrateTestSuite struct { - suite.Suite - - addresses []sdk.AccAddress - v15genstate v015issuance.GenesisState - cdc codec.Codec - legacyCdc *codec.LegacyAmino -} - -func (s *migrateTestSuite) SetupTest() { - app.SetSDKConfig() - - s.v15genstate = v015issuance.GenesisState{ - Params: v015issuance.Params{}, - Supplies: v015issuance.AssetSupplies{}, - } - - config := app.MakeEncodingConfig() - s.cdc = config.Marshaler - - legacyCodec := codec.NewLegacyAmino() - s.legacyCdc = legacyCodec - - _, accAddresses := app.GeneratePrivKeyAddressPairs(10) - s.addresses = accAddresses -} - -func (s *migrateTestSuite) TestMigrate_JSON() { - // Migrate v15 issuance to v16 - data := `{ - "params": { - "assets": [ - { - "blockable": true, - "blocked_addresses": null, - "denom": "hbtc", - "owner": "kava1dmm9zpdnm6mfhywzt9sstm4p33y0cnsd0m673z", - "paused": false, - "rate_limit": { - "active": false, - "limit": "0", - "time_period": "0" - } - } - ] - }, - "supplies": [ - { - "current_supply": { "denom": "ukava", "amount": "100" }, - "time_elapsed": "3600000000000" - }, - { - "current_supply": { "denom": "bnb", "amount": "300" }, - "time_elapsed": "300000000000" - } - ] - }` - err := s.legacyCdc.UnmarshalJSON([]byte(data), &s.v15genstate) - s.Require().NoError(err) - genstate := Migrate(s.v15genstate) - - // Compare expect v16 issuance json with migrated json - expected := `{ - "params": { - "assets": [ - { - "blockable": true, - "blocked_addresses": [], - "denom": "hbtc", - "owner": "kava1dmm9zpdnm6mfhywzt9sstm4p33y0cnsd0m673z", - "paused": false, - "rate_limit": { - "active": false, - "limit": "0", - "time_period": "0s" - } - } - ] - }, - "supplies": [ - { - "current_supply": { "denom": "ukava", "amount": "100" }, - "time_elapsed": "3600s" - }, - { - "current_supply": { "denom": "bnb", "amount": "300" }, - "time_elapsed": "300s" - } - ] - }` - actual := s.cdc.MustMarshalJSON(genstate) - s.Require().NoError(err) - s.Require().JSONEq(expected, string(actual)) -} - -func (s *migrateTestSuite) TestMigrate_Params() { - s.v15genstate.Params = v015issuance.Params{ - Assets: v015issuance.Assets{ - { - Owner: s.addresses[0], - Denom: "ukava", - BlockedAddresses: s.addresses[1:2], - Paused: true, - Blockable: true, - RateLimit: v015issuance.RateLimit{ - Active: true, - Limit: sdkmath.NewInt(10), - TimePeriod: 1 * time.Hour, - }, - }, - }, - } - expectedParams := v016issuance.Params{ - Assets: []v016issuance.Asset{ - { - Owner: s.addresses[0].String(), - Denom: "ukava", - BlockedAddresses: []string{s.addresses[1].String()}, - Paused: true, - Blockable: true, - RateLimit: v016issuance.RateLimit{ - Active: true, - Limit: sdkmath.NewInt(10), - TimePeriod: 1 * time.Hour, - }, - }, - }, - } - genState := Migrate(s.v15genstate) - s.Require().Equal(expectedParams, genState.Params) -} - -func (s *migrateTestSuite) TestMigrate_Supplies() { - s.v15genstate.Supplies = v015issuance.AssetSupplies{ - { - CurrentSupply: sdk.NewCoin("ukava", sdkmath.NewInt(100)), - TimeElapsed: time.Duration(1 * time.Hour), - }, - { - CurrentSupply: sdk.NewCoin("bnb", sdkmath.NewInt(300)), - TimeElapsed: time.Duration(5 * time.Minute), - }, - } - expected := []v016issuance.AssetSupply{ - { - CurrentSupply: sdk.NewCoin("ukava", sdkmath.NewInt(100)), - TimeElapsed: time.Duration(1 * time.Hour), - }, - { - CurrentSupply: sdk.NewCoin("bnb", sdkmath.NewInt(300)), - TimeElapsed: time.Duration(5 * time.Minute), - }, - } - genState := Migrate(s.v15genstate) - s.Require().Equal(expected, genState.Supplies) -} - -func TestIssuanceMigrateTestSuite(t *testing.T) { - suite.Run(t, new(migrateTestSuite)) -} diff --git a/x/issuance/module.go b/x/issuance/module.go deleted file mode 100644 index a5b5f4ae..00000000 --- a/x/issuance/module.go +++ /dev/null @@ -1,138 +0,0 @@ -package issuance - -import ( - "context" - "encoding/json" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/kava-labs/kava/x/issuance/client/cli" - "github.com/kava-labs/kava/x/issuance/keeper" - "github.com/kava-labs/kava/x/issuance/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - gs := types.DefaultGenesisState() - return cdc.MustMarshalJSON(&gs) -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) - if err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the gov module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) -} - -// GetTxCmd returns the root tx command for the swap module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the swap module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper types.AccountKeeper, bankKeeper types.BankKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - } -} - -// Name module name -func (AppModule) Name() string { - return types.ModuleName -} - -// RegisterInvariants register module invariants -func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) -} - -// InitGenesis module init-genesis -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { - var genState types.GenesisState - cdc.MustUnmarshalJSON(gs, &genState) - InitGenesis(ctx, am.keeper, am.accountKeeper, genState) - - return []abci.ValidatorUpdate{} -} - -// ExportGenesis module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(&gs) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) {} - -// EndBlock module end-block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/issuance/spec/01_concepts.md b/x/issuance/spec/01_concepts.md deleted file mode 100644 index a0f3b974..00000000 --- a/x/issuance/spec/01_concepts.md +++ /dev/null @@ -1,7 +0,0 @@ - - -# Concepts - -The issuance mechanism in this module is designed to allow a trusted party to issue an asset on to the Kava blockchain. The issuer has sole discretion over the minting and redemption (burning) of the asset, as well as restricting access to the asset via asset seizure. The functionality of this module is similar to that of ERC-20 contracts for stablecoins that have a single issuer. diff --git a/x/issuance/spec/02_state.md b/x/issuance/spec/02_state.md deleted file mode 100644 index b815df25..00000000 --- a/x/issuance/spec/02_state.md +++ /dev/null @@ -1,31 +0,0 @@ - - -# State - -## Parameters and Genesis State - -```go - -// Asset type for assets in the issuance module -type Asset struct { - Owner sdk.AccAddress `json:"owner" yaml:"owner"` - Denom string `json:"denom" yaml:"denom"` - BlockedAddresses []sdk.AccAddress `json:"blocked_addresses" yaml:"blocked_addresses"` - Paused bool `json:"paused" yaml:"paused"` -} - -// Assets array of Asset -type Assets []Asset - -// Params governance parameters for the issuance module -type Params struct { - Assets Assets `json:"assets" yaml:"assets"` -} - -// GenesisState state that must be provided at genesis -type GenesisState struct { - Assets Assets `json:"assets" yaml:"assets"` -} -``` diff --git a/x/issuance/spec/03_messages.md b/x/issuance/spec/03_messages.md deleted file mode 100644 index 6de4869c..00000000 --- a/x/issuance/spec/03_messages.md +++ /dev/null @@ -1,68 +0,0 @@ - - -# Messages - -The issuer can issue new tokens using a `MsgIssueTokens` - -```go -// MsgIssueTokens message type used to issue tokens -type MsgIssueTokens struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - Tokens sdk.Coin `json:"tokens" yaml:"tokens"` - Receiver sdk.AccAddress `json:"receiver" yaml:"receiver"` -} -``` - -## State Modifications - -* New tokens are minted from the issuance module account -* New tokens are transferred from the module account to the receiver - -The issuer can redeem (burn) tokens using `MsgRedeemTokens`. - -```go -// MsgRedeemTokens message type used to redeem (burn) tokens -type MsgRedeemTokens struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - Tokens sdk.Coin `json:"tokens" yaml:"tokens"` -} -``` - -## State Modifications - -* Tokens are transferred from the owner address to the issuer module account -* Tokens are burned - -Addresses can be added to the blocked list using `MsgBlockAddress` - -```go -// MsgBlockAddress message type used by the issuer to block an address from holding or transferring tokens -type MsgBlockAddress struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - Denom string `json:"denom" yaml:"denom"` - BlockedAddress sdk.AccAddress `json:"blocked_address" yaml:"blocked_address"` -} -``` - -## State Modifications - -* The address is added to the block list, which prevents the account from holding coins of that denom -* Tokens are sent back to the issuer - -The issuer can pause or un-pause the contract using `MsgChangePauseStatus` - -```go -// MsgChangePauseStatus message type used by the issuer to issue new tokens -type MsgChangePauseStatus struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - Denom string `json:"denom" yaml:"denom"` - Status bool `json:"status" yaml:"status"` -} -``` - -## State Modifications - -* The `Paused` value of the correspond asset is updated to `Status`. -* Issuance and redemption are paused if `Paused` is false diff --git a/x/issuance/spec/04_events.md b/x/issuance/spec/04_events.md deleted file mode 100644 index 2ede622c..00000000 --- a/x/issuance/spec/04_events.md +++ /dev/null @@ -1,18 +0,0 @@ - - -# Events - -The `x/issuance` module emits the following events: - -## BeginBlock - -| Type | Attribute Key | Attribute Value | -|----------------------|---------------------|-----------------| -| issue_tokens | amount_issued | `{amount}` | -| redeem_tokens | amount_redeemed | `{amount}` | -| block_address | address_blocked | `{address}` | -| block_address | denom | `{denom}` | -| change_pause_status | pause_status | `{bool}` | -| change_pause_status | denom | `{denom}` | \ No newline at end of file diff --git a/x/issuance/spec/05_params.md b/x/issuance/spec/05_params.md deleted file mode 100644 index f87d0a3a..00000000 --- a/x/issuance/spec/05_params.md +++ /dev/null @@ -1,21 +0,0 @@ - - -# Parameters - -The issuance module has the following parameters: - -| Key | Type | Example | Description | -|------------|----------------|-----------------|---------------------------------------------| -| Assets | array (Asset) | `[{see below}]` | array of assets created via issuance module | - - -Each `Asset` has the following parameters - -| Key | Type | Example | Description | -|-------------------|------------------------|-------------------------------------------------|-------------------------------------------------------| -| Owner | sdk.AccAddress | "kava1cd8z53n7gh2hvz0lmmkzxkysfp5pghufat3h4a" | the address that controls the issuance of the asset | -| Denom | string | "usdtoken" | the denomination or exchange symbol of the asset | -| BlockedAccounts | array (sdk.AccAddress) | ["kava1tp9u8t8ang53a8tjh2mhqvvwdngqzjvmp3mamc"] | addresses which are blocked from holding the asset | -| Paused | boolean | false | boolean for if issuance and redemption are paused | diff --git a/x/issuance/spec/06_begin_block.md b/x/issuance/spec/06_begin_block.md deleted file mode 100644 index 9031f031..00000000 --- a/x/issuance/spec/06_begin_block.md +++ /dev/null @@ -1,16 +0,0 @@ - - -# Begin Block - -At the start of each block, coins held by blocked addresses are redeemed - -```go - func BeginBlocker(ctx sdk.Context, k Keeper) { - err := k.RedeemTokensFromBlockedAddresses(ctx, k) - if err != nil { - panic(err) - } - } -``` diff --git a/x/issuance/spec/README.md b/x/issuance/spec/README.md deleted file mode 100644 index 6d3f6298..00000000 --- a/x/issuance/spec/README.md +++ /dev/null @@ -1,20 +0,0 @@ - - -# `issuance` - - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** -5. **[Params](05_params.md)** -6. **[BeginBlock](06_begin_block.md)** - -## Abstract - -`x/issuance` is an implementation of a Cosmos SDK Module that allows for an issuer to control the minting and burning of an asset. The issuer is a white-listed address, which may be a multisig address, that can mint and burn coins of a particular denomination. The issuer is the only entity that can mint or burn tokens of that asset type (i.e., there is no outside inflation or deflation). Additionally, the issuer can place transfer-restrictions on addresses, which prevents addresses from transferring and holding tokens with the issued denomination. Coins are minted and burned at the discretion of the issuer, using `MsgIssueTokens` and `MsgRedeemTokens` transaction types, respectively. diff --git a/x/issuance/types/codec.go b/x/issuance/types/codec.go deleted file mode 100644 index e88e97f9..00000000 --- a/x/issuance/types/codec.go +++ /dev/null @@ -1,46 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the -// issuance module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgIssueTokens{}, "issuance/MsgIssueTokens", nil) - cdc.RegisterConcrete(&MsgRedeemTokens{}, "issuance/MsgRedeemTokens", nil) - cdc.RegisterConcrete(&MsgBlockAddress{}, "issuance/MsgBlockAddress", nil) - cdc.RegisterConcrete(&MsgUnblockAddress{}, "issuance/MsgUnblockAddress", nil) - cdc.RegisterConcrete(&MsgSetPauseStatus{}, "issuance/MsgChangePauseStatus", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgIssueTokens{}, - &MsgRedeemTokens{}, - &MsgBlockAddress{}, - &MsgUnblockAddress{}, - &MsgSetPauseStatus{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/issuance/types/errors.go b/x/issuance/types/errors.go deleted file mode 100644 index ec29f747..00000000 --- a/x/issuance/types/errors.go +++ /dev/null @@ -1,19 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// DONTCOVER - -// Errors used by the issuance module -var ( - ErrAssetNotFound = errorsmod.Register(ModuleName, 2, "no asset with input denom found") - ErrNotAuthorized = errorsmod.Register(ModuleName, 3, "account not authorized") - ErrAssetPaused = errorsmod.Register(ModuleName, 4, "asset is paused") - ErrAccountBlocked = errorsmod.Register(ModuleName, 5, "account is blocked") - ErrAccountAlreadyBlocked = errorsmod.Register(ModuleName, 6, "account is already blocked") - ErrAccountAlreadyUnblocked = errorsmod.Register(ModuleName, 7, "account is already unblocked") - ErrIssueToModuleAccount = errorsmod.Register(ModuleName, 8, "cannot issue tokens to module account") - ErrExceedsSupplyLimit = errorsmod.Register(ModuleName, 9, "asset supply over limit") - ErrAssetUnblockable = errorsmod.Register(ModuleName, 10, "asset does not support block/unblock functionality") - ErrAccountNotFound = errorsmod.Register(ModuleName, 11, "cannot block account that does not exist in state") -) diff --git a/x/issuance/types/events.go b/x/issuance/types/events.go deleted file mode 100644 index 4b279fb2..00000000 --- a/x/issuance/types/events.go +++ /dev/null @@ -1,19 +0,0 @@ -package types - -// Events emitted by the issuance module -const ( - EventTypeIssue = "issue_tokens" - EventTypeRedeem = "redeem_tokens" - EventTypeBlock = "block_address" - EventTypeUnblock = "unblock_address" - EventTypePause = "change_pause_status" - EventTypeSeize = "seize_coins_from_blocked_address" - AttributeValueCategory = ModuleName - AttributeKeyDenom = "denom" - AttributeKeyIssueAmount = "amount_issued" - AttributeKeyRedeemAmount = "amount_redeemed" - AttributeKeyBlock = "address_blocked" - AttributeKeyUnblock = "address_unblocked" - AttributeKeyAddress = "address" - AttributeKeyPauseStatus = "pause_status" -) diff --git a/x/issuance/types/expected_keepers.go b/x/issuance/types/expected_keepers.go deleted file mode 100644 index db742385..00000000 --- a/x/issuance/types/expected_keepers.go +++ /dev/null @@ -1,21 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// BankKeeper defines the expected interface needed to send coins -type BankKeeper interface { - 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 - BurnCoins(ctx sdk.Context, name string, amt sdk.Coins) error - MintCoins(ctx sdk.Context, name string, amt sdk.Coins) error - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins -} - -// AccountKeeper expected interface for the account keeper (noalias) -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI - GetModuleAccount(ctx sdk.Context, name string) types.ModuleAccountI -} diff --git a/x/issuance/types/genesis.go b/x/issuance/types/genesis.go deleted file mode 100644 index 4b4e91b7..00000000 --- a/x/issuance/types/genesis.go +++ /dev/null @@ -1,32 +0,0 @@ -package types - -// DefaultSupplies is used to set default asset supplies in default genesis state -var DefaultSupplies = []AssetSupply{} - -// NewGenesisState returns a new GenesisState -func NewGenesisState(params Params, supplies []AssetSupply) GenesisState { - return GenesisState{ - Params: params, - Supplies: supplies, - } -} - -// DefaultGenesisState returns the default GenesisState for the issuance module -func DefaultGenesisState() GenesisState { - return GenesisState{ - Params: DefaultParams(), - Supplies: DefaultSupplies, - } -} - -// Validate performs basic validation of genesis data returning an -// error for any failed validation criteria. -func (gs GenesisState) Validate() error { - for _, supply := range gs.Supplies { - err := supply.Validate() - if err != nil { - return err - } - } - return gs.Params.Validate() -} diff --git a/x/issuance/types/genesis_test.go b/x/issuance/types/genesis_test.go deleted file mode 100644 index 5c1db540..00000000 --- a/x/issuance/types/genesis_test.go +++ /dev/null @@ -1,207 +0,0 @@ -package types_test - -import ( - "strings" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/issuance/types" -) - -type GenesisTestSuite struct { - suite.Suite - - addrs []string -} - -func (suite *GenesisTestSuite) SetupTest() { - _, addrs := app.GeneratePrivKeyAddressPairs(2) - var strAddrs []string - for _, addr := range addrs { - strAddrs = append(strAddrs, addr.String()) - } - suite.addrs = strAddrs -} - -func (suite *GenesisTestSuite) TestValidate() { - type args struct { - assets []types.Asset - supplies []types.AssetSupply - } - type errArgs struct { - expectPass bool - contains string - } - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - "default", - args{ - assets: types.DefaultAssets, - supplies: types.DefaultSupplies, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "with asset", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - supplies: []types.AssetSupply{types.NewAssetSupply(sdk.NewCoin("usdtoken", sdkmath.NewInt(1000000)), time.Hour)}, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "with asset rate limit", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(true, sdkmath.NewInt(1000000000), time.Hour*24)), - }, - supplies: []types.AssetSupply{}, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "with multiple assets", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - types.NewAsset(suite.addrs[0], "pegtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - supplies: []types.AssetSupply{}, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "blocked owner", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[0]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - supplies: []types.AssetSupply{}, - }, - errArgs{ - expectPass: false, - contains: "asset owner cannot be blocked", - }, - }, - { - "empty owner", - args{ - assets: []types.Asset{ - types.NewAsset("", "usdtoken", []string{suite.addrs[0]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - supplies: []types.AssetSupply{}, - }, - errArgs{ - expectPass: false, - contains: "owner must not be empty", - }, - }, - { - "empty blocked address", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{""}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - supplies: []types.AssetSupply{}, - }, - errArgs{ - expectPass: false, - contains: "blocked address must not be empty", - }, - }, - { - "invalid denom", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "USD2T ", []string{}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - supplies: []types.AssetSupply{}, - }, - errArgs{ - expectPass: false, - contains: "invalid denom", - }, - }, - { - "duplicate denom", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - types.NewAsset(suite.addrs[1], "usdtoken", []string{}, true, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - supplies: []types.AssetSupply{}, - }, - errArgs{ - expectPass: false, - contains: "duplicate asset denoms", - }, - }, - { - "duplicate asset", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, true, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - supplies: []types.AssetSupply{}, - }, - errArgs{ - expectPass: false, - contains: "duplicate asset denoms", - }, - }, - { - "invalid block list", - args{ - assets: []types.Asset{ - types.NewAsset(suite.addrs[0], "usdtoken", []string{suite.addrs[1]}, false, false, types.NewRateLimit(false, sdk.ZeroInt(), time.Duration(0))), - }, - supplies: []types.AssetSupply{types.NewAssetSupply(sdk.NewCoin("usdtoken", sdk.ZeroInt()), time.Hour)}, - }, - errArgs{ - expectPass: false, - contains: "blocked-list should be empty", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - gs := types.NewGenesisState(types.NewParams(tc.args.assets), tc.args.supplies) - err := gs.Validate() - if tc.errArgs.expectPass { - suite.Require().NoError(err, tc.name) - } else { - suite.Require().Error(err, tc.name) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(GenesisTestSuite)) -} diff --git a/x/issuance/types/keys.go b/x/issuance/types/keys.go deleted file mode 100644 index 57d33fd6..00000000 --- a/x/issuance/types/keys.go +++ /dev/null @@ -1,21 +0,0 @@ -package types - -const ( - // ModuleName The name that will be used throughout the module - ModuleName = "issuance" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default name for parameter store - DefaultParamspace = ModuleName -) - -// KVStore key prefixes -var ( - AssetSupplyPrefix = []byte{0x01} - PreviousBlockTimeKey = []byte{0x02} -) diff --git a/x/issuance/types/msg.go b/x/issuance/types/msg.go deleted file mode 100644 index 3fe765a6..00000000 --- a/x/issuance/types/msg.go +++ /dev/null @@ -1,252 +0,0 @@ -package types - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -const ( - TypeMsgIssueTokens = "issue_tokens" - TypeMsgRedeemTokens = "redeem_tokens" - TypeMsgBlockAddress = "block_address" - TypeMsgUnBlockAddress = "unblock_address" - TypeMsgSetPauseStatus = "change_pause_status" -) - -// ensure Msg interface compliance at compile time -var ( - _ sdk.Msg = &MsgIssueTokens{} - _ sdk.Msg = &MsgRedeemTokens{} - _ sdk.Msg = &MsgBlockAddress{} - _ sdk.Msg = &MsgUnblockAddress{} - _ sdk.Msg = &MsgSetPauseStatus{} -) - -// NewMsgIssueTokens returns a new MsgIssueTokens -func NewMsgIssueTokens(sender string, tokens sdk.Coin, receiver string) *MsgIssueTokens { - return &MsgIssueTokens{ - Sender: sender, - Tokens: tokens, - Receiver: receiver, - } -} - -// Route return the message type used for routing the message. -func (msg MsgIssueTokens) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgIssueTokens) Type() string { return TypeMsgIssueTokens } - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgIssueTokens) ValidateBasic() error { - if len(msg.Sender) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty") - } - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "invalid sender bech32 address") - } - if msg.Tokens.IsZero() || !msg.Tokens.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "invalid tokens %s", msg.Tokens) - } - if len(msg.Receiver) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "receiver address cannot be empty") - } - _, err = sdk.AccAddressFromBech32(msg.Receiver) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "invalid receiver bech32 address") - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg -func (msg MsgIssueTokens) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign -func (msg MsgIssueTokens) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgRedeemTokens returns a new MsgRedeemTokens -func NewMsgRedeemTokens(sender string, tokens sdk.Coin) *MsgRedeemTokens { - return &MsgRedeemTokens{ - Sender: sender, - Tokens: tokens, - } -} - -// Route return the message type used for routing the message. -func (msg MsgRedeemTokens) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgRedeemTokens) Type() string { return TypeMsgRedeemTokens } - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgRedeemTokens) ValidateBasic() error { - if len(msg.Sender) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty") - } - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "invalid sender bech32 address") - } - if msg.Tokens.IsZero() || !msg.Tokens.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "invalid tokens %s", msg.Tokens) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg -func (msg MsgRedeemTokens) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign -func (msg MsgRedeemTokens) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgBlockAddress returns a new MsgBlockAddress -func NewMsgBlockAddress(sender string, denom string, addr string) *MsgBlockAddress { - return &MsgBlockAddress{ - Sender: sender, - Denom: denom, - BlockedAddress: addr, - } -} - -// Route return the message type used for routing the message. -func (msg MsgBlockAddress) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgBlockAddress) Type() string { return TypeMsgBlockAddress } - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgBlockAddress) ValidateBasic() error { - if len(msg.Sender) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty") - } - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "invalid sender bech32 address") - } - if len(msg.BlockedAddress) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "blocked address cannot be empty") - } - return sdk.ValidateDenom(msg.Denom) -} - -// GetSignBytes gets the canonical byte representation of the Msg -func (msg MsgBlockAddress) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign -func (msg MsgBlockAddress) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgUnblockAddress returns a new MsgUnblockAddress -func NewMsgUnblockAddress(sender string, denom string, addr string) *MsgUnblockAddress { - return &MsgUnblockAddress{ - Sender: sender, - Denom: denom, - BlockedAddress: addr, - } -} - -// Route return the message type used for routing the message. -func (msg MsgUnblockAddress) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgUnblockAddress) Type() string { return TypeMsgUnBlockAddress } - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgUnblockAddress) ValidateBasic() error { - if len(msg.Sender) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty") - } - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "invalid sender bech32 address") - } - if len(msg.BlockedAddress) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "blocked address cannot be empty") - } - return sdk.ValidateDenom(msg.Denom) -} - -// GetSignBytes gets the canonical byte representation of the Msg -func (msg MsgUnblockAddress) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign -func (msg MsgUnblockAddress) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgSetPauseStatus returns a new MsgSetPauseStatus -func NewMsgSetPauseStatus(sender string, denom string, status bool) *MsgSetPauseStatus { - return &MsgSetPauseStatus{ - Sender: sender, - Denom: denom, - Status: status, - } -} - -// Route return the message type used for routing the message. -func (msg MsgSetPauseStatus) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgSetPauseStatus) Type() string { return TypeMsgSetPauseStatus } - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgSetPauseStatus) ValidateBasic() error { - if len(msg.Sender) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty") - } - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "invalid sender bech32 address") - } - return sdk.ValidateDenom(msg.Denom) -} - -// GetSignBytes gets the canonical byte representation of the Msg -func (msg MsgSetPauseStatus) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign -func (msg MsgSetPauseStatus) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} diff --git a/x/issuance/types/msg_test.go b/x/issuance/types/msg_test.go deleted file mode 100644 index e7932166..00000000 --- a/x/issuance/types/msg_test.go +++ /dev/null @@ -1,359 +0,0 @@ -package types_test - -import ( - "strings" - "testing" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/issuance/types" -) - -type MsgTestSuite struct { - suite.Suite - - addrs []string -} - -func (suite *MsgTestSuite) SetupTest() { - _, addrs := app.GeneratePrivKeyAddressPairs(2) - var strAddrs []string - for _, addr := range addrs { - strAddrs = append(strAddrs, addr.String()) - } - suite.addrs = strAddrs -} - -func (suite *MsgTestSuite) TestMsgIssueTokens() { - type args struct { - sender string - tokens sdk.Coin - receiver string - } - type errArgs struct { - expectPass bool - contains string - } - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - "default", - args{ - sender: suite.addrs[0], - tokens: sdk.NewCoin("valid", sdkmath.NewInt(100)), - receiver: suite.addrs[1], - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid sender", - args{ - sender: "", - tokens: sdk.NewCoin("valid", sdkmath.NewInt(100)), - receiver: suite.addrs[1], - }, - errArgs{ - expectPass: false, - contains: "sender address cannot be empty", - }, - }, - { - "invalid receiver", - args{ - sender: suite.addrs[0], - tokens: sdk.NewCoin("valid", sdkmath.NewInt(100)), - receiver: "", - }, - errArgs{ - expectPass: false, - contains: "receiver address cannot be empty", - }, - }, - { - "invalid tokens", - args{ - sender: suite.addrs[0], - tokens: sdk.Coin{Denom: "In~val~id", Amount: sdkmath.NewInt(100)}, - receiver: suite.addrs[1], - }, - errArgs{ - expectPass: false, - contains: "invalid tokens", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - testMsg := types.NewMsgIssueTokens(tc.args.sender, tc.args.tokens, tc.args.receiver) - err := testMsg.ValidateBasic() - if tc.errArgs.expectPass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *MsgTestSuite) TestMsgRedeemTokens() { - type args struct { - sender string - tokens sdk.Coin - } - type errArgs struct { - expectPass bool - contains string - } - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - "default", - args{ - sender: suite.addrs[0], - tokens: sdk.NewCoin("valid", sdkmath.NewInt(100)), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid sender", - args{ - sender: "", - tokens: sdk.NewCoin("valid", sdkmath.NewInt(100)), - }, - errArgs{ - expectPass: false, - contains: "sender address cannot be empty", - }, - }, - { - "invalid tokens", - args{ - sender: suite.addrs[0], - tokens: sdk.Coin{Denom: "In~val~id", Amount: sdkmath.NewInt(100)}, - }, - errArgs{ - expectPass: false, - contains: "invalid tokens", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - testMsg := types.NewMsgRedeemTokens(tc.args.sender, tc.args.tokens) - err := testMsg.ValidateBasic() - if tc.errArgs.expectPass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *MsgTestSuite) TestMsgBlockAddress() { - type args struct { - sender string - denom string - address string - } - type errArgs struct { - expectPass bool - contains string - } - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - "default", - args{ - sender: suite.addrs[0], - denom: "valid", - address: suite.addrs[1], - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid sender", - args{ - sender: "", - denom: "valid", - address: suite.addrs[1], - }, - errArgs{ - expectPass: false, - contains: "sender address cannot be empty", - }, - }, - { - "invalid blocked", - args{ - sender: suite.addrs[0], - denom: "valid", - address: "", - }, - errArgs{ - expectPass: false, - contains: "blocked address cannot be empty", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - testMsg := types.NewMsgBlockAddress(tc.args.sender, tc.args.denom, tc.args.address) - err := testMsg.ValidateBasic() - if tc.errArgs.expectPass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *MsgTestSuite) TestMsgUnblockAddress() { - type args struct { - sender string - denom string - address string - } - type errArgs struct { - expectPass bool - contains string - } - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - "default", - args{ - sender: suite.addrs[0], - denom: "valid", - address: suite.addrs[1], - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid sender", - args{ - sender: "", - denom: "valid", - address: suite.addrs[1], - }, - errArgs{ - expectPass: false, - contains: "sender address cannot be empty", - }, - }, - { - "invalid blocked", - args{ - sender: suite.addrs[0], - denom: "valid", - address: "", - }, - errArgs{ - expectPass: false, - contains: "blocked address cannot be empty", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - testMsg := types.NewMsgUnblockAddress(tc.args.sender, tc.args.denom, tc.args.address) - err := testMsg.ValidateBasic() - if tc.errArgs.expectPass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *MsgTestSuite) TestMsgSetPauseStatus() { - type args struct { - sender string - denom string - status bool - } - type errArgs struct { - expectPass bool - contains string - } - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - "default", - args{ - sender: suite.addrs[0], - denom: "valid", - status: true, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid sender", - args{ - sender: "", - denom: "valid", - status: true, - }, - errArgs{ - expectPass: false, - contains: "sender address cannot be empty", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - testMsg := types.NewMsgSetPauseStatus(tc.args.sender, tc.args.denom, tc.args.status) - err := testMsg.ValidateBasic() - if tc.errArgs.expectPass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func TestMsgTestSuite(t *testing.T) { - suite.Run(t, new(MsgTestSuite)) -} diff --git a/x/issuance/types/params.go b/x/issuance/types/params.go deleted file mode 100644 index d18fae9d..00000000 --- a/x/issuance/types/params.go +++ /dev/null @@ -1,127 +0,0 @@ -package types - -import ( - "fmt" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// Parameter keys and default values -var ( - KeyAssets = []byte("Assets") - DefaultAssets = []Asset{} - ModuleAccountName = ModuleName -) - -// NewParams returns a new params object -func NewParams(assets []Asset) Params { - return Params{ - Assets: assets, - } -} - -// DefaultParams returns default params for issuance module -func DefaultParams() Params { - return NewParams(DefaultAssets) -} - -// ParamKeyTable Key declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements the ParamSet interface and returns all the key/value pairs -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyAssets, &p.Assets, validateAssetsParam), - } -} - -// Validate checks that the parameters have valid values. -func (p Params) Validate() error { - return validateAssetsParam(p.Assets) -} - -func validateAssetsParam(i interface{}) error { - assets, ok := i.([]Asset) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - return ValidateAssets(assets) -} - -// String implements fmt.Stringer -func (p Params) String() string { - return fmt.Sprintf(`Params: - Assets: %s - `, p.Assets) -} - -// NewAsset returns a new Asset -func NewAsset(owner string, denom string, blockedAddresses []string, paused bool, blockable bool, limit RateLimit) Asset { - return Asset{ - Owner: owner, - Denom: denom, - BlockedAddresses: blockedAddresses, - Paused: paused, - Blockable: blockable, - RateLimit: limit, - } -} - -// Validate performs a basic check of asset fields -func (a Asset) Validate() error { - if len(a.Owner) == 0 { - return fmt.Errorf("owner must not be empty") - } - if !a.Blockable && len(a.BlockedAddresses) > 0 { - return fmt.Errorf("asset %s does not support blocking, blocked-list should be empty: %s", a.Denom, a.BlockedAddresses) - } - for _, address := range a.BlockedAddresses { - if len(address) == 0 { - return fmt.Errorf("blocked address must not be empty") - } - if a.Owner == address { - return fmt.Errorf("asset owner cannot be blocked") - } - } - return sdk.ValidateDenom(a.Denom) -} - -// String implements fmt.Stringer -func (a Asset) String() string { - return fmt.Sprintf(`Asset: - Owner: %s - Paused: %t - Denom: %s - Blocked Addresses: %s - Rate limits: %s`, - a.Owner, a.Paused, a.Denom, a.BlockedAddresses, a.RateLimit.String()) -} - -// Validate checks if all assets are valid and there are no duplicate entries -func ValidateAssets(as []Asset) error { - assetDenoms := make(map[string]bool) - for _, a := range as { - if assetDenoms[a.Denom] { - return fmt.Errorf("cannot have duplicate asset denoms: %s", a.Denom) - } - if err := a.Validate(); err != nil { - return err - } - assetDenoms[a.Denom] = true - } - return nil -} - -// NewRateLimit initializes a new RateLimit -func NewRateLimit(active bool, limit sdkmath.Int, timePeriod time.Duration) RateLimit { - return RateLimit{ - Active: active, - Limit: limit, - TimePeriod: timePeriod, - } -} diff --git a/x/issuance/types/supply.go b/x/issuance/types/supply.go deleted file mode 100644 index c73aaafe..00000000 --- a/x/issuance/types/supply.go +++ /dev/null @@ -1,41 +0,0 @@ -package types - -import ( - "fmt" - "time" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// NewAssetSupply initializes a new AssetSupply -func NewAssetSupply(currentSupply sdk.Coin, timeElapsed time.Duration) AssetSupply { - return AssetSupply{ - CurrentSupply: currentSupply, - TimeElapsed: timeElapsed, - } -} - -// Validate performs a basic validation of an asset supply fields. -func (a AssetSupply) Validate() error { - if !a.CurrentSupply.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "outgoing supply %s", a.CurrentSupply) - } - return nil -} - -// String implements stringer -func (a AssetSupply) String() string { - return fmt.Sprintf(` - asset supply: - Current supply: %s - Time elapsed: %s - `, - a.CurrentSupply, a.TimeElapsed) -} - -// GetDenom getter method for the denom of the asset supply -func (a AssetSupply) GetDenom() string { - return a.CurrentSupply.Denom -} diff --git a/x/issuance/types/tx.pb.go b/x/issuance/types/tx.pb.go deleted file mode 100644 index e0416cc9..00000000 --- a/x/issuance/types/tx.pb.go +++ /dev/null @@ -1,2216 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/issuance/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - 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 - -// MsgIssueTokens represents a message used by the issuer to issue new tokens -type MsgIssueTokens struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Tokens types.Coin `protobuf:"bytes,2,opt,name=tokens,proto3" json:"tokens"` - Receiver string `protobuf:"bytes,3,opt,name=receiver,proto3" json:"receiver,omitempty"` -} - -func (m *MsgIssueTokens) Reset() { *m = MsgIssueTokens{} } -func (m *MsgIssueTokens) String() string { return proto.CompactTextString(m) } -func (*MsgIssueTokens) ProtoMessage() {} -func (*MsgIssueTokens) Descriptor() ([]byte, []int) { - return fileDescriptor_0cb7117b12e184a2, []int{0} -} -func (m *MsgIssueTokens) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgIssueTokens) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgIssueTokens.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 *MsgIssueTokens) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgIssueTokens.Merge(m, src) -} -func (m *MsgIssueTokens) XXX_Size() int { - return m.Size() -} -func (m *MsgIssueTokens) XXX_DiscardUnknown() { - xxx_messageInfo_MsgIssueTokens.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgIssueTokens proto.InternalMessageInfo - -// MsgIssueTokensResponse defines the Msg/IssueTokens response type. -type MsgIssueTokensResponse struct { -} - -func (m *MsgIssueTokensResponse) Reset() { *m = MsgIssueTokensResponse{} } -func (m *MsgIssueTokensResponse) String() string { return proto.CompactTextString(m) } -func (*MsgIssueTokensResponse) ProtoMessage() {} -func (*MsgIssueTokensResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0cb7117b12e184a2, []int{1} -} -func (m *MsgIssueTokensResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgIssueTokensResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgIssueTokensResponse.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 *MsgIssueTokensResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgIssueTokensResponse.Merge(m, src) -} -func (m *MsgIssueTokensResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgIssueTokensResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgIssueTokensResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgIssueTokensResponse proto.InternalMessageInfo - -// MsgRedeemTokens represents a message used by the issuer to redeem (burn) tokens -type MsgRedeemTokens struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Tokens types.Coin `protobuf:"bytes,2,opt,name=tokens,proto3" json:"tokens"` -} - -func (m *MsgRedeemTokens) Reset() { *m = MsgRedeemTokens{} } -func (m *MsgRedeemTokens) String() string { return proto.CompactTextString(m) } -func (*MsgRedeemTokens) ProtoMessage() {} -func (*MsgRedeemTokens) Descriptor() ([]byte, []int) { - return fileDescriptor_0cb7117b12e184a2, []int{2} -} -func (m *MsgRedeemTokens) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgRedeemTokens) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgRedeemTokens.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 *MsgRedeemTokens) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgRedeemTokens.Merge(m, src) -} -func (m *MsgRedeemTokens) XXX_Size() int { - return m.Size() -} -func (m *MsgRedeemTokens) XXX_DiscardUnknown() { - xxx_messageInfo_MsgRedeemTokens.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgRedeemTokens proto.InternalMessageInfo - -// MsgRedeemTokensResponse defines the Msg/RedeemTokens response type. -type MsgRedeemTokensResponse struct { -} - -func (m *MsgRedeemTokensResponse) Reset() { *m = MsgRedeemTokensResponse{} } -func (m *MsgRedeemTokensResponse) String() string { return proto.CompactTextString(m) } -func (*MsgRedeemTokensResponse) ProtoMessage() {} -func (*MsgRedeemTokensResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0cb7117b12e184a2, []int{3} -} -func (m *MsgRedeemTokensResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgRedeemTokensResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgRedeemTokensResponse.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 *MsgRedeemTokensResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgRedeemTokensResponse.Merge(m, src) -} -func (m *MsgRedeemTokensResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgRedeemTokensResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgRedeemTokensResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgRedeemTokensResponse proto.InternalMessageInfo - -// MsgBlockAddress represents a message used by the issuer to block an address from holding or transferring tokens -type MsgBlockAddress struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Denom string `protobuf:"bytes,2,opt,name=denom,proto3" json:"denom,omitempty"` - BlockedAddress string `protobuf:"bytes,3,opt,name=blocked_address,json=blockedAddress,proto3" json:"blocked_address,omitempty"` -} - -func (m *MsgBlockAddress) Reset() { *m = MsgBlockAddress{} } -func (m *MsgBlockAddress) String() string { return proto.CompactTextString(m) } -func (*MsgBlockAddress) ProtoMessage() {} -func (*MsgBlockAddress) Descriptor() ([]byte, []int) { - return fileDescriptor_0cb7117b12e184a2, []int{4} -} -func (m *MsgBlockAddress) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgBlockAddress) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgBlockAddress.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 *MsgBlockAddress) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgBlockAddress.Merge(m, src) -} -func (m *MsgBlockAddress) XXX_Size() int { - return m.Size() -} -func (m *MsgBlockAddress) XXX_DiscardUnknown() { - xxx_messageInfo_MsgBlockAddress.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgBlockAddress proto.InternalMessageInfo - -// MsgBlockAddressResponse defines the Msg/BlockAddress response type. -type MsgBlockAddressResponse struct { -} - -func (m *MsgBlockAddressResponse) Reset() { *m = MsgBlockAddressResponse{} } -func (m *MsgBlockAddressResponse) String() string { return proto.CompactTextString(m) } -func (*MsgBlockAddressResponse) ProtoMessage() {} -func (*MsgBlockAddressResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0cb7117b12e184a2, []int{5} -} -func (m *MsgBlockAddressResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgBlockAddressResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgBlockAddressResponse.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 *MsgBlockAddressResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgBlockAddressResponse.Merge(m, src) -} -func (m *MsgBlockAddressResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgBlockAddressResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgBlockAddressResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgBlockAddressResponse proto.InternalMessageInfo - -// MsgUnblockAddress message type used by the issuer to unblock an address from holding or transferring tokens -type MsgUnblockAddress struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Denom string `protobuf:"bytes,2,opt,name=denom,proto3" json:"denom,omitempty"` - BlockedAddress string `protobuf:"bytes,3,opt,name=blocked_address,json=blockedAddress,proto3" json:"blocked_address,omitempty"` -} - -func (m *MsgUnblockAddress) Reset() { *m = MsgUnblockAddress{} } -func (m *MsgUnblockAddress) String() string { return proto.CompactTextString(m) } -func (*MsgUnblockAddress) ProtoMessage() {} -func (*MsgUnblockAddress) Descriptor() ([]byte, []int) { - return fileDescriptor_0cb7117b12e184a2, []int{6} -} -func (m *MsgUnblockAddress) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgUnblockAddress) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUnblockAddress.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 *MsgUnblockAddress) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUnblockAddress.Merge(m, src) -} -func (m *MsgUnblockAddress) XXX_Size() int { - return m.Size() -} -func (m *MsgUnblockAddress) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUnblockAddress.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUnblockAddress proto.InternalMessageInfo - -// MsgUnblockAddressResponse defines the Msg/UnblockAddress response type. -type MsgUnblockAddressResponse struct { -} - -func (m *MsgUnblockAddressResponse) Reset() { *m = MsgUnblockAddressResponse{} } -func (m *MsgUnblockAddressResponse) String() string { return proto.CompactTextString(m) } -func (*MsgUnblockAddressResponse) ProtoMessage() {} -func (*MsgUnblockAddressResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0cb7117b12e184a2, []int{7} -} -func (m *MsgUnblockAddressResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgUnblockAddressResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUnblockAddressResponse.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 *MsgUnblockAddressResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUnblockAddressResponse.Merge(m, src) -} -func (m *MsgUnblockAddressResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgUnblockAddressResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUnblockAddressResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUnblockAddressResponse proto.InternalMessageInfo - -// MsgSetPauseStatus message type used by the issuer to pause or unpause status -type MsgSetPauseStatus struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Denom string `protobuf:"bytes,2,opt,name=denom,proto3" json:"denom,omitempty"` - Status bool `protobuf:"varint,3,opt,name=status,proto3" json:"status,omitempty"` -} - -func (m *MsgSetPauseStatus) Reset() { *m = MsgSetPauseStatus{} } -func (m *MsgSetPauseStatus) String() string { return proto.CompactTextString(m) } -func (*MsgSetPauseStatus) ProtoMessage() {} -func (*MsgSetPauseStatus) Descriptor() ([]byte, []int) { - return fileDescriptor_0cb7117b12e184a2, []int{8} -} -func (m *MsgSetPauseStatus) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSetPauseStatus) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSetPauseStatus.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 *MsgSetPauseStatus) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSetPauseStatus.Merge(m, src) -} -func (m *MsgSetPauseStatus) XXX_Size() int { - return m.Size() -} -func (m *MsgSetPauseStatus) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSetPauseStatus.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSetPauseStatus proto.InternalMessageInfo - -// MsgSetPauseStatusResponse defines the Msg/SetPauseStatus response type. -type MsgSetPauseStatusResponse struct { -} - -func (m *MsgSetPauseStatusResponse) Reset() { *m = MsgSetPauseStatusResponse{} } -func (m *MsgSetPauseStatusResponse) String() string { return proto.CompactTextString(m) } -func (*MsgSetPauseStatusResponse) ProtoMessage() {} -func (*MsgSetPauseStatusResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0cb7117b12e184a2, []int{9} -} -func (m *MsgSetPauseStatusResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSetPauseStatusResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSetPauseStatusResponse.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 *MsgSetPauseStatusResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSetPauseStatusResponse.Merge(m, src) -} -func (m *MsgSetPauseStatusResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgSetPauseStatusResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSetPauseStatusResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSetPauseStatusResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgIssueTokens)(nil), "kava.issuance.v1beta1.MsgIssueTokens") - proto.RegisterType((*MsgIssueTokensResponse)(nil), "kava.issuance.v1beta1.MsgIssueTokensResponse") - proto.RegisterType((*MsgRedeemTokens)(nil), "kava.issuance.v1beta1.MsgRedeemTokens") - proto.RegisterType((*MsgRedeemTokensResponse)(nil), "kava.issuance.v1beta1.MsgRedeemTokensResponse") - proto.RegisterType((*MsgBlockAddress)(nil), "kava.issuance.v1beta1.MsgBlockAddress") - proto.RegisterType((*MsgBlockAddressResponse)(nil), "kava.issuance.v1beta1.MsgBlockAddressResponse") - proto.RegisterType((*MsgUnblockAddress)(nil), "kava.issuance.v1beta1.MsgUnblockAddress") - proto.RegisterType((*MsgUnblockAddressResponse)(nil), "kava.issuance.v1beta1.MsgUnblockAddressResponse") - proto.RegisterType((*MsgSetPauseStatus)(nil), "kava.issuance.v1beta1.MsgSetPauseStatus") - proto.RegisterType((*MsgSetPauseStatusResponse)(nil), "kava.issuance.v1beta1.MsgSetPauseStatusResponse") -} - -func init() { proto.RegisterFile("kava/issuance/v1beta1/tx.proto", fileDescriptor_0cb7117b12e184a2) } - -var fileDescriptor_0cb7117b12e184a2 = []byte{ - // 496 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x94, 0xbf, 0x6e, 0xd3, 0x50, - 0x14, 0xc6, 0x6d, 0x5a, 0xa2, 0xf4, 0x14, 0xa5, 0xc2, 0x2a, 0x25, 0x31, 0x92, 0x53, 0x45, 0x02, - 0x22, 0xa4, 0x5e, 0xd3, 0x32, 0x20, 0xb1, 0x11, 0x58, 0x18, 0x22, 0x21, 0x17, 0x16, 0x16, 0x74, - 0x6d, 0x1f, 0x8c, 0x95, 0xc4, 0x37, 0xf2, 0xb9, 0x8e, 0xca, 0x13, 0xc0, 0xc8, 0xc4, 0xdc, 0xc7, - 0xe9, 0xd8, 0x91, 0x09, 0xa1, 0x64, 0xe1, 0x31, 0x90, 0xaf, 0x9d, 0xc4, 0xce, 0x3f, 0x85, 0x81, - 0x6e, 0xf7, 0xdc, 0xf3, 0x9d, 0xf3, 0xfd, 0x64, 0x7d, 0xbe, 0x60, 0xf5, 0xf8, 0x88, 0xdb, 0x21, - 0x51, 0xc2, 0x23, 0x0f, 0xed, 0xd1, 0xa9, 0x8b, 0x92, 0x9f, 0xda, 0xf2, 0x82, 0x0d, 0x63, 0x21, - 0x85, 0x71, 0x2f, 0xed, 0xb3, 0x69, 0x9f, 0xe5, 0x7d, 0xd3, 0xf2, 0x04, 0x0d, 0x04, 0xd9, 0x2e, - 0xa7, 0xf9, 0x90, 0x27, 0xc2, 0x28, 0x1b, 0x33, 0x0f, 0x03, 0x11, 0x08, 0x75, 0xb4, 0xd3, 0x53, - 0x76, 0xdb, 0xfa, 0xaa, 0x43, 0xad, 0x4b, 0xc1, 0x1b, 0xa2, 0x04, 0xdf, 0x89, 0x1e, 0x46, 0x64, - 0x1c, 0x41, 0x85, 0x30, 0xf2, 0x31, 0xae, 0xeb, 0xc7, 0x7a, 0x7b, 0xcf, 0xc9, 0x2b, 0xe3, 0x39, - 0x54, 0xa4, 0x52, 0xd4, 0x6f, 0x1d, 0xeb, 0xed, 0xfd, 0xb3, 0x06, 0xcb, 0x1c, 0x59, 0xea, 0x38, - 0xc5, 0x60, 0xaf, 0x44, 0x18, 0x75, 0x76, 0xaf, 0x7e, 0x35, 0x35, 0x27, 0x97, 0x1b, 0x26, 0x54, - 0x63, 0xf4, 0x30, 0x1c, 0x61, 0x5c, 0xdf, 0x51, 0x2b, 0x67, 0xf5, 0x8b, 0xea, 0xb7, 0xcb, 0xa6, - 0xf6, 0xe7, 0xb2, 0xa9, 0xb5, 0xea, 0x70, 0x54, 0x06, 0x71, 0x90, 0x86, 0x22, 0x22, 0x6c, 0xf5, - 0xe1, 0xa0, 0x4b, 0x81, 0x83, 0x3e, 0xe2, 0xe0, 0x3f, 0x31, 0x16, 0x38, 0x1a, 0x70, 0x7f, 0xc1, - 0x6d, 0x06, 0x12, 0x2b, 0x90, 0x4e, 0x5f, 0x78, 0xbd, 0x97, 0xbe, 0x1f, 0x23, 0xad, 0x07, 0x39, - 0x84, 0xdb, 0x3e, 0x46, 0x62, 0xa0, 0x38, 0xf6, 0x9c, 0xac, 0x30, 0x1e, 0xc3, 0x81, 0x9b, 0x4e, - 0xa3, 0xff, 0x91, 0x67, 0x0b, 0xf2, 0x0f, 0x52, 0xcb, 0xaf, 0xf3, 0xb5, 0x4b, 0x38, 0x45, 0xcf, - 0x19, 0x8e, 0x84, 0xbb, 0x5d, 0x0a, 0xde, 0x47, 0xee, 0x8d, 0x02, 0x3d, 0x80, 0xc6, 0x92, 0xeb, - 0x0c, 0xc9, 0x53, 0x48, 0xe7, 0x28, 0xdf, 0xf2, 0x84, 0xf0, 0x5c, 0x72, 0x99, 0xfc, 0x2b, 0x52, - 0xaa, 0x56, 0x73, 0x8a, 0xa4, 0xea, 0xe4, 0xd5, 0x12, 0x41, 0xd9, 0x64, 0x4a, 0x70, 0xf6, 0x63, - 0x17, 0x76, 0xba, 0x14, 0x18, 0x1e, 0xec, 0x17, 0x43, 0xfd, 0x90, 0xad, 0xfc, 0x6b, 0x58, 0x39, - 0x72, 0xe6, 0xc9, 0x56, 0xb2, 0xa9, 0x99, 0xf1, 0x09, 0xee, 0x94, 0x62, 0xf9, 0x68, 0xfd, 0x78, - 0x51, 0x67, 0xb2, 0xed, 0x74, 0x45, 0x9f, 0x52, 0xea, 0x36, 0xf8, 0x14, 0x75, 0x9b, 0x7c, 0x56, - 0x25, 0xca, 0xe8, 0x43, 0x6d, 0x21, 0x4e, 0xed, 0xf5, 0x1b, 0xca, 0x4a, 0xf3, 0xe9, 0xb6, 0xca, - 0xa2, 0xdb, 0x42, 0x52, 0x36, 0xb8, 0x95, 0x95, 0x9b, 0xdc, 0x56, 0x07, 0xa3, 0xf3, 0xfa, 0x6a, - 0x6c, 0xe9, 0xd7, 0x63, 0x4b, 0xff, 0x3d, 0xb6, 0xf4, 0xef, 0x13, 0x4b, 0xbb, 0x9e, 0x58, 0xda, - 0xcf, 0x89, 0xa5, 0x7d, 0x78, 0x12, 0x84, 0xf2, 0x73, 0xe2, 0x32, 0x4f, 0x0c, 0xec, 0x74, 0xeb, - 0x49, 0x9f, 0xbb, 0xa4, 0x4e, 0xf6, 0xc5, 0xfc, 0x1d, 0x96, 0x5f, 0x86, 0x48, 0x6e, 0x45, 0x3d, - 0x9b, 0xcf, 0xfe, 0x06, 0x00, 0x00, 0xff, 0xff, 0x5f, 0x6f, 0x10, 0xd6, 0xa5, 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 - -// 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 { - // IssueTokens message type used by the issuer to issue new tokens - IssueTokens(ctx context.Context, in *MsgIssueTokens, opts ...grpc.CallOption) (*MsgIssueTokensResponse, error) - // RedeemTokens message type used by the issuer to redeem (burn) tokens - RedeemTokens(ctx context.Context, in *MsgRedeemTokens, opts ...grpc.CallOption) (*MsgRedeemTokensResponse, error) - // BlockAddress message type used by the issuer to block an address from holding or transferring tokens - BlockAddress(ctx context.Context, in *MsgBlockAddress, opts ...grpc.CallOption) (*MsgBlockAddressResponse, error) - // UnblockAddress message type used by the issuer to unblock an address from holding or transferring tokens - UnblockAddress(ctx context.Context, in *MsgUnblockAddress, opts ...grpc.CallOption) (*MsgUnblockAddressResponse, error) - // SetPauseStatus message type used to pause or unpause status - SetPauseStatus(ctx context.Context, in *MsgSetPauseStatus, opts ...grpc.CallOption) (*MsgSetPauseStatusResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) IssueTokens(ctx context.Context, in *MsgIssueTokens, opts ...grpc.CallOption) (*MsgIssueTokensResponse, error) { - out := new(MsgIssueTokensResponse) - err := c.cc.Invoke(ctx, "/kava.issuance.v1beta1.Msg/IssueTokens", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) RedeemTokens(ctx context.Context, in *MsgRedeemTokens, opts ...grpc.CallOption) (*MsgRedeemTokensResponse, error) { - out := new(MsgRedeemTokensResponse) - err := c.cc.Invoke(ctx, "/kava.issuance.v1beta1.Msg/RedeemTokens", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) BlockAddress(ctx context.Context, in *MsgBlockAddress, opts ...grpc.CallOption) (*MsgBlockAddressResponse, error) { - out := new(MsgBlockAddressResponse) - err := c.cc.Invoke(ctx, "/kava.issuance.v1beta1.Msg/BlockAddress", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) UnblockAddress(ctx context.Context, in *MsgUnblockAddress, opts ...grpc.CallOption) (*MsgUnblockAddressResponse, error) { - out := new(MsgUnblockAddressResponse) - err := c.cc.Invoke(ctx, "/kava.issuance.v1beta1.Msg/UnblockAddress", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) SetPauseStatus(ctx context.Context, in *MsgSetPauseStatus, opts ...grpc.CallOption) (*MsgSetPauseStatusResponse, error) { - out := new(MsgSetPauseStatusResponse) - err := c.cc.Invoke(ctx, "/kava.issuance.v1beta1.Msg/SetPauseStatus", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // IssueTokens message type used by the issuer to issue new tokens - IssueTokens(context.Context, *MsgIssueTokens) (*MsgIssueTokensResponse, error) - // RedeemTokens message type used by the issuer to redeem (burn) tokens - RedeemTokens(context.Context, *MsgRedeemTokens) (*MsgRedeemTokensResponse, error) - // BlockAddress message type used by the issuer to block an address from holding or transferring tokens - BlockAddress(context.Context, *MsgBlockAddress) (*MsgBlockAddressResponse, error) - // UnblockAddress message type used by the issuer to unblock an address from holding or transferring tokens - UnblockAddress(context.Context, *MsgUnblockAddress) (*MsgUnblockAddressResponse, error) - // SetPauseStatus message type used to pause or unpause status - SetPauseStatus(context.Context, *MsgSetPauseStatus) (*MsgSetPauseStatusResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) IssueTokens(ctx context.Context, req *MsgIssueTokens) (*MsgIssueTokensResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method IssueTokens not implemented") -} -func (*UnimplementedMsgServer) RedeemTokens(ctx context.Context, req *MsgRedeemTokens) (*MsgRedeemTokensResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RedeemTokens not implemented") -} -func (*UnimplementedMsgServer) BlockAddress(ctx context.Context, req *MsgBlockAddress) (*MsgBlockAddressResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method BlockAddress not implemented") -} -func (*UnimplementedMsgServer) UnblockAddress(ctx context.Context, req *MsgUnblockAddress) (*MsgUnblockAddressResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UnblockAddress not implemented") -} -func (*UnimplementedMsgServer) SetPauseStatus(ctx context.Context, req *MsgSetPauseStatus) (*MsgSetPauseStatusResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SetPauseStatus not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_IssueTokens_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgIssueTokens) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).IssueTokens(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.issuance.v1beta1.Msg/IssueTokens", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).IssueTokens(ctx, req.(*MsgIssueTokens)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_RedeemTokens_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgRedeemTokens) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).RedeemTokens(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.issuance.v1beta1.Msg/RedeemTokens", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).RedeemTokens(ctx, req.(*MsgRedeemTokens)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_BlockAddress_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgBlockAddress) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).BlockAddress(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.issuance.v1beta1.Msg/BlockAddress", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).BlockAddress(ctx, req.(*MsgBlockAddress)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_UnblockAddress_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgUnblockAddress) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).UnblockAddress(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.issuance.v1beta1.Msg/UnblockAddress", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).UnblockAddress(ctx, req.(*MsgUnblockAddress)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_SetPauseStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgSetPauseStatus) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).SetPauseStatus(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.issuance.v1beta1.Msg/SetPauseStatus", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).SetPauseStatus(ctx, req.(*MsgSetPauseStatus)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.issuance.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "IssueTokens", - Handler: _Msg_IssueTokens_Handler, - }, - { - MethodName: "RedeemTokens", - Handler: _Msg_RedeemTokens_Handler, - }, - { - MethodName: "BlockAddress", - Handler: _Msg_BlockAddress_Handler, - }, - { - MethodName: "UnblockAddress", - Handler: _Msg_UnblockAddress_Handler, - }, - { - MethodName: "SetPauseStatus", - Handler: _Msg_SetPauseStatus_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/issuance/v1beta1/tx.proto", -} - -func (m *MsgIssueTokens) 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 *MsgIssueTokens) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgIssueTokens) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Receiver) > 0 { - i -= len(m.Receiver) - copy(dAtA[i:], m.Receiver) - i = encodeVarintTx(dAtA, i, uint64(len(m.Receiver))) - i-- - dAtA[i] = 0x1a - } - { - size, err := m.Tokens.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgIssueTokensResponse) 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 *MsgIssueTokensResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgIssueTokensResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgRedeemTokens) 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 *MsgRedeemTokens) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgRedeemTokens) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Tokens.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgRedeemTokensResponse) 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 *MsgRedeemTokensResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgRedeemTokensResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgBlockAddress) 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 *MsgBlockAddress) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgBlockAddress) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.BlockedAddress) > 0 { - i -= len(m.BlockedAddress) - copy(dAtA[i:], m.BlockedAddress) - i = encodeVarintTx(dAtA, i, uint64(len(m.BlockedAddress))) - i-- - dAtA[i] = 0x1a - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintTx(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgBlockAddressResponse) 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 *MsgBlockAddressResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgBlockAddressResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgUnblockAddress) 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 *MsgUnblockAddress) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUnblockAddress) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.BlockedAddress) > 0 { - i -= len(m.BlockedAddress) - copy(dAtA[i:], m.BlockedAddress) - i = encodeVarintTx(dAtA, i, uint64(len(m.BlockedAddress))) - i-- - dAtA[i] = 0x1a - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintTx(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgUnblockAddressResponse) 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 *MsgUnblockAddressResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUnblockAddressResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgSetPauseStatus) 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 *MsgSetPauseStatus) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSetPauseStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Status { - i-- - if m.Status { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x18 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintTx(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgSetPauseStatusResponse) 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 *MsgSetPauseStatusResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSetPauseStatusResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgIssueTokens) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Tokens.Size() - n += 1 + l + sovTx(uint64(l)) - l = len(m.Receiver) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgIssueTokensResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgRedeemTokens) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Tokens.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgRedeemTokensResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgBlockAddress) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.BlockedAddress) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgBlockAddressResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgUnblockAddress) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.BlockedAddress) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgUnblockAddressResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgSetPauseStatus) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.Status { - n += 2 - } - return n -} - -func (m *MsgSetPauseStatusResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgIssueTokens) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgIssueTokens: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgIssueTokens: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Tokens", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Tokens.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Receiver", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Receiver = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgIssueTokensResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgIssueTokensResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgIssueTokensResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgRedeemTokens) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgRedeemTokens: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgRedeemTokens: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Tokens", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Tokens.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgRedeemTokensResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgRedeemTokensResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgRedeemTokensResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgBlockAddress) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgBlockAddress: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgBlockAddress: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BlockedAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.BlockedAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgBlockAddressResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgBlockAddressResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgBlockAddressResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgUnblockAddress) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgUnblockAddress: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUnblockAddress: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BlockedAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.BlockedAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgUnblockAddressResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgUnblockAddressResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUnblockAddressResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgSetPauseStatus) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgSetPauseStatus: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSetPauseStatus: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Status = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgSetPauseStatusResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgSetPauseStatusResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSetPauseStatusResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/kavadist/abci.go b/x/kavadist/abci.go deleted file mode 100644 index dbe53d41..00000000 --- a/x/kavadist/abci.go +++ /dev/null @@ -1,20 +0,0 @@ -package kavadist - -import ( - "time" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/kavadist/keeper" - "github.com/kava-labs/kava/x/kavadist/types" -) - -func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - - err := k.MintPeriodInflation(ctx) - if err != nil { - panic(err) - } -} diff --git a/x/kavadist/client/cli/query.go b/x/kavadist/client/cli/query.go deleted file mode 100644 index 5316113f..00000000 --- a/x/kavadist/client/cli/query.go +++ /dev/null @@ -1,81 +0,0 @@ -package cli - -import ( - "context" - "fmt" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - - "github.com/kava-labs/kava/x/kavadist/types" -) - -// GetQueryCmd returns the cli query commands for this module -func GetQueryCmd() *cobra.Command { - // Group kavadist 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( - queryParamsCmd(), - queryBalanceCmd(), - ) - - return cmd -} - -func queryParamsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "params", - Short: "get the kavadist module parameters", - Long: "Get the current global kavadist module parameters.", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(cliCtx) - res, err := queryClient.Params(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - return cliCtx.PrintProto(&res.Params) - }, - } - flags.AddQueryFlagsToCmd(cmd) - return cmd -} - -func queryBalanceCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "balance", - Short: "get the kavadist module balance", - Long: "Get the current kavadist module account balance.", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(cliCtx) - res, err := queryClient.Balance(context.Background(), &types.QueryBalanceRequest{}) - if err != nil { - return err - } - return cliCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - return cmd -} diff --git a/x/kavadist/client/cli/tx.go b/x/kavadist/client/cli/tx.go deleted file mode 100644 index b226d27f..00000000 --- a/x/kavadist/client/cli/tx.go +++ /dev/null @@ -1,91 +0,0 @@ -package cli - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/cosmos/cosmos-sdk/version" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - "github.com/kava-labs/kava/x/kavadist/types" -) - -// GetCmdSubmitProposal implements the command to submit a community-pool multi-spend proposal -func GetCmdSubmitProposal() *cobra.Command { - cmd := &cobra.Command{ - Use: "community-pool-multi-spend [proposal-file]", - Args: cobra.ExactArgs(1), - Short: "Submit a community pool multi-spend proposal", - Long: strings.TrimSpace( - fmt.Sprintf(`Submit a community pool multi-spend proposal along with an initial deposit. -The proposal details must be supplied via a JSON file. - -Example: -$ %s tx gov submit-proposal community-pool-multi-spend --from= - -Where proposal.json contains: - -{ - "title": "Community Pool Multi-Spend", - "description": "Pay many users some KAVA!", - "recipient_list": [ - { - "address": "kava1mz2003lathm95n5vnlthmtfvrzrjkrr53j4464", - "amount": [ - { - "denom": "ukava", - "amount": "1000000" - } - ] - }, - { - "address": "kava1zqezafa0luyetvtj8j67g336vaqtuudnsjq7vm", - "amount": [ - { - "denom": "ukava", - "amount": "1000000" - } - ] - } - ], - "deposit": [ - { - "denom": "ukava", - "amount": "1000000000" - } - ] -} -`, - version.AppName, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - proposal, err := ParseCommunityPoolMultiSpendProposalJSON(clientCtx.Codec, args[0]) - if err != nil { - return err - } - - from := clientCtx.GetFromAddress() - content := types.NewCommunityPoolMultiSpendProposal(proposal.Title, proposal.Description, proposal.RecipientList) - msg, err := govv1beta1.NewMsgSubmitProposal(content, proposal.Deposit, from) - if err != nil { - return err - } - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - return cmd -} diff --git a/x/kavadist/client/cli/utils.go b/x/kavadist/client/cli/utils.go deleted file mode 100644 index 3159065c..00000000 --- a/x/kavadist/client/cli/utils.go +++ /dev/null @@ -1,24 +0,0 @@ -package cli - -import ( - "io/ioutil" - - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/kava-labs/kava/x/kavadist/types" -) - -// ParseCommunityPoolMultiSpendProposalJSON reads and parses a CommunityPoolMultiSpendProposalJSON from a file. -func ParseCommunityPoolMultiSpendProposalJSON(cdc codec.JSONCodec, proposalFile string) (types.CommunityPoolMultiSpendProposalJSON, error) { - proposal := types.CommunityPoolMultiSpendProposalJSON{} - contents, err := ioutil.ReadFile(proposalFile) - if err != nil { - return proposal, err - } - - if err := cdc.UnmarshalJSON(contents, &proposal); err != nil { - return proposal, err - } - - return proposal, nil -} diff --git a/x/kavadist/client/proposal_handler.go b/x/kavadist/client/proposal_handler.go deleted file mode 100644 index cadeaa21..00000000 --- a/x/kavadist/client/proposal_handler.go +++ /dev/null @@ -1,12 +0,0 @@ -package client - -import ( - govclient "github.com/cosmos/cosmos-sdk/x/gov/client" - - "github.com/kava-labs/kava/x/kavadist/client/cli" -) - -// community-pool multi-spend proposal handler -var ( - ProposalHandler = govclient.NewProposalHandler(cli.GetCmdSubmitProposal) -) diff --git a/x/kavadist/genesis.go b/x/kavadist/genesis.go deleted file mode 100644 index 78079bef..00000000 --- a/x/kavadist/genesis.go +++ /dev/null @@ -1,49 +0,0 @@ -package kavadist - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/kavadist/keeper" - "github.com/kava-labs/kava/x/kavadist/types" -) - -// InitGenesis initializes the store state from a genesis state. -func InitGenesis(ctx sdk.Context, k keeper.Keeper, accountKeeper types.AccountKeeper, gs *types.GenesisState) { - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - k.SetParams(ctx, gs.Params) - - // only set the previous block time if it's different than default - if !gs.PreviousBlockTime.Equal(types.DefaultPreviousBlockTime) { - k.SetPreviousBlockTime(ctx, gs.PreviousBlockTime) - } - - // check if the module account exists - moduleAcc := accountKeeper.GetModuleAccount(ctx, types.KavaDistMacc) - if moduleAcc == nil { - panic(fmt.Sprintf("%s module account has not been set", types.KavaDistMacc)) - } - - // check if the fund account exists - fundModuleAcc := accountKeeper.GetModuleAccount(ctx, types.FundModuleAccount) - if fundModuleAcc == nil { - panic(fmt.Sprintf("%s module account has not been set", types.FundModuleAccount)) - } -} - -// ExportGenesis export genesis state for cdp module -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { - params := k.GetParams(ctx) - previousBlockTime, found := k.GetPreviousBlockTime(ctx) - if !found { - previousBlockTime = types.DefaultPreviousBlockTime - } - return &types.GenesisState{ - Params: params, - PreviousBlockTime: previousBlockTime, - } -} diff --git a/x/kavadist/genesis_test.go b/x/kavadist/genesis_test.go deleted file mode 100644 index 171a4fee..00000000 --- a/x/kavadist/genesis_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package kavadist_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - tmtime "github.com/cometbft/cometbft/types/time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/kavadist" - testutil "github.com/kava-labs/kava/x/kavadist/testutil" - "github.com/kava-labs/kava/x/kavadist/types" -) - -type genesisTestSuite struct { - testutil.Suite -} - -func (suite *genesisTestSuite) TestInitGenesis_ValidationPanic() { - invalidState := types.NewGenesisState( - types.Params{ - Active: true, - Periods: []types.Period{ - { - Start: time.Date(2021, 1, 1, 1, 1, 1, 1, time.UTC), - End: tmtime.Canonical(time.Unix(1, 0)), - Inflation: sdk.OneDec(), - }, - }, - }, - tmtime.Canonical(time.Unix(1, 0)), - ) - - suite.Require().Panics(func() { - kavadist.InitGenesis(suite.Ctx, suite.Keeper, suite.AccountKeeper, invalidState) - }, "expected init genesis to panic with invalid state") -} - -func (suite *genesisTestSuite) TestInitAndExportGenesis() { - state := types.NewGenesisState( - types.Params{ - Active: true, - Periods: []types.Period{ - { - Start: time.Date(2021, 1, 1, 1, 1, 1, 1, time.UTC), - End: time.Date(2021, 2, 1, 1, 1, 1, 1, time.UTC), - Inflation: sdk.OneDec(), - }, - }, - }, - time.Date(2020, 1, 2, 1, 1, 1, 1, time.UTC), - ) - - kavadist.InitGenesis(suite.Ctx, suite.Keeper, suite.AccountKeeper, state) - suite.Require().Equal(state.Params, suite.Keeper.GetParams(suite.Ctx)) - - exportedState := kavadist.ExportGenesis(suite.Ctx, suite.Keeper) - suite.Require().Equal(state, exportedState) -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(genesisTestSuite)) -} diff --git a/x/kavadist/handler.go b/x/kavadist/handler.go deleted file mode 100644 index decad8ea..00000000 --- a/x/kavadist/handler.go +++ /dev/null @@ -1,23 +0,0 @@ -package kavadist - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - "github.com/kava-labs/kava/x/kavadist/keeper" - "github.com/kava-labs/kava/x/kavadist/types" -) - -// NewCommunityPoolMultiSpendProposalHandler -func NewCommunityPoolMultiSpendProposalHandler(k keeper.Keeper) govv1beta1.Handler { - return func(ctx sdk.Context, content govv1beta1.Content) error { - switch c := content.(type) { - case *types.CommunityPoolMultiSpendProposal: - return keeper.HandleCommunityPoolMultiSpendProposal(ctx, k, c) - default: - return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized kavadist proposal content type: %T", c) - } - } -} diff --git a/x/kavadist/keeper/grpc_query.go b/x/kavadist/keeper/grpc_query.go deleted file mode 100644 index 6c9426eb..00000000 --- a/x/kavadist/keeper/grpc_query.go +++ /dev/null @@ -1,34 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/kavadist/types" -) - -type queryServer struct { - keeper Keeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -var _ types.QueryServer = queryServer{} - -func (s queryServer) Balance(ctx context.Context, req *types.QueryBalanceRequest) (*types.QueryBalanceResponse, error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) - acc := s.keeper.accountKeeper.GetModuleAccount(sdkCtx, types.KavaDistMacc) - balance := s.keeper.bankKeeper.GetAllBalances(sdkCtx, acc.GetAddress()) - return &types.QueryBalanceResponse{Coins: balance}, nil -} - -func (s queryServer) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) - params := s.keeper.GetParams(sdkCtx) - - return &types.QueryParamsResponse{Params: params}, nil -} diff --git a/x/kavadist/keeper/grpc_query_test.go b/x/kavadist/keeper/grpc_query_test.go deleted file mode 100644 index 8dec832f..00000000 --- a/x/kavadist/keeper/grpc_query_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package keeper_test - -import ( - "context" - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/kavadist/types" -) - -func (suite *keeperTestSuite) TestGRPCParams() { - ctx, keeper, queryClient := suite.Ctx, suite.Keeper, suite.QueryClient - - var ( - params types.Params - req *types.QueryParamsRequest - expParams types.Params - ) - - testCases := []struct { - msg string - malleate func() - expPass bool - }{ - { - "response with default params", - func() { - expParams = types.DefaultParams() - keeper.SetParams(ctx, expParams) - req = &types.QueryParamsRequest{} - }, - true, - }, - { - "response with params", - func() { - params = types.Params{ - Active: true, - Periods: suite.TestPeriods, - } - keeper.SetParams(ctx, params) - req = &types.QueryParamsRequest{} - expParams = params - }, - true, - }, - } - - for _, testCase := range testCases { - suite.Run(fmt.Sprintf("Case %s", testCase.msg), func() { - testCase.malleate() - - paramsRes, err := queryClient.Params(context.Background(), req) - - if testCase.expPass { - suite.Require().NoError(err) - suite.Require().NotNil(paramsRes) - suite.Require().True(expParams.Equal(paramsRes.Params)) - } else { - suite.Require().Error(err) - } - }) - } -} - -func (suite *keeperTestSuite) TestGRPCBalance() { - ctx, queryClient := suite.Ctx, suite.QueryClient - - var ( - req *types.QueryBalanceRequest - expCoins sdk.Coins - ) - - testCases := []struct { - msg string - malleate func() - expPass bool - }{ - { - "response with no balance", - func() { - expCoins = sdk.Coins{} - req = &types.QueryBalanceRequest{} - }, - true, - }, - { - "response with balance", - func() { - expCoins = sdk.Coins{ - sdk.NewCoin("ukava", sdkmath.NewInt(100)), - } - suite.App.FundModuleAccount(ctx, types.ModuleName, expCoins) - req = &types.QueryBalanceRequest{} - }, - true, - }, - } - - for _, testCase := range testCases { - suite.Run(fmt.Sprintf("Case %s", testCase.msg), func() { - testCase.malleate() - - res, err := queryClient.Balance(context.Background(), req) - - if testCase.expPass { - suite.Require().NoError(err) - suite.Require().True(expCoins.IsEqual(res.Coins)) - } else { - suite.Require().Error(err) - } - }) - } -} diff --git a/x/kavadist/keeper/infrastructure.go b/x/kavadist/keeper/infrastructure.go deleted file mode 100644 index 0445d662..00000000 --- a/x/kavadist/keeper/infrastructure.go +++ /dev/null @@ -1,101 +0,0 @@ -package keeper - -import ( - "fmt" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/kavadist/types" -) - -func (k Keeper) mintInfrastructurePeriods(ctx sdk.Context, periods types.Periods, previousBlockTime time.Time) (sdk.Coin, sdkmath.Int, error) { - var err error - coinsMinted := sdk.NewCoin(types.GovDenom, sdk.ZeroInt()) - timeElapsed := sdk.ZeroInt() - for _, period := range periods { - switch { - // Case 1 - period is fully expired - case period.End.Before(previousBlockTime): - continue - - // Case 2 - period has ended since the previous block time - case period.End.After(previousBlockTime) && (period.End.Before(ctx.BlockTime()) || period.End.Equal(ctx.BlockTime())): - // calculate time elapsed relative to the periods end time - timeElapsed = sdkmath.NewInt(period.End.Unix() - previousBlockTime.Unix()) - coins, errI := k.mintInflationaryCoins(ctx, period.Inflation, timeElapsed, types.GovDenom) - err = errI - if !coins.IsZero() { - coinsMinted = coinsMinted.Add(coins) - } - // update the value of previousBlockTime so that the next period starts from the end of the last - // period and not the original value of previousBlockTime - previousBlockTime = period.End - - // Case 3 - period is ongoing - case (period.Start.Before(previousBlockTime) || period.Start.Equal(previousBlockTime)) && period.End.After(ctx.BlockTime()): - // calculate time elapsed relative to the current block time - timeElapsed = sdkmath.NewInt(ctx.BlockTime().Unix() - previousBlockTime.Unix()) - coins, errI := k.mintInflationaryCoins(ctx, period.Inflation, timeElapsed, types.GovDenom) - if !coins.IsZero() { - coinsMinted = coinsMinted.Add(coins) - } - err = errI - - // Case 4 - period hasn't started - case period.Start.After(ctx.BlockTime()) || period.Start.Equal(ctx.BlockTime()): - timeElapsed = sdkmath.NewInt(ctx.BlockTime().Unix() - previousBlockTime.Unix()) - continue - } - - if err != nil { - return sdk.Coin{}, sdkmath.Int{}, err - } - } - return coinsMinted, timeElapsed, nil -} - -func (k Keeper) distributeInfrastructureCoins(ctx sdk.Context, partnerRewards types.PartnerRewards, coreRewards types.CoreRewards, timeElapsed sdkmath.Int, coinsToDistribute sdk.Coin) error { - if timeElapsed.IsZero() { - return nil - } - if coinsToDistribute.IsZero() { - return nil - } - for _, pr := range partnerRewards { - coinsToSend := sdk.NewCoin(types.GovDenom, pr.RewardsPerSecond.Amount.Mul(timeElapsed)) - // TODO check balance, log if insufficient and return rather than error - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, pr.Address, sdk.NewCoins(coinsToSend)) - if err != nil { - return err - } - neg, updatedCoins := safeSub(coinsToDistribute, coinsToSend) - if neg { - return fmt.Errorf("negative coins") - } - coinsToDistribute = updatedCoins - } - for _, cr := range coreRewards { - coinsToSend := sdk.NewCoin(types.GovDenom, sdk.NewDecFromInt(coinsToDistribute.Amount).Mul(cr.Weight).RoundInt()) - // TODO check balance, log if insufficient and return rather than error - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, cr.Address, sdk.NewCoins(coinsToSend)) - if err != nil { - return err - } - neg, updatedCoins := safeSub(coinsToDistribute, coinsToSend) - if neg { - return fmt.Errorf("negative coins") - } - coinsToDistribute = updatedCoins - } - return nil -} - -func safeSub(a, b sdk.Coin) (bool, sdk.Coin) { - isNeg := a.IsLT(b) - if isNeg { - return true, sdk.Coin{} - } - return false, a.Sub(b) -} diff --git a/x/kavadist/keeper/keeper.go b/x/kavadist/keeper/keeper.go deleted file mode 100644 index cc324c53..00000000 --- a/x/kavadist/keeper/keeper.go +++ /dev/null @@ -1,68 +0,0 @@ -package keeper - -import ( - "time" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store/prefix" - 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/kava-labs/kava/x/kavadist/types" -) - -// Keeper keeper for the cdp module -type Keeper struct { - key storetypes.StoreKey - cdc codec.BinaryCodec - paramSubspace paramtypes.Subspace - bankKeeper types.BankKeeper - distKeeper types.DistKeeper - accountKeeper types.AccountKeeper - - blacklistedAddrs map[string]bool -} - -// NewKeeper creates a new keeper -func NewKeeper( - cdc codec.BinaryCodec, key storetypes.StoreKey, paramstore paramtypes.Subspace, bk types.BankKeeper, ak types.AccountKeeper, - dk types.DistKeeper, blacklistedAddrs map[string]bool, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - key: key, - cdc: cdc, - paramSubspace: paramstore, - bankKeeper: bk, - distKeeper: dk, - accountKeeper: ak, - blacklistedAddrs: blacklistedAddrs, - } -} - -// GetPreviousBlockTime get the blocktime for the previous block -func (k Keeper) GetPreviousBlockTime(ctx sdk.Context) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousBlockTimeKey) - b := store.Get(types.PreviousBlockTimeKey) - if b == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(b); err != nil { - return time.Time{}, false - } - return blockTime, true -} - -// SetPreviousBlockTime set the time of the previous block -func (k Keeper) SetPreviousBlockTime(ctx sdk.Context, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousBlockTimeKey) - b, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set(types.PreviousBlockTimeKey, b) -} diff --git a/x/kavadist/keeper/keeper_test.go b/x/kavadist/keeper/keeper_test.go deleted file mode 100644 index 92ce928f..00000000 --- a/x/kavadist/keeper/keeper_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/x/kavadist/testutil" -) - -type keeperTestSuite struct { - testutil.Suite -} - -func (suite *keeperTestSuite) SetupTest() { - suite.Suite.SetupTest() -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(keeperTestSuite)) -} - -func (suite *keeperTestSuite) TestSetAndGetPreviousBlockTime() { - newTime := time.Date(2020, time.March, 1, 1, 0, 0, 0, time.UTC) - suite.Keeper.SetPreviousBlockTime(suite.Ctx, newTime) - blockTime, found := suite.Keeper.GetPreviousBlockTime(suite.Ctx) - suite.Require().True(found) - suite.Require().Equal(newTime, blockTime) -} diff --git a/x/kavadist/keeper/mint.go b/x/kavadist/keeper/mint.go deleted file mode 100644 index e9a20ca5..00000000 --- a/x/kavadist/keeper/mint.go +++ /dev/null @@ -1,113 +0,0 @@ -package keeper - -import ( - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/kavadist/types" -) - -// MintPeriodInflation mints new tokens according to the inflation schedule specified in the parameters -func (k Keeper) MintPeriodInflation(ctx sdk.Context) error { - params := k.GetParams(ctx) - if !params.Active { - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeKavaDist, - sdk.NewAttribute(types.AttributeKeyStatus, types.AttributeValueInactive), - ), - ) - return nil - } - - previousBlockTime, found := k.GetPreviousBlockTime(ctx) - if !found { - previousBlockTime = ctx.BlockTime() - k.SetPreviousBlockTime(ctx, previousBlockTime) - return nil - } - err := k.mintIncentivePeriods(ctx, params.Periods, previousBlockTime) - if err != nil { - return err - } - - coinsToDistribute, timeElapsed, err := k.mintInfrastructurePeriods(ctx, params.InfrastructureParams.InfrastructurePeriods, previousBlockTime) - if err != nil { - return err - } - - err = k.distributeInfrastructureCoins(ctx, params.InfrastructureParams.PartnerRewards, params.InfrastructureParams.CoreRewards, timeElapsed, coinsToDistribute) - if err != nil { - return err - } - k.SetPreviousBlockTime(ctx, ctx.BlockTime()) - return nil -} - -func (k Keeper) mintIncentivePeriods(ctx sdk.Context, periods types.Periods, previousBlockTime time.Time) error { - var err error - for _, period := range periods { - switch { - // Case 1 - period is fully expired - case period.End.Before(previousBlockTime): - continue - - // Case 2 - period has ended since the previous block time - case period.End.After(previousBlockTime) && (period.End.Before(ctx.BlockTime()) || period.End.Equal(ctx.BlockTime())): - // calculate time elapsed relative to the periods end time - timeElapsed := sdkmath.NewInt(period.End.Unix() - previousBlockTime.Unix()) - _, err = k.mintInflationaryCoins(ctx, period.Inflation, timeElapsed, types.GovDenom) - // update the value of previousBlockTime so that the next period starts from the end of the last - // period and not the original value of previousBlockTime - previousBlockTime = period.End - - // Case 3 - period is ongoing - case (period.Start.Before(previousBlockTime) || period.Start.Equal(previousBlockTime)) && period.End.After(ctx.BlockTime()): - // calculate time elapsed relative to the current block time - timeElapsed := sdkmath.NewInt(ctx.BlockTime().Unix() - previousBlockTime.Unix()) - _, err = k.mintInflationaryCoins(ctx, period.Inflation, timeElapsed, types.GovDenom) - - // Case 4 - period hasn't started - case period.Start.After(ctx.BlockTime()) || period.Start.Equal(ctx.BlockTime()): - continue - } - - if err != nil { - return err - } - } - return nil -} - -func (k Keeper) mintInflationaryCoins(ctx sdk.Context, inflationRate sdk.Dec, timePeriods sdkmath.Int, denom string) (sdk.Coin, error) { - totalSupply := k.bankKeeper.GetSupply(ctx, denom) - // used to scale accumulator calculations by 10^18 - scalar := sdkmath.NewInt(1000000000000000000) - // convert inflation rate to integer - inflationInt := sdkmath.NewUintFromBigInt(inflationRate.Mul(sdk.NewDecFromInt(scalar)).TruncateInt().BigInt()) - timePeriodsUint := sdkmath.NewUintFromBigInt(timePeriods.BigInt()) - scalarUint := sdkmath.NewUintFromBigInt(scalar.BigInt()) - // calculate the multiplier (amount to multiply the total supply by to achieve the desired inflation) - // multiply the result by 10^-18 because RelativePow returns the result scaled by 10^18 - accumulator := sdk.NewDecFromBigInt(sdkmath.RelativePow(inflationInt, timePeriodsUint, scalarUint).BigInt()).Mul(sdk.SmallestDec()) - // calculate the number of coins to mint - amountToMint := (sdk.NewDecFromInt(totalSupply.Amount).Mul(accumulator)).Sub(sdk.NewDecFromInt(totalSupply.Amount)).TruncateInt() - if amountToMint.IsZero() { - return sdk.Coin{}, nil - } - err := k.bankKeeper.MintCoins(ctx, types.KavaDistMacc, sdk.NewCoins(sdk.NewCoin(denom, amountToMint))) - if err != nil { - return sdk.Coin{}, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeKavaDist, - sdk.NewAttribute(types.AttributeKeyInflation, sdk.NewCoin(denom, amountToMint).String()), - ), - ) - - return sdk.NewCoin(denom, amountToMint), nil -} diff --git a/x/kavadist/keeper/mint_test.go b/x/kavadist/keeper/mint_test.go deleted file mode 100644 index c58923d1..00000000 --- a/x/kavadist/keeper/mint_test.go +++ /dev/null @@ -1,408 +0,0 @@ -package keeper_test - -import ( - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/kavadist/types" -) - -func (suite *keeperTestSuite) TestMintExpiredPeriod() { - initialSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - suite.Require().NotPanics(func() { suite.Keeper.SetPreviousBlockTime(suite.Ctx, time.Date(2022, 1, 1, 0, 0, 0, 0, time.UTC)) }) - ctx := suite.Ctx.WithBlockTime(time.Date(2022, 1, 1, 0, 7, 0, 0, time.UTC)) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - finalSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - suite.Require().Equal(initialSupply, finalSupply) -} - -func (suite *keeperTestSuite) TestMintPeriodNotStarted() { - initialSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - suite.Require().NotPanics(func() { suite.Keeper.SetPreviousBlockTime(suite.Ctx, time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)) }) - ctx := suite.Ctx.WithBlockTime(time.Date(2019, 1, 1, 0, 7, 0, 0, time.UTC)) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - finalSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - suite.Require().Equal(initialSupply, finalSupply) -} - -func (suite *keeperTestSuite) TestMintOngoingPeriod() { - initialSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - suite.Require().NotPanics(func() { - suite.Keeper.SetPreviousBlockTime(suite.Ctx, time.Date(2020, time.March, 1, 1, 0, 1, 0, time.UTC)) - }) - ctx := suite.Ctx.WithBlockTime(time.Date(2021, 2, 28, 23, 59, 59, 0, time.UTC)) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - finalSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - suite.Require().True(finalSupply.Amount.GT(initialSupply.Amount)) - mAcc := suite.AccountKeeper.GetModuleAccount(ctx, types.ModuleName) - mAccSupply := suite.BankKeeper.GetAllBalances(ctx, mAcc.GetAddress()).AmountOf(types.GovDenom) - suite.Require().True(mAccSupply.Equal(finalSupply.Amount.Sub(initialSupply.Amount))) - // expect that inflation is ~10% - expectedSupply := sdk.NewDecFromInt(initialSupply.Amount).Mul(sdk.MustNewDecFromStr("1.1")) - supplyError := sdk.OneDec().Sub((sdk.NewDecFromInt(finalSupply.Amount).Quo(expectedSupply))).Abs() - suite.Require().True(supplyError.LTE(sdk.MustNewDecFromStr("0.001"))) -} - -func (suite *keeperTestSuite) TestMintPeriodTransition() { - initialSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - params := suite.Keeper.GetParams(suite.Ctx) - periods := []types.Period{ - suite.TestPeriods[0], - { - Start: time.Date(2021, time.March, 1, 1, 0, 0, 0, time.UTC), - End: time.Date(2022, time.March, 1, 1, 0, 0, 0, time.UTC), - Inflation: sdk.MustNewDecFromStr("1.000000003022265980"), - }, - } - params.Periods = periods - suite.Require().NotPanics(func() { - suite.Keeper.SetParams(suite.Ctx, params) - }) - suite.Require().NotPanics(func() { - suite.Keeper.SetPreviousBlockTime(suite.Ctx, time.Date(2020, time.March, 1, 1, 0, 1, 0, time.UTC)) - }) - ctx := suite.Ctx.WithBlockTime(time.Date(2021, 3, 10, 0, 0, 0, 0, time.UTC)) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - finalSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - suite.Require().True(finalSupply.Amount.GT(initialSupply.Amount)) -} - -func (suite *keeperTestSuite) TestMintNotActive() { - initialSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - params := suite.Keeper.GetParams(suite.Ctx) - params.Active = false - suite.Require().NotPanics(func() { - suite.Keeper.SetParams(suite.Ctx, params) - }) - suite.Require().NotPanics(func() { - suite.Keeper.SetPreviousBlockTime(suite.Ctx, time.Date(2020, time.March, 1, 1, 0, 1, 0, time.UTC)) - }) - ctx := suite.Ctx.WithBlockTime(time.Date(2021, 2, 28, 23, 59, 59, 0, time.UTC)) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - finalSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - suite.Require().Equal(initialSupply, finalSupply) -} - -func (suite *keeperTestSuite) TestInfraMinting() { - type args struct { - startTime time.Time - endTime time.Time - infraPeriods types.Periods - expectedFinalSupply sdk.Coin - marginOfError sdk.Dec - } - - type errArgs struct { - expectPass bool - contains string - } - - type test struct { - name string - args args - errArgs errArgs - } - - testCases := []test{ - { - "5% apy one year", - args{ - startTime: time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), - endTime: time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), - infraPeriods: types.Periods{types.NewPeriod(time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), sdk.MustNewDecFromStr("1.000000001547125958"))}, - expectedFinalSupply: sdk.NewCoin(types.GovDenom, sdkmath.NewInt(1050000000000)), - marginOfError: sdk.MustNewDecFromStr("0.0001"), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "5% apy 10 seconds", - args{ - startTime: time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), - endTime: time.Date(2022, time.October, 1, 1, 0, 10, 0, time.UTC), - infraPeriods: types.Periods{types.NewPeriod(time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), sdk.MustNewDecFromStr("1.000000001547125958"))}, - expectedFinalSupply: sdk.NewCoin(types.GovDenom, sdkmath.NewInt(1000000015471)), - marginOfError: sdk.MustNewDecFromStr("0.0001"), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - } - - for _, tc := range testCases { - suite.SetupTest() - params := types.NewParams(true, types.DefaultPeriods, types.NewInfraParams(tc.args.infraPeriods, types.DefaultInfraParams.PartnerRewards, types.DefaultInfraParams.CoreRewards)) - ctx := suite.Ctx.WithBlockTime(tc.args.startTime) - suite.Keeper.SetParams(ctx, params) - suite.Require().NotPanics(func() { - suite.Keeper.SetPreviousBlockTime(ctx, tc.args.startTime) - }) - - // Delete initial genesis tokens to start with a clean slate - suite.App.DeleteGenesisValidator(suite.T(), suite.Ctx) - suite.App.DeleteGenesisValidatorCoins(suite.T(), suite.Ctx) - - ctx = suite.Ctx.WithBlockTime(tc.args.endTime) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - - finalSupply := suite.BankKeeper.GetSupply(ctx, types.GovDenom) - marginHigh := sdk.NewDecFromInt(tc.args.expectedFinalSupply.Amount).Mul(sdk.OneDec().Add(tc.args.marginOfError)) - marginLow := sdk.NewDecFromInt(tc.args.expectedFinalSupply.Amount).Mul(sdk.OneDec().Sub(tc.args.marginOfError)) - suite.Require().Truef( - sdk.NewDecFromInt(finalSupply.Amount).LTE(marginHigh), - "final supply %s is not <= %s high margin", - finalSupply.Amount.String(), - marginHigh.String(), - ) - suite.Require().Truef( - sdk.NewDecFromInt(finalSupply.Amount).GTE(marginLow), - "final supply %s is not >= %s low margin", - finalSupply.Amount.String(), - ) - - } - -} - -func (suite *keeperTestSuite) TestInfraPayoutCore() { - - type args struct { - startTime time.Time - endTime time.Time - infraPeriods types.Periods - expectedFinalSupply sdk.Coin - expectedBalanceIncrease sdk.Coin - marginOfError sdk.Dec - } - - type errArgs struct { - expectPass bool - contains string - } - - type test struct { - name string - args args - errArgs errArgs - } - - testCases := []test{ - { - "5% apy one year", - args{ - startTime: time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), - endTime: time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), - infraPeriods: types.Periods{types.NewPeriod(time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), sdk.MustNewDecFromStr("1.000000001547125958"))}, - expectedFinalSupply: sdk.NewCoin(types.GovDenom, sdkmath.NewInt(1050000000000)), - expectedBalanceIncrease: sdk.NewCoin(types.GovDenom, sdkmath.NewInt(50000000000)), - marginOfError: sdk.MustNewDecFromStr("0.0001"), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - } - - for _, tc := range testCases { - suite.SetupTest() - coreReward := types.NewCoreReward(suite.Addrs[0], sdk.OneDec()) - params := types.NewParams(true, types.DefaultPeriods, types.NewInfraParams(tc.args.infraPeriods, types.DefaultInfraParams.PartnerRewards, types.CoreRewards{coreReward})) - ctx := suite.Ctx.WithBlockTime(tc.args.startTime) - suite.Keeper.SetParams(ctx, params) - suite.Require().NotPanics(func() { - suite.Keeper.SetPreviousBlockTime(ctx, tc.args.startTime) - }) - - // Delete initial genesis tokens to start with a clean slate - suite.App.DeleteGenesisValidator(suite.T(), suite.Ctx) - suite.App.DeleteGenesisValidatorCoins(suite.T(), suite.Ctx) - - initialBalance := suite.BankKeeper.GetBalance(ctx, suite.Addrs[0], types.GovDenom) - ctx = suite.Ctx.WithBlockTime(tc.args.endTime) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - finalSupply := suite.BankKeeper.GetSupply(ctx, types.GovDenom) - marginHigh := sdk.NewDecFromInt(tc.args.expectedFinalSupply.Amount).Mul(sdk.OneDec().Add(tc.args.marginOfError)) - marginLow := sdk.NewDecFromInt(tc.args.expectedFinalSupply.Amount).Mul(sdk.OneDec().Sub(tc.args.marginOfError)) - suite.Require().True(sdk.NewDecFromInt(finalSupply.Amount).LTE(marginHigh)) - suite.Require().True(sdk.NewDecFromInt(finalSupply.Amount).GTE(marginLow)) - - finalBalance := suite.BankKeeper.GetBalance(ctx, suite.Addrs[0], types.GovDenom) - suite.Require().Equal(tc.args.expectedBalanceIncrease, finalBalance.Sub(initialBalance)) - - } - -} - -func (suite *keeperTestSuite) TestInfraPayoutPartner() { - - type args struct { - startTime time.Time - endTime time.Time - infraPeriods types.Periods - expectedFinalSupply sdk.Coin - expectedBalanceIncrease sdk.Coin - marginOfError sdk.Dec - } - - type errArgs struct { - expectPass bool - contains string - } - - type test struct { - name string - args args - errArgs errArgs - } - - testCases := []test{ - { - "5% apy one year", - args{ - startTime: time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), - endTime: time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), - infraPeriods: types.Periods{types.NewPeriod(time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), sdk.MustNewDecFromStr("1.000000001547125958"))}, - expectedFinalSupply: sdk.NewCoin(types.GovDenom, sdkmath.NewInt(1050000000000)), - expectedBalanceIncrease: sdk.NewCoin(types.GovDenom, sdkmath.NewInt(63072000)), - marginOfError: sdk.MustNewDecFromStr("0.0001"), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - } - - for _, tc := range testCases { - suite.SetupTest() - partnerReward := types.NewPartnerReward(suite.Addrs[0], sdk.NewCoin(types.GovDenom, sdkmath.NewInt(2))) - params := types.NewParams(true, types.DefaultPeriods, types.NewInfraParams(tc.args.infraPeriods, types.PartnerRewards{partnerReward}, types.DefaultInfraParams.CoreRewards)) - ctx := suite.Ctx.WithBlockTime(tc.args.startTime) - suite.Keeper.SetParams(ctx, params) - suite.Require().NotPanics(func() { - suite.Keeper.SetPreviousBlockTime(ctx, tc.args.startTime) - }) - - // Delete initial genesis tokens to start with a clean slate - suite.App.DeleteGenesisValidator(suite.T(), suite.Ctx) - suite.App.DeleteGenesisValidatorCoins(suite.T(), suite.Ctx) - - initialBalance := suite.BankKeeper.GetBalance(ctx, suite.Addrs[0], types.GovDenom) - ctx = suite.Ctx.WithBlockTime(tc.args.endTime) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - finalSupply := suite.BankKeeper.GetSupply(ctx, types.GovDenom) - marginHigh := sdk.NewDecFromInt(tc.args.expectedFinalSupply.Amount).Mul(sdk.OneDec().Add(tc.args.marginOfError)) - marginLow := sdk.NewDecFromInt(tc.args.expectedFinalSupply.Amount).Mul(sdk.OneDec().Sub(tc.args.marginOfError)) - suite.Require().True(sdk.NewDecFromInt(finalSupply.Amount).LTE(marginHigh)) - suite.Require().True(sdk.NewDecFromInt(finalSupply.Amount).GTE(marginLow)) - - finalBalance := suite.BankKeeper.GetBalance(ctx, suite.Addrs[0], types.GovDenom) - suite.Require().Equal(tc.args.expectedBalanceIncrease, finalBalance.Sub(initialBalance)) - - } - -} - -func (suite *keeperTestSuite) TestInfraPayoutE2E() { - - type balance struct { - address sdk.AccAddress - amount sdk.Coins - } - - type balances []balance - - type args struct { - periods types.Periods - startTime time.Time - endTime time.Time - infraPeriods types.Periods - coreRewards types.CoreRewards - partnerRewards types.PartnerRewards - expectedFinalSupply sdk.Coin - expectedBalances balances - marginOfError sdk.Dec - } - - type errArgs struct { - expectPass bool - contains string - } - - type test struct { - name string - args args - errArgs errArgs - } - - _, addrs := app.GeneratePrivKeyAddressPairs(3) - - testCases := []test{ - { - "5% apy one year", - args{ - periods: types.Periods{types.NewPeriod(time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), sdk.MustNewDecFromStr("1.000000001547125958"))}, - startTime: time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), - endTime: time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), - infraPeriods: types.Periods{types.NewPeriod(time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), sdk.MustNewDecFromStr("1.000000001547125958"))}, - coreRewards: types.CoreRewards{types.NewCoreReward(addrs[1], sdk.OneDec())}, - partnerRewards: types.PartnerRewards{types.NewPartnerReward(addrs[2], sdk.NewCoin("ukava", sdkmath.NewInt(2)))}, - expectedFinalSupply: sdk.NewCoin(types.GovDenom, sdkmath.NewInt(1102500000000)), - expectedBalances: balances{ - balance{addrs[1], sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(52436928000)))}, - balance{addrs[2], sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(63072000)))}, - }, - marginOfError: sdk.MustNewDecFromStr("0.0001"), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - } - - for _, tc := range testCases { - suite.SetupTest() - params := types.NewParams(true, tc.args.periods, types.NewInfraParams(tc.args.infraPeriods, tc.args.partnerRewards, tc.args.coreRewards)) - ctx := suite.Ctx.WithBlockTime(tc.args.startTime) - suite.Keeper.SetParams(ctx, params) - suite.Require().NotPanics(func() { - suite.Keeper.SetPreviousBlockTime(ctx, tc.args.startTime) - }) - - // Delete initial genesis tokens to start with a clean slate - suite.App.DeleteGenesisValidator(suite.T(), suite.Ctx) - suite.App.DeleteGenesisValidatorCoins(suite.T(), suite.Ctx) - - ctx = suite.Ctx.WithBlockTime(tc.args.endTime) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - finalSupply := suite.BankKeeper.GetSupply(ctx, types.GovDenom) - marginHigh := sdk.NewDecFromInt(tc.args.expectedFinalSupply.Amount).Mul(sdk.OneDec().Add(tc.args.marginOfError)) - marginLow := sdk.NewDecFromInt(tc.args.expectedFinalSupply.Amount).Mul(sdk.OneDec().Sub(tc.args.marginOfError)) - suite.Require().True(sdk.NewDecFromInt(finalSupply.Amount).LTE(marginHigh)) - suite.Require().True(sdk.NewDecFromInt(finalSupply.Amount).GTE(marginLow)) - - for _, bal := range tc.args.expectedBalances { - finalBalance := suite.BankKeeper.GetAllBalances(ctx, bal.address) - suite.Require().Equal(bal.amount, finalBalance) - } - } -} diff --git a/x/kavadist/keeper/params.go b/x/kavadist/keeper/params.go deleted file mode 100644 index db4a3fbe..00000000 --- a/x/kavadist/keeper/params.go +++ /dev/null @@ -1,18 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/kavadist/types" -) - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { - k.paramSubspace.GetParamSet(ctx, ¶ms) - return params -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} diff --git a/x/kavadist/keeper/proposal_handler.go b/x/kavadist/keeper/proposal_handler.go deleted file mode 100644 index 3f51d539..00000000 --- a/x/kavadist/keeper/proposal_handler.go +++ /dev/null @@ -1,24 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/kava-labs/kava/x/kavadist/types" -) - -// HandleCommunityPoolMultiSpendProposal is a handler for executing a passed community multi-spend proposal -func HandleCommunityPoolMultiSpendProposal(ctx sdk.Context, k Keeper, p *types.CommunityPoolMultiSpendProposal) error { - for _, receiverInfo := range p.RecipientList { - if k.blacklistedAddrs[receiverInfo.Address] { - return errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "%s is blacklisted from receiving external funds", receiverInfo.Address) - } - err := k.distKeeper.DistributeFromFeePool(ctx, receiverInfo.Amount, receiverInfo.GetAddress()) - if err != nil { - return err - } - } - - return nil -} diff --git a/x/kavadist/keeper/proposal_handler_test.go b/x/kavadist/keeper/proposal_handler_test.go deleted file mode 100644 index fe6317ce..00000000 --- a/x/kavadist/keeper/proposal_handler_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package keeper_test - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/kavadist/keeper" - "github.com/kava-labs/kava/x/kavadist/types" -) - -func (suite *keeperTestSuite) TestHandleCommunityPoolMultiSpendProposal() { - addr, distrKeeper, ctx := suite.Addrs[0], suite.App.GetDistrKeeper(), suite.Ctx - initBalances := suite.BankKeeper.GetAllBalances(ctx, addr) - - // add coins to the module account and fund fee pool - macc := distrKeeper.GetDistributionAccount(ctx) - fundAmount := sdk.NewCoins(sdk.NewInt64Coin("ukava", 1000000)) - suite.Require().NoError(suite.App.FundModuleAccount(ctx, macc.GetName(), fundAmount)) - feePool := distrKeeper.GetFeePool(ctx) - feePool.CommunityPool = sdk.NewDecCoinsFromCoins(fundAmount...) - distrKeeper.SetFeePool(ctx, feePool) - - proposalAmount1 := int64(1100) - proposalAmount2 := int64(1200) - proposal := types.NewCommunityPoolMultiSpendProposal("test title", "description", []types.MultiSpendRecipient{ - { - Address: addr.String(), - Amount: sdk.NewCoins(sdk.NewInt64Coin("ukava", proposalAmount1)), - }, - { - Address: addr.String(), - Amount: sdk.NewCoins(sdk.NewInt64Coin("ukava", proposalAmount2)), - }, - }) - err := keeper.HandleCommunityPoolMultiSpendProposal(ctx, suite.Keeper, proposal) - suite.Require().Nil(err) - - balances := suite.BankKeeper.GetAllBalances(ctx, addr) - expected := initBalances.AmountOf("ukava").Add(sdkmath.NewInt(proposalAmount1 + proposalAmount2)) - suite.Require().Equal(expected, balances.AmountOf("ukava")) -} diff --git a/x/kavadist/module.go b/x/kavadist/module.go deleted file mode 100644 index 11d01d8b..00000000 --- a/x/kavadist/module.go +++ /dev/null @@ -1,144 +0,0 @@ -package kavadist - -import ( - "context" - "encoding/json" - "fmt" - - "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/kava-labs/kava/x/kavadist/client/cli" - "github.com/kava-labs/kava/x/kavadist/keeper" - "github.com/kava-labs/kava/x/kavadist/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// ---------------------------------------------------------------------------- -// AppModuleBasic -// ---------------------------------------------------------------------------- - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -func NewAppModuleBasic() AppModuleBasic { - return AppModuleBasic{} -} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// Registers legacy amino codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// RegisterInterfaces registers the module's interface types -func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { - types.RegisterInterfaces(reg) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) -} - -// ValidateGenesis module validate genesis -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 kavadist module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) -} - -// GetTxCmd returns kavadist module's root tx command. -func (a AppModuleBasic) GetTxCmd() *cobra.Command { return nil } - -// GetQueryCmd returns kavadist module's root query command. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -// ---------------------------------------------------------------------------- -// AppModule -// ---------------------------------------------------------------------------- - -// AppModule implements the AppModule interface for kavadist module. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper types.AccountKeeper) AppModule { - return AppModule{ - AppModuleBasic: NewAppModuleBasic(), - keeper: keeper, - accountKeeper: accountKeeper, - } -} - -// Name returns kavadist module's name. -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// RegisterServices registers a GRPC query service to respond to the -// module-specific GRPC queries. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) -} - -// RegisterInvariants registers kavadist module's invariants. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// InitGenesis performs kavadist 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 - cdc.MustUnmarshalJSON(gs, &genState) - InitGenesis(ctx, am.keeper, am.accountKeeper, &genState) - return []abci.ValidatorUpdate{} -} - -// ExportGenesis returns kavadist 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 implements ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return 1 } - -// BeginBlock executes all ABCI BeginBlock logic respective to kavadist module. -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { - BeginBlocker(ctx, am.keeper) -} - -// EndBlock executes all ABCI EndBlock logic respective to kavadist module. It -// returns no validator updates. -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/kavadist/spec/01_concepts.md b/x/kavadist/spec/01_concepts.md deleted file mode 100644 index df42d852..00000000 --- a/x/kavadist/spec/01_concepts.md +++ /dev/null @@ -1,9 +0,0 @@ - - -# Concepts - -The minting mechanism in this module is designed to allow governance to determine a set of inflationary periods and the APR rate of inflation for each period. This module mints coins each block according to the schedule such that after 1 year the APR inflation worth of coins will have been minted. Governance can alter the APR inflation using a parameter change proposal. Parameter change proposals that change the APR will take effect in the block after they pass. - -Additionally this module has parameters defining an inflationary period for minting rewards to a governance-specified list of infrastructure partners. Governance can alter the inflationary period and infrastructure reward distribution using a parameter change proposal. Parameter changes that change the distribution or inflationary period take effect the block after they pass. diff --git a/x/kavadist/spec/02_state.md b/x/kavadist/spec/02_state.md deleted file mode 100644 index abc3a0e6..00000000 --- a/x/kavadist/spec/02_state.md +++ /dev/null @@ -1,34 +0,0 @@ - - -# State - -## Parameters and Genesis State - -`Parameters` define the rate at which inflationary coins are minted and for how long inflationary periods last. - -```go -// Params governance parameters for kavadist module -type Params struct { - Active bool `json:"active" yaml:"active"` - Periods Periods `json:"periods" yaml:"periods"` -} - -// Period stores the specified start and end dates, and the inflation, expressed as a decimal representing the yearly APR of tokens that will be minted during that period -type Period struct { - Start time.Time `json:"start" yaml:"start"` // example "2020-03-01T15:20:00Z" - End time.Time `json:"end" yaml:"end"` // example "2020-06-01T15:20:00Z" - Inflation sdk.Dec `json:"inflation" yaml:"inflation"` // example "1.000000003022265980" - 10% inflation -} -``` - -`GenesisState` defines the state that must be persisted when the blockchain stops/restarts in order for normal function of the kavadist module to resume. - -```go -// GenesisState is the state that must be provided at genesis. -type GenesisState struct { - Params Params `json:"params" yaml:"params"` - PreviousBlockTime time.Time `json:"previous_block_time" yaml:"previous_block_time"` -} -``` diff --git a/x/kavadist/spec/03_messages.md b/x/kavadist/spec/03_messages.md deleted file mode 100644 index e72b7783..00000000 --- a/x/kavadist/spec/03_messages.md +++ /dev/null @@ -1,7 +0,0 @@ - - -# Messages - -There are no messages in the kavadist module. All state transitions are controlled by parameters, which can be updated via parameter change proposals. diff --git a/x/kavadist/spec/04_events.md b/x/kavadist/spec/04_events.md deleted file mode 100644 index c76d8b65..00000000 --- a/x/kavadist/spec/04_events.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# Events - -The `x/kavadist` module emits the following events: - -## BeginBlock - -| Type | Attribute Key | Attribute Value | -|----------------------|---------------------|-----------------| -| kavadist | kava_dist_inflation | `{amount}` | -| kavadist | kava_dist_status | "inactive" | diff --git a/x/kavadist/spec/05_params.md b/x/kavadist/spec/05_params.md deleted file mode 100644 index 3860bc94..00000000 --- a/x/kavadist/spec/05_params.md +++ /dev/null @@ -1,43 +0,0 @@ - - -# Parameters - -The kavadist module has the following parameters: - -| Key | Type | Example | Description | -| -------------------- | -------------------- | ------------- | -------------------------------------------------------- | -| Active | bool | true | an all-or-nothing toggle of token minting in this module | -| Periods | array (Period) | [{see below}] | array of params for each inflationary period | -| InfrastructureParams | InfrastructureParams | [{see below}] | object containing infrastructure partner payout params | - -`InfrastructureParams` has the following parameters - -| Key | Type | Example | Description | -| --------------------- | --------------------- | ------------- | ----------------------------------------------------------- | -| InfrastructurePeriods | array (Period) | [{see below}] | array of params for each inflationary period | -| CoreRewards | array (CoreReward) | [{see below}] | array of params for reward weights for core infra providers | -| PartnerRewards | array (PartnerReward) | [{see below}] | array of params for infrastructure partner reward schedules | - -Each `Period` has the following parameters - -| Key | Type | Example | Description | -| --------- | --------- | ---------------------- | --------------------------------------- | -| Start | time.Time | "2020-03-01T15:20:00Z" | the time when the period will start | -| End | time.Time | "2020-06-01T15:20:00Z" | the time when the period will end | -| Inflation | sdk.Dec | "1.000000003022265980" | the per-second inflation for the period | - -Each `CoreReward` has the following properties - -| Key | Type | Example | Description | -| ------- | -------------- | --------------------------------------------- | -------------------------------------------------------- | -| Address | sdk.AccAddress | "kava1x07eng0q9027j7wayap8nvqegpf625uu0w90tq" | address of core infrastructure provider | -| Weight | sdk.Dec | "0.912345678907654321" | % of remaining minted rewards allocated to this provider | - -Each `PartnerReward` has the following properties - -| Key | Type | Example | Description | -| ---------------- | -------------- | --------------------------------------------- | ---------------------------------- | -| Address | sdk.AccAddress | "kava1x0cztstumgcfrw69s5nd5qtu9vdcg7alqtyhgr" | address of infrastructure partner | -| RewardsPerSecond | object (coin) | {"denom": "ukava", "amount": "1285" } | per second reward for this partner | diff --git a/x/kavadist/spec/06_begin_block.md b/x/kavadist/spec/06_begin_block.md deleted file mode 100644 index 783116cd..00000000 --- a/x/kavadist/spec/06_begin_block.md +++ /dev/null @@ -1,30 +0,0 @@ - - -# Begin Block - -At the start of each block, the inflationary coins for the ongoing period, if any, are minted. The logic is as follows: - -```go - func BeginBlocker(ctx sdk.Context, k Keeper) { - err := k.MintPeriodInflation(ctx) - if err != nil { - panic(err) - } - } -``` - -## Inflationary Coin Minting - -The `MintPeriodInflation` method mints inflationary coins for the two schedules defined in the parameters when `params.Active` is `true`. Coins are minted based off the number of seconds passed since the last block. When `params.Active` is `false`, the method is a no-op. - -Firstly, it mints coins at a per second rate derived from `params.Periods`. The coins are minted into `x/kavadist`'s module account. - -Next, it mints coins for infrastructure partner rewards at a per second rate derived from `params.InfrastructureParams.InfrastructurePeriods`. The coins are minted to the module account but are then immediately distributed to the infrastructure partners. - -## Infrastructure Partner Reward Distribution - -The coins minted for the `InfrastructurePeriods` are distributed as follows: -* A distribution is made to each of the infrastructure partners based on the number of seconds since the last distribution for each of the defined `params.InfrastructureParams.PartnerRewards`. -* The remaining coins are distributed to the core infrastructure providers by the weights defined in `params.InfrastructureParams.CoreRewards`. diff --git a/x/kavadist/spec/README.md b/x/kavadist/spec/README.md deleted file mode 100644 index 63c57d9e..00000000 --- a/x/kavadist/spec/README.md +++ /dev/null @@ -1,20 +0,0 @@ - - -# `kavadist` - - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** -5. **[Params](05_params.md)** -6. **[BeginBlock](06_begin_block.md)** - -## Abstract - -`x/kavadist` is an implementation of a Cosmos SDK Module that allows for governance controlled minting of coins into a module account. Coins are minted during inflationary periods, for which each period has a governance specified APR and duration. Additionally, coin rewards for governance specified infrastructure partners are minted and distributed. diff --git a/x/kavadist/testutil/suite.go b/x/kavadist/testutil/suite.go deleted file mode 100644 index 58a001da..00000000 --- a/x/kavadist/testutil/suite.go +++ /dev/null @@ -1,82 +0,0 @@ -package testutil - -import ( - "fmt" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - accountkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/kavadist/keeper" - "github.com/kava-labs/kava/x/kavadist/types" -) - -// Suite implements a test suite for the kavadist module integration tests -type Suite struct { - suite.Suite - - Keeper keeper.Keeper - BankKeeper bankkeeper.Keeper - AccountKeeper accountkeeper.AccountKeeper - App app.TestApp - Ctx sdk.Context - TestPeriods []types.Period - Addrs []sdk.AccAddress - QueryClient types.QueryClient -} - -// SetupTest instantiates a new app, keepers, and sets suite state -func (suite *Suite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - tApp := app.NewTestApp() - _, addrs := app.GeneratePrivKeyAddressPairs(1) - coins := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000000000000))) - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) - - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - testPeriods := []types.Period{ - { - Start: time.Date(2020, time.March, 1, 1, 0, 0, 0, time.UTC), - End: time.Date(2021, time.March, 1, 1, 0, 0, 0, time.UTC), - Inflation: sdk.MustNewDecFromStr("1.000000003022265980"), - }, - } - params := types.NewParams(true, testPeriods, types.DefaultInfraParams) - moduleGs := types.ModuleCdc.MustMarshalJSON(types.NewGenesisState(params, types.DefaultPreviousBlockTime)) - gs := app.GenesisState{types.ModuleName: moduleGs} - suite.App = tApp.InitializeFromGenesisStates(authGS, gs) - suite.Ctx = ctx - suite.Addrs = addrs - suite.Keeper = tApp.GetKavadistKeeper() - suite.BankKeeper = tApp.GetBankKeeper() - suite.AccountKeeper = tApp.GetAccountKeeper() - suite.TestPeriods = testPeriods - - // Set query client - queryHelper := tApp.NewQueryServerTestHelper(ctx) - types.RegisterQueryServer(queryHelper, keeper.NewQueryServerImpl(suite.Keeper)) - suite.QueryClient = types.NewQueryClient(queryHelper) -} - -// CreateAccount creates a new account with the provided balance -func (suite *Suite) CreateAccount(initialBalance sdk.Coins) authtypes.AccountI { - _, addrs := app.GeneratePrivKeyAddressPairs(1) - fmt.Println(addrs[0].String()) - acc := suite.AccountKeeper.NewAccountWithAddress(suite.Ctx, addrs[0]) - suite.AccountKeeper.SetAccount(suite.Ctx, acc) - suite.Require().NoError(suite.App.FundAccount(suite.Ctx, addrs[0], initialBalance)) - suite.AccountKeeper.SetAccount(suite.Ctx, acc) - return acc -} diff --git a/x/kavadist/types/codec.go b/x/kavadist/types/codec.go deleted file mode 100644 index 10685c24..00000000 --- a/x/kavadist/types/codec.go +++ /dev/null @@ -1,37 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -// RegisterLegacyAminoCodec registers the necessary kavadist interfaces and concrete types -// on the provided LegacyAmino codec. These types are used for Amino JSON serialization. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&CommunityPoolMultiSpendProposal{}, "kava/CommunityPoolMultiSpendProposal", nil) -} - -func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { - registry.RegisterImplementations( - (*govv1beta1.Content)(nil), - &CommunityPoolMultiSpendProposal{}, - ) -} - -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - amino.Seal() - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/kavadist/types/errors.go b/x/kavadist/types/errors.go deleted file mode 100644 index b0ab3910..00000000 --- a/x/kavadist/types/errors.go +++ /dev/null @@ -1,9 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// x/kavadist errors -var ( - ErrInvalidProposalAmount = errorsmod.Register(ModuleName, 2, "invalid community pool multi-spend proposal amount") - ErrEmptyProposalRecipient = errorsmod.Register(ModuleName, 3, "invalid community pool multi-spend proposal recipient") -) diff --git a/x/kavadist/types/events.go b/x/kavadist/types/events.go deleted file mode 100644 index 3391bd73..00000000 --- a/x/kavadist/types/events.go +++ /dev/null @@ -1,8 +0,0 @@ -package types - -const ( - EventTypeKavaDist = ModuleName - AttributeKeyInflation = "kava_dist_inflation" - AttributeKeyStatus = "kava_dist_status" - AttributeValueInactive = "inactive" -) diff --git a/x/kavadist/types/expected_keepers.go b/x/kavadist/types/expected_keepers.go deleted file mode 100644 index e78d3d9f..00000000 --- a/x/kavadist/types/expected_keepers.go +++ /dev/null @@ -1,26 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - authTypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// DistKeeper defines the expected distribution keeper interface -type DistKeeper interface { - DistributeFromFeePool(ctx sdk.Context, amount sdk.Coins, receiveAddr sdk.AccAddress) error -} - -// AccountKeeper defines the expected account keeper interface -type AccountKeeper interface { - GetModuleAccount(ctx sdk.Context, moduleName string) authTypes.ModuleAccountI - SetModuleAccount(ctx sdk.Context, macc authTypes.ModuleAccountI) - NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) authTypes.AccountI -} - -// BankKeeper defines the expected bank keeper interface -type BankKeeper interface { - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - MintCoins(ctx sdk.Context, moduleName string, amounts sdk.Coins) error - GetSupply(ctx sdk.Context, denom string) sdk.Coin - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error -} diff --git a/x/kavadist/types/genesis.go b/x/kavadist/types/genesis.go deleted file mode 100644 index 1f702133..00000000 --- a/x/kavadist/types/genesis.go +++ /dev/null @@ -1,34 +0,0 @@ -package types - -import ( - "fmt" - "time" -) - -// NewGenesisState returns a new genesis state -func NewGenesisState(params Params, previousBlockTime time.Time) *GenesisState { - return &GenesisState{ - Params: params, - PreviousBlockTime: previousBlockTime, - } -} - -// DefaultGenesisState returns a default genesis state -func DefaultGenesisState() *GenesisState { - return &GenesisState{ - Params: DefaultParams(), - PreviousBlockTime: DefaultPreviousBlockTime, - } -} - -// Validate performs basic validation of genesis data returning an -// error for any failed validation criteria. -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - if gs.PreviousBlockTime.Equal(time.Time{}) { - return fmt.Errorf("previous block time not set") - } - return nil -} diff --git a/x/kavadist/types/genesis.pb.go b/x/kavadist/types/genesis.pb.go deleted file mode 100644 index d89ed141..00000000 --- a/x/kavadist/types/genesis.pb.go +++ /dev/null @@ -1,383 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/kavadist/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 kavadist module's genesis state. -type GenesisState struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - PreviousBlockTime time.Time `protobuf:"bytes,2,opt,name=previous_block_time,json=previousBlockTime,proto3,stdtime" json:"previous_block_time"` -} - -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_77f4885f7744ff13, []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) GetPreviousBlockTime() time.Time { - if m != nil { - return m.PreviousBlockTime - } - return time.Time{} -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.kavadist.v1beta1.GenesisState") -} - -func init() { - proto.RegisterFile("kava/kavadist/v1beta1/genesis.proto", fileDescriptor_77f4885f7744ff13) -} - -var fileDescriptor_77f4885f7744ff13 = []byte{ - // 279 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xce, 0x4e, 0x2c, 0x4b, - 0xd4, 0x07, 0x11, 0x29, 0x99, 0xc5, 0x25, 0xfa, 0x65, 0x86, 0x49, 0xa9, 0x25, 0x89, 0x86, 0xfa, - 0xe9, 0xa9, 0x79, 0xa9, 0xc5, 0x99, 0xc5, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0xa2, 0x20, - 0x79, 0x3d, 0x98, 0x22, 0x3d, 0xa8, 0x22, 0x29, 0x91, 0xf4, 0xfc, 0xf4, 0x7c, 0xb0, 0x0a, 0x7d, - 0x10, 0x0b, 0xa2, 0x58, 0x4a, 0x3e, 0x3d, 0x3f, 0x3f, 0x3d, 0x27, 0x55, 0x1f, 0xcc, 0x4b, 0x2a, - 0x4d, 0xd3, 0x2f, 0xc9, 0xcc, 0x4d, 0x2d, 0x2e, 0x49, 0xcc, 0x2d, 0x80, 0x2a, 0x50, 0xc2, 0x6e, - 0x65, 0x41, 0x62, 0x51, 0x62, 0x2e, 0xd4, 0x46, 0xa5, 0x85, 0x8c, 0x5c, 0x3c, 0xee, 0x10, 0x37, - 0x04, 0x97, 0x24, 0x96, 0xa4, 0x0a, 0x59, 0x73, 0xb1, 0x41, 0x14, 0x48, 0x30, 0x2a, 0x30, 0x6a, - 0x70, 0x1b, 0xc9, 0xea, 0x61, 0x75, 0x93, 0x5e, 0x00, 0x58, 0x91, 0x13, 0xcb, 0x89, 0x7b, 0xf2, - 0x0c, 0x41, 0x50, 0x2d, 0x42, 0x21, 0x5c, 0xc2, 0x05, 0x45, 0xa9, 0x65, 0x99, 0xf9, 0xa5, 0xc5, - 0xf1, 0x49, 0x39, 0xf9, 0xc9, 0xd9, 0xf1, 0x20, 0x37, 0x49, 0x30, 0x81, 0x4d, 0x92, 0xd2, 0x83, - 0x38, 0x58, 0x0f, 0xe6, 0x60, 0xbd, 0x10, 0x98, 0x83, 0x9d, 0x38, 0x40, 0xc6, 0x4c, 0xb8, 0x2f, - 0xcf, 0x18, 0x24, 0x08, 0x33, 0xc0, 0x09, 0xa4, 0x1f, 0xa4, 0xc2, 0xc9, 0xe5, 0xc4, 0x23, 0x39, - 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, - 0x39, 0x86, 0x1b, 0x8f, 0xe5, 0x18, 0xa2, 0xb4, 0xd2, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, - 0xf3, 0x73, 0xc1, 0xfe, 0xd4, 0xcd, 0x49, 0x4c, 0x2a, 0x06, 0xb3, 0xf4, 0x2b, 0x10, 0x1e, 0x2f, - 0xa9, 0x2c, 0x48, 0x2d, 0x4e, 0x62, 0x03, 0x5b, 0x6b, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0x10, - 0xd1, 0xf3, 0x3d, 0x89, 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 - n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.PreviousBlockTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousBlockTime):]) - if err1 != nil { - return 0, err1 - } - i -= n1 - i = encodeVarintGenesis(dAtA, i, uint64(n1)) - 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)) - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousBlockTime) - 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 PreviousBlockTime", 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 := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.PreviousBlockTime, 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/kavadist/types/keys.go b/x/kavadist/types/keys.go deleted file mode 100644 index a7b91014..00000000 --- a/x/kavadist/types/keys.go +++ /dev/null @@ -1,26 +0,0 @@ -package types - -const ( - // ModuleName name that will be used throughout the module - ModuleName = "kavadist" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default name for parameter store - DefaultParamspace = ModuleName - - // KavaDistMacc module account for kavadist - KavaDistMacc = ModuleName - - // Treasury - FundModuleAccount = "kava-fund" -) - -var ( - CurrentDistPeriodKey = []byte{0x00} - PreviousBlockTimeKey = []byte{0x01} -) diff --git a/x/kavadist/types/params.go b/x/kavadist/types/params.go deleted file mode 100644 index ad807448..00000000 --- a/x/kavadist/types/params.go +++ /dev/null @@ -1,191 +0,0 @@ -package types - -import ( - "fmt" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - - tmtime "github.com/cometbft/cometbft/types/time" - // cdptypes "github.com/kava-labs/kava/x/cdp/types" -) - -// Parameter keys and default values -var ( - KeyActive = []byte("Active") - KeyPeriods = []byte("Periods") - KeyInfra = []byte("InfrastructureParams") - DefaultActive = false - DefaultPeriods = []Period{} - DefaultInfraParams = InfrastructureParams{} - DefaultPreviousBlockTime = tmtime.Canonical(time.Unix(1, 0)) - GovDenom = "ukava" // TODO: replace with cdptypes.DefaultGovDenom -) - -func NewParams(active bool, periods []Period, infraParams InfrastructureParams) Params { - return Params{ - Active: active, - Periods: periods, - InfrastructureParams: infraParams, - } -} - -func DefaultParams() Params { - return NewParams(DefaultActive, DefaultPeriods, DefaultInfraParams) -} - -func (p Params) String() string { - periods := "Periods\n" - for _, pr := range p.Periods { - periods += fmt.Sprintf("%s\n", pr) - } - return fmt.Sprintf(`Params: - Active: %t - Periods %s`, p.Active, periods) -} - -func (p Params) Equal(other Params) bool { - if p.Active != other.Active { - return false - } - - if len(p.Periods) != len(other.Periods) { - return false - } - - for i, period := range p.Periods { - if !period.Equal(other.Periods[i]) { - return false - } - } - - return true -} - -// ParamKeyTable Key declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements the ParamSet interface and returns all the key/value pairs -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyActive, &p.Active, validateActiveParam), - paramtypes.NewParamSetPair(KeyPeriods, &p.Periods, validatePeriodsParams), - paramtypes.NewParamSetPair(KeyInfra, &p.InfrastructureParams, validateInfraParams), - } -} - -// Validate checks that the parameters have valid values. -func (p Params) Validate() error { - if err := validateActiveParam(p.Active); err != nil { - return err - } - - return validatePeriodsParams(p.Periods) -} - -// NewPeriod returns a new instance of Period -func NewPeriod(start time.Time, end time.Time, inflation sdk.Dec) Period { - return Period{ - Start: start, - End: end, - Inflation: inflation, - } -} - -type Periods []Period - -// String implements fmt.Stringer -func (pr Period) String() string { - return fmt.Sprintf(`Period: - Start: %s - End: %s - Inflation: %s`, pr.Start, pr.End, pr.Inflation) -} - -func NewInfraParams(p Periods, pr PartnerRewards, cr CoreRewards) InfrastructureParams { - return InfrastructureParams{ - InfrastructurePeriods: p, - PartnerRewards: pr, - CoreRewards: cr, - } -} - -func NewPartnerReward(addr sdk.AccAddress, rps sdk.Coin) PartnerReward { - return PartnerReward{ - Address: addr, - RewardsPerSecond: rps, - } -} - -func NewCoreReward(addr sdk.AccAddress, w sdk.Dec) CoreReward { - return CoreReward{ - Address: addr, - Weight: w, - } -} - -func validateActiveParam(i interface{}) error { - _, ok := i.(bool) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return nil -} - -func validatePeriodsParams(i interface{}) error { - periods, ok := i.([]Period) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - prevEnd := tmtime.Canonical(time.Unix(0, 0)) - for _, pr := range periods { - if pr.End.Before(pr.Start) { - return fmt.Errorf("end time for period is before start time: %s", pr) - } - - if pr.Start.Before(prevEnd) { - return fmt.Errorf("periods must be in chronological order: %s", periods) - } - prevEnd = pr.End - - if pr.Start.Unix() <= 0 || pr.End.Unix() <= 0 { - return fmt.Errorf("start or end time cannot be zero: %s", pr) - } - - // TODO: validate period Inflation? - } - - return nil -} - -func validateInfraParams(i interface{}) error { - infraParams, ok := i.(InfrastructureParams) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - for _, pr := range infraParams.InfrastructurePeriods { - if pr.End.Before(pr.Start) { - return fmt.Errorf("end time for period is before start time: %s", pr) - } - prevEnd := tmtime.Canonical(time.Unix(0, 0)) - if pr.Start.Before(prevEnd) { - return fmt.Errorf("periods must be in chronological order: %s", infraParams.InfrastructurePeriods) - } - prevEnd = pr.End - - if pr.Start.Unix() <= 0 || pr.End.Unix() <= 0 { - return fmt.Errorf("start or end time cannot be zero: %s", pr) - } - - // TODO: validate period Inflation? - } - return nil -} - -type CoreRewards []CoreReward -type PartnerRewards []PartnerReward diff --git a/x/kavadist/types/params.pb.go b/x/kavadist/types/params.pb.go deleted file mode 100644 index 49eb8475..00000000 --- a/x/kavadist/types/params.pb.go +++ /dev/null @@ -1,1436 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/kavadist/v1beta1/params.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" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 governance parameters for kavadist module -type Params struct { - Active bool `protobuf:"varint,1,opt,name=active,proto3" json:"active,omitempty"` - Periods []Period `protobuf:"bytes,3,rep,name=periods,proto3" json:"periods"` - InfrastructureParams InfrastructureParams `protobuf:"bytes,4,opt,name=infrastructure_params,json=infrastructureParams,proto3" json:"infrastructure_params"` -} - -func (m *Params) Reset() { *m = Params{} } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_2c7a7a4b0c884a4e, []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 - -// InfrastructureParams define the parameters for infrastructure rewards. -type InfrastructureParams struct { - InfrastructurePeriods Periods `protobuf:"bytes,1,rep,name=infrastructure_periods,json=infrastructurePeriods,proto3,castrepeated=Periods" json:"infrastructure_periods"` - CoreRewards CoreRewards `protobuf:"bytes,2,rep,name=core_rewards,json=coreRewards,proto3,castrepeated=CoreRewards" json:"core_rewards"` - PartnerRewards PartnerRewards `protobuf:"bytes,3,rep,name=partner_rewards,json=partnerRewards,proto3,castrepeated=PartnerRewards" json:"partner_rewards"` -} - -func (m *InfrastructureParams) Reset() { *m = InfrastructureParams{} } -func (m *InfrastructureParams) String() string { return proto.CompactTextString(m) } -func (*InfrastructureParams) ProtoMessage() {} -func (*InfrastructureParams) Descriptor() ([]byte, []int) { - return fileDescriptor_2c7a7a4b0c884a4e, []int{1} -} -func (m *InfrastructureParams) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *InfrastructureParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_InfrastructureParams.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 *InfrastructureParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_InfrastructureParams.Merge(m, src) -} -func (m *InfrastructureParams) XXX_Size() int { - return m.Size() -} -func (m *InfrastructureParams) XXX_DiscardUnknown() { - xxx_messageInfo_InfrastructureParams.DiscardUnknown(m) -} - -var xxx_messageInfo_InfrastructureParams proto.InternalMessageInfo - -// CoreReward defines the reward weights for core infrastructure providers. -type CoreReward struct { - Address github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=address,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"address,omitempty"` - Weight github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=weight,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"weight"` -} - -func (m *CoreReward) Reset() { *m = CoreReward{} } -func (m *CoreReward) String() string { return proto.CompactTextString(m) } -func (*CoreReward) ProtoMessage() {} -func (*CoreReward) Descriptor() ([]byte, []int) { - return fileDescriptor_2c7a7a4b0c884a4e, []int{2} -} -func (m *CoreReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CoreReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CoreReward.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 *CoreReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_CoreReward.Merge(m, src) -} -func (m *CoreReward) XXX_Size() int { - return m.Size() -} -func (m *CoreReward) XXX_DiscardUnknown() { - xxx_messageInfo_CoreReward.DiscardUnknown(m) -} - -var xxx_messageInfo_CoreReward proto.InternalMessageInfo - -// PartnerRewards defines the reward schedule for partner infrastructure providers. -type PartnerReward struct { - Address github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=address,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"address,omitempty"` - RewardsPerSecond types.Coin `protobuf:"bytes,2,opt,name=rewards_per_second,json=rewardsPerSecond,proto3" json:"rewards_per_second"` -} - -func (m *PartnerReward) Reset() { *m = PartnerReward{} } -func (m *PartnerReward) String() string { return proto.CompactTextString(m) } -func (*PartnerReward) ProtoMessage() {} -func (*PartnerReward) Descriptor() ([]byte, []int) { - return fileDescriptor_2c7a7a4b0c884a4e, []int{3} -} -func (m *PartnerReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *PartnerReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PartnerReward.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 *PartnerReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_PartnerReward.Merge(m, src) -} -func (m *PartnerReward) XXX_Size() int { - return m.Size() -} -func (m *PartnerReward) XXX_DiscardUnknown() { - xxx_messageInfo_PartnerReward.DiscardUnknown(m) -} - -var xxx_messageInfo_PartnerReward proto.InternalMessageInfo - -// Period stores the specified start and end dates, and the inflation, expressed as a decimal -// representing the yearly APR of KAVA tokens that will be minted during that period -type Period struct { - // example "2020-03-01T15:20:00Z" - Start time.Time `protobuf:"bytes,1,opt,name=start,proto3,stdtime" json:"start"` - // example "2020-06-01T15:20:00Z" - End time.Time `protobuf:"bytes,2,opt,name=end,proto3,stdtime" json:"end"` - // example "1.000000003022265980" - 10% inflation - Inflation github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=inflation,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"inflation"` -} - -func (m *Period) Reset() { *m = Period{} } -func (*Period) ProtoMessage() {} -func (*Period) Descriptor() ([]byte, []int) { - return fileDescriptor_2c7a7a4b0c884a4e, []int{4} -} -func (m *Period) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Period) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Period.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 *Period) XXX_Merge(src proto.Message) { - xxx_messageInfo_Period.Merge(m, src) -} -func (m *Period) XXX_Size() int { - return m.Size() -} -func (m *Period) XXX_DiscardUnknown() { - xxx_messageInfo_Period.DiscardUnknown(m) -} - -var xxx_messageInfo_Period proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Params)(nil), "kava.kavadist.v1beta1.Params") - proto.RegisterType((*InfrastructureParams)(nil), "kava.kavadist.v1beta1.InfrastructureParams") - proto.RegisterType((*CoreReward)(nil), "kava.kavadist.v1beta1.CoreReward") - proto.RegisterType((*PartnerReward)(nil), "kava.kavadist.v1beta1.PartnerReward") - proto.RegisterType((*Period)(nil), "kava.kavadist.v1beta1.Period") -} - -func init() { - proto.RegisterFile("kava/kavadist/v1beta1/params.proto", fileDescriptor_2c7a7a4b0c884a4e) -} - -var fileDescriptor_2c7a7a4b0c884a4e = []byte{ - // 649 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x54, 0x3f, 0x4f, 0x1b, 0x3f, - 0x18, 0x8e, 0x49, 0x7e, 0x01, 0x1c, 0x7e, 0x50, 0x99, 0x3f, 0x0a, 0x48, 0xbd, 0x4b, 0xa3, 0xaa, - 0x8a, 0x5a, 0xe5, 0x4e, 0xa4, 0x52, 0x07, 0xd4, 0x0e, 0x5c, 0x19, 0x5a, 0x89, 0x4a, 0xe8, 0xca, - 0xd2, 0x2e, 0x91, 0xcf, 0xe7, 0x04, 0x0b, 0x72, 0x3e, 0xd9, 0x0e, 0x94, 0x6f, 0xc1, 0xd8, 0x91, - 0xb9, 0x33, 0x5f, 0xa1, 0x6a, 0x86, 0x0e, 0x88, 0x09, 0x75, 0x80, 0x02, 0x4b, 0x3f, 0x43, 0xa7, - 0xea, 0x6c, 0x87, 0x10, 0x04, 0x52, 0xba, 0x74, 0x49, 0xee, 0x7d, 0xfd, 0x3e, 0xcf, 0xfb, 0x3e, - 0xe7, 0xe7, 0x3d, 0x58, 0xdd, 0xc6, 0xbb, 0xd8, 0xcf, 0x7e, 0x62, 0x26, 0x95, 0xbf, 0xbb, 0x1c, - 0x51, 0x85, 0x97, 0xfd, 0x14, 0x0b, 0xdc, 0x91, 0x5e, 0x2a, 0xb8, 0xe2, 0x68, 0x3e, 0x3b, 0xf6, - 0xfa, 0x35, 0x9e, 0xad, 0x59, 0x72, 0x08, 0x97, 0x1d, 0x2e, 0xfd, 0x08, 0x4b, 0x7a, 0x0d, 0x24, - 0x9c, 0x25, 0x06, 0xb6, 0xb4, 0x68, 0xce, 0x9b, 0x3a, 0xf2, 0x4d, 0x60, 0x8f, 0xe6, 0xda, 0xbc, - 0xcd, 0x4d, 0x3e, 0x7b, 0xb2, 0x59, 0xb7, 0xcd, 0x79, 0x7b, 0x87, 0xfa, 0x3a, 0x8a, 0xba, 0x2d, - 0x5f, 0xb1, 0x0e, 0x95, 0x0a, 0x77, 0x52, 0x53, 0x50, 0xfd, 0x06, 0x60, 0x71, 0x43, 0x4f, 0x86, - 0x16, 0x60, 0x11, 0x13, 0xc5, 0x76, 0x69, 0x19, 0x54, 0x40, 0x6d, 0x22, 0xb4, 0x11, 0x7a, 0x05, - 0xc7, 0x53, 0x2a, 0x18, 0x8f, 0x65, 0x39, 0x5f, 0xc9, 0xd7, 0x4a, 0x8d, 0x87, 0xde, 0x9d, 0xd3, - 0x7b, 0x1b, 0xba, 0x2a, 0x28, 0xf4, 0xce, 0xdc, 0x5c, 0xd8, 0xc7, 0xa0, 0x16, 0x9c, 0x67, 0x49, - 0x4b, 0x60, 0xa9, 0x44, 0x97, 0xa8, 0xae, 0xa0, 0x4d, 0xf3, 0x26, 0xca, 0x85, 0x0a, 0xa8, 0x95, - 0x1a, 0xcf, 0xee, 0x21, 0x7b, 0x3b, 0x84, 0x31, 0x23, 0x5a, 0xea, 0x39, 0x76, 0xc7, 0x59, 0xf5, - 0xeb, 0x18, 0x9c, 0xbb, 0x0b, 0x84, 0x28, 0x5c, 0xb8, 0x3d, 0x80, 0x95, 0x03, 0x46, 0x91, 0x33, - 0x93, 0xf5, 0xfc, 0x72, 0xee, 0x8e, 0x9b, 0x58, 0x86, 0xb7, 0xe4, 0xd8, 0x34, 0xfa, 0x00, 0xa7, - 0x08, 0x17, 0xb4, 0x29, 0xe8, 0x1e, 0x16, 0xb1, 0x2c, 0x8f, 0x69, 0xf2, 0x47, 0xf7, 0x90, 0xbf, - 0xe6, 0x82, 0x86, 0xba, 0x32, 0x98, 0xb5, 0x0d, 0x4a, 0x83, 0x9c, 0x0c, 0x4b, 0x64, 0x10, 0x20, - 0x0a, 0x67, 0x52, 0x2c, 0x54, 0x42, 0xc5, 0x35, 0xbb, 0xb9, 0x89, 0xc7, 0xf7, 0x8d, 0x6e, 0xaa, - 0x6d, 0x83, 0x05, 0xdb, 0x60, 0x7a, 0x28, 0x2d, 0xc3, 0xe9, 0x74, 0x28, 0x5e, 0x29, 0x7c, 0x3e, - 0x74, 0x41, 0xf5, 0x3b, 0x80, 0x70, 0x30, 0x09, 0x8a, 0xe0, 0x38, 0x8e, 0x63, 0x41, 0xa5, 0xd4, - 0xb6, 0x98, 0x0a, 0xde, 0xfc, 0x3e, 0x73, 0xeb, 0x6d, 0xa6, 0xb6, 0xba, 0x91, 0x47, 0x78, 0xc7, - 0xba, 0xd0, 0xfe, 0xd5, 0x65, 0xbc, 0xed, 0xab, 0xfd, 0x94, 0x4a, 0x6f, 0x95, 0x90, 0x55, 0x03, - 0x3c, 0x39, 0xaa, 0xcf, 0x5a, 0xaf, 0xda, 0x4c, 0xb0, 0xaf, 0xa8, 0x0c, 0xfb, 0xc4, 0x68, 0x13, - 0x16, 0xf7, 0x28, 0x6b, 0x6f, 0xa9, 0xf2, 0x58, 0x05, 0xd4, 0x26, 0x83, 0x97, 0xd9, 0xc0, 0x3f, - 0xce, 0xdc, 0x27, 0x23, 0xb4, 0x59, 0xa3, 0xe4, 0xe4, 0xa8, 0x0e, 0x2d, 0xff, 0x1a, 0x25, 0xa1, - 0xe5, 0xb2, 0x72, 0x7a, 0x00, 0xfe, 0x3f, 0xa4, 0xfb, 0x9f, 0x28, 0x7a, 0x07, 0x91, 0xbd, 0xa9, - 0xcc, 0x6c, 0x4d, 0x49, 0x09, 0x4f, 0x62, 0xad, 0xae, 0xd4, 0x58, 0xf4, 0x2c, 0x34, 0xdb, 0xf2, - 0x1b, 0x86, 0x60, 0x89, 0xf5, 0xf7, 0x03, 0x0b, 0xdd, 0xa0, 0xe2, 0xbd, 0x06, 0x5a, 0x29, 0xc7, - 0xd9, 0xae, 0x6a, 0xb7, 0xa1, 0x15, 0xf8, 0x9f, 0x54, 0x58, 0x28, 0xad, 0xa0, 0xd4, 0x58, 0xf2, - 0xcc, 0x9e, 0x7b, 0xfd, 0x3d, 0xf7, 0x36, 0xfb, 0x7b, 0x1e, 0x4c, 0x64, 0x9c, 0x07, 0xe7, 0x2e, - 0x08, 0x0d, 0x04, 0xbd, 0x80, 0x79, 0x7a, 0x3d, 0xcc, 0x68, 0xc8, 0x0c, 0x80, 0xd6, 0xe1, 0x24, - 0x4b, 0x5a, 0x3b, 0x58, 0x31, 0x9e, 0x94, 0xf3, 0xfa, 0xcd, 0x79, 0x7f, 0x77, 0x51, 0xe1, 0x80, - 0x60, 0xa5, 0xf0, 0xeb, 0xd0, 0x05, 0xc1, 0x7a, 0xef, 0xc2, 0xc9, 0x9d, 0x5e, 0x38, 0xb9, 0xde, - 0xa5, 0x03, 0x8e, 0x2f, 0x1d, 0xf0, 0xf3, 0xd2, 0x01, 0x07, 0x57, 0x4e, 0xee, 0xf8, 0xca, 0xc9, - 0x9d, 0x5e, 0x39, 0xb9, 0x8f, 0x4f, 0x6f, 0x50, 0x67, 0x3e, 0xaf, 0xef, 0xe0, 0x48, 0xea, 0x27, - 0xff, 0xd3, 0xe0, 0x23, 0xab, 0x5b, 0x44, 0x45, 0x2d, 0xe2, 0xf9, 0x9f, 0x00, 0x00, 0x00, 0xff, - 0xff, 0xca, 0x25, 0xda, 0x69, 0x82, 0x05, 0x00, 0x00, -} - -func (this *Period) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*Period) - if !ok { - that2, ok := that.(Period) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if !this.Start.Equal(that1.Start) { - return false - } - if !this.End.Equal(that1.End) { - return false - } - if !this.Inflation.Equal(that1.Inflation) { - return false - } - return true -} -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 - { - size, err := m.InfrastructureParams.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - if len(m.Periods) > 0 { - for iNdEx := len(m.Periods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Periods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if m.Active { - i-- - if m.Active { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *InfrastructureParams) 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 *InfrastructureParams) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *InfrastructureParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.PartnerRewards) > 0 { - for iNdEx := len(m.PartnerRewards) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.PartnerRewards[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.CoreRewards) > 0 { - for iNdEx := len(m.CoreRewards) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.CoreRewards[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.InfrastructurePeriods) > 0 { - for iNdEx := len(m.InfrastructurePeriods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.InfrastructurePeriods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *CoreReward) 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 *CoreReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CoreReward) 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 = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintParams(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *PartnerReward) 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 *PartnerReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PartnerReward) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.RewardsPerSecond.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintParams(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *Period) 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 *Period) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Period) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Inflation.Size() - i -= size - if _, err := m.Inflation.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - n3, err3 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.End, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.End):]) - if err3 != nil { - return 0, err3 - } - i -= n3 - i = encodeVarintParams(dAtA, i, uint64(n3)) - i-- - dAtA[i] = 0x12 - n4, err4 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Start, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Start):]) - if err4 != nil { - return 0, err4 - } - i -= n4 - i = encodeVarintParams(dAtA, i, uint64(n4)) - i-- - dAtA[i] = 0xa - 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 - if m.Active { - n += 2 - } - if len(m.Periods) > 0 { - for _, e := range m.Periods { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - l = m.InfrastructureParams.Size() - n += 1 + l + sovParams(uint64(l)) - return n -} - -func (m *InfrastructureParams) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.InfrastructurePeriods) > 0 { - for _, e := range m.InfrastructurePeriods { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - if len(m.CoreRewards) > 0 { - for _, e := range m.CoreRewards { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - if len(m.PartnerRewards) > 0 { - for _, e := range m.PartnerRewards { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - return n -} - -func (m *CoreReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovParams(uint64(l)) - } - l = m.Weight.Size() - n += 1 + l + sovParams(uint64(l)) - return n -} - -func (m *PartnerReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovParams(uint64(l)) - } - l = m.RewardsPerSecond.Size() - n += 1 + l + sovParams(uint64(l)) - return n -} - -func (m *Period) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Start) - n += 1 + l + sovParams(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.End) - n += 1 + l + sovParams(uint64(l)) - l = m.Inflation.Size() - n += 1 + l + sovParams(uint64(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 { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Active", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Active = bool(v != 0) - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Periods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Periods = append(m.Periods, Period{}) - if err := m.Periods[len(m.Periods)-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 InfrastructureParams", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.InfrastructureParams.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - 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 (m *InfrastructureParams) 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: InfrastructureParams: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: InfrastructureParams: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InfrastructurePeriods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.InfrastructurePeriods = append(m.InfrastructurePeriods, Period{}) - if err := m.InfrastructurePeriods[len(m.InfrastructurePeriods)-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 CoreRewards", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CoreRewards = append(m.CoreRewards, CoreReward{}) - if err := m.CoreRewards[len(m.CoreRewards)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PartnerRewards", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PartnerRewards = append(m.PartnerRewards, PartnerReward{}) - if err := m.PartnerRewards[len(m.PartnerRewards)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - 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 (m *CoreReward) 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: CoreReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CoreReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = append(m.Address[:0], dAtA[iNdEx:postIndex]...) - if m.Address == nil { - m.Address = []byte{} - } - 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 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 - } - if err := m.Weight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - 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 (m *PartnerReward) 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: PartnerReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PartnerReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = append(m.Address[:0], dAtA[iNdEx:postIndex]...) - if m.Address == nil { - m.Address = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardsPerSecond", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.RewardsPerSecond.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - 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 (m *Period) 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: Period: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Period: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Start", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Start, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field End", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.End, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Inflation", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Inflation.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - 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/kavadist/types/params_test.go b/x/kavadist/types/params_test.go deleted file mode 100644 index 49b068aa..00000000 --- a/x/kavadist/types/params_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package types_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/kavadist/types" -) - -type paramTest struct { - params types.Params - expectPass bool -} - -type ParamTestSuite struct { - suite.Suite - - tests []paramTest -} - -func (suite *ParamTestSuite) SetupTest() { - p1 := types.Params{ - Active: true, - Periods: []types.Period{ - { - Start: time.Date(2020, time.March, 1, 1, 0, 0, 0, time.UTC), - End: time.Date(2021, time.March, 1, 1, 0, 0, 0, time.UTC), - Inflation: sdk.MustNewDecFromStr("1.000000003022265980"), - }, - { - Start: time.Date(2021, time.March, 1, 1, 0, 0, 0, time.UTC), - End: time.Date(2022, time.March, 1, 1, 0, 0, 0, time.UTC), - Inflation: sdk.MustNewDecFromStr("1.000000003022265980"), - }, - }, - } - p2 := types.Params{ - Active: true, - Periods: []types.Period{ - { - Start: time.Date(2022, time.March, 1, 1, 0, 0, 0, time.UTC), - End: time.Date(2021, time.March, 1, 1, 0, 0, 0, time.UTC), - Inflation: sdk.MustNewDecFromStr("1.000000003022265980"), - }, - { - Start: time.Date(2023, time.March, 1, 1, 0, 0, 0, time.UTC), - End: time.Date(2024, time.March, 1, 1, 0, 0, 0, time.UTC), - Inflation: sdk.MustNewDecFromStr("1.000000003022265980"), - }, - }, - } - p3 := types.Params{ - Active: true, - Periods: []types.Period{ - { - Start: time.Date(2020, time.March, 1, 1, 0, 0, 0, time.UTC), - End: time.Date(2021, time.March, 1, 1, 0, 0, 0, time.UTC), - Inflation: sdk.MustNewDecFromStr("1.000000003022265980"), - }, - { - Start: time.Date(2020, time.March, 1, 1, 0, 0, 0, time.UTC), - End: time.Date(2022, time.March, 1, 1, 0, 0, 0, time.UTC), - Inflation: sdk.MustNewDecFromStr("1.000000003022265980"), - }, - }, - } - - suite.tests = []paramTest{ - { - params: p1, - expectPass: true, - }, - { - params: p2, - expectPass: false, - }, - { - params: p3, - expectPass: false, - }, - } -} - -func (suite *ParamTestSuite) TestParamValidation() { - for _, t := range suite.tests { - err := t.params.Validate() - if t.expectPass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - } - } -} - -func TestParamsTestSuite(t *testing.T) { - suite.Run(t, new(ParamTestSuite)) -} diff --git a/x/kavadist/types/proposal.go b/x/kavadist/types/proposal.go deleted file mode 100644 index 3fa8e06f..00000000 --- a/x/kavadist/types/proposal.go +++ /dev/null @@ -1,106 +0,0 @@ -package types - -import ( - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - govcodec "github.com/cosmos/cosmos-sdk/x/gov/codec" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -const ( - // ProposalTypeCommunityPoolMultiSpend defines the type for a CommunityPoolMultiSpendProposal - ProposalTypeCommunityPoolMultiSpend = "CommunityPoolMultiSpend" -) - -// Assert CommunityPoolMultiSpendProposal implements govtypes.Content at compile-time -var _ govv1beta1.Content = CommunityPoolMultiSpendProposal{} - -func init() { - govv1beta1.RegisterProposalType(ProposalTypeCommunityPoolMultiSpend) - govcodec.ModuleCdc.Amino.RegisterConcrete(CommunityPoolMultiSpendProposal{}, "kava/CommunityPoolMultiSpendProposal", nil) -} - -// NewCommunityPoolMultiSpendProposal creates a new community pool multi-spend proposal. -func NewCommunityPoolMultiSpendProposal(title, description string, recipientList []MultiSpendRecipient) *CommunityPoolMultiSpendProposal { - return &CommunityPoolMultiSpendProposal{ - Title: title, - Description: description, - RecipientList: recipientList, - } -} - -// GetTitle returns the title of a community pool multi-spend proposal. -func (csp CommunityPoolMultiSpendProposal) GetTitle() string { return csp.Title } - -// GetDescription returns the description of a community pool multi-spend proposal. -func (csp CommunityPoolMultiSpendProposal) GetDescription() string { return csp.Description } - -// GetDescription returns the routing key of a community pool multi-spend proposal. -func (csp CommunityPoolMultiSpendProposal) ProposalRoute() string { return RouterKey } - -// ProposalType returns the type of a community pool multi-spend proposal. -func (csp CommunityPoolMultiSpendProposal) ProposalType() string { - return ProposalTypeCommunityPoolMultiSpend -} - -// ValidateBasic stateless validation of a community pool multi-spend proposal. -func (csp CommunityPoolMultiSpendProposal) ValidateBasic() error { - err := govv1beta1.ValidateAbstract(csp) - if err != nil { - return err - } - for _, msr := range csp.RecipientList { - if err := msr.Validate(); err != nil { - return err - } - } - return nil -} - -// String implements fmt.Stringer -func (csp CommunityPoolMultiSpendProposal) String() string { - receiptList := "" - for _, msr := range csp.RecipientList { - receiptList += msr.String() - } - var b strings.Builder - b.WriteString(fmt.Sprintf(`Community Pool Multi Spend Proposal: - Title: %s - Description: %s - Recipient List: %s -`, csp.Title, csp.Description, receiptList)) - return b.String() -} - -// Validate stateless validation of MultiSpendRecipient -func (msr MultiSpendRecipient) Validate() error { - if !msr.Amount.IsValid() { - return ErrInvalidProposalAmount - } - if msr.Address == "" { - return ErrEmptyProposalRecipient - } - if _, err := sdk.AccAddressFromBech32(msr.Address); err != nil { - return err - } - return nil -} - -// String implements fmt.Stringer -func (msr MultiSpendRecipient) String() string { - return fmt.Sprintf(`Receiver: %s - Amount: %s - `, msr.Address, msr.Amount) -} - -// Gets recipient address in sdk.AccAddress -func (msr MultiSpendRecipient) GetAddress() sdk.AccAddress { - addr, err := sdk.AccAddressFromBech32(msr.Address) - if err != nil { - panic(fmt.Errorf("couldn't convert %q to account address: %v", msr.Address, err)) - } - - return addr -} diff --git a/x/kavadist/types/proposal.pb.go b/x/kavadist/types/proposal.pb.go deleted file mode 100644 index 22f201f0..00000000 --- a/x/kavadist/types/proposal.pb.go +++ /dev/null @@ -1,964 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/kavadist/v1beta1/proposal.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 - -// CommunityPoolMultiSpendProposal spends from the community pool by sending to one or more -// addresses -type CommunityPoolMultiSpendProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - RecipientList []MultiSpendRecipient `protobuf:"bytes,3,rep,name=recipient_list,json=recipientList,proto3" json:"recipient_list"` -} - -func (m *CommunityPoolMultiSpendProposal) Reset() { *m = CommunityPoolMultiSpendProposal{} } -func (*CommunityPoolMultiSpendProposal) ProtoMessage() {} -func (*CommunityPoolMultiSpendProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_22ee2c0b398254fd, []int{0} -} -func (m *CommunityPoolMultiSpendProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolMultiSpendProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolMultiSpendProposal.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 *CommunityPoolMultiSpendProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolMultiSpendProposal.Merge(m, src) -} -func (m *CommunityPoolMultiSpendProposal) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolMultiSpendProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolMultiSpendProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolMultiSpendProposal proto.InternalMessageInfo - -// CommunityPoolMultiSpendProposalJSON defines a CommunityPoolMultiSpendProposal with a deposit -type CommunityPoolMultiSpendProposalJSON struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - RecipientList []MultiSpendRecipient `protobuf:"bytes,3,rep,name=recipient_list,json=recipientList,proto3" json:"recipient_list"` - Deposit github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,4,rep,name=deposit,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"deposit"` -} - -func (m *CommunityPoolMultiSpendProposalJSON) Reset() { *m = CommunityPoolMultiSpendProposalJSON{} } -func (m *CommunityPoolMultiSpendProposalJSON) String() string { return proto.CompactTextString(m) } -func (*CommunityPoolMultiSpendProposalJSON) ProtoMessage() {} -func (*CommunityPoolMultiSpendProposalJSON) Descriptor() ([]byte, []int) { - return fileDescriptor_22ee2c0b398254fd, []int{1} -} -func (m *CommunityPoolMultiSpendProposalJSON) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolMultiSpendProposalJSON) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolMultiSpendProposalJSON.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 *CommunityPoolMultiSpendProposalJSON) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolMultiSpendProposalJSON.Merge(m, src) -} -func (m *CommunityPoolMultiSpendProposalJSON) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolMultiSpendProposalJSON) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolMultiSpendProposalJSON.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolMultiSpendProposalJSON proto.InternalMessageInfo - -// MultiSpendRecipient defines a recipient and the amount of coins they are receiving -type MultiSpendRecipient struct { - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MultiSpendRecipient) Reset() { *m = MultiSpendRecipient{} } -func (*MultiSpendRecipient) ProtoMessage() {} -func (*MultiSpendRecipient) Descriptor() ([]byte, []int) { - return fileDescriptor_22ee2c0b398254fd, []int{2} -} -func (m *MultiSpendRecipient) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MultiSpendRecipient) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MultiSpendRecipient.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 *MultiSpendRecipient) XXX_Merge(src proto.Message) { - xxx_messageInfo_MultiSpendRecipient.Merge(m, src) -} -func (m *MultiSpendRecipient) XXX_Size() int { - return m.Size() -} -func (m *MultiSpendRecipient) XXX_DiscardUnknown() { - xxx_messageInfo_MultiSpendRecipient.DiscardUnknown(m) -} - -var xxx_messageInfo_MultiSpendRecipient proto.InternalMessageInfo - -func init() { - proto.RegisterType((*CommunityPoolMultiSpendProposal)(nil), "kava.kavadist.v1beta1.CommunityPoolMultiSpendProposal") - proto.RegisterType((*CommunityPoolMultiSpendProposalJSON)(nil), "kava.kavadist.v1beta1.CommunityPoolMultiSpendProposalJSON") - proto.RegisterType((*MultiSpendRecipient)(nil), "kava.kavadist.v1beta1.MultiSpendRecipient") -} - -func init() { - proto.RegisterFile("kava/kavadist/v1beta1/proposal.proto", fileDescriptor_22ee2c0b398254fd) -} - -var fileDescriptor_22ee2c0b398254fd = []byte{ - // 409 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x93, 0xbf, 0x0f, 0xd2, 0x40, - 0x14, 0xc7, 0x7b, 0x80, 0xa0, 0x47, 0x74, 0xa8, 0x98, 0x54, 0x86, 0x96, 0xa0, 0x03, 0x21, 0xe1, - 0x4e, 0x74, 0x73, 0x04, 0x27, 0xe3, 0x0f, 0x52, 0x06, 0x13, 0x17, 0x73, 0x6d, 0x2f, 0x78, 0xa1, - 0xed, 0xbb, 0xf4, 0xae, 0x44, 0xfe, 0x03, 0x47, 0x47, 0x27, 0xc3, 0x66, 0xe2, 0xdf, 0xe0, 0x1f, - 0xc0, 0xc8, 0xe8, 0xa4, 0x06, 0xfe, 0x11, 0xd3, 0x9f, 0x30, 0x90, 0xb8, 0x38, 0xb8, 0xb4, 0xef, - 0xae, 0xef, 0xfb, 0xb9, 0xf7, 0xde, 0xb7, 0x87, 0x1f, 0xae, 0xd9, 0x86, 0xd1, 0xec, 0x11, 0x08, - 0xa5, 0xe9, 0x66, 0xea, 0x71, 0xcd, 0xa6, 0x54, 0x26, 0x20, 0x41, 0xb1, 0x90, 0xc8, 0x04, 0x34, - 0x98, 0xf7, 0xb2, 0x04, 0x52, 0x65, 0x91, 0x32, 0xab, 0x6f, 0xfb, 0xa0, 0x22, 0x50, 0xd4, 0x63, - 0x8a, 0xd7, 0x52, 0x1f, 0x44, 0x5c, 0xc8, 0xfa, 0xbd, 0x15, 0xac, 0x20, 0x0f, 0x69, 0x16, 0x15, - 0xbb, 0xc3, 0xef, 0x08, 0x3b, 0x73, 0x88, 0xa2, 0x34, 0x16, 0x7a, 0xbb, 0x00, 0x08, 0x5f, 0xa6, - 0xa1, 0x16, 0x4b, 0xc9, 0xe3, 0x60, 0x51, 0x1e, 0x6b, 0xf6, 0xf0, 0x0d, 0x2d, 0x74, 0xc8, 0x2d, - 0x34, 0x40, 0xa3, 0x5b, 0x6e, 0xb1, 0x30, 0x07, 0xb8, 0x1b, 0x70, 0xe5, 0x27, 0x42, 0x6a, 0x01, - 0xb1, 0xd5, 0xc8, 0xbf, 0x5d, 0x6e, 0x99, 0x6f, 0xf0, 0x9d, 0x84, 0xfb, 0x42, 0x0a, 0x1e, 0xeb, - 0x77, 0xa1, 0x50, 0xda, 0x6a, 0x0e, 0x9a, 0xa3, 0xee, 0xe3, 0x31, 0xb9, 0xda, 0x01, 0x39, 0x1f, - 0xed, 0x56, 0xb2, 0x59, 0x6b, 0xff, 0xd3, 0x31, 0xdc, 0xdb, 0x35, 0xe7, 0x85, 0x50, 0xfa, 0xe9, - 0xcd, 0x8f, 0x3b, 0xc7, 0xf8, 0xbc, 0x73, 0x8c, 0xe1, 0xd7, 0x06, 0x7e, 0xf0, 0x97, 0xf2, 0x9f, - 0x2f, 0x5f, 0xbf, 0xfa, 0xef, 0x5a, 0x30, 0x39, 0xee, 0x04, 0x5c, 0x82, 0x12, 0xda, 0x6a, 0xe5, - 0xc4, 0xfb, 0xa4, 0xf0, 0x8f, 0x64, 0xfe, 0xd5, 0xbc, 0x39, 0x88, 0x78, 0xf6, 0x28, 0x03, 0x7c, - 0xfb, 0xe5, 0x8c, 0x56, 0x42, 0xbf, 0x4f, 0x3d, 0xe2, 0x43, 0x44, 0x4b, 0xb3, 0x8b, 0xd7, 0x44, - 0x05, 0x6b, 0xaa, 0xb7, 0x92, 0xab, 0x5c, 0xa0, 0xdc, 0x8a, 0x5d, 0x4f, 0x0a, 0x0d, 0xbf, 0x20, - 0x7c, 0xf7, 0x4a, 0x75, 0xa6, 0x85, 0x3b, 0x2c, 0x08, 0x12, 0xae, 0x54, 0x39, 0x9b, 0x6a, 0x69, - 0xfa, 0xb8, 0xcd, 0x22, 0x48, 0x63, 0x6d, 0x35, 0xfe, 0x7d, 0x85, 0x25, 0xfa, 0x6c, 0xe5, 0xec, - 0xd9, 0xfe, 0x68, 0xa3, 0xc3, 0xd1, 0x46, 0xbf, 0x8f, 0x36, 0xfa, 0x74, 0xb2, 0x8d, 0xc3, 0xc9, - 0x36, 0x7e, 0x9c, 0x6c, 0xe3, 0xed, 0xf8, 0x82, 0x9a, 0x4d, 0x7c, 0x12, 0x32, 0x4f, 0xe5, 0x11, - 0xfd, 0x70, 0xbe, 0x2d, 0x39, 0xdd, 0x6b, 0xe7, 0xbf, 0xf5, 0x93, 0x3f, 0x01, 0x00, 0x00, 0xff, - 0xff, 0x02, 0xb8, 0xb8, 0x96, 0x4b, 0x03, 0x00, 0x00, -} - -func (m *CommunityPoolMultiSpendProposal) 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 *CommunityPoolMultiSpendProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolMultiSpendProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RecipientList) > 0 { - for iNdEx := len(m.RecipientList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RecipientList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CommunityPoolMultiSpendProposalJSON) 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 *CommunityPoolMultiSpendProposalJSON) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolMultiSpendProposalJSON) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Deposit) > 0 { - for iNdEx := len(m.Deposit) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposit[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.RecipientList) > 0 { - for iNdEx := len(m.RecipientList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RecipientList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MultiSpendRecipient) 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 *MultiSpendRecipient) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MultiSpendRecipient) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintProposal(dAtA []byte, offset int, v uint64) int { - offset -= sovProposal(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *CommunityPoolMultiSpendProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.RecipientList) > 0 { - for _, e := range m.RecipientList { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func (m *CommunityPoolMultiSpendProposalJSON) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.RecipientList) > 0 { - for _, e := range m.RecipientList { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - if len(m.Deposit) > 0 { - for _, e := range m.Deposit { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func (m *MultiSpendRecipient) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func sovProposal(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozProposal(x uint64) (n int) { - return sovProposal(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *CommunityPoolMultiSpendProposal) 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 ErrIntOverflowProposal - } - 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: CommunityPoolMultiSpendProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolMultiSpendProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RecipientList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RecipientList = append(m.RecipientList, MultiSpendRecipient{}) - if err := m.RecipientList[len(m.RecipientList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityPoolMultiSpendProposalJSON) 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 ErrIntOverflowProposal - } - 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: CommunityPoolMultiSpendProposalJSON: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolMultiSpendProposalJSON: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RecipientList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RecipientList = append(m.RecipientList, MultiSpendRecipient{}) - if err := m.RecipientList[len(m.RecipientList)-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 Deposit", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Deposit = append(m.Deposit, types.Coin{}) - if err := m.Deposit[len(m.Deposit)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MultiSpendRecipient) 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 ErrIntOverflowProposal - } - 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: MultiSpendRecipient: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MultiSpendRecipient: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipProposal(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, ErrIntOverflowProposal - } - 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, ErrIntOverflowProposal - } - 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, ErrIntOverflowProposal - } - 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, ErrInvalidLengthProposal - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupProposal - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthProposal - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthProposal = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowProposal = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupProposal = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/kavadist/types/query.pb.go b/x/kavadist/types/query.pb.go deleted file mode 100644 index 397fc89f..00000000 --- a/x/kavadist/types/query.pb.go +++ /dev/null @@ -1,883 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/kavadist/v1beta1/query.proto - -package types - -import ( - context "context" - 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" - 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 defines the request type for querying x/kavadist parameters. -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_08142b3a0a4f2f78, []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 defines the response type for querying x/kavadist parameters. -type QueryParamsResponse struct { - 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_08142b3a0a4f2f78, []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{} -} - -// QueryBalanceRequest defines the request type for querying x/kavadist balance. -type QueryBalanceRequest struct { -} - -func (m *QueryBalanceRequest) Reset() { *m = QueryBalanceRequest{} } -func (m *QueryBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*QueryBalanceRequest) ProtoMessage() {} -func (*QueryBalanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_08142b3a0a4f2f78, []int{2} -} -func (m *QueryBalanceRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryBalanceRequest.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 *QueryBalanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryBalanceRequest.Merge(m, src) -} -func (m *QueryBalanceRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryBalanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryBalanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryBalanceRequest proto.InternalMessageInfo - -// QueryBalanceResponse defines the response type for querying x/kavadist balance. -type QueryBalanceResponse struct { - Coins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=coins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"coins"` -} - -func (m *QueryBalanceResponse) Reset() { *m = QueryBalanceResponse{} } -func (m *QueryBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*QueryBalanceResponse) ProtoMessage() {} -func (*QueryBalanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_08142b3a0a4f2f78, []int{3} -} -func (m *QueryBalanceResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryBalanceResponse.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 *QueryBalanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryBalanceResponse.Merge(m, src) -} -func (m *QueryBalanceResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryBalanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryBalanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryBalanceResponse proto.InternalMessageInfo - -func (m *QueryBalanceResponse) GetCoins() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Coins - } - return nil -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.kavadist.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.kavadist.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryBalanceRequest)(nil), "kava.kavadist.v1beta1.QueryBalanceRequest") - proto.RegisterType((*QueryBalanceResponse)(nil), "kava.kavadist.v1beta1.QueryBalanceResponse") -} - -func init() { proto.RegisterFile("kava/kavadist/v1beta1/query.proto", fileDescriptor_08142b3a0a4f2f78) } - -var fileDescriptor_08142b3a0a4f2f78 = []byte{ - // 400 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x52, 0xcf, 0x6e, 0xda, 0x30, - 0x1c, 0x4e, 0xd8, 0x60, 0x92, 0xb9, 0x79, 0x20, 0x6d, 0xd1, 0x66, 0x20, 0x93, 0x26, 0x60, 0xc2, - 0x1e, 0xec, 0xb8, 0x5b, 0xb6, 0x07, 0xd8, 0x72, 0xec, 0xcd, 0x09, 0x56, 0x1a, 0x01, 0x71, 0x88, - 0x0d, 0x2a, 0xd7, 0x1e, 0x7b, 0xaa, 0xd4, 0x27, 0xe8, 0xb5, 0x4f, 0xc2, 0x11, 0xa9, 0x97, 0x9e, - 0xda, 0x0a, 0xfa, 0x20, 0x95, 0x63, 0x43, 0x8b, 0x0a, 0x88, 0x4b, 0x62, 0xfd, 0xfc, 0x7d, 0xbf, - 0xef, 0x4f, 0x02, 0x1a, 0x03, 0x3a, 0xa5, 0x44, 0x3d, 0xfa, 0xb1, 0x90, 0x64, 0xda, 0x0d, 0x98, - 0xa4, 0x5d, 0x32, 0x9e, 0xb0, 0x6c, 0x86, 0xd3, 0x8c, 0x4b, 0x0e, 0xab, 0xea, 0x16, 0xaf, 0x21, - 0xd8, 0x40, 0x1c, 0x14, 0x72, 0x31, 0xe2, 0x82, 0x04, 0x54, 0xb0, 0x0d, 0x2f, 0xe4, 0x71, 0xa2, - 0x69, 0x4e, 0x25, 0xe2, 0x11, 0xcf, 0x8f, 0x44, 0x9d, 0xcc, 0xf4, 0x4b, 0xc4, 0x79, 0x34, 0x64, - 0x84, 0xa6, 0x31, 0xa1, 0x49, 0xc2, 0x25, 0x95, 0x31, 0x4f, 0x84, 0xb9, 0x75, 0x77, 0xbb, 0x49, - 0x69, 0x46, 0x47, 0x06, 0xe3, 0x56, 0x00, 0xfc, 0xaf, 0xdc, 0xfd, 0xcb, 0x87, 0x3e, 0x1b, 0x4f, - 0x98, 0x90, 0xae, 0x0f, 0x3e, 0x6e, 0x4d, 0x45, 0xca, 0x13, 0xc1, 0xe0, 0x6f, 0x50, 0xd2, 0xe4, - 0x4f, 0x76, 0xdd, 0x6e, 0x96, 0x7b, 0x5f, 0xf1, 0xce, 0x30, 0x58, 0xd3, 0xbc, 0xf7, 0xf3, 0xfb, - 0x9a, 0xe5, 0x1b, 0x8a, 0x5b, 0x35, 0x3b, 0x3d, 0x3a, 0xa4, 0x49, 0xc8, 0xd6, 0x52, 0x33, 0x50, - 0xd9, 0x1e, 0x1b, 0x2d, 0x0a, 0x8a, 0x2a, 0xbe, 0x92, 0x7a, 0xd7, 0x2c, 0xf7, 0x3e, 0x63, 0x5d, - 0x10, 0x56, 0x05, 0x6d, 0x84, 0xfe, 0xf0, 0x38, 0xf1, 0x7e, 0x2a, 0x99, 0x9b, 0x87, 0x5a, 0x33, - 0x8a, 0xe5, 0xe9, 0x24, 0xc0, 0x21, 0x1f, 0x11, 0xd3, 0xa6, 0x7e, 0x75, 0x44, 0x7f, 0x40, 0xe4, - 0x2c, 0x65, 0x22, 0x27, 0x08, 0x5f, 0x6f, 0xee, 0x5d, 0x17, 0x40, 0x31, 0xd7, 0x86, 0x17, 0x36, - 0x28, 0x69, 0xd3, 0xb0, 0xb5, 0x27, 0xd3, 0xdb, 0x96, 0x9c, 0xf6, 0x31, 0x50, 0x1d, 0xc7, 0x6d, - 0x9d, 0xdf, 0x3e, 0x5d, 0x15, 0xbe, 0xc1, 0x06, 0x39, 0xf0, 0x51, 0x98, 0x64, 0x99, 0x50, 0x66, - 0x3e, 0x98, 0x36, 0xe0, 0x41, 0x89, 0xed, 0x26, 0x9d, 0x1f, 0x47, 0x61, 0x8d, 0x9f, 0xef, 0xb9, - 0x9f, 0x3a, 0x44, 0x7b, 0xfc, 0x04, 0x1a, 0xef, 0xfd, 0x9d, 0x2f, 0x91, 0xbd, 0x58, 0x22, 0xfb, - 0x71, 0x89, 0xec, 0xcb, 0x15, 0xb2, 0x16, 0x2b, 0x64, 0xdd, 0xad, 0x90, 0x75, 0xd2, 0x7e, 0x55, - 0xb7, 0xa2, 0x77, 0x86, 0x34, 0x10, 0x7a, 0xdb, 0xd9, 0xcb, 0xbe, 0xbc, 0xf6, 0xa0, 0x94, 0xff, - 0x6c, 0xbf, 0x9e, 0x03, 0x00, 0x00, 0xff, 0xff, 0x28, 0xdc, 0x24, 0xfa, 0x20, 0x03, 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 { - // Params queries the parameters of x/kavadist module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Balance queries the balance of all coins of x/kavadist module. - Balance(ctx context.Context, in *QueryBalanceRequest, opts ...grpc.CallOption) (*QueryBalanceResponse, 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, "/kava.kavadist.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Balance(ctx context.Context, in *QueryBalanceRequest, opts ...grpc.CallOption) (*QueryBalanceResponse, error) { - out := new(QueryBalanceResponse) - err := c.cc.Invoke(ctx, "/kava.kavadist.v1beta1.Query/Balance", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries the parameters of x/kavadist module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Balance queries the balance of all coins of x/kavadist module. - Balance(context.Context, *QueryBalanceRequest) (*QueryBalanceResponse, 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) Balance(ctx context.Context, req *QueryBalanceRequest) (*QueryBalanceResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Balance 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: "/kava.kavadist.v1beta1.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_Balance_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryBalanceRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Balance(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.kavadist.v1beta1.Query/Balance", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Balance(ctx, req.(*QueryBalanceRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.kavadist.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Balance", - Handler: _Query_Balance_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/kavadist/v1beta1/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 *QueryBalanceRequest) 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 *QueryBalanceRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryBalanceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryBalanceResponse) 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 *QueryBalanceResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryBalanceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Coins) > 0 { - for iNdEx := len(m.Coins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Coins[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 *QueryBalanceRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryBalanceResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Coins) > 0 { - for _, e := range m.Coins { - l = e.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 *QueryBalanceRequest) 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: QueryBalanceRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryBalanceRequest: 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 *QueryBalanceResponse) 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: QueryBalanceResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryBalanceResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Coins", 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.Coins = append(m.Coins, types.Coin{}) - if err := m.Coins[len(m.Coins)-1].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/kavadist/types/query.pb.gw.go b/x/kavadist/types/query.pb.gw.go deleted file mode 100644 index 2f6503d3..00000000 --- a/x/kavadist/types/query.pb.gw.go +++ /dev/null @@ -1,218 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/kavadist/v1beta1/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_Balance_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryBalanceRequest - var metadata runtime.ServerMetadata - - msg, err := client.Balance(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Balance_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryBalanceRequest - var metadata runtime.ServerMetadata - - msg, err := server.Balance(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_Balance_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_Balance_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_Balance_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_Balance_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_Balance_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_Balance_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{"kava", "kavadist", "v1beta1", "parameters"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Balance_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "kavadist", "v1beta1", "balance"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Balance_0 = runtime.ForwardResponseMessage -) diff --git a/x/liquid/client/cli/query.go b/x/liquid/client/cli/query.go deleted file mode 100644 index 70054c2a..00000000 --- a/x/liquid/client/cli/query.go +++ /dev/null @@ -1,31 +0,0 @@ -package cli - -import ( - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - - "github.com/kava-labs/kava/x/liquid/types" -) - -// GetQueryCmd returns the cli query commands for this module -func GetQueryCmd() *cobra.Command { - liquidQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the liquid module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{} - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - liquidQueryCmd.AddCommand(cmds...) - - return liquidQueryCmd -} diff --git a/x/liquid/client/cli/tx.go b/x/liquid/client/cli/tx.go deleted file mode 100644 index 1c0aca51..00000000 --- a/x/liquid/client/cli/tx.go +++ /dev/null @@ -1,109 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/spf13/cobra" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/kava-labs/kava/x/liquid/types" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - liquidTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "liquid transactions subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - getCmdMintDerivative(), - getCmdBurnDerivative(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - liquidTxCmd.AddCommand(cmds...) - - return liquidTxCmd -} - -func getCmdMintDerivative() *cobra.Command { - return &cobra.Command{ - Use: "mint [validator-addr] [amount]", - Short: "mints staking derivative from a delegation", - Long: "Mint removes a portion of a user's staking delegation and issues them validator specific staking derivative tokens.", - Args: cobra.ExactArgs(2), - Example: fmt.Sprintf( - `%s tx %s mint kavavaloper16lnfpgn6llvn4fstg5nfrljj6aaxyee9z59jqd 10000000ukava --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - valAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - coin, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - msg := types.NewMsgMintDerivative(clientCtx.GetFromAddress(), valAddr, coin) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -func getCmdBurnDerivative() *cobra.Command { - return &cobra.Command{ - Use: "burn [amount]", - Short: "burns staking derivative to redeem a delegation", - Long: "Burn removes some staking derivative from a user's account and converts it back to a staking delegation.", - Example: fmt.Sprintf( - `%s tx %s burn 10000000bkava-kavavaloper16lnfpgn6llvn4fstg5nfrljj6aaxyee9z59jqd --from `, version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - amount, err := sdk.ParseCoinNormalized(args[0]) - if err != nil { - return err - } - - valAddr, err := types.ParseLiquidStakingTokenDenom(amount.Denom) - if err != nil { - return errorsmod.Wrap(types.ErrInvalidDenom, err.Error()) - } - - msg := types.NewMsgBurnDerivative(clientCtx.GetFromAddress(), valAddr, amount) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} diff --git a/x/liquid/keeper/claim.go b/x/liquid/keeper/claim.go deleted file mode 100644 index 89b8827e..00000000 --- a/x/liquid/keeper/claim.go +++ /dev/null @@ -1,55 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/liquid/types" -) - -func (k Keeper) CollectStakingRewards( - ctx sdk.Context, - validator sdk.ValAddress, - destinationModAccount string, -) (sdk.Coins, error) { - macc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - - // Ensure withdraw address is as expected - withdrawAddr := k.distributionKeeper.GetDelegatorWithdrawAddr(ctx, macc.GetAddress()) - if !withdrawAddr.Equals(macc.GetAddress()) { - panic(fmt.Sprintf( - "unexpected withdraw address for liquid staking module account, expected %s, got %s", - macc.GetAddress(), withdrawAddr, - )) - } - - rewards, err := k.distributionKeeper.WithdrawDelegationRewards(ctx, macc.GetAddress(), validator) - if err != nil { - return nil, err - } - - if rewards.IsZero() { - return rewards, nil - } - - err = k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleAccountName, destinationModAccount, rewards) - if err != nil { - return nil, err - } - - return rewards, nil -} - -func (k Keeper) CollectStakingRewardsByDenom( - ctx sdk.Context, - derivativeDenom string, - destinationModAccount string, -) (sdk.Coins, error) { - valAddr, err := types.ParseLiquidStakingTokenDenom(derivativeDenom) - if err != nil { - return nil, err - } - - return k.CollectStakingRewards(ctx, valAddr, destinationModAccount) -} diff --git a/x/liquid/keeper/claim_test.go b/x/liquid/keeper/claim_test.go deleted file mode 100644 index 457318ae..00000000 --- a/x/liquid/keeper/claim_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package keeper_test - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/liquid/types" - - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" -) - -func (suite *KeeperTestSuite) TestCollectStakingRewards() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr1, delegator := addrs[0], addrs[1] - valAddr1 := sdk.ValAddress(valAccAddr1) - - initialBalance := i(1e9) - delegateAmount := i(100e6) - - suite.NoError(suite.App.FundModuleAccount( - suite.Ctx, - distrtypes.ModuleName, - sdk.NewCoins( - sdk.NewCoin("ukava", initialBalance), - ), - )) - - suite.CreateAccountWithAddress(valAccAddr1, suite.NewBondCoins(initialBalance)) - suite.CreateAccountWithAddress(delegator, suite.NewBondCoins(initialBalance)) - - suite.CreateNewUnbondedValidator(valAddr1, initialBalance) - suite.CreateDelegation(valAddr1, delegator, delegateAmount) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - // Transfers delegation to module account - _, err := suite.Keeper.MintDerivative(suite.Ctx, delegator, valAddr1, suite.NewBondCoin(delegateAmount)) - suite.Require().NoError(err) - - validator, found := suite.StakingKeeper.GetValidator(suite.Ctx, valAddr1) - suite.Require().True(found) - - suite.Ctx = suite.Ctx.WithBlockHeight(2) - - distrKeeper := suite.App.GetDistrKeeper() - stakingKeeper := suite.App.GetStakingKeeper() - accKeeper := suite.App.GetAccountKeeper() - liquidMacc := accKeeper.GetModuleAccount(suite.Ctx, types.ModuleAccountName) - - // Add rewards - rewardCoins := sdk.NewDecCoins(sdk.NewDecCoin("ukava", sdkmath.NewInt(500e6))) - distrKeeper.AllocateTokensToValidator(suite.Ctx, validator, rewardCoins) - - delegation, found := stakingKeeper.GetDelegation(suite.Ctx, liquidMacc.GetAddress(), valAddr1) - suite.Require().True(found) - - // Get amount of rewards - endingPeriod := distrKeeper.IncrementValidatorPeriod(suite.Ctx, validator) - delegationRewards := distrKeeper.CalculateDelegationRewards(suite.Ctx, validator, delegation, endingPeriod) - truncatedRewards, _ := delegationRewards.TruncateDecimal() - - suite.Run("collect staking rewards", func() { - // Collect rewards - derivativeDenom := suite.Keeper.GetLiquidStakingTokenDenom(valAddr1) - rewards, err := suite.Keeper.CollectStakingRewardsByDenom(suite.Ctx, derivativeDenom, types.ModuleName) - suite.Require().NoError(err) - suite.Require().Equal(truncatedRewards, rewards) - - suite.True(rewards.AmountOf("ukava").IsPositive()) - - // Check balances - suite.AccountBalanceEqual(liquidMacc.GetAddress(), rewards) - }) - - suite.Run("collect staking rewards with non-validator", func() { - // acc2 not a validator - derivativeDenom := suite.Keeper.GetLiquidStakingTokenDenom(sdk.ValAddress(addrs[2])) - _, err := suite.Keeper.CollectStakingRewardsByDenom(suite.Ctx, derivativeDenom, types.ModuleName) - suite.Require().Error(err) - suite.Require().Equal("no validator distribution info", err.Error()) - }) - - suite.Run("collect staking rewards with invalid denom", func() { - derivativeDenom := "bkava" - _, err := suite.Keeper.CollectStakingRewardsByDenom(suite.Ctx, derivativeDenom, types.ModuleName) - suite.Require().Error(err) - suite.Require().Equal("cannot parse denom bkava", err.Error()) - }) -} diff --git a/x/liquid/keeper/derivative.go b/x/liquid/keeper/derivative.go deleted file mode 100644 index 1a752e32..00000000 --- a/x/liquid/keeper/derivative.go +++ /dev/null @@ -1,198 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/liquid/types" -) - -// MintDerivative removes a user's staking delegation and mints them equivalent staking derivative coins. -// -// The input staking token amount is used to calculate shares in the user's delegation, which are transferred to a delegation owned by the module. -// Derivative coins are them minted and transferred to the user. -func (k Keeper) MintDerivative(ctx sdk.Context, delegatorAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) (sdk.Coin, error) { - bondDenom := k.stakingKeeper.BondDenom(ctx) - if amount.Denom != bondDenom { - return sdk.Coin{}, errorsmod.Wrapf(types.ErrInvalidDenom, "expected %s", bondDenom) - } - - derivativeAmount, shares, err := k.CalculateDerivativeSharesFromTokens(ctx, delegatorAddr, valAddr, amount.Amount) - if err != nil { - return sdk.Coin{}, err - } - - // Fetching the module account will create it if it doesn't exist. - // This is necessary as otherwise TransferDelegation will create a normal account. - modAcc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - if _, err := k.TransferDelegation(ctx, valAddr, delegatorAddr, modAcc.GetAddress(), shares); err != nil { - return sdk.Coin{}, err - } - - liquidTokenDenom := k.GetLiquidStakingTokenDenom(valAddr) - liquidToken := sdk.NewCoin(liquidTokenDenom, derivativeAmount) - if err = k.mintCoins(ctx, delegatorAddr, sdk.NewCoins(liquidToken)); err != nil { - return sdk.Coin{}, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeMintDerivative, - sdk.NewAttribute(types.AttributeKeyDelegator, delegatorAddr.String()), - sdk.NewAttribute(types.AttributeKeyValidator, valAddr.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, liquidToken.String()), - sdk.NewAttribute(types.AttributeKeySharesTransferred, shares.String()), - ), - ) - - return liquidToken, nil -} - -// CalculateDerivativeSharesFromTokens converts a staking token amount into its equivalent delegation shares, and staking derivative amount. -// This combines the code for calculating the shares to be transferred, and the derivative coins to be minted. -func (k Keeper) CalculateDerivativeSharesFromTokens(ctx sdk.Context, delegator sdk.AccAddress, validator sdk.ValAddress, tokens sdkmath.Int) (sdkmath.Int, sdk.Dec, error) { - if !tokens.IsPositive() { - return sdkmath.Int{}, sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, "token amount must be positive") - } - shares, err := k.stakingKeeper.ValidateUnbondAmount(ctx, delegator, validator, tokens) - if err != nil { - return sdkmath.Int{}, sdk.Dec{}, err - } - return shares.TruncateInt(), shares, nil -} - -// BurnDerivative burns an user's staking derivative coins and returns them an equivalent staking delegation. -// -// The derivative coins are burned, and an equivalent number of shares in the module's staking delegation are transferred back to the user. -func (k Keeper) BurnDerivative(ctx sdk.Context, delegatorAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) (sdk.Dec, error) { - - if amount.Denom != k.GetLiquidStakingTokenDenom(valAddr) { - return sdk.Dec{}, errorsmod.Wrap(types.ErrInvalidDenom, "derivative denom does not match validator") - } - - if err := k.burnCoins(ctx, delegatorAddr, sdk.NewCoins(amount)); err != nil { - return sdk.Dec{}, err - } - - modAcc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - shares := sdk.NewDecFromInt(amount.Amount) - receivedShares, err := k.TransferDelegation(ctx, valAddr, modAcc.GetAddress(), delegatorAddr, shares) - if err != nil { - return sdk.Dec{}, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeBurnDerivative, - sdk.NewAttribute(types.AttributeKeyDelegator, delegatorAddr.String()), - sdk.NewAttribute(types.AttributeKeyValidator, valAddr.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, amount.String()), - sdk.NewAttribute(types.AttributeKeySharesTransferred, shares.String()), - ), - ) - return receivedShares, nil -} - -func (k Keeper) GetLiquidStakingTokenDenom(valAddr sdk.ValAddress) string { - return types.GetLiquidStakingTokenDenom(k.derivativeDenom, valAddr) -} - -// IsDerivativeDenom returns true if the denom is a valid derivative denom and -// corresponds to a valid validator. -func (k Keeper) IsDerivativeDenom(ctx sdk.Context, denom string) bool { - valAddr, err := types.ParseLiquidStakingTokenDenom(denom) - if err != nil { - return false - } - - _, found := k.stakingKeeper.GetValidator(ctx, valAddr) - return found -} - -// GetStakedTokensForDerivatives returns the total value of the provided derivatives -// in staked tokens, accounting for the specific share prices. -func (k Keeper) GetStakedTokensForDerivatives(ctx sdk.Context, coins sdk.Coins) (sdk.Coin, error) { - total := sdk.ZeroInt() - - for _, coin := range coins { - valAddr, err := types.ParseLiquidStakingTokenDenom(coin.Denom) - if err != nil { - return sdk.Coin{}, fmt.Errorf("invalid derivative denom: %w", err) - } - - validator, found := k.stakingKeeper.GetValidator(ctx, valAddr) - if !found { - return sdk.Coin{}, fmt.Errorf("invalid derivative denom %s: validator not found", coin.Denom) - } - - // bkava is 1:1 to delegation shares - valTokens := validator.TokensFromSharesTruncated(sdk.NewDecFromInt(coin.Amount)) - total = total.Add(valTokens.TruncateInt()) - } - - totalCoin := sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), total) - return totalCoin, nil -} - -// GetTotalDerivativeValue returns the total sum value of all derivative coins -// for all validators denominated by the bond token (ukava). -func (k Keeper) GetTotalDerivativeValue(ctx sdk.Context) (sdk.Coin, error) { - bkavaCoins := sdk.NewCoins() - - k.bankKeeper.IterateTotalSupply(ctx, func(c sdk.Coin) bool { - if k.IsDerivativeDenom(ctx, c.Denom) { - bkavaCoins = bkavaCoins.Add(c) - } - - return false - }) - - return k.GetStakedTokensForDerivatives(ctx, bkavaCoins) -} - -// GetDerivativeValue returns the total underlying value of the provided -// derivative denominated by the bond token (ukava). -func (k Keeper) GetDerivativeValue(ctx sdk.Context, denom string) (sdk.Coin, error) { - return k.GetStakedTokensForDerivatives(ctx, sdk.NewCoins(k.bankKeeper.GetSupply(ctx, denom))) -} - -func (k Keeper) mintCoins(ctx sdk.Context, receiver sdk.AccAddress, amount sdk.Coins) error { - if err := k.bankKeeper.MintCoins(ctx, types.ModuleAccountName, amount); err != nil { - return err - } - if err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, receiver, amount); err != nil { - return err - } - return nil -} - -func (k Keeper) burnCoins(ctx sdk.Context, sender sdk.AccAddress, amount sdk.Coins) error { - if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleAccountName, amount); err != nil { - return err - } - if err := k.bankKeeper.BurnCoins(ctx, types.ModuleAccountName, amount); err != nil { - return err - } - return nil -} - -// DerivativeFromTokens calculates the approximate amount of derivative coins that would be minted for a given amount of staking tokens. -func (k Keeper) DerivativeFromTokens(ctx sdk.Context, valAddr sdk.ValAddress, tokens sdk.Coin) (sdk.Coin, error) { - bondDenom := k.stakingKeeper.BondDenom(ctx) - if tokens.Denom != bondDenom { - return sdk.Coin{}, errorsmod.Wrapf(types.ErrInvalidDenom, "'%s' does not match staking denom '%s'", tokens.Denom, bondDenom) - } - - // Use GetModuleAddress instead of GetModuleAccount to avoid creating a module account if it doesn't exist. - modAddress := k.accountKeeper.GetModuleAddress(types.ModuleAccountName) - derivative, _, err := k.CalculateDerivativeSharesFromTokens(ctx, modAddress, valAddr, tokens.Amount) - if err != nil { - return sdk.Coin{}, err - } - liquidTokenDenom := k.GetLiquidStakingTokenDenom(valAddr) - liquidToken := sdk.NewCoin(liquidTokenDenom, derivative) - return liquidToken, nil -} diff --git a/x/liquid/keeper/derivative_test.go b/x/liquid/keeper/derivative_test.go deleted file mode 100644 index adaf74df..00000000 --- a/x/liquid/keeper/derivative_test.go +++ /dev/null @@ -1,551 +0,0 @@ -package keeper_test - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/liquid/types" -) - -func (suite *KeeperTestSuite) TestBurnDerivative() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, user := addrs[0], addrs[1] - valAddr := sdk.ValAddress(valAccAddr) - - liquidDenom := suite.Keeper.GetLiquidStakingTokenDenom(valAddr) - - testCases := []struct { - name string - balance sdk.Coin - moduleDelegation sdkmath.Int - burnAmount sdk.Coin - expectedErr error - }{ - { - name: "user can burn their entire balance", - balance: c(liquidDenom, 1e9), - moduleDelegation: i(1e9), - burnAmount: c(liquidDenom, 1e9), - }, - { - name: "user can burn minimum derivative unit", - balance: c(liquidDenom, 1e9), - moduleDelegation: i(1e9), - burnAmount: c(liquidDenom, 1), - }, - { - name: "error when denom cannot be parsed", - balance: c(liquidDenom, 1e9), - moduleDelegation: i(1e9), - burnAmount: c(fmt.Sprintf("ckava-%s", valAddr), 1e6), - expectedErr: types.ErrInvalidDenom, - }, - { - name: "error when burn amount is 0", - balance: c(liquidDenom, 1e9), - moduleDelegation: i(1e9), - burnAmount: c(liquidDenom, 0), - expectedErr: types.ErrUntransferableShares, - }, - { - name: "error when user doesn't have enough funds", - balance: c("ukava", 10), - moduleDelegation: i(1e9), - burnAmount: c(liquidDenom, 1e9), - expectedErr: sdkerrors.ErrInsufficientFunds, - }, - { - name: "error when backing delegation isn't large enough", - balance: c(liquidDenom, 1e9), - moduleDelegation: i(999_999_999), - burnAmount: c(liquidDenom, 1e9), - expectedErr: stakingtypes.ErrNotEnoughDelegationShares, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(i(1e6))) - suite.CreateAccountWithAddress(user, sdk.NewCoins(tc.balance)) - suite.AddCoinsToModule(types.ModuleAccountName, suite.NewBondCoins(tc.moduleDelegation)) - - // create delegation from module account to back the derivatives - moduleAccAddress := authtypes.NewModuleAddress(types.ModuleAccountName) - suite.CreateNewUnbondedValidator(valAddr, i(1e6)) - suite.CreateDelegation(valAddr, moduleAccAddress, tc.moduleDelegation) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - modBalance := suite.BankKeeper.GetAllBalances(suite.Ctx, moduleAccAddress) - - _, err := suite.Keeper.BurnDerivative(suite.Ctx, user, valAddr, tc.burnAmount) - - suite.Require().ErrorIs(err, tc.expectedErr) - if tc.expectedErr != nil { - // if an error is expected, state should be reverted so don't need to test state is unchanged - return - } - - suite.AccountBalanceEqual(user, sdk.NewCoins(tc.balance.Sub(tc.burnAmount))) - suite.AccountBalanceEqual(moduleAccAddress, modBalance) // ensure derivatives are burned, and not in module account - - sharesTransferred := sdk.NewDecFromInt(tc.burnAmount.Amount) - suite.DelegationSharesEqual(valAddr, user, sharesTransferred) - suite.DelegationSharesEqual(valAddr, moduleAccAddress, sdk.NewDecFromInt(tc.moduleDelegation).Sub(sharesTransferred)) - - suite.EventsContains(suite.Ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeBurnDerivative, - sdk.NewAttribute(types.AttributeKeyDelegator, user.String()), - sdk.NewAttribute(types.AttributeKeyValidator, valAddr.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, tc.burnAmount.String()), - sdk.NewAttribute(types.AttributeKeySharesTransferred, sharesTransferred.String()), - )) - }) - } -} - -func (suite *KeeperTestSuite) TestCalculateShares() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, delegator := addrs[0], addrs[1] - valAddr := sdk.ValAddress(valAccAddr) - - type returns struct { - derivatives sdkmath.Int - shares sdk.Dec - err error - } - type validator struct { - tokens sdkmath.Int - delegatorShares sdk.Dec - } - testCases := []struct { - name string - validator *validator - delegation sdk.Dec - transfer sdkmath.Int - expected returns - }{ - { - name: "error when validator not found", - validator: nil, - delegation: d("1000000000"), - transfer: i(500e6), - expected: returns{ - err: stakingtypes.ErrNoValidatorFound, - }, - }, - { - name: "error when delegation not found", - validator: &validator{i(1e9), d("1000000000")}, - delegation: sdk.Dec{}, - transfer: i(500e6), - expected: returns{ - err: stakingtypes.ErrNoDelegation, - }, - }, - { - name: "error when transfer < 0", - validator: &validator{i(10), d("10")}, - delegation: d("10"), - transfer: i(-1), - expected: returns{ - err: types.ErrUntransferableShares, - }, - }, - { // disallow zero transfers - name: "error when transfer = 0", - validator: &validator{i(10), d("10")}, - delegation: d("10"), - transfer: i(0), - expected: returns{ - err: types.ErrUntransferableShares, - }, - }, - { - name: "error when transfer > delegated shares", - validator: &validator{i(10), d("10")}, - delegation: d("10"), - transfer: i(11), - expected: returns{ - err: sdkerrors.ErrInvalidRequest, - }, - }, - { - name: "error when validator has no tokens", - validator: &validator{i(0), d("10")}, - delegation: d("10"), - transfer: i(5), - expected: returns{ - err: stakingtypes.ErrInsufficientShares, - }, - }, - { - name: "shares and derivatives are truncated", - validator: &validator{i(3), d("4")}, - delegation: d("4"), - transfer: i(2), - expected: returns{ - derivatives: i(2), // truncated down - shares: d("2.666666666666666666"), // 2/3 * 4 not rounded to ...667 - }, - }, - { - name: "error if calculated shares > shares in delegation", - validator: &validator{i(3), d("4")}, - delegation: d("2.666666666666666665"), // one less than 2/3 * 4 - transfer: i(2), - expected: returns{ - err: sdkerrors.ErrInvalidRequest, - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - if tc.validator != nil { - suite.StakingKeeper.SetValidator(suite.Ctx, stakingtypes.Validator{ - OperatorAddress: valAddr.String(), - Tokens: tc.validator.tokens, - DelegatorShares: tc.validator.delegatorShares, - }) - } - if !tc.delegation.IsNil() { - suite.StakingKeeper.SetDelegation(suite.Ctx, stakingtypes.Delegation{ - DelegatorAddress: delegator.String(), - ValidatorAddress: valAddr.String(), - Shares: tc.delegation, - }) - } - - derivatives, shares, err := suite.Keeper.CalculateDerivativeSharesFromTokens(suite.Ctx, delegator, valAddr, tc.transfer) - if tc.expected.err != nil { - suite.ErrorIs(err, tc.expected.err) - } else { - suite.NoError(err) - suite.Equal(tc.expected.derivatives, derivatives, "expected '%s' got '%s'", tc.expected.derivatives, derivatives) - suite.Equal(tc.expected.shares, shares) - } - }) - } -} - -func (suite *KeeperTestSuite) TestMintDerivative() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, delegator := addrs[0], addrs[1] - valAddr := sdk.ValAddress(valAccAddr) - moduleAccAddress := authtypes.NewModuleAddress(types.ModuleAccountName) - - initialBalance := i(1e9) - vestedBalance := i(500e6) - - testCases := []struct { - name string - amount sdk.Coin - expectedDerivatives sdkmath.Int - expectedSharesRemaining sdk.Dec - expectedSharesAdded sdk.Dec - expectedErr error - }{ - { - name: "derivative is minted", - amount: suite.NewBondCoin(vestedBalance), - expectedDerivatives: i(500e6), - expectedSharesRemaining: d("500000000.0"), - expectedSharesAdded: d("500000000.0"), - }, - { - name: "error when the input denom isn't correct", - amount: sdk.NewCoin("invalid", i(1000)), - expectedErr: types.ErrInvalidDenom, - }, - { - name: "error when shares cannot be calculated", - amount: suite.NewBondCoin(initialBalance.Mul(i(100))), - expectedErr: sdkerrors.ErrInvalidRequest, - }, - { - name: "error when shares cannot be transferred", - amount: suite.NewBondCoin(initialBalance), // trying to move vesting coins will fail in `TransferShares` - expectedErr: sdkerrors.ErrInsufficientFunds, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(initialBalance)) - suite.CreateVestingAccountWithAddress(delegator, suite.NewBondCoins(initialBalance), suite.NewBondCoins(vestedBalance)) - - suite.CreateNewUnbondedValidator(valAddr, initialBalance) - suite.CreateDelegation(valAddr, delegator, initialBalance) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - _, err := suite.Keeper.MintDerivative(suite.Ctx, delegator, valAddr, tc.amount) - - suite.Require().ErrorIs(err, tc.expectedErr) - if tc.expectedErr != nil { - // if an error is expected, state should be reverted so don't need to test state is unchanged - return - } - - derivative := sdk.NewCoins(sdk.NewCoin(fmt.Sprintf("bkava-%s", valAddr), tc.expectedDerivatives)) - suite.AccountBalanceEqual(delegator, derivative) - - suite.DelegationSharesEqual(valAddr, delegator, tc.expectedSharesRemaining) - suite.DelegationSharesEqual(valAddr, moduleAccAddress, tc.expectedSharesAdded) - - sharesTransferred := sdk.NewDecFromInt(initialBalance).Sub(tc.expectedSharesRemaining) - suite.EventsContains(suite.Ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeMintDerivative, - sdk.NewAttribute(types.AttributeKeyDelegator, delegator.String()), - sdk.NewAttribute(types.AttributeKeyValidator, valAddr.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, derivative.String()), - sdk.NewAttribute(types.AttributeKeySharesTransferred, sharesTransferred.String()), - )) - }) - } -} - -func (suite *KeeperTestSuite) TestIsDerivativeDenom() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr1, delegator, valAccAddr2 := addrs[0], addrs[1], addrs[2] - valAddr1 := sdk.ValAddress(valAccAddr1) - - // Validator addr that has **not** delegated anything - valAddr2 := sdk.ValAddress(valAccAddr2) - - initialBalance := i(1e9) - vestedBalance := i(500e6) - - suite.CreateAccountWithAddress(valAccAddr1, suite.NewBondCoins(initialBalance)) - suite.CreateVestingAccountWithAddress(delegator, suite.NewBondCoins(initialBalance), suite.NewBondCoins(vestedBalance)) - - suite.CreateNewUnbondedValidator(valAddr1, initialBalance) - suite.CreateDelegation(valAddr1, delegator, initialBalance) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - testCases := []struct { - name string - denom string - wantIsDenom bool - }{ - { - name: "valid derivative denom", - denom: suite.Keeper.GetLiquidStakingTokenDenom(valAddr1), - wantIsDenom: true, - }, - { - name: "invalid - undelegated validator addr", - denom: suite.Keeper.GetLiquidStakingTokenDenom(valAddr2), - wantIsDenom: false, - }, - { - name: "invalid - invalid val addr", - denom: "bkava-asdfasdf", - wantIsDenom: false, - }, - { - name: "invalid - ukava", - denom: "ukava", - wantIsDenom: false, - }, - { - name: "invalid - plain bkava", - denom: "bkava", - wantIsDenom: false, - }, - { - name: "invalid - bkava prefix", - denom: "bkava-", - wantIsDenom: false, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - isDenom := suite.Keeper.IsDerivativeDenom(suite.Ctx, tc.denom) - - suite.Require().Equal(tc.wantIsDenom, isDenom) - }) - } -} - -func (suite *KeeperTestSuite) TestGetStakedTokensForDerivatives() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr1, delegator, valAccAddr2, valAccAddr3 := addrs[0], addrs[1], addrs[2], addrs[3] - valAddr1 := sdk.ValAddress(valAccAddr1) - - // Validator addr that has **not** delegated anything - valAddr2 := sdk.ValAddress(valAccAddr2) - - valAddr3 := sdk.ValAddress(valAccAddr3) - - initialBalance := i(1e9) - vestedBalance := i(500e6) - delegateAmount := i(100e6) - - suite.CreateAccountWithAddress(valAccAddr1, suite.NewBondCoins(initialBalance)) - suite.CreateVestingAccountWithAddress(delegator, suite.NewBondCoins(initialBalance), suite.NewBondCoins(vestedBalance)) - - suite.CreateNewUnbondedValidator(valAddr1, initialBalance) - suite.CreateDelegation(valAddr1, delegator, delegateAmount) - - suite.CreateAccountWithAddress(valAccAddr3, suite.NewBondCoins(initialBalance)) - - suite.CreateNewUnbondedValidator(valAddr3, initialBalance) - suite.CreateDelegation(valAddr3, delegator, delegateAmount) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - suite.SlashValidator(valAddr3, d("0.05")) - - _, err := suite.Keeper.MintDerivative(suite.Ctx, delegator, valAddr1, suite.NewBondCoin(delegateAmount)) - suite.Require().NoError(err) - - testCases := []struct { - name string - derivatives sdk.Coins - wantKavaAmount sdkmath.Int - err error - }{ - { - name: "valid derivative denom", - derivatives: sdk.NewCoins( - sdk.NewCoin(suite.Keeper.GetLiquidStakingTokenDenom(valAddr1), vestedBalance), - ), - wantKavaAmount: vestedBalance, - }, - { - name: "valid - slashed validator", - derivatives: sdk.NewCoins( - sdk.NewCoin(suite.Keeper.GetLiquidStakingTokenDenom(valAddr3), vestedBalance), - ), - // vestedBalance * 95% - wantKavaAmount: vestedBalance.Mul(sdkmath.NewInt(95)).Quo(sdkmath.NewInt(100)), - }, - { - name: "valid - sum", - derivatives: sdk.NewCoins( - sdk.NewCoin(suite.Keeper.GetLiquidStakingTokenDenom(valAddr3), vestedBalance), - sdk.NewCoin(suite.Keeper.GetLiquidStakingTokenDenom(valAddr1), vestedBalance), - ), - // vestedBalance + (vestedBalance * 95%) - wantKavaAmount: vestedBalance.Mul(sdkmath.NewInt(95)).Quo(sdkmath.NewInt(100)).Add(vestedBalance), - }, - { - name: "invalid - undelegated validator address denom", - derivatives: sdk.NewCoins( - sdk.NewCoin(suite.Keeper.GetLiquidStakingTokenDenom(valAddr2), vestedBalance), - ), - err: fmt.Errorf("invalid derivative denom %s: validator not found", suite.Keeper.GetLiquidStakingTokenDenom(valAddr2)), - }, - { - name: "invalid - denom", - derivatives: sdk.NewCoins( - sdk.NewCoin("kava", vestedBalance), - ), - err: fmt.Errorf("invalid derivative denom: cannot parse denom kava"), - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - kavaAmount, err := suite.Keeper.GetStakedTokensForDerivatives(suite.Ctx, tc.derivatives) - - if tc.err != nil { - suite.Require().Error(err) - } else { - suite.Require().NoError(err) - suite.Require().Equal(suite.NewBondCoin(tc.wantKavaAmount), kavaAmount) - } - }) - } -} - -func (suite *KeeperTestSuite) TestGetDerivativeValue() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr1, delegator, valAccAddr2 := addrs[0], addrs[1], addrs[2] - valAddr1 := sdk.ValAddress(valAccAddr1) - - valAddr2 := sdk.ValAddress(valAccAddr2) - - initialBalance := i(1e9) - vestedBalance := i(500e6) - delegateAmount := i(100e6) - - suite.CreateAccountWithAddress(valAccAddr1, suite.NewBondCoins(initialBalance)) - suite.CreateVestingAccountWithAddress(delegator, suite.NewBondCoins(initialBalance), suite.NewBondCoins(vestedBalance)) - - suite.CreateNewUnbondedValidator(valAddr1, initialBalance) - suite.CreateDelegation(valAddr1, delegator, delegateAmount) - - suite.CreateAccountWithAddress(valAccAddr2, suite.NewBondCoins(initialBalance)) - - suite.CreateNewUnbondedValidator(valAddr2, initialBalance) - suite.CreateDelegation(valAddr2, delegator, delegateAmount) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - _, err := suite.Keeper.MintDerivative(suite.Ctx, delegator, valAddr1, suite.NewBondCoin(delegateAmount)) - suite.Require().NoError(err) - - _, err = suite.Keeper.MintDerivative(suite.Ctx, delegator, valAddr2, suite.NewBondCoin(delegateAmount)) - suite.Require().NoError(err) - - suite.SlashValidator(valAddr2, d("0.05")) - - suite.Run("total value", func() { - totalValue, err := suite.Keeper.GetTotalDerivativeValue(suite.Ctx) - suite.Require().NoError(err) - suite.Require().Equal( - // delegateAmount + (delegateAmount * 95%) - delegateAmount.Add(delegateAmount.MulRaw(95).QuoRaw(100)), - totalValue.Amount, - ) - }) - - suite.Run("1:1 derivative value", func() { - derivativeValue, err := suite.Keeper.GetDerivativeValue(suite.Ctx, suite.Keeper.GetLiquidStakingTokenDenom(valAddr1)) - suite.Require().NoError(err) - suite.Require().Equal(suite.NewBondCoin(delegateAmount), derivativeValue) - }) - - suite.Run("slashed derivative value", func() { - derivativeValue, err := suite.Keeper.GetDerivativeValue(suite.Ctx, suite.Keeper.GetLiquidStakingTokenDenom(valAddr2)) - suite.Require().NoError(err) - // delegateAmount * 95% - suite.Require().Equal(delegateAmount.MulRaw(95).QuoRaw(100), derivativeValue.Amount) - }) -} - -func (suite *KeeperTestSuite) TestDerivativeFromTokens() { - _, addrs := app.GeneratePrivKeyAddressPairs(1) - valAccAddr := addrs[0] - valAddr := sdk.ValAddress(valAccAddr) - moduleAccAddress := authtypes.NewModuleAddress(types.ModuleAccountName) - - initialBalance := i(1e9) - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(initialBalance)) - suite.AddCoinsToModule(types.ModuleAccountName, suite.NewBondCoins(initialBalance)) - - suite.CreateNewUnbondedValidator(valAddr, initialBalance) - suite.CreateDelegation(valAddr, moduleAccAddress, initialBalance) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - _, err := suite.Keeper.DerivativeFromTokens(suite.Ctx, valAddr, sdk.NewCoin("invalid", initialBalance)) - suite.ErrorIs(err, types.ErrInvalidDenom) - - derivatives, err := suite.Keeper.DerivativeFromTokens(suite.Ctx, valAddr, suite.NewBondCoin(initialBalance)) - suite.NoError(err) - expected := sdk.NewCoin(fmt.Sprintf("bkava-%s", valAddr), initialBalance) - suite.Equal(expected, derivatives) -} diff --git a/x/liquid/keeper/grpc_query.go b/x/liquid/keeper/grpc_query.go deleted file mode 100644 index 3be393b4..00000000 --- a/x/liquid/keeper/grpc_query.go +++ /dev/null @@ -1,99 +0,0 @@ -package keeper - -import ( - "context" - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - vestingexported "github.com/cosmos/cosmos-sdk/x/auth/vesting/exported" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/kava-labs/kava/x/liquid/types" -) - -type queryServer struct { - keeper Keeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -var _ types.QueryServer = queryServer{} - -func (s queryServer) DelegatedBalance( - goCtx context.Context, - req *types.QueryDelegatedBalanceRequest, -) (*types.QueryDelegatedBalanceResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - delegator, err := sdk.AccAddressFromBech32(req.Delegator) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid delegator address: %s", err) - } - - delegated := s.getDelegatedBalance(ctx, delegator) - - bondDenom := s.keeper.stakingKeeper.BondDenom(ctx) - vesting := s.getVesting(ctx, delegator).AmountOf(bondDenom) - - vestingDelegated := sdk.MinInt(vesting, delegated) - vestedDelegated := delegated.Sub(vestingDelegated) - - res := types.QueryDelegatedBalanceResponse{ - Vested: sdk.NewCoin(bondDenom, vestedDelegated), - Vesting: sdk.NewCoin(bondDenom, vestingDelegated), - } - return &res, nil -} - -func (s queryServer) TotalSupply( - goCtx context.Context, - req *types.QueryTotalSupplyRequest, -) (*types.QueryTotalSupplyResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - totalValue, err := s.keeper.GetTotalDerivativeValue(ctx) - if err != nil { - return nil, err - } - - return &types.QueryTotalSupplyResponse{ - Height: ctx.BlockHeight(), - Result: []sdk.Coin{totalValue}, - }, nil -} - -func (s queryServer) getDelegatedBalance(ctx sdk.Context, delegator sdk.AccAddress) sdkmath.Int { - balance := sdk.ZeroDec() - - s.keeper.stakingKeeper.IterateDelegatorDelegations(ctx, delegator, func(delegation stakingtypes.Delegation) bool { - validator, found := s.keeper.stakingKeeper.GetValidator(ctx, delegation.GetValidatorAddr()) - if !found { - panic(fmt.Sprintf("validator %s for delegation not found", delegation.GetValidatorAddr())) - } - tokens := validator.TokensFromSharesTruncated(delegation.GetShares()) - balance = balance.Add(tokens) - - return false - }) - return balance.TruncateInt() -} - -func (s queryServer) getVesting(ctx sdk.Context, delegator sdk.AccAddress) sdk.Coins { - acc := s.keeper.accountKeeper.GetAccount(ctx, delegator) - if acc == nil { - // account doesn't exist so amount vesting is 0 - return nil - } - vestAcc, ok := acc.(vestingexported.VestingAccount) - if !ok { - // account is not vesting type, so amount vesting is 0 - return nil - } - return vestAcc.GetVestingCoins(ctx.BlockTime()) -} diff --git a/x/liquid/keeper/grpc_query_test.go b/x/liquid/keeper/grpc_query_test.go deleted file mode 100644 index 5c0b4142..00000000 --- a/x/liquid/keeper/grpc_query_test.go +++ /dev/null @@ -1,292 +0,0 @@ -package keeper_test - -import ( - "context" - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/liquid/keeper" - "github.com/kava-labs/kava/x/liquid/types" -) - -type grpcQueryTestSuite struct { - KeeperTestSuite - - queryClient types.QueryClient -} - -func (suite *grpcQueryTestSuite) SetupTest() { - suite.KeeperTestSuite.SetupTest() - - queryHelper := baseapp.NewQueryServerTestHelper(suite.Ctx, suite.App.InterfaceRegistry()) - types.RegisterQueryServer(queryHelper, keeper.NewQueryServerImpl(suite.Keeper)) - - suite.queryClient = types.NewQueryClient(queryHelper) -} - -func TestGrpcQueryTestSuite(t *testing.T) { - suite.Run(t, new(grpcQueryTestSuite)) -} - -func (suite *grpcQueryTestSuite) TestQueryDelegatedBalance() { - zeroResponse := &types.QueryDelegatedBalanceResponse{ - Vested: suite.NewBondCoin(sdk.ZeroInt()), - Vesting: suite.NewBondCoin(sdk.ZeroInt()), - } - - testCases := []struct { - name string - setup func() string - expectedRes *types.QueryDelegatedBalanceResponse - expectedErr error - }{ - { - name: "vesting account with stake less than vesting", - setup: func() string { - initBalance := suite.NewBondCoin(i(1e9)) - _, addrs := app.GeneratePrivKeyAddressPairs(2) - valAddr, delAddr := addrs[0], addrs[1] - - suite.CreateAccountWithAddress(valAddr, sdk.NewCoins(initBalance)) - - suite.CreateVestingAccountWithAddress(delAddr, sdk.NewCoins(initBalance), suite.NewBondCoins(initBalance.Amount.QuoRaw(2))) - - suite.CreateNewUnbondedValidator(sdk.ValAddress(valAddr), initBalance.Amount) - suite.CreateDelegation(sdk.ValAddress(valAddr), delAddr, initBalance.Amount.QuoRaw(4)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) // bond the validator - - return delAddr.String() - }, - expectedRes: &types.QueryDelegatedBalanceResponse{ - Vested: suite.NewBondCoin(sdk.ZeroInt()), - Vesting: suite.NewBondCoin(i(250e6)), - }, - }, - { - name: "vesting account with stake greater than vesting", - setup: func() string { - initBalance := suite.NewBondCoin(i(1e9)) - _, addrs := app.GeneratePrivKeyAddressPairs(2) - valAddr, delAddr := addrs[0], addrs[1] - - suite.CreateAccountWithAddress(valAddr, sdk.NewCoins(initBalance)) - - suite.CreateVestingAccountWithAddress(delAddr, sdk.NewCoins(initBalance), suite.NewBondCoins(initBalance.Amount.QuoRaw(2))) - - suite.CreateNewUnbondedValidator(sdk.ValAddress(valAddr), initBalance.Amount) - threeQuarters := initBalance.Amount.QuoRaw(4).MulRaw(3) - suite.CreateDelegation(sdk.ValAddress(valAddr), delAddr, threeQuarters) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) // bond the validator - - return delAddr.String() - }, - expectedRes: &types.QueryDelegatedBalanceResponse{ - Vested: suite.NewBondCoin(i(250e6)), - Vesting: suite.NewBondCoin(i(500e6)), - }, - }, - { - name: "no account returns zeros", - setup: func() string { - return "kava10wlnqzyss4accfqmyxwx5jy5x9nfkwh6qm7n4t" - }, - expectedRes: zeroResponse, - }, - { - name: "base account no delegations returns zeros", - setup: func() string { - acc := suite.CreateAccount(suite.NewBondCoins(i(1e9)), 0) - return acc.GetAddress().String() - }, - expectedRes: zeroResponse, - }, - { - name: "base account with delegations returns delegated", - setup: func() string { - initBalance := suite.NewBondCoin(i(1e9)) - val1Acc := suite.CreateAccount(sdk.NewCoins(initBalance), 0) - val2Acc := suite.CreateAccount(sdk.NewCoins(initBalance), 1) - delAcc := suite.CreateAccount(sdk.NewCoins(initBalance), 2) - - suite.CreateNewUnbondedValidator(val1Acc.GetAddress().Bytes(), initBalance.Amount) - suite.CreateNewUnbondedValidator(val2Acc.GetAddress().Bytes(), initBalance.Amount) - - suite.CreateDelegation(val1Acc.GetAddress().Bytes(), delAcc.GetAddress(), initBalance.Amount.QuoRaw(2)) - suite.CreateDelegation(val2Acc.GetAddress().Bytes(), delAcc.GetAddress(), initBalance.Amount.QuoRaw(2)) - - return delAcc.GetAddress().String() - }, - expectedRes: &types.QueryDelegatedBalanceResponse{ - Vested: suite.NewBondCoin(i(1e9)), - Vesting: suite.NewBondCoin(sdk.ZeroInt()), - }, - }, - { - name: "base account with delegations and unbonding delegations returns only delegations", - setup: func() string { - initBalance := suite.NewBondCoin(i(1e9)) - valAcc := suite.CreateAccount(sdk.NewCoins(initBalance), 0) - delAcc := suite.CreateAccount(sdk.NewCoins(initBalance), 1) - - suite.CreateNewUnbondedValidator(valAcc.GetAddress().Bytes(), initBalance.Amount) - suite.CreateDelegation(valAcc.GetAddress().Bytes(), delAcc.GetAddress(), initBalance.Amount) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) // bond the validator - - suite.CreateUnbondingDelegation(delAcc.GetAddress(), valAcc.GetAddress().Bytes(), initBalance.Amount.QuoRaw(2)) - - return delAcc.GetAddress().String() - }, - expectedRes: &types.QueryDelegatedBalanceResponse{ - Vested: suite.NewBondCoin(i(500e6)), - Vesting: suite.NewBondCoin(sdk.ZeroInt()), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - address := tc.setup() - - res, err := suite.queryClient.DelegatedBalance( - context.Background(), - &types.QueryDelegatedBalanceRequest{ - Delegator: address, - }, - ) - suite.ErrorIs(err, tc.expectedErr) - if err == nil { - suite.Equal(tc.expectedRes, res) - } - }) - } -} - -func (suite *grpcQueryTestSuite) TestQueryTotalSupply() { - testCases := []struct { - name string - setup func() - expectedTotal sdkmath.Int - expectedErr error - }{ - { - name: "no liquid kava means no tvl", - setup: func() {}, - expectedTotal: sdk.ZeroInt(), - expectedErr: nil, - }, - { - name: "returns TVL from one bkava denom", - setup: func() { - initBalance := suite.NewBondCoin(i(1e9)) - valAcc := suite.CreateAccount(sdk.NewCoins(initBalance), 0) - delAcc := suite.CreateAccount(sdk.NewCoins(initBalance), 1) - - suite.CreateNewUnbondedValidator(valAcc.GetAddress().Bytes(), initBalance.Amount) - suite.CreateDelegation(valAcc.GetAddress().Bytes(), delAcc.GetAddress(), initBalance.Amount) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) // bond the validator - - _, err := suite.Keeper.MintDerivative( - suite.Ctx, - delAcc.GetAddress(), - valAcc.GetAddress().Bytes(), - initBalance, - ) - suite.Require().NoError(err) - }, - expectedTotal: i(1e9), - expectedErr: nil, - }, - { - name: "returns TVL from multiple bkava denoms", - setup: func() { - initBalance := suite.NewBondCoin(i(1e9)) - val1Acc := suite.CreateAccount(sdk.NewCoins(initBalance), 0) - val2Acc := suite.CreateAccount(sdk.NewCoins(initBalance), 1) - delAcc := suite.CreateAccount(sdk.NewCoins(initBalance.Add(initBalance)), 2) - - suite.CreateNewUnbondedValidator(val1Acc.GetAddress().Bytes(), initBalance.Amount) - suite.CreateDelegation(val1Acc.GetAddress().Bytes(), delAcc.GetAddress(), initBalance.Amount) - suite.CreateNewUnbondedValidator(val2Acc.GetAddress().Bytes(), initBalance.Amount) - suite.CreateDelegation(val2Acc.GetAddress().Bytes(), delAcc.GetAddress(), initBalance.Amount) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) // bond the validator - - _, err := suite.Keeper.MintDerivative(suite.Ctx, delAcc.GetAddress(), val1Acc.GetAddress().Bytes(), initBalance) - suite.Require().NoError(err) - _, err = suite.Keeper.MintDerivative(suite.Ctx, delAcc.GetAddress(), val2Acc.GetAddress().Bytes(), initBalance) - suite.Require().NoError(err) - }, - expectedTotal: i(2e9), - expectedErr: nil, - }, - { - name: "returns TVL from multiple delegators", - setup: func() { - initBalance := suite.NewBondCoin(i(1e9)) - valAcc := suite.CreateAccount(sdk.NewCoins(initBalance), 0) - del1Acc := suite.CreateAccount(sdk.NewCoins(initBalance), 1) - del2Acc := suite.CreateAccount(sdk.NewCoins(initBalance), 2) - - suite.CreateNewUnbondedValidator(valAcc.GetAddress().Bytes(), initBalance.Amount) - suite.CreateDelegation(valAcc.GetAddress().Bytes(), del1Acc.GetAddress(), initBalance.Amount) - suite.CreateDelegation(valAcc.GetAddress().Bytes(), del2Acc.GetAddress(), initBalance.Amount) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) // bond the validator - - _, err := suite.Keeper.MintDerivative(suite.Ctx, del1Acc.GetAddress(), valAcc.GetAddress().Bytes(), initBalance) - suite.Require().NoError(err) - _, err = suite.Keeper.MintDerivative(suite.Ctx, del2Acc.GetAddress(), valAcc.GetAddress().Bytes(), initBalance) - suite.Require().NoError(err) - }, - expectedTotal: i(2e9), - expectedErr: nil, - }, - { - name: "handles calculating tvl after slashing", - setup: func() { - initBalance := suite.NewBondCoin(i(1e9)) - val1Acc := suite.CreateAccount(sdk.NewCoins(initBalance), 0) - val2Acc := suite.CreateAccount(sdk.NewCoins(initBalance), 1) - delAcc := suite.CreateAccount(sdk.NewCoins(initBalance.Add(initBalance)), 2) - - suite.CreateNewUnbondedValidator(val1Acc.GetAddress().Bytes(), initBalance.Amount) - suite.CreateDelegation(val1Acc.GetAddress().Bytes(), delAcc.GetAddress(), initBalance.Amount) - suite.CreateNewUnbondedValidator(val2Acc.GetAddress().Bytes(), initBalance.Amount) - suite.CreateDelegation(val2Acc.GetAddress().Bytes(), delAcc.GetAddress(), initBalance.Amount) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) // bond the validator - - _, err := suite.Keeper.MintDerivative(suite.Ctx, delAcc.GetAddress(), val1Acc.GetAddress().Bytes(), initBalance) - suite.Require().NoError(err) - _, err = suite.Keeper.MintDerivative(suite.Ctx, delAcc.GetAddress(), val2Acc.GetAddress().Bytes(), initBalance) - suite.Require().NoError(err) - - suite.SlashValidator(val2Acc.GetAddress().Bytes(), d("0.1")) - }, - // delegation + (delegation * 90%) - expectedTotal: i(1e9).Add(i(1e9).MulRaw(90).QuoRaw(100)), - expectedErr: nil, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - tc.setup() - - res, err := suite.queryClient.TotalSupply( - context.Background(), - &types.QueryTotalSupplyRequest{}, - ) - - suite.ErrorIs(err, tc.expectedErr) - if err == nil { - suite.Equal(tc.expectedTotal, res.Result[0].Amount) - } - }) - } -} diff --git a/x/liquid/keeper/keeper.go b/x/liquid/keeper/keeper.go deleted file mode 100644 index ab167239..00000000 --- a/x/liquid/keeper/keeper.go +++ /dev/null @@ -1,54 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/liquid/types" -) - -// Keeper struct for the liquid module. -type Keeper struct { - cdc codec.Codec - - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - stakingKeeper types.StakingKeeper - distributionKeeper types.DistributionKeeper - - derivativeDenom string -} - -// NewKeeper returns a new keeper for the liquid module. -func NewKeeper( - cdc codec.Codec, - ak types.AccountKeeper, bk types.BankKeeper, sk types.StakingKeeper, dk types.DistributionKeeper, - derivativeDenom string, -) Keeper { - - return Keeper{ - cdc: cdc, - accountKeeper: ak, - bankKeeper: bk, - stakingKeeper: sk, - distributionKeeper: dk, - derivativeDenom: derivativeDenom, - } -} - -// NewDefaultKeeper returns a new keeper for the liquid module with default values. -func NewDefaultKeeper( - cdc codec.Codec, - ak types.AccountKeeper, bk types.BankKeeper, sk types.StakingKeeper, dk types.DistributionKeeper, -) Keeper { - - return NewKeeper(cdc, ak, bk, sk, dk, types.DefaultDerivativeDenom) -} - -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) -} diff --git a/x/liquid/keeper/keeper_test.go b/x/liquid/keeper/keeper_test.go deleted file mode 100644 index af60bf41..00000000 --- a/x/liquid/keeper/keeper_test.go +++ /dev/null @@ -1,251 +0,0 @@ -package keeper_test - -import ( - "fmt" - "reflect" - "testing" - - sdkmath "cosmossdk.io/math" - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/liquid/keeper" -) - -// Test suite used for all keeper tests -type KeeperTestSuite struct { - suite.Suite - App app.TestApp - Ctx sdk.Context - Keeper keeper.Keeper - BankKeeper bankkeeper.Keeper - StakingKeeper *stakingkeeper.Keeper -} - -// The default state used by each test -func (suite *KeeperTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - tApp.InitializeFromGenesisStates() - - suite.App = tApp - suite.Ctx = ctx - suite.Keeper = tApp.GetLiquidKeeper() - suite.StakingKeeper = tApp.GetStakingKeeper() - suite.BankKeeper = tApp.GetBankKeeper() -} - -// CreateAccount creates a new account (with a fixed address) from the provided balance. -func (suite *KeeperTestSuite) CreateAccount(initialBalance sdk.Coins, index int) authtypes.AccountI { - _, addrs := app.GeneratePrivKeyAddressPairs(index + 1) - - return suite.CreateAccountWithAddress(addrs[index], initialBalance) -} - -// CreateAccount creates a new account from the provided balance and address -func (suite *KeeperTestSuite) CreateAccountWithAddress(addr sdk.AccAddress, initialBalance sdk.Coins) authtypes.AccountI { - ak := suite.App.GetAccountKeeper() - - acc := ak.NewAccountWithAddress(suite.Ctx, addr) - ak.SetAccount(suite.Ctx, acc) - - err := suite.App.FundAccount(suite.Ctx, acc.GetAddress(), initialBalance) - suite.Require().NoError(err) - - return acc -} - -// CreateVestingAccount creates a new vesting account. `vestingBalance` should be a fraction of `initialBalance`. -func (suite *KeeperTestSuite) CreateVestingAccountWithAddress(addr sdk.AccAddress, initialBalance sdk.Coins, vestingBalance sdk.Coins) authtypes.AccountI { - if vestingBalance.IsAnyGT(initialBalance) { - panic("vesting balance must be less than initial balance") - } - acc := suite.CreateAccountWithAddress(addr, initialBalance) - bacc := acc.(*authtypes.BaseAccount) - - periods := vestingtypes.Periods{ - vestingtypes.Period{ - Length: 31556952, - Amount: vestingBalance, - }, - } - vacc := vestingtypes.NewPeriodicVestingAccount(bacc, vestingBalance, suite.Ctx.BlockTime().Unix(), periods) - suite.App.GetAccountKeeper().SetAccount(suite.Ctx, vacc) - return vacc -} - -// AddCoinsToModule adds coins to the a module account, creating it if it doesn't exist. -func (suite *KeeperTestSuite) AddCoinsToModule(module string, amount sdk.Coins) { - err := suite.App.FundModuleAccount(suite.Ctx, module, amount) - suite.Require().NoError(err) -} - -// AccountBalanceEqual checks if an account has the specified coins. -func (suite *KeeperTestSuite) AccountBalanceEqual(addr sdk.AccAddress, coins sdk.Coins) { - balance := suite.BankKeeper.GetAllBalances(suite.Ctx, addr) - suite.Truef(coins.IsEqual(balance), "expected account balance to equal coins %s, but got %s", coins, balance) -} - -func (suite *KeeperTestSuite) deliverMsgCreateValidator(ctx sdk.Context, address sdk.ValAddress, selfDelegation sdk.Coin) error { - msg, err := stakingtypes.NewMsgCreateValidator( - address, - ed25519.GenPrivKey().PubKey(), - selfDelegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - sdkmath.NewInt(1e6), - ) - if err != nil { - return err - } - - msgServer := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.Ctx), msg) - return err -} - -// NewBondCoin creates a Coin with the current staking denom. -func (suite *KeeperTestSuite) NewBondCoin(amount sdkmath.Int) sdk.Coin { - stakingDenom := suite.StakingKeeper.BondDenom(suite.Ctx) - return sdk.NewCoin(stakingDenom, amount) -} - -// NewBondCoins creates Coins with the current staking denom. -func (suite *KeeperTestSuite) NewBondCoins(amount sdkmath.Int) sdk.Coins { - return sdk.NewCoins(suite.NewBondCoin(amount)) -} - -// CreateNewUnbondedValidator creates a new validator in the staking module. -// New validators are unbonded until the end blocker is run. -func (suite *KeeperTestSuite) CreateNewUnbondedValidator(addr sdk.ValAddress, selfDelegation sdkmath.Int) stakingtypes.Validator { - // Create a validator - err := suite.deliverMsgCreateValidator(suite.Ctx, addr, suite.NewBondCoin(selfDelegation)) - suite.Require().NoError(err) - - // New validators are created in an unbonded state. Note if the end blocker is run later this validator could become bonded. - - validator, found := suite.StakingKeeper.GetValidator(suite.Ctx, addr) - suite.Require().True(found) - return validator -} - -// SlashValidator burns tokens staked in a validator. new_tokens = old_tokens * (1-slashFraction) -func (suite *KeeperTestSuite) SlashValidator(addr sdk.ValAddress, slashFraction sdk.Dec) { - validator, found := suite.StakingKeeper.GetValidator(suite.Ctx, addr) - suite.Require().True(found) - consAddr, err := validator.GetConsAddr() - suite.Require().NoError(err) - - // Assume infraction was at current height. Note unbonding delegations and redelegations are only slashed if created after - // the infraction height so none will be slashed. - infractionHeight := suite.Ctx.BlockHeight() - - power := suite.StakingKeeper.TokensToConsensusPower(suite.Ctx, validator.GetTokens()) - - suite.StakingKeeper.Slash(suite.Ctx, consAddr, infractionHeight, power, slashFraction) -} - -// CreateDelegation delegates tokens to a validator. -func (suite *KeeperTestSuite) CreateDelegation(valAddr sdk.ValAddress, delegator sdk.AccAddress, amount sdkmath.Int) sdk.Dec { - stakingDenom := suite.StakingKeeper.BondDenom(suite.Ctx) - msg := stakingtypes.NewMsgDelegate( - delegator, - valAddr, - sdk.NewCoin(stakingDenom, amount), - ) - - msgServer := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - _, err := msgServer.Delegate(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - del, found := suite.StakingKeeper.GetDelegation(suite.Ctx, delegator, valAddr) - suite.Require().True(found) - return del.Shares -} - -// CreateRedelegation undelegates tokens from one validator and delegates to another. -func (suite *KeeperTestSuite) CreateRedelegation(delegator sdk.AccAddress, fromValidator, toValidator sdk.ValAddress, amount sdkmath.Int) { - stakingDenom := suite.StakingKeeper.BondDenom(suite.Ctx) - msg := stakingtypes.NewMsgBeginRedelegate( - delegator, - fromValidator, - toValidator, - sdk.NewCoin(stakingDenom, amount), - ) - - msgServer := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - _, err := msgServer.BeginRedelegate(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) -} - -// CreateUnbondingDelegation undelegates tokens from a validator. -func (suite *KeeperTestSuite) CreateUnbondingDelegation(delegator sdk.AccAddress, validator sdk.ValAddress, amount sdkmath.Int) { - stakingDenom := suite.StakingKeeper.BondDenom(suite.Ctx) - msg := stakingtypes.NewMsgUndelegate( - delegator, - validator, - sdk.NewCoin(stakingDenom, amount), - ) - msgServer := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - _, err := msgServer.Undelegate(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) -} - -// DelegationSharesEqual checks if a delegation has the specified shares. -// It expects delegations with zero shares to not be stored in state. -func (suite *KeeperTestSuite) DelegationSharesEqual(valAddr sdk.ValAddress, delegator sdk.AccAddress, shares sdk.Dec) bool { - del, found := suite.StakingKeeper.GetDelegation(suite.Ctx, delegator, valAddr) - - if shares.IsZero() { - return suite.Falsef(found, "expected delegator to not be found, got %s shares", del.Shares) - } else { - res := suite.True(found, "expected delegator to be found") - return res && suite.Truef(shares.Equal(del.Shares), "expected %s delegator shares but got %s", shares, del.Shares) - } -} - -// EventsContains asserts that the expected event is in the provided events -func (suite *KeeperTestSuite) EventsContains(events sdk.Events, expectedEvent sdk.Event) { - foundMatch := false - for _, event := range events { - if event.Type == expectedEvent.Type { - if reflect.DeepEqual(attrsToMap(expectedEvent.Attributes), attrsToMap(event.Attributes)) { - foundMatch = true - } - } - } - - suite.True(foundMatch, fmt.Sprintf("event of type %s not found or did not match", expectedEvent.Type)) -} - -// EventsDoNotContainType asserts that the provided events do contain an event of a certain type. -func (suite *KeeperTestSuite) EventsDoNotContainType(events sdk.Events, eventType string) { - for _, event := range events { - suite.Falsef(event.Type == eventType, "found unexpected event %s", eventType) - } -} - -func attrsToMap(attrs []abci.EventAttribute) []sdk.Attribute { - out := []sdk.Attribute{} - - for _, attr := range attrs { - out = append(out, sdk.NewAttribute(string(attr.Key), string(attr.Value))) - } - - return out -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} diff --git a/x/liquid/keeper/msg_server.go b/x/liquid/keeper/msg_server.go deleted file mode 100644 index b09e6b4b..00000000 --- a/x/liquid/keeper/msg_server.go +++ /dev/null @@ -1,84 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/liquid/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the liquid MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -// MintDerivative handles MintDerivative msgs. -func (k msgServer) MintDerivative(goCtx context.Context, msg *types.MsgMintDerivative) (*types.MsgMintDerivativeResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - validator, err := sdk.ValAddressFromBech32(msg.Validator) - if err != nil { - return nil, err - } - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - mintedDerivative, err := k.keeper.MintDerivative(ctx, sender, validator, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - ), - ) - - return &types.MsgMintDerivativeResponse{ - Received: mintedDerivative, - }, nil -} - -// BurnDerivative handles BurnDerivative msgs. -func (k msgServer) BurnDerivative(goCtx context.Context, msg *types.MsgBurnDerivative) (*types.MsgBurnDerivativeResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - validator, err := sdk.ValAddressFromBech32(msg.Validator) - if err != nil { - return nil, err - } - - sharesReceived, err := k.keeper.BurnDerivative(ctx, sender, validator, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - ), - ) - return &types.MsgBurnDerivativeResponse{ - Received: sharesReceived, - }, nil -} diff --git a/x/liquid/keeper/staking.go b/x/liquid/keeper/staking.go deleted file mode 100644 index bd453a97..00000000 --- a/x/liquid/keeper/staking.go +++ /dev/null @@ -1,110 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/kava-labs/kava/x/liquid/types" -) - -// TransferDelegation moves some delegation shares between addresses, while keeping the same validator. -// -// Internally shares are unbonded, tokens moved then bonded again. This limits only vested tokens from being transferred. -// The sending delegation must not have any active redelegations. -// A validator cannot reduce self delegated shares below its min self delegation. -// Attempting to transfer zero shares will error. -func (k Keeper) TransferDelegation(ctx sdk.Context, valAddr sdk.ValAddress, fromDelegator, toDelegator sdk.AccAddress, shares sdk.Dec) (sdk.Dec, error) { - // Redelegations link a delegation to it's previous validator so slashes are propagated to the new validator. - // If the delegation is transferred to a new owner, the redelegation object must be updated. - // For expediency all transfers with redelegations are blocked. - if k.stakingKeeper.HasReceivingRedelegation(ctx, fromDelegator, valAddr) { - return sdk.Dec{}, types.ErrRedelegationsNotCompleted - } - - if shares.IsNil() || shares.LT(sdk.ZeroDec()) { - return sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, "nil or negative shares") - } - if shares.Equal(sdk.ZeroDec()) { - // Block 0 transfers to reduce edge cases. - return sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, "zero shares") - } - - fromDelegation, found := k.stakingKeeper.GetDelegation(ctx, fromDelegator, valAddr) - if !found { - return sdk.Dec{}, types.ErrNoDelegatorForAddress - } - validator, found := k.stakingKeeper.GetValidator(ctx, valAddr) - if !found { - return sdk.Dec{}, types.ErrNoValidatorFound - } - // Prevent validators from reducing their self delegation below the min. - isValidatorOperator := fromDelegator.Equals(valAddr) - if isValidatorOperator { - if isBelowMinSelfDelegation(validator, fromDelegation.Shares.Sub(shares)) { - return sdk.Dec{}, types.ErrSelfDelegationBelowMinimum - } - } - - returnAmount, err := k.fastUndelegate(ctx, valAddr, fromDelegator, shares) - if err != nil { - return sdk.Dec{}, err - } - returnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount)) - - if err := k.bankKeeper.SendCoins(ctx, fromDelegator, toDelegator, returnCoins); err != nil { - return sdk.Dec{}, err - } - receivedShares, err := k.delegateFromAccount(ctx, valAddr, toDelegator, returnAmount) - if err != nil { - return sdk.Dec{}, err - } - - return receivedShares, nil -} - -// isBelowMinSelfDelegation check if the supplied shares, converted to tokens, are under the validator's min_self_delegation. -func isBelowMinSelfDelegation(validator stakingtypes.ValidatorI, shares sdk.Dec) bool { - return validator.TokensFromShares(shares).TruncateInt().LT(validator.GetMinSelfDelegation()) -} - -// fastUndelegate undelegates shares from a validator skipping the unbonding period and not creating any unbonding delegations. -func (k Keeper) fastUndelegate(ctx sdk.Context, valAddr sdk.ValAddress, delegator sdk.AccAddress, shares sdk.Dec) (sdkmath.Int, error) { - validator, found := k.stakingKeeper.GetValidator(ctx, valAddr) - if !found { - return sdkmath.Int{}, types.ErrNoDelegatorForAddress - } - - returnAmount, err := k.stakingKeeper.Unbond(ctx, delegator, valAddr, shares) - if err != nil { - return sdkmath.Int{}, err - } - returnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount)) - - // transfer the validator tokens to the not bonded pool - if validator.IsBonded() { - if err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, returnCoins); err != nil { - panic(err) - } - } - - if err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, stakingtypes.NotBondedPoolName, delegator, returnCoins); err != nil { - return sdkmath.Int{}, err - } - return returnAmount, nil -} - -// delegateFromAccount delegates to a validator from an account (vs redelegating from an existing delegation) -func (k Keeper) delegateFromAccount(ctx sdk.Context, valAddr sdk.ValAddress, delegator sdk.AccAddress, amount sdkmath.Int) (sdk.Dec, error) { - validator, found := k.stakingKeeper.GetValidator(ctx, valAddr) - if !found { - return sdk.Dec{}, types.ErrNoValidatorFound - } - // source tokens are from an account, so subtractAccount true and tokenSrc unbonded - newShares, err := k.stakingKeeper.Delegate(ctx, delegator, amount, stakingtypes.Unbonded, validator, true) - if err != nil { - return sdk.Dec{}, err - } - return newShares, nil -} diff --git a/x/liquid/keeper/staking_test.go b/x/liquid/keeper/staking_test.go deleted file mode 100644 index 430858ad..00000000 --- a/x/liquid/keeper/staking_test.go +++ /dev/null @@ -1,379 +0,0 @@ -package keeper_test - -import ( - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/liquid/types" -) - -var ( - // d is an alias for sdk.MustNewDecFromStr - d = sdk.MustNewDecFromStr - // i is an alias for sdkmath.NewInt - i = sdkmath.NewInt - // c is an alias for sdk.NewInt64Coin - c = sdk.NewInt64Coin -) - -func (suite *KeeperTestSuite) TestTransferDelegation_ValidatorStates() { - _, addrs := app.GeneratePrivKeyAddressPairs(3) - valAccAddr, fromDelegator, toDelegator := addrs[0], addrs[1], addrs[2] - valAddr := sdk.ValAddress(valAccAddr) - - initialBalance := i(1e9) - - notBondedModAddr := authtypes.NewModuleAddress(stakingtypes.NotBondedPoolName) - bondedModAddr := authtypes.NewModuleAddress(stakingtypes.BondedPoolName) - - testCases := []struct { - name string - createValidator func() (delegatorShares sdk.Dec, err error) - }{ - { - name: "bonded validator", - createValidator: func() (sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, initialBalance) - delegatorShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - - // Run end blocker to update validator state to bonded. - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return delegatorShares, nil - }, - }, - { - name: "unbonded validator", - createValidator: func() (sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, initialBalance) - delegatorShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - - // Don't run end blocker, new validators are by default unbonded. - return delegatorShares, nil - }, - }, - { - name: "ubonding (jailed) validator", - createValidator: func() (sdk.Dec, error) { - val := suite.CreateNewUnbondedValidator(valAddr, initialBalance) - delegatorShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - - // Run end blocker to update validator state to bonded. - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - // Jail and run end blocker to transition validator to unbonding. - consAddr, err := val.GetConsAddr() - if err != nil { - return sdk.Dec{}, err - } - suite.StakingKeeper.Jail(suite.Ctx, consAddr) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return delegatorShares, nil - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(i(1e9))) - suite.CreateAccountWithAddress(fromDelegator, suite.NewBondCoins(i(1e9))) - - fromDelegationShares, err := tc.createValidator() - suite.Require().NoError(err) - - validator, found := suite.StakingKeeper.GetValidator(suite.Ctx, valAddr) - suite.Require().True(found) - notBondedBalance := suite.BankKeeper.GetAllBalances(suite.Ctx, notBondedModAddr) - bondedBalance := suite.BankKeeper.GetAllBalances(suite.Ctx, bondedModAddr) - - shares := d("1000") - - _, err = suite.Keeper.TransferDelegation(suite.Ctx, valAddr, fromDelegator, toDelegator, shares) - suite.Require().NoError(err) - - // Transferring a delegation should move shares, and leave the validator and pool balances the same. - - suite.DelegationSharesEqual(valAddr, fromDelegator, fromDelegationShares.Sub(shares)) - suite.DelegationSharesEqual(valAddr, toDelegator, shares) // also creates new delegation - - validatorAfter, found := suite.StakingKeeper.GetValidator(suite.Ctx, valAddr) - suite.Require().True(found) - suite.Equal(validator.GetTokens(), validatorAfter.GetTokens()) - suite.Equal(validator.GetDelegatorShares(), validatorAfter.GetDelegatorShares()) - suite.Equal(validator.GetStatus(), validatorAfter.GetStatus()) - - suite.AccountBalanceEqual(notBondedModAddr, notBondedBalance) - suite.AccountBalanceEqual(bondedModAddr, bondedBalance) - }) - } -} - -func (suite *KeeperTestSuite) TestTransferDelegation_Shares() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, fromDelegator, toDelegator := addrs[0], addrs[1], addrs[2] - valAddr := sdk.ValAddress(valAccAddr) - - initialBalance := i(1e12) - - testCases := []struct { - name string - createDelegations func() (fromDelegatorShares, toDelegatorShares sdk.Dec, err error) - shares sdk.Dec - expectReceived sdk.Dec - expectedErr error - }{ - { - name: "negative shares cannot be transferred", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - // Run end blocker to update validator state to bonded. - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return fromDelegationShares, sdk.ZeroDec(), nil - }, - shares: d("-1.0"), - expectedErr: types.ErrUntransferableShares, - }, - { - name: "nil shares cannot be transferred", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return fromDelegationShares, sdk.ZeroDec(), nil - }, - shares: sdk.Dec{}, - expectedErr: types.ErrUntransferableShares, - }, - { - name: "0 shares cannot be transferred", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - toDelegationShares := suite.CreateDelegation(valAddr, toDelegator, i(2e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return fromDelegationShares, toDelegationShares, nil - }, - shares: sdk.ZeroDec(), - expectedErr: types.ErrUntransferableShares, - }, - { - name: "all shares can be transferred", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - toDelegationShares := suite.CreateDelegation(valAddr, toDelegator, i(2e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return fromDelegationShares, toDelegationShares, nil - }, - shares: d("1000000000.0"), - expectReceived: d("1000000000.0"), - }, - { - name: "excess shares cannot be transferred", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return fromDelegationShares, sdk.ZeroDec(), nil - }, - shares: d("1000000000.000000000000000001"), - expectedErr: stakingtypes.ErrNotEnoughDelegationShares, - }, - { - name: "shares can be transferred to a non existent delegation", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return fromDelegationShares, sdk.ZeroDec(), nil - }, - shares: d("500000000.0"), - expectReceived: d("500000000.0"), - }, - { - name: "shares cannot be transferred from a non existent delegation", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return sdk.ZeroDec(), sdk.ZeroDec(), nil - }, - shares: d("500000000.0"), - expectedErr: types.ErrNoDelegatorForAddress, - }, - { - name: "slashed validator shares can be transferred", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - suite.SlashValidator(valAddr, d("0.05")) - - return fromDelegationShares, sdk.ZeroDec(), nil - }, - shares: d("500000000.0"), - expectReceived: d("500000000.0"), - }, - { - name: "zero shares received when transfer < 1 token", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - toDelegationShares := suite.CreateDelegation(valAddr, toDelegator, i(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - // make 1 share worth more than 1 token - suite.SlashValidator(valAddr, d("0.05")) - - return fromDelegationShares, toDelegationShares, nil - }, - shares: d("1.0"), // send 1 share (truncates to zero tokens) - expectReceived: d("0.0"), - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(initialBalance)) - suite.CreateAccountWithAddress(fromDelegator, suite.NewBondCoins(initialBalance)) - suite.CreateAccountWithAddress(toDelegator, suite.NewBondCoins(initialBalance)) - - fromDelegationShares, toDelegationShares, err := tc.createDelegations() - suite.Require().NoError(err) - validator, found := suite.StakingKeeper.GetValidator(suite.Ctx, valAddr) - suite.Require().True(found) - - _, err = suite.Keeper.TransferDelegation(suite.Ctx, valAddr, fromDelegator, toDelegator, tc.shares) - - if tc.expectedErr != nil { - suite.ErrorIs(err, tc.expectedErr) - return - } - - suite.NoError(err) - suite.DelegationSharesEqual(valAddr, fromDelegator, fromDelegationShares.Sub(tc.shares)) - suite.DelegationSharesEqual(valAddr, toDelegator, toDelegationShares.Add(tc.expectReceived)) - - validatorAfter, found := suite.StakingKeeper.GetValidator(suite.Ctx, valAddr) - suite.Require().True(found) - // total tokens should not change - suite.Equal(validator.GetTokens(), validatorAfter.GetTokens()) - // but total shares can differ - suite.Equal( - validator.GetDelegatorShares().Sub(tc.shares).Add(tc.expectReceived), - validatorAfter.GetDelegatorShares(), - ) - }) - } -} - -func (suite *KeeperTestSuite) TestTransferDelegation_RedelegationsForbidden() { - _, addrs := app.GeneratePrivKeyAddressPairs(4) - val1AccAddr, val2AccAddr, fromDelegator, toDelegator := addrs[0], addrs[1], addrs[2], addrs[3] - val1Addr := sdk.ValAddress(val1AccAddr) - val2Addr := sdk.ValAddress(val2AccAddr) - - initialBalance := i(1e12) - - suite.CreateAccountWithAddress(val1AccAddr, suite.NewBondCoins(initialBalance)) - suite.CreateAccountWithAddress(val2AccAddr, suite.NewBondCoins(initialBalance)) - suite.CreateAccountWithAddress(fromDelegator, suite.NewBondCoins(initialBalance)) - - // create bonded validator 1 with a delegation - suite.CreateNewUnbondedValidator(val1Addr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(val1Addr, fromDelegator, i(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - // create validator 2 and redelegate to it - suite.CreateNewUnbondedValidator(val2Addr, i(1e9)) - suite.CreateRedelegation(fromDelegator, val1Addr, val2Addr, i(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - _, err := suite.Keeper.TransferDelegation(suite.Ctx, val2Addr, fromDelegator, toDelegator, fromDelegationShares) - suite.ErrorIs(err, types.ErrRedelegationsNotCompleted) - suite.DelegationSharesEqual(val2Addr, fromDelegator, fromDelegationShares) - suite.DelegationSharesEqual(val2Addr, toDelegator, sdk.ZeroDec()) -} - -func (suite *KeeperTestSuite) TestTransferDelegation_CompliesWithMinSelfDelegation() { - _, addrs := app.GeneratePrivKeyAddressPairs(4) - valAccAddr, toDelegator := addrs[0], addrs[1] - valAddr := sdk.ValAddress(valAccAddr) - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(i(1e12))) - - // create bonded validator with minimum delegated - minSelfDelegation := i(1e9) - delegation := suite.NewBondCoin(i(1e9)) - msg, err := stakingtypes.NewMsgCreateValidator( - valAddr, - ed25519.GenPrivKey().PubKey(), - delegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - minSelfDelegation, - ) - suite.Require().NoError(err) - - msgServer := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - _, err = suite.Keeper.TransferDelegation(suite.Ctx, valAddr, valAccAddr, toDelegator, d("0.000000000000000001")) - suite.ErrorIs(err, types.ErrSelfDelegationBelowMinimum) - suite.DelegationSharesEqual(valAddr, valAccAddr, sdk.NewDecFromInt(delegation.Amount)) -} - -func (suite *KeeperTestSuite) TestTransferDelegation_CanTransferVested() { - _, addrs := app.GeneratePrivKeyAddressPairs(4) - valAccAddr, fromDelegator, toDelegator := addrs[0], addrs[1], addrs[2] - valAddr := sdk.ValAddress(valAccAddr) - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(i(1e9))) - suite.CreateVestingAccountWithAddress(fromDelegator, suite.NewBondCoins(i(2e9)), suite.NewBondCoins(i(1e9))) - - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(2e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - shares := d("1000000000.0") - _, err := suite.Keeper.TransferDelegation(suite.Ctx, valAddr, fromDelegator, toDelegator, shares) - suite.NoError(err) - suite.DelegationSharesEqual(valAddr, fromDelegator, fromDelegationShares.Sub(shares)) - suite.DelegationSharesEqual(valAddr, toDelegator, shares) -} - -func (suite *KeeperTestSuite) TestTransferDelegation_CannotTransferVesting() { - _, addrs := app.GeneratePrivKeyAddressPairs(4) - valAccAddr, fromDelegator, toDelegator := addrs[0], addrs[1], addrs[2] - valAddr := sdk.ValAddress(valAccAddr) - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(i(1e9))) - suite.CreateVestingAccountWithAddress(fromDelegator, suite.NewBondCoins(i(2e9)), suite.NewBondCoins(i(1e9))) - - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - suite.CreateDelegation(valAddr, fromDelegator, i(2e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - _, err := suite.Keeper.TransferDelegation(suite.Ctx, valAddr, fromDelegator, toDelegator, d("1000000001.0")) - suite.ErrorIs(err, sdkerrors.ErrInsufficientFunds) -} diff --git a/x/liquid/module.go b/x/liquid/module.go deleted file mode 100644 index 63639201..00000000 --- a/x/liquid/module.go +++ /dev/null @@ -1,125 +0,0 @@ -package liquid - -import ( - "context" - "encoding/json" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/kava-labs/kava/x/liquid/client/cli" - "github.com/kava-labs/kava/x/liquid/keeper" - "github.com/kava-labs/kava/x/liquid/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { - return []byte("{}") -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, _ client.TxEncodingConfig, _ json.RawMessage) error { - return nil -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// GetTxCmd returns the root tx command for the module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - } -} - -// Name module name -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// RegisterInvariants register module invariants -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) -} - -// InitGenesis module init-genesis -func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONCodec, _ json.RawMessage) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} - -// ExportGenesis module export genesis -func (am AppModule) ExportGenesis(_ sdk.Context, cdc codec.JSONCodec) json.RawMessage { - return am.DefaultGenesis(cdc) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - -// EndBlock module end-block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/liquid/spec/01_concepts.md b/x/liquid/spec/01_concepts.md deleted file mode 100644 index e6798dc6..00000000 --- a/x/liquid/spec/01_concepts.md +++ /dev/null @@ -1,7 +0,0 @@ - - -# Concepts - -This module is responsible for the minting and burning of liquid staking receipt tokens, collectively referred to as `bkava`. Delegated kava can be converted to delegator-specific `bkava`. Ie, 100 KAVA delegated to validator `kavavaloper123` can be converted to 100 `bkava-kavavaloper123`. Similarly, 100 `bkava-kavavaloper123` can be converted back to a delegation of 100 KAVA to `kavavaloper123`. In this design, all validators can permissionlessly participate in liquid staking while users retain the delegator specific slashing risk and voting rights of their original validator. Note that because each `bkava` denom is validator specific, this module does not specify a fungibility mechanism for `bkava` denoms. \ No newline at end of file diff --git a/x/liquid/spec/02_state.md b/x/liquid/spec/02_state.md deleted file mode 100644 index cff1c133..00000000 --- a/x/liquid/spec/02_state.md +++ /dev/null @@ -1,16 +0,0 @@ - - -# State - -## Module Account -The liquid module defines a module account with name `liquid` that has `Minter` and `Burner` module account permissions. The associated bech32 account address is `kava1gggszchqvw2l65my03mak6q5qfhz9cn2g0px29`. - -## Genesis state - -The liquid module does not require any module specific genesis state. - -## Store - -The liquid module does not store any module specific data. All `bkava` token receipts are minted directly to the delegators account, and the delegation object is transferred to the liquid module account. \ No newline at end of file diff --git a/x/liquid/spec/03_messages.md b/x/liquid/spec/03_messages.md deleted file mode 100644 index e12b68c0..00000000 --- a/x/liquid/spec/03_messages.md +++ /dev/null @@ -1,79 +0,0 @@ - - -# Messages - -`bkava` is minted using `MsgMintDerivative`. - - -```go -// MsgMintDerivative defines the Msg/MintDerivative request type. -type MsgMintDerivative struct { - // sender is the owner of the delegation to be converted - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // validator is the validator of the delegation to be converted - Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` - // amount is the quantity of staked assets to be converted - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} -``` - -### Actions - -* converts an existing delegation into bkava tokens -* delegation is transferred from the sender to a module account -* validator specific bkava are minted and sent to the sender - -### Example: - -```jsonc -{ - // user who owns the delegation - "sender": "kava10wlnqzyss4accfqmyxwx5jy5x9nfkwh6qm7n4t", - // validator the user has delegated to - "validator": "kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42", - // amount of staked ukava to be converted into bkava - "amount": { - "amount": "1000000000", - "denom": "ukava" - } -} -``` - -`bkava` can be burned using `MsgBurnDerivative`. - -```go -// MsgBurnDerivative defines the Msg/BurnDerivative request type. -type MsgBurnDerivative struct { - // sender is the owner of the derivatives to be converted - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // validator is the validator of the derivatives to be converted - Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` - // amount is the quantity of derivatives to be converted - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} -``` - -### Actions - -* converts bkava tokens into a delegation -* bkava is burned -* a delegation equal to number of bkava is transferred to user - - -### Example - -```jsonc -{ - // user who owns the bkava - "sender": "kava10wlnqzyss4accfqmyxwx5jy5x9nfkwh6qm7n4t", - // the amount of bkava the user wants to convert back into normal staked kava - "amount": { - "amount": "1234000000", - "denom": "bkava-kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42" - }, - // the validator behind the bkava, this address must match the one embedded in the bkava denom above - "validator": "kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42" -} -``` diff --git a/x/liquid/spec/04_events.md b/x/liquid/spec/04_events.md deleted file mode 100644 index 07d7a086..00000000 --- a/x/liquid/spec/04_events.md +++ /dev/null @@ -1,25 +0,0 @@ - - -# Events - -The `x/liquid` module emits the following events: - -## MsgMintDerivative - -| Type | Attribute Key | Attribute Value | -| --------------- | ----------------- | ------------------ | -| mint_derivative | delegator | `{delegator address}` | -| mint_derivative | validator | `{validator address}` | -| mint_derivative | amount | `{amount}` | -| mint_derivative | shares_transferred| `{shares transferred}`| - -## MsgBurnDerivative - -| Type | Attribute Key | Attribute Value | -| --------------- | ----------------- | ------------------ | -| burn_derivative | delegator | `{delegator address}` | -| burn_derivative | validator | `{validator address}` | -| burn_derivative | amount | `{amount}` | -| burn_derivative | shares_transferred| `{shares transferred}`| \ No newline at end of file diff --git a/x/liquid/spec/05_params.md b/x/liquid/spec/05_params.md deleted file mode 100644 index 5df5c058..00000000 --- a/x/liquid/spec/05_params.md +++ /dev/null @@ -1,7 +0,0 @@ - - -# Parameters - -The liquid module has no parameters. \ No newline at end of file diff --git a/x/liquid/types/codec.go b/x/liquid/types/codec.go deleted file mode 100644 index adaea192..00000000 --- a/x/liquid/types/codec.go +++ /dev/null @@ -1,41 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgMintDerivative{}, "liquid/MsgMintDerivative", nil) - cdc.RegisterConcrete(&MsgBurnDerivative{}, "liquid/MsgBurnDerivative", nil) -} - -// RegisterInterfaces registers proto messages under their interfaces for unmarshalling, -// in addition to registering the msg service for handling tx msgs. -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgMintDerivative{}, - &MsgBurnDerivative{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/liquid/types/common_test.go b/x/liquid/types/common_test.go deleted file mode 100644 index e88e1d5e..00000000 --- a/x/liquid/types/common_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package types_test - -import ( - "os" - "testing" - - "github.com/kava-labs/kava/app" -) - -func TestMain(m *testing.M) { - app.SetSDKConfig() - os.Exit(m.Run()) -} diff --git a/x/liquid/types/errors.go b/x/liquid/types/errors.go deleted file mode 100644 index fe75247e..00000000 --- a/x/liquid/types/errors.go +++ /dev/null @@ -1,13 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -var ( - ErrNoValidatorFound = errorsmod.Register(ModuleName, 2, "validator does not exist") - ErrNoDelegatorForAddress = errorsmod.Register(ModuleName, 3, "delegator does not contain delegation") - ErrInvalidDenom = errorsmod.Register(ModuleName, 4, "invalid denom") - ErrNotEnoughDelegationShares = errorsmod.Register(ModuleName, 5, "not enough delegation shares") - ErrRedelegationsNotCompleted = errorsmod.Register(ModuleName, 6, "active redelegations cannot be transferred") - ErrUntransferableShares = errorsmod.Register(ModuleName, 7, "shares cannot be transferred") - ErrSelfDelegationBelowMinimum = errorsmod.Register(ModuleName, 8, "validator's self delegation must be greater than their minimum self delegation") -) diff --git a/x/liquid/types/events.go b/x/liquid/types/events.go deleted file mode 100644 index 27658719..00000000 --- a/x/liquid/types/events.go +++ /dev/null @@ -1,11 +0,0 @@ -package types - -const ( - EventTypeMintDerivative = "mint_derivative" - EventTypeBurnDerivative = "burn_derivative" - - AttributeValueCategory = ModuleName - AttributeKeyDelegator = "delegator" - AttributeKeyValidator = "validator" - AttributeKeySharesTransferred = "shares_transferred" -) diff --git a/x/liquid/types/expected_keepers.go b/x/liquid/types/expected_keepers.go deleted file mode 100644 index 3c059d59..00000000 --- a/x/liquid/types/expected_keepers.go +++ /dev/null @@ -1,57 +0,0 @@ -package types - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// BankKeeper defines the expected bank keeper -type BankKeeper interface { - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error - - MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - UndelegateCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - - IterateTotalSupply(ctx sdk.Context, cb func(sdk.Coin) bool) - GetSupply(ctx sdk.Context, denom string) sdk.Coin -} - -// AccountKeeper defines the expected keeper interface for interacting with account -type AccountKeeper interface { - GetModuleAddress(moduleName string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, name string) authtypes.ModuleAccountI - GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI -} - -// StakingKeeper defines the expected keeper interface for interacting with staking -type StakingKeeper interface { - BondDenom(ctx sdk.Context) (res string) - - GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool) - GetDelegation(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) (delegation stakingtypes.Delegation, found bool) - IterateDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress, cb func(delegation stakingtypes.Delegation) (stop bool)) - HasReceivingRedelegation(ctx sdk.Context, delAddr sdk.AccAddress, valDstAddr sdk.ValAddress) bool - - ValidateUnbondAmount( - ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, amt sdkmath.Int, - ) (shares sdk.Dec, err error) - - Delegate( - ctx sdk.Context, delAddr sdk.AccAddress, bondAmt sdkmath.Int, tokenSrc stakingtypes.BondStatus, - validator stakingtypes.Validator, subtractAccount bool, - ) (newShares sdk.Dec, err error) - Unbond( - ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, shares sdk.Dec, - ) (amount sdkmath.Int, err error) -} - -type DistributionKeeper interface { - GetDelegatorWithdrawAddr(ctx sdk.Context, delAddr sdk.AccAddress) sdk.AccAddress - WithdrawDelegationRewards(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) (sdk.Coins, error) -} diff --git a/x/liquid/types/key.go b/x/liquid/types/key.go deleted file mode 100644 index a244ec5e..00000000 --- a/x/liquid/types/key.go +++ /dev/null @@ -1,46 +0,0 @@ -package types - -import ( - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName The name that will be used throughout the module - ModuleName = "liquid" - - // RouterKey Top level router key - RouterKey = ModuleName - - // ModuleAccountName is the module account's name - ModuleAccountName = ModuleName - - DefaultDerivativeDenom = "bkava" - - DenomSeparator = "-" -) - -func GetLiquidStakingTokenDenom(bondDenom string, valAddr sdk.ValAddress) string { - return fmt.Sprintf("%s%s%s", bondDenom, DenomSeparator, valAddr.String()) -} - -// ParseLiquidStakingTokenDenom extracts a validator address from a derivative denom. -func ParseLiquidStakingTokenDenom(denom string) (sdk.ValAddress, error) { - elements := strings.Split(denom, DenomSeparator) - if len(elements) != 2 { - return nil, fmt.Errorf("cannot parse denom %s", denom) - } - - if elements[0] != DefaultDerivativeDenom { - return nil, fmt.Errorf("invalid denom prefix, expected %s, got %s", DefaultDerivativeDenom, elements[0]) - } - - addr, err := sdk.ValAddressFromBech32(elements[1]) - if err != nil { - return nil, fmt.Errorf("invalid denom validator address: %w", err) - } - - return addr, nil -} diff --git a/x/liquid/types/key_test.go b/x/liquid/types/key_test.go deleted file mode 100644 index bb324a46..00000000 --- a/x/liquid/types/key_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package types_test - -import ( - "fmt" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/liquid/types" - "github.com/stretchr/testify/require" -) - -func TestParseLiquidStakingTokenDenom(t *testing.T) { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - tests := []struct { - name string - giveDenom string - wantAddress sdk.ValAddress - wantErr error - }{ - { - name: "valid denom", - giveDenom: "bkava-kavavaloper1ze7y9qwdddejmy7jlw4cymqqlt2wh05y6cpt5a", - wantAddress: mustValAddressFromBech32("kavavaloper1ze7y9qwdddejmy7jlw4cymqqlt2wh05y6cpt5a"), - wantErr: nil, - }, - { - name: "invalid prefix", - giveDenom: "ukava-kavavaloper1ze7y9qwdddejmy7jlw4cymqqlt2wh05y6cpt5a", - wantAddress: mustValAddressFromBech32("kavavaloper1ze7y9qwdddejmy7jlw4cymqqlt2wh05y6cpt5a"), - wantErr: fmt.Errorf("invalid denom prefix, expected %s, got %s", types.DefaultDerivativeDenom, "ukava"), - }, - { - name: "invalid validator address", - giveDenom: "bkava-kavavaloper1ze7y9qw", - wantAddress: sdk.ValAddress{}, - wantErr: fmt.Errorf("invalid denom validator address: decoding bech32 failed: invalid checksum"), - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - addr, err := types.ParseLiquidStakingTokenDenom(tt.giveDenom) - - if tt.wantErr != nil { - require.Error(t, err) - require.Contains(t, err.Error(), tt.wantErr.Error()) - } else { - require.NoError(t, err) - require.Equal(t, tt.wantAddress, addr) - } - }) - } -} diff --git a/x/liquid/types/msg.go b/x/liquid/types/msg.go deleted file mode 100644 index 0b94f4a3..00000000 --- a/x/liquid/types/msg.go +++ /dev/null @@ -1,121 +0,0 @@ -package types - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" -) - -const ( - // TypeMsgMintDerivative represents the type string for MsgMintDerivative - TypeMsgMintDerivative = "mint_derivative" - // TypeMsgBurnDerivative represents the type string for MsgBurnDerivative - TypeMsgBurnDerivative = "burn_derivative" -) - -// ensure Msg interface compliance at compile time -var ( - _ sdk.Msg = &MsgMintDerivative{} - _ legacytx.LegacyMsg = &MsgMintDerivative{} - _ sdk.Msg = &MsgBurnDerivative{} - _ legacytx.LegacyMsg = &MsgBurnDerivative{} -) - -// NewMsgMintDerivative returns a new MsgMintDerivative -func NewMsgMintDerivative(sender sdk.AccAddress, validator sdk.ValAddress, amount sdk.Coin) MsgMintDerivative { - return MsgMintDerivative{ - Sender: sender.String(), - Validator: validator.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgMintDerivative) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgMintDerivative) Type() string { return TypeMsgMintDerivative } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgMintDerivative) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - _, err = sdk.ValAddressFromBech32(msg.Validator) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if msg.Amount.IsNil() || !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "'%s'", msg.Amount) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgMintDerivative) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgMintDerivative) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgBurnDerivative returns a new MsgBurnDerivative -func NewMsgBurnDerivative(sender sdk.AccAddress, validator sdk.ValAddress, amount sdk.Coin) MsgBurnDerivative { - return MsgBurnDerivative{ - Sender: sender.String(), - Validator: validator.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgBurnDerivative) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgBurnDerivative) Type() string { return TypeMsgBurnDerivative } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgBurnDerivative) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - _, err = sdk.ValAddressFromBech32(msg.Validator) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if msg.Amount.IsNil() || !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "'%s'", msg.Amount) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgBurnDerivative) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgBurnDerivative) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} diff --git a/x/liquid/types/msg_test.go b/x/liquid/types/msg_test.go deleted file mode 100644 index 48b92e61..00000000 --- a/x/liquid/types/msg_test.go +++ /dev/null @@ -1,164 +0,0 @@ -package types_test - -import ( - fmt "fmt" - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/kava-labs/kava/x/liquid/types" -) - -func TestMsgMintDerivative_Signing(t *testing.T) { - address := mustAccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - validatorAddress := mustValAddressFromBech32("kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42") - - msg := types.NewMsgMintDerivative( - address, - validatorAddress, - sdk.NewCoin("ukava", sdkmath.NewInt(1e9)), - ) - - // checking for the "type" field ensures the msg is registered on the amino codec - signBytes := []byte( - `{"type":"liquid/MsgMintDerivative","value":{"amount":{"amount":"1000000000","denom":"ukava"},"sender":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","validator":"kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42"}}`, - ) - - assert.Equal(t, []sdk.AccAddress{address}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsgBurnDerivative_Signing(t *testing.T) { - address := mustAccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - validatorAddress := mustValAddressFromBech32("kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42") - - msg := types.NewMsgBurnDerivative( - address, - validatorAddress, - sdk.NewCoin("bkava-kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42", sdkmath.NewInt(1e9)), - ) - - // checking for the "type" field ensures the msg is registered on the amino codec - signBytes := []byte( - `{"type":"liquid/MsgBurnDerivative","value":{"amount":{"amount":"1000000000","denom":"bkava-kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42"},"sender":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","validator":"kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42"}}`, - ) - - assert.Equal(t, []sdk.AccAddress{address}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsg_Validate(t *testing.T) { - validAddress := mustAccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - validValidatorAddress := mustValAddressFromBech32("kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42") - validCoin := sdk.NewInt64Coin("ukava", 1e9) - - type msgArgs struct { - sender string - validator string - amount sdk.Coin - } - tests := []struct { - name string - msgArgs msgArgs - expectedErr error - }{ - { - name: "normal is valid", - msgArgs: msgArgs{ - sender: validAddress.String(), - validator: validValidatorAddress.String(), - amount: validCoin, - }, - }, - { - name: "invalid sender", - msgArgs: msgArgs{ - sender: "invalid", - validator: validValidatorAddress.String(), - amount: validCoin, - }, - expectedErr: sdkerrors.ErrInvalidAddress, - }, - { - name: "invalid short sender", - msgArgs: msgArgs{ - sender: "kava1uexte6", // encoded zero length address - validator: validValidatorAddress.String(), - amount: validCoin, - }, - expectedErr: sdkerrors.ErrInvalidAddress, - }, - { - name: "invalid validator", - msgArgs: msgArgs{ - sender: validAddress.String(), - validator: "invalid", - amount: validCoin, - }, - expectedErr: sdkerrors.ErrInvalidAddress, - }, - { - name: "invalid nil coin", - msgArgs: msgArgs{ - sender: validAddress.String(), - validator: validValidatorAddress.String(), - amount: sdk.Coin{}, - }, - expectedErr: sdkerrors.ErrInvalidCoins, - }, - { - name: "invalid zero coin", - msgArgs: msgArgs{ - sender: validAddress.String(), - validator: validValidatorAddress.String(), - amount: sdk.NewInt64Coin("ukava", 0), - }, - expectedErr: sdkerrors.ErrInvalidCoins, - }, - } - - for _, tc := range tests { - msgs := []sdk.Msg{ - &types.MsgMintDerivative{ - Sender: tc.msgArgs.sender, - Validator: tc.msgArgs.validator, - Amount: tc.msgArgs.amount, - }, - &types.MsgBurnDerivative{ - Sender: tc.msgArgs.sender, - Validator: tc.msgArgs.validator, - Amount: tc.msgArgs.amount, - }, - } - for _, msg := range msgs { - t.Run(fmt.Sprintf("%s/%T", tc.name, msg), func(t *testing.T) { - err := msg.ValidateBasic() - if tc.expectedErr == nil { - require.NoError(t, err) - } else { - require.ErrorIs(t, err, tc.expectedErr, "expected error '%s' not found in actual '%s'", tc.expectedErr, err) - } - }) - } - } -} - -func mustAccAddressFromBech32(address string) sdk.AccAddress { - addr, err := sdk.AccAddressFromBech32(address) - if err != nil { - panic(err) - } - return addr -} - -func mustValAddressFromBech32(address string) sdk.ValAddress { - addr, err := sdk.ValAddressFromBech32(address) - if err != nil { - panic(err) - } - return addr -} diff --git a/x/liquid/types/query.pb.go b/x/liquid/types/query.pb.go deleted file mode 100644 index f771eb3b..00000000 --- a/x/liquid/types/query.pb.go +++ /dev/null @@ -1,1002 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/liquid/v1beta1/query.proto - -package types - -import ( - context "context" - 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" - 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 - -// QueryDelegatedBalanceRequest defines the request type for Query/DelegatedBalance method. -type QueryDelegatedBalanceRequest struct { - // delegator is the address of the account to query - Delegator string `protobuf:"bytes,1,opt,name=delegator,proto3" json:"delegator,omitempty"` -} - -func (m *QueryDelegatedBalanceRequest) Reset() { *m = QueryDelegatedBalanceRequest{} } -func (m *QueryDelegatedBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDelegatedBalanceRequest) ProtoMessage() {} -func (*QueryDelegatedBalanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_0d745428489be444, []int{0} -} -func (m *QueryDelegatedBalanceRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDelegatedBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDelegatedBalanceRequest.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 *QueryDelegatedBalanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDelegatedBalanceRequest.Merge(m, src) -} -func (m *QueryDelegatedBalanceRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDelegatedBalanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDelegatedBalanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDelegatedBalanceRequest proto.InternalMessageInfo - -// DelegatedBalanceResponse defines the response type for the Query/DelegatedBalance method. -type QueryDelegatedBalanceResponse struct { - // vested is the amount of all delegated coins that have vested (ie not locked) - Vested types.Coin `protobuf:"bytes,1,opt,name=vested,proto3" json:"vested"` - // vesting is the amount of all delegated coins that are still vesting (ie locked) - Vesting types.Coin `protobuf:"bytes,2,opt,name=vesting,proto3" json:"vesting"` -} - -func (m *QueryDelegatedBalanceResponse) Reset() { *m = QueryDelegatedBalanceResponse{} } -func (m *QueryDelegatedBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDelegatedBalanceResponse) ProtoMessage() {} -func (*QueryDelegatedBalanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0d745428489be444, []int{1} -} -func (m *QueryDelegatedBalanceResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDelegatedBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDelegatedBalanceResponse.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 *QueryDelegatedBalanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDelegatedBalanceResponse.Merge(m, src) -} -func (m *QueryDelegatedBalanceResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDelegatedBalanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDelegatedBalanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDelegatedBalanceResponse proto.InternalMessageInfo - -// QueryTotalSupplyRequest defines the request type for Query/TotalSupply method. -type QueryTotalSupplyRequest struct { -} - -func (m *QueryTotalSupplyRequest) Reset() { *m = QueryTotalSupplyRequest{} } -func (m *QueryTotalSupplyRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalSupplyRequest) ProtoMessage() {} -func (*QueryTotalSupplyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_0d745428489be444, []int{2} -} -func (m *QueryTotalSupplyRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalSupplyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalSupplyRequest.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 *QueryTotalSupplyRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalSupplyRequest.Merge(m, src) -} -func (m *QueryTotalSupplyRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalSupplyRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalSupplyRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalSupplyRequest proto.InternalMessageInfo - -// TotalSupplyResponse defines the response type for the Query/TotalSupply method. -type QueryTotalSupplyResponse struct { - // Height is the block height at which these totals apply - Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` - // Result is a list of coins supplied to liquid - Result github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=result,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"result"` -} - -func (m *QueryTotalSupplyResponse) Reset() { *m = QueryTotalSupplyResponse{} } -func (m *QueryTotalSupplyResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalSupplyResponse) ProtoMessage() {} -func (*QueryTotalSupplyResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0d745428489be444, []int{3} -} -func (m *QueryTotalSupplyResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalSupplyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalSupplyResponse.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 *QueryTotalSupplyResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalSupplyResponse.Merge(m, src) -} -func (m *QueryTotalSupplyResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalSupplyResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalSupplyResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalSupplyResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryDelegatedBalanceRequest)(nil), "kava.liquid.v1beta1.QueryDelegatedBalanceRequest") - proto.RegisterType((*QueryDelegatedBalanceResponse)(nil), "kava.liquid.v1beta1.QueryDelegatedBalanceResponse") - proto.RegisterType((*QueryTotalSupplyRequest)(nil), "kava.liquid.v1beta1.QueryTotalSupplyRequest") - proto.RegisterType((*QueryTotalSupplyResponse)(nil), "kava.liquid.v1beta1.QueryTotalSupplyResponse") -} - -func init() { proto.RegisterFile("kava/liquid/v1beta1/query.proto", fileDescriptor_0d745428489be444) } - -var fileDescriptor_0d745428489be444 = []byte{ - // 499 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x53, 0x4f, 0x6f, 0xd3, 0x30, - 0x1c, 0x8d, 0x3b, 0x28, 0x9a, 0x77, 0x41, 0x66, 0x82, 0xac, 0x1a, 0xe9, 0x08, 0x97, 0x21, 0xd1, - 0x98, 0x16, 0x04, 0x82, 0x1b, 0x05, 0x71, 0x27, 0x43, 0x1c, 0xb8, 0x54, 0x4e, 0x62, 0xb9, 0xd6, - 0x32, 0x3b, 0x8d, 0x9d, 0x8a, 0x0a, 0x71, 0xe1, 0x13, 0x20, 0x4d, 0x88, 0xef, 0xc0, 0x19, 0xbe, - 0x43, 0x8f, 0x13, 0x1c, 0xe0, 0xc4, 0x9f, 0x96, 0x0f, 0x82, 0x62, 0xbb, 0x63, 0x62, 0xdd, 0x34, - 0x4e, 0xb1, 0xfd, 0x7b, 0xef, 0xf9, 0xf9, 0xf7, 0x7e, 0x81, 0xed, 0x5d, 0x32, 0x26, 0x38, 0xe7, - 0xa3, 0x8a, 0x67, 0x78, 0xdc, 0x4d, 0xa8, 0x26, 0x5d, 0x3c, 0xaa, 0x68, 0x39, 0x89, 0x8a, 0x52, - 0x6a, 0x89, 0x2e, 0xd5, 0x80, 0xc8, 0x02, 0x22, 0x07, 0x68, 0x05, 0xa9, 0x54, 0x7b, 0x52, 0xe1, - 0x84, 0x28, 0x7a, 0xc8, 0x4a, 0x25, 0x17, 0x96, 0xd4, 0xda, 0xb0, 0xf5, 0x81, 0xd9, 0x61, 0xbb, - 0x71, 0xa5, 0x75, 0x26, 0x99, 0xb4, 0xe7, 0xf5, 0xca, 0x9d, 0x6e, 0x32, 0x29, 0x59, 0x4e, 0x31, - 0x29, 0x38, 0x26, 0x42, 0x48, 0x4d, 0x34, 0x97, 0xc2, 0x71, 0xc2, 0xe7, 0x70, 0xf3, 0x69, 0x6d, - 0xe9, 0x31, 0xcd, 0x29, 0x23, 0x9a, 0x66, 0x7d, 0x92, 0x13, 0x91, 0xd2, 0x98, 0x8e, 0x2a, 0xaa, - 0x34, 0xba, 0x0b, 0x57, 0x33, 0x5b, 0x92, 0xa5, 0x0f, 0xb6, 0xc0, 0xf6, 0x6a, 0xdf, 0xff, 0xfc, - 0xb1, 0xb3, 0xee, 0x2e, 0x7e, 0x98, 0x65, 0x25, 0x55, 0x6a, 0x47, 0x97, 0x5c, 0xb0, 0xf8, 0x2f, - 0x34, 0xdc, 0x07, 0xf0, 0xea, 0x09, 0xc2, 0xaa, 0x90, 0x42, 0x51, 0x74, 0x0f, 0x36, 0xc7, 0x54, - 0x69, 0x9a, 0x19, 0xd9, 0xb5, 0xde, 0x46, 0xe4, 0x34, 0xeb, 0x97, 0x2f, 0xda, 0x11, 0x3d, 0x92, - 0x5c, 0xf4, 0xcf, 0x4d, 0xbf, 0xb7, 0xbd, 0xd8, 0xc1, 0xd1, 0x7d, 0x78, 0xa1, 0x5e, 0x71, 0xc1, - 0xfc, 0xc6, 0xd9, 0x98, 0x0b, 0x7c, 0xb8, 0x01, 0xaf, 0x18, 0x53, 0xcf, 0xa4, 0x26, 0xf9, 0x4e, - 0x55, 0x14, 0xf9, 0xc4, 0x3d, 0x34, 0x7c, 0x0f, 0xa0, 0x7f, 0xbc, 0xe6, 0xbc, 0x5e, 0x86, 0xcd, - 0x21, 0xe5, 0x6c, 0xa8, 0x8d, 0xd7, 0x95, 0xd8, 0xed, 0x50, 0x0a, 0x9b, 0x25, 0x55, 0x55, 0xae, - 0xfd, 0xc6, 0xd6, 0xca, 0xe9, 0x4e, 0x6e, 0xd5, 0x4e, 0x3e, 0xfc, 0x68, 0x6f, 0x33, 0xae, 0x87, - 0x55, 0x12, 0xa5, 0x72, 0xcf, 0xa5, 0xe7, 0x3e, 0x1d, 0x95, 0xed, 0x62, 0x3d, 0x29, 0xa8, 0x32, - 0x04, 0x15, 0x3b, 0xe9, 0xde, 0xd7, 0x06, 0x3c, 0x6f, 0x9c, 0xa1, 0x4f, 0x00, 0x5e, 0xfc, 0xb7, - 0x9f, 0xa8, 0x1b, 0x2d, 0x19, 0xa3, 0xe8, 0xb4, 0x50, 0x5b, 0xbd, 0xff, 0xa1, 0xd8, 0x16, 0x84, - 0x0f, 0xde, 0x7c, 0xf9, 0xbd, 0xdf, 0xb8, 0x83, 0x7a, 0x78, 0xd9, 0x58, 0x67, 0x0b, 0xda, 0x20, - 0xb1, 0x3c, 0xfc, 0xea, 0x70, 0x16, 0x5e, 0xa3, 0x77, 0x00, 0xae, 0x1d, 0x69, 0x2b, 0xba, 0x79, - 0xf2, 0xfd, 0xc7, 0x93, 0x69, 0x75, 0xce, 0x88, 0x76, 0x46, 0x6f, 0x18, 0xa3, 0xd7, 0xd1, 0xb5, - 0xa5, 0x46, 0x75, 0xcd, 0x18, 0x28, 0x43, 0xe9, 0x3f, 0x99, 0xfe, 0x0a, 0xbc, 0xe9, 0x2c, 0x00, - 0x07, 0xb3, 0x00, 0xfc, 0x9c, 0x05, 0xe0, 0xed, 0x3c, 0xf0, 0x0e, 0xe6, 0x81, 0xf7, 0x6d, 0x1e, - 0x78, 0x2f, 0x8e, 0x26, 0x55, 0x4b, 0x75, 0x72, 0x92, 0x28, 0x2b, 0xfa, 0x72, 0x21, 0x6b, 0xf2, - 0x4a, 0x9a, 0xe6, 0x5f, 0xba, 0xfd, 0x27, 0x00, 0x00, 0xff, 0xff, 0xb8, 0xc2, 0xc4, 0x35, 0xf2, - 0x03, 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 { - // DelegatedBalance returns an account's vesting and vested coins currently delegated to validators. - // It ignores coins in unbonding delegations. - DelegatedBalance(ctx context.Context, in *QueryDelegatedBalanceRequest, opts ...grpc.CallOption) (*QueryDelegatedBalanceResponse, error) - // TotalSupply returns the total sum of all coins currently locked into the liquid module. - TotalSupply(ctx context.Context, in *QueryTotalSupplyRequest, opts ...grpc.CallOption) (*QueryTotalSupplyResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) DelegatedBalance(ctx context.Context, in *QueryDelegatedBalanceRequest, opts ...grpc.CallOption) (*QueryDelegatedBalanceResponse, error) { - out := new(QueryDelegatedBalanceResponse) - err := c.cc.Invoke(ctx, "/kava.liquid.v1beta1.Query/DelegatedBalance", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalSupply(ctx context.Context, in *QueryTotalSupplyRequest, opts ...grpc.CallOption) (*QueryTotalSupplyResponse, error) { - out := new(QueryTotalSupplyResponse) - err := c.cc.Invoke(ctx, "/kava.liquid.v1beta1.Query/TotalSupply", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // DelegatedBalance returns an account's vesting and vested coins currently delegated to validators. - // It ignores coins in unbonding delegations. - DelegatedBalance(context.Context, *QueryDelegatedBalanceRequest) (*QueryDelegatedBalanceResponse, error) - // TotalSupply returns the total sum of all coins currently locked into the liquid module. - TotalSupply(context.Context, *QueryTotalSupplyRequest) (*QueryTotalSupplyResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) DelegatedBalance(ctx context.Context, req *QueryDelegatedBalanceRequest) (*QueryDelegatedBalanceResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DelegatedBalance not implemented") -} -func (*UnimplementedQueryServer) TotalSupply(ctx context.Context, req *QueryTotalSupplyRequest) (*QueryTotalSupplyResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalSupply not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_DelegatedBalance_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDelegatedBalanceRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).DelegatedBalance(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.liquid.v1beta1.Query/DelegatedBalance", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).DelegatedBalance(ctx, req.(*QueryDelegatedBalanceRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalSupply_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalSupplyRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalSupply(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.liquid.v1beta1.Query/TotalSupply", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalSupply(ctx, req.(*QueryTotalSupplyRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.liquid.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "DelegatedBalance", - Handler: _Query_DelegatedBalance_Handler, - }, - { - MethodName: "TotalSupply", - Handler: _Query_TotalSupply_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/liquid/v1beta1/query.proto", -} - -func (m *QueryDelegatedBalanceRequest) 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 *QueryDelegatedBalanceRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDelegatedBalanceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Delegator) > 0 { - i -= len(m.Delegator) - copy(dAtA[i:], m.Delegator) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Delegator))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDelegatedBalanceResponse) 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 *QueryDelegatedBalanceResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDelegatedBalanceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Vesting.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.Vested.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 *QueryTotalSupplyRequest) 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 *QueryTotalSupplyRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalSupplyRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryTotalSupplyResponse) 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 *QueryTotalSupplyResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalSupplyResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Result) > 0 { - for iNdEx := len(m.Result) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Result[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if m.Height != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.Height)) - i-- - dAtA[i] = 0x8 - } - 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 *QueryDelegatedBalanceRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Delegator) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDelegatedBalanceResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Vested.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.Vesting.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryTotalSupplyRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryTotalSupplyResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Height != 0 { - n += 1 + sovQuery(uint64(m.Height)) - } - if len(m.Result) > 0 { - for _, e := range m.Result { - l = e.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 *QueryDelegatedBalanceRequest) 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: QueryDelegatedBalanceRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDelegatedBalanceRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Delegator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Delegator = string(dAtA[iNdEx:postIndex]) - 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 *QueryDelegatedBalanceResponse) 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: QueryDelegatedBalanceResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDelegatedBalanceResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Vested", 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.Vested.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Vesting", 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.Vesting.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 *QueryTotalSupplyRequest) 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: QueryTotalSupplyRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalSupplyRequest: 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 *QueryTotalSupplyResponse) 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: QueryTotalSupplyResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalSupplyResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) - } - m.Height = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Height |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Result", 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.Result = append(m.Result, types.Coin{}) - if err := m.Result[len(m.Result)-1].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/liquid/types/tx.pb.go b/x/liquid/types/tx.pb.go deleted file mode 100644 index 1fde9eba..00000000 --- a/x/liquid/types/tx.pb.go +++ /dev/null @@ -1,1188 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/liquid/v1beta1/tx.proto - -package types - -import ( - context "context" - 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" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - 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 - -// MsgMintDerivative defines the Msg/MintDerivative request type. -type MsgMintDerivative struct { - // sender is the owner of the delegation to be converted - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // validator is the validator of the delegation to be converted - Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` - // amount is the quantity of staked assets to be converted - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *MsgMintDerivative) Reset() { *m = MsgMintDerivative{} } -func (m *MsgMintDerivative) String() string { return proto.CompactTextString(m) } -func (*MsgMintDerivative) ProtoMessage() {} -func (*MsgMintDerivative) Descriptor() ([]byte, []int) { - return fileDescriptor_738981106e50f269, []int{0} -} -func (m *MsgMintDerivative) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgMintDerivative) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMintDerivative.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 *MsgMintDerivative) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMintDerivative.Merge(m, src) -} -func (m *MsgMintDerivative) XXX_Size() int { - return m.Size() -} -func (m *MsgMintDerivative) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMintDerivative.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMintDerivative proto.InternalMessageInfo - -func (m *MsgMintDerivative) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgMintDerivative) GetValidator() string { - if m != nil { - return m.Validator - } - return "" -} - -func (m *MsgMintDerivative) GetAmount() types.Coin { - if m != nil { - return m.Amount - } - return types.Coin{} -} - -// MsgMintDerivativeResponse defines the Msg/MintDerivative response type. -type MsgMintDerivativeResponse struct { - // received is the amount of staking derivative minted and sent to the sender - Received types.Coin `protobuf:"bytes,1,opt,name=received,proto3" json:"received"` -} - -func (m *MsgMintDerivativeResponse) Reset() { *m = MsgMintDerivativeResponse{} } -func (m *MsgMintDerivativeResponse) String() string { return proto.CompactTextString(m) } -func (*MsgMintDerivativeResponse) ProtoMessage() {} -func (*MsgMintDerivativeResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_738981106e50f269, []int{1} -} -func (m *MsgMintDerivativeResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgMintDerivativeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMintDerivativeResponse.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 *MsgMintDerivativeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMintDerivativeResponse.Merge(m, src) -} -func (m *MsgMintDerivativeResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgMintDerivativeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMintDerivativeResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMintDerivativeResponse proto.InternalMessageInfo - -func (m *MsgMintDerivativeResponse) GetReceived() types.Coin { - if m != nil { - return m.Received - } - return types.Coin{} -} - -// MsgBurnDerivative defines the Msg/BurnDerivative request type. -type MsgBurnDerivative struct { - // sender is the owner of the derivatives to be converted - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // validator is the validator of the derivatives to be converted - Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` - // amount is the quantity of derivatives to be converted - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *MsgBurnDerivative) Reset() { *m = MsgBurnDerivative{} } -func (m *MsgBurnDerivative) String() string { return proto.CompactTextString(m) } -func (*MsgBurnDerivative) ProtoMessage() {} -func (*MsgBurnDerivative) Descriptor() ([]byte, []int) { - return fileDescriptor_738981106e50f269, []int{2} -} -func (m *MsgBurnDerivative) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgBurnDerivative) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgBurnDerivative.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 *MsgBurnDerivative) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgBurnDerivative.Merge(m, src) -} -func (m *MsgBurnDerivative) XXX_Size() int { - return m.Size() -} -func (m *MsgBurnDerivative) XXX_DiscardUnknown() { - xxx_messageInfo_MsgBurnDerivative.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgBurnDerivative proto.InternalMessageInfo - -func (m *MsgBurnDerivative) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgBurnDerivative) GetValidator() string { - if m != nil { - return m.Validator - } - return "" -} - -func (m *MsgBurnDerivative) GetAmount() types.Coin { - if m != nil { - return m.Amount - } - return types.Coin{} -} - -// MsgBurnDerivativeResponse defines the Msg/BurnDerivative response type. -type MsgBurnDerivativeResponse struct { - // received is the number of delegation shares sent to the sender - Received github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=received,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"received"` -} - -func (m *MsgBurnDerivativeResponse) Reset() { *m = MsgBurnDerivativeResponse{} } -func (m *MsgBurnDerivativeResponse) String() string { return proto.CompactTextString(m) } -func (*MsgBurnDerivativeResponse) ProtoMessage() {} -func (*MsgBurnDerivativeResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_738981106e50f269, []int{3} -} -func (m *MsgBurnDerivativeResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgBurnDerivativeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgBurnDerivativeResponse.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 *MsgBurnDerivativeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgBurnDerivativeResponse.Merge(m, src) -} -func (m *MsgBurnDerivativeResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgBurnDerivativeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgBurnDerivativeResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgBurnDerivativeResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgMintDerivative)(nil), "kava.liquid.v1beta1.MsgMintDerivative") - proto.RegisterType((*MsgMintDerivativeResponse)(nil), "kava.liquid.v1beta1.MsgMintDerivativeResponse") - proto.RegisterType((*MsgBurnDerivative)(nil), "kava.liquid.v1beta1.MsgBurnDerivative") - proto.RegisterType((*MsgBurnDerivativeResponse)(nil), "kava.liquid.v1beta1.MsgBurnDerivativeResponse") -} - -func init() { proto.RegisterFile("kava/liquid/v1beta1/tx.proto", fileDescriptor_738981106e50f269) } - -var fileDescriptor_738981106e50f269 = []byte{ - // 421 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x53, 0xbd, 0xae, 0xda, 0x30, - 0x14, 0x8e, 0x7b, 0x2b, 0x54, 0x5c, 0xe9, 0x4a, 0x4d, 0xef, 0x10, 0xd0, 0x55, 0x40, 0x0c, 0x88, - 0x25, 0x4e, 0xa1, 0x43, 0x87, 0x76, 0x69, 0xca, 0xca, 0x92, 0x2e, 0xa8, 0x4b, 0xe5, 0x24, 0x56, - 0xb0, 0x00, 0x9b, 0xda, 0x4e, 0x44, 0xdf, 0xa2, 0x0f, 0xd0, 0xc7, 0xe0, 0x21, 0x18, 0x11, 0x53, - 0xdb, 0x01, 0x55, 0xf0, 0x22, 0x55, 0x12, 0x13, 0xca, 0x9f, 0xc4, 0x78, 0x27, 0xdb, 0xe7, 0x3b, - 0xdf, 0xf1, 0xf9, 0xbe, 0x63, 0xc3, 0xc7, 0x31, 0x4e, 0xb1, 0x3b, 0xa1, 0xdf, 0x12, 0x1a, 0xb9, - 0x69, 0x37, 0x20, 0x0a, 0x77, 0x5d, 0x35, 0x47, 0x33, 0xc1, 0x15, 0x37, 0x5f, 0x67, 0x28, 0x2a, - 0x50, 0xa4, 0xd1, 0xba, 0x1d, 0x72, 0x39, 0xe5, 0xd2, 0x0d, 0xb0, 0x24, 0x25, 0x25, 0xe4, 0x94, - 0x15, 0xa4, 0x7a, 0xad, 0xc0, 0xbf, 0xe6, 0x27, 0xb7, 0x38, 0x68, 0xe8, 0x21, 0xe6, 0x31, 0x2f, - 0xe2, 0xd9, 0xae, 0x88, 0xb6, 0x7e, 0x02, 0xf8, 0x6a, 0x20, 0xe3, 0x01, 0x65, 0xaa, 0x4f, 0x04, - 0x4d, 0xb1, 0xa2, 0x29, 0x31, 0xdf, 0xc0, 0x8a, 0x24, 0x2c, 0x22, 0xc2, 0x02, 0x4d, 0xd0, 0xa9, - 0x7a, 0xd6, 0x7a, 0xe1, 0x3c, 0xe8, 0x6a, 0x1f, 0xa3, 0x48, 0x10, 0x29, 0x3f, 0x2b, 0x41, 0x59, - 0xec, 0xeb, 0x3c, 0xf3, 0x11, 0x56, 0x53, 0x3c, 0xa1, 0x11, 0x56, 0x5c, 0x58, 0xcf, 0x32, 0x92, - 0x7f, 0x08, 0x98, 0xef, 0x60, 0x05, 0x4f, 0x79, 0xc2, 0x94, 0x75, 0xd7, 0x04, 0x9d, 0x97, 0xbd, - 0x1a, 0xd2, 0xc5, 0x32, 0x1d, 0x7b, 0x71, 0xe8, 0x13, 0xa7, 0xcc, 0x7b, 0xbe, 0xdc, 0x34, 0x0c, - 0x5f, 0xa7, 0xb7, 0x86, 0xb0, 0x76, 0xd6, 0x9d, 0x4f, 0xe4, 0x8c, 0x33, 0x49, 0xcc, 0xf7, 0xf0, - 0x85, 0x20, 0x21, 0xa1, 0x29, 0x89, 0xf2, 0x3e, 0x6f, 0xa8, 0x5b, 0x12, 0xf6, 0xc2, 0xbd, 0x44, - 0xb0, 0xa7, 0x28, 0x3c, 0xc9, 0x85, 0x1f, 0x77, 0x57, 0x0a, 0x1f, 0x9e, 0x08, 0xaf, 0x7a, 0x1f, - 0x32, 0xf2, 0x9f, 0x4d, 0xa3, 0x1d, 0x53, 0x35, 0x4a, 0x02, 0x14, 0xf2, 0xa9, 0x9e, 0xbe, 0x5e, - 0x1c, 0x19, 0x8d, 0x5d, 0xf5, 0x7d, 0x46, 0x24, 0xea, 0x93, 0x70, 0xbd, 0x70, 0xa0, 0x6e, 0xa4, - 0x4f, 0xc2, 0x83, 0x2b, 0xbd, 0xdf, 0x00, 0xde, 0x0d, 0x64, 0x6c, 0x8e, 0xe0, 0xfd, 0xc9, 0x93, - 0x68, 0xa3, 0x0b, 0xef, 0x11, 0x9d, 0x0d, 0xa7, 0x8e, 0x6e, 0xcb, 0x2b, 0xb5, 0x8c, 0xe0, 0xfd, - 0xc9, 0x0c, 0xae, 0xde, 0x74, 0x9c, 0x77, 0xfd, 0xa6, 0xcb, 0xae, 0x79, 0xde, 0x72, 0x6b, 0x83, - 0xd5, 0xd6, 0x06, 0x7f, 0xb7, 0x36, 0xf8, 0xb1, 0xb3, 0x8d, 0xd5, 0xce, 0x36, 0x7e, 0xed, 0x6c, - 0xe3, 0x4b, 0xe7, 0x3f, 0xd7, 0xb2, 0x9a, 0xce, 0x04, 0x07, 0x32, 0xdf, 0xb9, 0xf3, 0xfd, 0xff, - 0xcc, 0xbd, 0x0b, 0x2a, 0xf9, 0xaf, 0x79, 0xfb, 0x2f, 0x00, 0x00, 0xff, 0xff, 0x40, 0x82, 0xe3, - 0xbf, 0xbb, 0x03, 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 { - // MintDerivative defines a method for converting a delegation into staking deriviatives. - MintDerivative(ctx context.Context, in *MsgMintDerivative, opts ...grpc.CallOption) (*MsgMintDerivativeResponse, error) - // BurnDerivative defines a method for converting staking deriviatives into a delegation. - BurnDerivative(ctx context.Context, in *MsgBurnDerivative, opts ...grpc.CallOption) (*MsgBurnDerivativeResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) MintDerivative(ctx context.Context, in *MsgMintDerivative, opts ...grpc.CallOption) (*MsgMintDerivativeResponse, error) { - out := new(MsgMintDerivativeResponse) - err := c.cc.Invoke(ctx, "/kava.liquid.v1beta1.Msg/MintDerivative", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) BurnDerivative(ctx context.Context, in *MsgBurnDerivative, opts ...grpc.CallOption) (*MsgBurnDerivativeResponse, error) { - out := new(MsgBurnDerivativeResponse) - err := c.cc.Invoke(ctx, "/kava.liquid.v1beta1.Msg/BurnDerivative", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // MintDerivative defines a method for converting a delegation into staking deriviatives. - MintDerivative(context.Context, *MsgMintDerivative) (*MsgMintDerivativeResponse, error) - // BurnDerivative defines a method for converting staking deriviatives into a delegation. - BurnDerivative(context.Context, *MsgBurnDerivative) (*MsgBurnDerivativeResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) MintDerivative(ctx context.Context, req *MsgMintDerivative) (*MsgMintDerivativeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method MintDerivative not implemented") -} -func (*UnimplementedMsgServer) BurnDerivative(ctx context.Context, req *MsgBurnDerivative) (*MsgBurnDerivativeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method BurnDerivative not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_MintDerivative_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgMintDerivative) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).MintDerivative(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.liquid.v1beta1.Msg/MintDerivative", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).MintDerivative(ctx, req.(*MsgMintDerivative)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_BurnDerivative_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgBurnDerivative) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).BurnDerivative(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.liquid.v1beta1.Msg/BurnDerivative", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).BurnDerivative(ctx, req.(*MsgBurnDerivative)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.liquid.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "MintDerivative", - Handler: _Msg_MintDerivative_Handler, - }, - { - MethodName: "BurnDerivative", - Handler: _Msg_BurnDerivative_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/liquid/v1beta1/tx.proto", -} - -func (m *MsgMintDerivative) 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 *MsgMintDerivative) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMintDerivative) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Validator) > 0 { - i -= len(m.Validator) - copy(dAtA[i:], m.Validator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Validator))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgMintDerivativeResponse) 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 *MsgMintDerivativeResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMintDerivativeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Received.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *MsgBurnDerivative) 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 *MsgBurnDerivative) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgBurnDerivative) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Validator) > 0 { - i -= len(m.Validator) - copy(dAtA[i:], m.Validator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Validator))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgBurnDerivativeResponse) 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 *MsgBurnDerivativeResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgBurnDerivativeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Received.Size() - i -= size - if _, err := m.Received.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgMintDerivative) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Validator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgMintDerivativeResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Received.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgBurnDerivative) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Validator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgBurnDerivativeResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Received.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgMintDerivative) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgMintDerivative: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMintDerivative: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Validator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgMintDerivativeResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgMintDerivativeResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMintDerivativeResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Received", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Received.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgBurnDerivative) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgBurnDerivative: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgBurnDerivative: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Validator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgBurnDerivativeResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgBurnDerivativeResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgBurnDerivativeResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Received", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Received.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/metrics/abci.go b/x/metrics/abci.go deleted file mode 100644 index 14a77d71..00000000 --- a/x/metrics/abci.go +++ /dev/null @@ -1,12 +0,0 @@ -package metrics - -import ( - "github.com/kava-labs/kava/x/metrics/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// BeginBlocker publishes metrics at the start of each block. -func BeginBlocker(ctx sdk.Context, metrics *types.Metrics) { - metrics.LatestBlockHeight.Set(float64(ctx.BlockHeight())) -} diff --git a/x/metrics/abci_test.go b/x/metrics/abci_test.go deleted file mode 100644 index 141d501b..00000000 --- a/x/metrics/abci_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package metrics_test - -import ( - "testing" - - kitmetrics "github.com/go-kit/kit/metrics" - "github.com/stretchr/testify/require" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/metrics" - "github.com/kava-labs/kava/x/metrics/types" -) - -type MockGauge struct { - value float64 -} - -func (mg *MockGauge) With(labelValues ...string) kitmetrics.Gauge { return mg } -func (mg *MockGauge) Set(value float64) { mg.value = value } -func (*MockGauge) Add(_ float64) {} - -func ctxWithHeight(height int64) sdk.Context { - tApp := app.NewTestApp() - tApp.InitializeFromGenesisStates() - return tApp.NewContext(false, tmproto.Header{Height: height}) -} - -func TestBeginBlockEmitsLatestHeight(t *testing.T) { - gauge := MockGauge{} - myMetrics := &types.Metrics{ - LatestBlockHeight: &gauge, - } - - metrics.BeginBlocker(ctxWithHeight(1), myMetrics) - require.EqualValues(t, 1, gauge.value) - - metrics.BeginBlocker(ctxWithHeight(100), myMetrics) - require.EqualValues(t, 100, gauge.value) - - metrics.BeginBlocker(ctxWithHeight(17e6), myMetrics) - require.EqualValues(t, 17e6, gauge.value) -} diff --git a/x/metrics/module.go b/x/metrics/module.go deleted file mode 100644 index 2ee0d656..00000000 --- a/x/metrics/module.go +++ /dev/null @@ -1,111 +0,0 @@ -package metrics - -import ( - "encoding/json" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/kava-labs/kava/x/metrics/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name returns the module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -// Deprecated: unused but necessary to fulfill AppModuleBasic interface -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { - return []byte("{}") -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, _ client.TxEncodingConfig, _ json.RawMessage) error { - return nil -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) {} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) {} - -// GetTxCmd returns the root tx command for the module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return nil -} - -// GetQueryCmd returns no root query command for the module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return nil -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - metrics *types.Metrics -} - -// NewAppModule creates a new AppModule object -func NewAppModule(telemetryOpts types.TelemetryOptions) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - metrics: types.NewMetrics(telemetryOpts), - } -} - -// Name module name -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// RegisterInvariants register module invariants -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return 1 } - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) {} - -// InitGenesis module init-genesis -func (am AppModule) InitGenesis(ctx sdk.Context, _ codec.JSONCodec, _ json.RawMessage) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} - -// ExportGenesis module export genesis -func (am AppModule) ExportGenesis(_ sdk.Context, cdc codec.JSONCodec) json.RawMessage { - return nil -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { - BeginBlocker(ctx, am.metrics) -} - -// EndBlock module end-block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/metrics/spec/README.md b/x/metrics/spec/README.md deleted file mode 100644 index 648ce38a..00000000 --- a/x/metrics/spec/README.md +++ /dev/null @@ -1,36 +0,0 @@ - - -# `metrics` - - -## Abstract - -`x/metrics` is a stateless module that does not affect consensus. It captures chain metrics and emits them when the `instrumentation.prometheus` option is enabled in `config.toml`. - -## Precision - -The metrics emitted by `x/metrics` are `float64`s. They use `github.com/go-kit/kit/metrics` Prometheus gauges. Cosmos-sdk's `telemetry` package was not used because, at the time of writing, it only supports `float32`s and so does not maintain accurate representations of ints larger than ~16.8M. With `float64`s, integers may be accurately represented up to ~9e15. - -## Metrics - -The following metrics are defined: -* `cometbft_blocksync_latest_block_height` - this emulates the blocksync `latest_block_height` metric in CometBFT v0.38+. The `cometbft` namespace comes from the `instrumentation.namespace` config.toml value. - -## Metric Labels - -All metrics emitted have the labels defined in app.toml's `telemetry.global-labels` field. This is the same field used by cosmos-sdk's `telemetry` package. - -example: -```toml -# app.toml -[telemetry] -global-labels = [ - ["chain_id", "kava_2222-10"], - ["my_label", "my_value"], -] -``` diff --git a/x/metrics/types/keys.go b/x/metrics/types/keys.go deleted file mode 100644 index c7a9577a..00000000 --- a/x/metrics/types/keys.go +++ /dev/null @@ -1,6 +0,0 @@ -package types - -const ( - // Name of the module - ModuleName = "metrics" -) diff --git a/x/metrics/types/metrics.go b/x/metrics/types/metrics.go deleted file mode 100644 index 7c01e474..00000000 --- a/x/metrics/types/metrics.go +++ /dev/null @@ -1,89 +0,0 @@ -package types - -import ( - "github.com/go-kit/kit/metrics" - "github.com/go-kit/kit/metrics/discard" - prometheus "github.com/go-kit/kit/metrics/prometheus" - stdprometheus "github.com/prometheus/client_golang/prometheus" - "github.com/spf13/cast" - - servertypes "github.com/cosmos/cosmos-sdk/server/types" -) - -// TelemetryOptions defines the app configurations for the x/metrics module -type TelemetryOptions struct { - // CometBFT config value for instrumentation.prometheus (config.toml) - PrometheusEnabled bool - // Namespace for CometBFT metrics. Used to emulate CometBFT metrics. - CometBFTMetricsNamespace string - // A list of keys and values used as labels on all metrics - GlobalLabelsAndValues []string -} - -// TelemetryOptionsFromAppOpts creates the TelemetryOptions from server AppOptions -func TelemetryOptionsFromAppOpts(appOpts servertypes.AppOptions) TelemetryOptions { - prometheusEnabled := cast.ToBool(appOpts.Get("instrumentation.prometheus")) - if !prometheusEnabled { - return TelemetryOptions{ - GlobalLabelsAndValues: []string{}, - } - } - - // parse the app.toml global-labels into a slice of alternating label & value strings - // the value is expected to be a list of [label, value] tuples. - rawLabels := cast.ToSlice(appOpts.Get("telemetry.global-labels")) - globalLabelsAndValues := make([]string, 0, len(rawLabels)*2) - for _, gl := range rawLabels { - l := cast.ToStringSlice(gl) - globalLabelsAndValues = append(globalLabelsAndValues, l[0], l[1]) - } - - return TelemetryOptions{ - PrometheusEnabled: true, - CometBFTMetricsNamespace: cast.ToString(appOpts.Get("instrumentation.namespace")), - GlobalLabelsAndValues: globalLabelsAndValues, - } -} - -// Metrics contains metrics exposed by this module. -// They use go-kit metrics like CometBFT as opposed to using cosmos-sdk telemetry -// because the sdk's telemetry only supports float32s, whereas go-kit prometheus -// metrics correctly handle float64s (and thus a larger number of int64s) -type Metrics struct { - // The height of the latest block. - // This gauges exactly emulates the default blocksync metric in CometBFT v0.38+ - // It should be removed when kava has been updated to CometBFT v0.38+. - // see https://github.com/cometbft/cometbft/blob/v0.38.0-rc3/blocksync/metrics.gen.go - LatestBlockHeight metrics.Gauge -} - -// NewMetrics creates a new Metrics object based on whether or not prometheus instrumentation is enabled. -func NewMetrics(opts TelemetryOptions) *Metrics { - if opts.PrometheusEnabled { - return PrometheusMetrics(opts) - } - return NoopMetrics() -} - -// PrometheusMetrics returns the gauges for when prometheus instrumentation is enabled. -func PrometheusMetrics(opts TelemetryOptions) *Metrics { - labels := []string{} - for i := 0; i < len(opts.GlobalLabelsAndValues); i += 2 { - labels = append(labels, opts.GlobalLabelsAndValues[i]) - } - return &Metrics{ - LatestBlockHeight: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Namespace: opts.CometBFTMetricsNamespace, - Subsystem: "blocksync", - Name: "latest_block_height", - Help: "The height of the latest block.", - }, labels).With(opts.GlobalLabelsAndValues...), - } -} - -// NoopMetrics are a do-nothing placeholder used when prometheus instrumentation is not enabled. -func NoopMetrics() *Metrics { - return &Metrics{ - LatestBlockHeight: discard.NewGauge(), - } -} diff --git a/x/metrics/types/metrics_test.go b/x/metrics/types/metrics_test.go deleted file mode 100644 index 2af68d25..00000000 --- a/x/metrics/types/metrics_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/go-kit/kit/metrics" - "github.com/go-kit/kit/metrics/prometheus" - "github.com/kava-labs/kava/x/metrics/types" - "github.com/stretchr/testify/require" -) - -func isPrometheusGauge(g metrics.Gauge) bool { - _, ok := g.(*prometheus.Gauge) - return ok -} - -var ( - disabledOpts = types.TelemetryOptions{ - PrometheusEnabled: false, - } - enabledOpts = types.TelemetryOptions{ - PrometheusEnabled: true, - CometBFTMetricsNamespace: "cometbft", - GlobalLabelsAndValues: []string{"label1", "value1", "label2", "value2"}, - } -) - -func TestNewMetrics_DisabledVsEnabled(t *testing.T) { - myMetrics := types.NewMetrics(disabledOpts) - require.False(t, isPrometheusGauge(myMetrics.LatestBlockHeight)) - - myMetrics = types.NewMetrics(enabledOpts) - require.True(t, isPrometheusGauge(myMetrics.LatestBlockHeight)) -} - -type MockAppOpts struct { - store map[string]interface{} -} - -func (mao *MockAppOpts) Get(key string) interface{} { - return mao.store[key] -} - -func TestTelemetryOptionsFromAppOpts(t *testing.T) { - appOpts := MockAppOpts{store: make(map[string]interface{})} - - // test disabled functionality - appOpts.store["instrumentation.prometheus"] = false - - opts := types.TelemetryOptionsFromAppOpts(&appOpts) - require.False(t, opts.PrometheusEnabled) - - // test enabled functionality - appOpts.store["instrumentation.prometheus"] = true - appOpts.store["instrumentation.namespace"] = "magic" - appOpts.store["telemetry.global-labels"] = []interface{}{} - - opts = types.TelemetryOptionsFromAppOpts(&appOpts) - require.True(t, opts.PrometheusEnabled) - require.Equal(t, "magic", opts.CometBFTMetricsNamespace) - require.Len(t, opts.GlobalLabelsAndValues, 0) - - appOpts.store["telemetry.global-labels"] = []interface{}{ - []interface{}{"label1", "value1"}, - []interface{}{"label2", "value2"}, - } - opts = types.TelemetryOptionsFromAppOpts(&appOpts) - require.True(t, opts.PrometheusEnabled) - require.Equal(t, "magic", opts.CometBFTMetricsNamespace) - require.Len(t, opts.GlobalLabelsAndValues, 4) - require.Equal(t, enabledOpts.GlobalLabelsAndValues, opts.GlobalLabelsAndValues) -} diff --git a/x/pricefeed/abci.go b/x/pricefeed/abci.go deleted file mode 100644 index a6f2ff3a..00000000 --- a/x/pricefeed/abci.go +++ /dev/null @@ -1,17 +0,0 @@ -package pricefeed - -import ( - "time" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/pricefeed/keeper" - "github.com/kava-labs/kava/x/pricefeed/types" -) - -// EndBlocker updates the current pricefeed -func EndBlocker(ctx sdk.Context, k keeper.Keeper) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyEndBlocker) - - k.SetCurrentPricesForAllMarkets(ctx) -} diff --git a/x/pricefeed/abci_test.go b/x/pricefeed/abci_test.go deleted file mode 100644 index 9f9de46e..00000000 --- a/x/pricefeed/abci_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package pricefeed_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/pricefeed" - "github.com/kava-labs/kava/x/pricefeed/keeper" - "github.com/kava-labs/kava/x/pricefeed/testutil" -) - -func TestEndBlocker_UpdatesMultipleMarkets(t *testing.T) { - testutil.SetCurrentPrices_PriceCalculations(t, func(ctx sdk.Context, keeper keeper.Keeper) { - pricefeed.EndBlocker(ctx, keeper) - }) - - testutil.SetCurrentPrices_EventEmission(t, func(ctx sdk.Context, keeper keeper.Keeper) { - pricefeed.EndBlocker(ctx, keeper) - }) -} diff --git a/x/pricefeed/client/cli/query.go b/x/pricefeed/client/cli/query.go deleted file mode 100644 index 57d9daee..00000000 --- a/x/pricefeed/client/cli/query.go +++ /dev/null @@ -1,204 +0,0 @@ -package cli - -import ( - "context" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - - "github.com/kava-labs/kava/x/pricefeed/types" -) - -// GetQueryCmd returns the cli query commands for this module -func GetQueryCmd() *cobra.Command { - // Group nameservice queries under a subcommand - pricefeedQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the pricefeed module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - GetCmdPrice(), - GetCmdQueryPrices(), - GetCmdRawPrices(), - GetCmdOracles(), - GetCmdMarkets(), - GetCmdQueryParams(), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - pricefeedQueryCmd.AddCommand(cmds...) - - return pricefeedQueryCmd -} - -// GetCmdOracles queries the oracle set of an asset -func GetCmdOracles() *cobra.Command { - return &cobra.Command{ - Use: "oracles [marketID]", - Short: "get the oracle set for a market", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - marketID := args[0] - - params := types.QueryOraclesRequest{ - MarketId: marketID, - } - - res, err := queryClient.Oracles(context.Background(), ¶ms) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -// GetCmdPrice queries the current price of an asset -func GetCmdPrice() *cobra.Command { - return &cobra.Command{ - Use: "price [marketID]", - Short: "get the current price for the input market", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - marketID := args[0] - - params := types.QueryPriceRequest{ - MarketId: marketID, - } - - res, err := queryClient.Price(context.Background(), ¶ms) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -// GetCmdQueryPrices queries the pricefeed module for current prices -func GetCmdQueryPrices() *cobra.Command { - return &cobra.Command{ - Use: "prices", - Short: "get the current price of each market", - Long: "Get the current prices of each market in the pricefeed 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.Prices(context.Background(), &types.QueryPricesRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -// GetCmdRawPrices queries the current price of an asset -func GetCmdRawPrices() *cobra.Command { - return &cobra.Command{ - Use: "rawprices [marketID]", - Short: "get the raw oracle prices for the input market", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - marketID := args[0] - - params := types.QueryRawPricesRequest{ - MarketId: marketID, - } - - res, err := queryClient.RawPrices(context.Background(), ¶ms) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -// GetCmdMarkets queries list of markets in the pricefeed -func GetCmdMarkets() *cobra.Command { - return &cobra.Command{ - Use: "markets", - Short: "get the markets in the pricefeed", - 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.Markets(context.Background(), &types.QueryMarketsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -// GetCmdQueryParams queries the pricefeed module parameters -func GetCmdQueryParams() *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: "get the pricefeed module parameters", - Long: "Get the current global pricefeed module parameters.", - 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(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } -} diff --git a/x/pricefeed/client/cli/tx.go b/x/pricefeed/client/cli/tx.go deleted file mode 100644 index 0b41cde0..00000000 --- a/x/pricefeed/client/cli/tx.go +++ /dev/null @@ -1,83 +0,0 @@ -package cli - -import ( - "fmt" - "strconv" - "time" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/x/pricefeed/types" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - pricefeedTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Pricefeed transactions subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - GetCmdPostPrice(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - pricefeedTxCmd.AddCommand(cmds...) - - return pricefeedTxCmd -} - -// GetCmdPostPrice cli command for posting prices. -func GetCmdPostPrice() *cobra.Command { - return &cobra.Command{ - Use: "postprice [marketID] [price] [expiry]", - Short: "post the latest price for a particular market with a given expiry as a UNIX time", - Example: fmt.Sprintf("%s tx %s postprice bnb:usd 25 9999999999 --from validator", - version.AppName, types.ModuleName), - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - price, err := sdk.NewDecFromStr(args[1]) - if err != nil { - return err - } - - expiryInt, err := strconv.ParseInt(args[2], 10, 64) - if err != nil { - return fmt.Errorf("invalid expiry %s: %w", args[2], err) - } - - if expiryInt > types.MaxExpiry { - return fmt.Errorf("invalid expiry; got %d, max: %d", expiryInt, types.MaxExpiry) - } - - expiry := tmtime.Canonical(time.Unix(expiryInt, 0)) - - from := clientCtx.GetFromAddress() - msg := types.NewMsgPostPrice(from.String(), args[0], price, expiry) - if err = msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} diff --git a/x/pricefeed/genesis.go b/x/pricefeed/genesis.go deleted file mode 100644 index f7774704..00000000 --- a/x/pricefeed/genesis.go +++ /dev/null @@ -1,55 +0,0 @@ -package pricefeed - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/pricefeed/keeper" - "github.com/kava-labs/kava/x/pricefeed/types" -) - -// InitGenesis sets distribution information for genesis. -func InitGenesis(ctx sdk.Context, k keeper.Keeper, gs types.GenesisState) { - // Set the markets and oracles from params - k.SetParams(ctx, gs.Params) - - // Iterate through the posted prices and set them in the store if they are not expired - for _, pp := range gs.PostedPrices { - if pp.Expiry.After(ctx.BlockTime()) { - _, err := k.SetPrice(ctx, pp.OracleAddress, pp.MarketID, pp.Price, pp.Expiry) - if err != nil { - panic(err) - } - } - } - params := k.GetParams(ctx) - - // Set the current price (if any) based on what's now in the store - for _, market := range params.Markets { - if !market.Active { - continue - } - rps := k.GetRawPrices(ctx, market.MarketID) - - if len(rps) == 0 { - continue - } - err := k.SetCurrentPrices(ctx, market.MarketID) - if err != nil { - panic(err) - } - } -} - -// ExportGenesis returns a GenesisState for a given context and keeper. -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { - // Get the params for markets and oracles - params := k.GetParams(ctx) - - var postedPrices []types.PostedPrice - for _, market := range k.GetMarkets(ctx) { - pp := k.GetRawPrices(ctx, market.MarketID) - postedPrices = append(postedPrices, pp...) - } - - return types.NewGenesisState(params, postedPrices) -} diff --git a/x/pricefeed/genesis_test.go b/x/pricefeed/genesis_test.go deleted file mode 100644 index b8d0889d..00000000 --- a/x/pricefeed/genesis_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package pricefeed_test - -import ( - "testing" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/pricefeed" - "github.com/kava-labs/kava/x/pricefeed/keeper" - - "github.com/stretchr/testify/suite" -) - -type GenesisTestSuite struct { - suite.Suite - - tApp app.TestApp - ctx sdk.Context - keeper keeper.Keeper -} - -func (suite *GenesisTestSuite) SetupTest() { - suite.tApp = app.NewTestApp() - suite.ctx = suite.tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - suite.keeper = suite.tApp.GetPriceFeedKeeper() -} - -func (suite *GenesisTestSuite) TestValidGenState() { - suite.NotPanics(func() { - suite.tApp.InitializeFromGenesisStates( - NewPricefeedGenStateMulti(), - ) - }) - _, addrs := app.GeneratePrivKeyAddressPairs(10) - - // Must create a new TestApp or InitChain will panic with index already set - suite.tApp = app.NewTestApp() - suite.NotPanics(func() { - suite.tApp.InitializeFromGenesisStates( - NewPricefeedGenStateWithOracles(addrs), - ) - }) -} - -func (suite *GenesisTestSuite) TestInitExportGenState() { - gs := NewPricefeedGen() - - suite.NotPanics(func() { - pricefeed.InitGenesis(suite.ctx, suite.keeper, gs) - }) - - exportedGs := pricefeed.ExportGenesis(suite.ctx, suite.keeper) - suite.NoError(gs.VerboseEqual(exportedGs), "exported genesis should match init genesis") -} - -func (suite *GenesisTestSuite) TestParamPricesGenState() { - gs := NewPricefeedGen() - - suite.NotPanics(func() { - pricefeed.InitGenesis(suite.ctx, suite.keeper, gs) - }) - - params := suite.keeper.GetParams(suite.ctx) - suite.NoError(gs.Params.VerboseEqual(params), "params should equal init params") - - pps := suite.keeper.GetRawPrices(suite.ctx, "btc:usd") - suite.NoError(gs.PostedPrices[0].VerboseEqual(pps[0]), "posted prices should equal init posted prices") -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(GenesisTestSuite)) -} diff --git a/x/pricefeed/integration_test.go b/x/pricefeed/integration_test.go deleted file mode 100644 index b8d230f7..00000000 --- a/x/pricefeed/integration_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package pricefeed_test - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/pricefeed/types" -) - -func NewPricefeedGen() types.GenesisState { - return types.GenesisState{ - Params: types.Params{ - Markets: []types.Market{ - {MarketID: "btc:usd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "xrp:usd", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []types.PostedPrice{ - { - MarketID: "btc:usd", - OracleAddress: sdk.AccAddress("oracle1"), - Price: sdk.MustNewDecFromStr("8000.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "xrp:usd", - OracleAddress: sdk.AccAddress("oracle2"), - Price: sdk.MustNewDecFromStr("0.25"), - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } -} - -func NewPricefeedGenStateMulti() app.GenesisState { - pfGenesis := NewPricefeedGen() - return app.GenesisState{types.ModuleName: types.ModuleCdc.LegacyAmino.MustMarshalJSON(pfGenesis)} -} - -func NewPricefeedGenStateWithOracles(addrs []sdk.AccAddress) app.GenesisState { - pfGenesis := types.GenesisState{ - Params: types.Params{ - Markets: []types.Market{ - {MarketID: "btc:usd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: addrs, Active: true}, - {MarketID: "xrp:usd", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: addrs, Active: true}, - }, - }, - PostedPrices: []types.PostedPrice{ - { - MarketID: "btc:usd", - OracleAddress: addrs[0], - Price: sdk.MustNewDecFromStr("8000.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "xrp:usd", - OracleAddress: addrs[0], - Price: sdk.MustNewDecFromStr("0.25"), - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - return app.GenesisState{types.ModuleName: types.ModuleCdc.LegacyAmino.MustMarshalJSON(pfGenesis)} -} diff --git a/x/pricefeed/keeper/grpc_query.go b/x/pricefeed/keeper/grpc_query.go deleted file mode 100644 index a329792c..00000000 --- a/x/pricefeed/keeper/grpc_query.go +++ /dev/null @@ -1,122 +0,0 @@ -package keeper - -import ( - "context" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/pricefeed/types" -) - -type queryServer struct { - keeper Keeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -var _ types.QueryServer = queryServer{} - -// Params implements the gRPC service handler for querying x/pricefeed parameters. -func (s queryServer) Params(c context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(c) - params := s.keeper.GetParams(sdkCtx) - - return &types.QueryParamsResponse{Params: params}, nil -} - -// Price implements the gRPC service handler for querying x/pricefeed price. -func (s queryServer) Price(c context.Context, req *types.QueryPriceRequest) (*types.QueryPriceResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - _, found := s.keeper.GetMarket(ctx, req.MarketId) - if !found { - return nil, status.Error(codes.NotFound, "invalid market ID") - } - currentPrice, sdkErr := s.keeper.GetCurrentPrice(ctx, req.MarketId) - if sdkErr != nil { - return nil, sdkErr - } - - return &types.QueryPriceResponse{ - Price: types.CurrentPriceResponse(currentPrice), - }, nil -} - -func (s queryServer) Prices(c context.Context, req *types.QueryPricesRequest) (*types.QueryPricesResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - var currentPrices types.CurrentPriceResponses - for _, cp := range s.keeper.GetCurrentPrices(ctx) { - if cp.MarketID != "" { - currentPrices = append(currentPrices, types.CurrentPriceResponse(cp)) - } - } - - return &types.QueryPricesResponse{ - Prices: currentPrices, - }, nil -} - -func (s queryServer) RawPrices(c context.Context, req *types.QueryRawPricesRequest) (*types.QueryRawPricesResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - _, found := s.keeper.GetMarket(ctx, req.MarketId) - if !found { - return nil, status.Error(codes.NotFound, "invalid market ID") - } - - var prices types.PostedPriceResponses - for _, rp := range s.keeper.GetRawPrices(ctx, req.MarketId) { - prices = append(prices, types.PostedPriceResponse{ - MarketID: rp.MarketID, - OracleAddress: rp.OracleAddress.String(), - Price: rp.Price, - Expiry: rp.Expiry, - }) - } - - return &types.QueryRawPricesResponse{ - RawPrices: prices, - }, nil -} - -func (s queryServer) Oracles(c context.Context, req *types.QueryOraclesRequest) (*types.QueryOraclesResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - oracles, err := s.keeper.GetOracles(ctx, req.MarketId) - if err != nil { - return nil, status.Error(codes.NotFound, "invalid market ID") - } - - var strOracles []string - for _, oracle := range oracles { - strOracles = append(strOracles, oracle.String()) - } - - return &types.QueryOraclesResponse{ - Oracles: strOracles, - }, nil -} - -func (s queryServer) Markets(c context.Context, req *types.QueryMarketsRequest) (*types.QueryMarketsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - var markets types.MarketResponses - for _, market := range s.keeper.GetMarkets(ctx) { - markets = append(markets, market.ToMarketResponse()) - } - - return &types.QueryMarketsResponse{ - Markets: markets, - }, nil -} diff --git a/x/pricefeed/keeper/grpc_query_test.go b/x/pricefeed/keeper/grpc_query_test.go deleted file mode 100644 index abe950dc..00000000 --- a/x/pricefeed/keeper/grpc_query_test.go +++ /dev/null @@ -1,270 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/pricefeed/keeper" - "github.com/kava-labs/kava/x/pricefeed/types" - "github.com/stretchr/testify/suite" -) - -type grpcQueryTestSuite struct { - suite.Suite - - tApp app.TestApp - ctx sdk.Context - keeper keeper.Keeper - queryServer types.QueryServer - addrs []sdk.AccAddress - strAddrs []string - now time.Time -} - -func (suite *grpcQueryTestSuite) SetupTest() { - suite.tApp = app.NewTestApp() - suite.ctx = suite.tApp.NewContext(true, tmprototypes.Header{}). - WithBlockTime(time.Now().UTC()) - suite.keeper = suite.tApp.GetPriceFeedKeeper() - suite.queryServer = keeper.NewQueryServerImpl(suite.keeper) - - _, addrs := app.GeneratePrivKeyAddressPairs(5) - suite.addrs = addrs - - var strAddrs []string - for _, a := range addrs { - strAddrs = append(strAddrs, a.String()) - } - suite.strAddrs = strAddrs - - suite.now = time.Now().UTC() -} - -func (suite *grpcQueryTestSuite) setTestParams() { - params := types.NewParams([]types.Market{ - {MarketID: "tstusd", BaseAsset: "tst", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }) - suite.keeper.SetParams(suite.ctx, params) -} - -func (suite *grpcQueryTestSuite) TestGrpcParams() { - tests := []struct { - giveMsg string - giveParams types.Params - wantAccepted bool - }{ - {"default params", types.DefaultParams(), true}, - {"test params", types.NewParams([]types.Market{ - {MarketID: "tstusd", BaseAsset: "tst", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }), true}, - } - - for _, tt := range tests { - suite.Run(tt.giveMsg, func() { - suite.keeper.SetParams(suite.ctx, tt.giveParams) - - res, err := suite.queryServer.Params(sdk.WrapSDKContext(suite.ctx), &types.QueryParamsRequest{}) - - if tt.wantAccepted { - suite.NoError(err) - suite.NoError(tt.giveParams.VerboseEqual(res.Params), "params query should respond with set params") - } else { - suite.Error(err) - } - }) - } -} - -func (suite *grpcQueryTestSuite) TestGrpcPrice() { - suite.setTestParams() - suite.setTstPrice() - - expectedPrice := types.NewCurrentPriceResponse("tstusd", sdk.MustNewDecFromStr("0.34")) - - res, err := suite.queryServer.Price(sdk.WrapSDKContext(suite.ctx), &types.QueryPriceRequest{MarketId: "tstusd"}) - suite.NoError(err) - suite.Equal(expectedPrice, res.Price) -} - -func (suite *grpcQueryTestSuite) TestGrpcPrice_NoPriceSet() { - suite.setTestParams() - - // No prices set yet, should error - _, err := suite.queryServer.Price(sdk.WrapSDKContext(suite.ctx), &types.QueryPriceRequest{MarketId: "tstusd"}) - suite.ErrorIs(types.ErrNoValidPrice, err) -} - -func (suite *grpcQueryTestSuite) TestGrpcPrice_InvalidMarket() { - suite.setTestParams() - suite.setTstPrice() - - _, err := suite.queryServer.Price(sdk.WrapSDKContext(suite.ctx), &types.QueryPriceRequest{MarketId: "invalid"}) - suite.Equal("rpc error: code = NotFound desc = invalid market ID", err.Error()) -} - -func (suite *grpcQueryTestSuite) TestGrpcPrices() { - suite.setTestParams() - suite.setTstPrice() - - expectedPrice := types.NewCurrentPriceResponse("tstusd", sdk.MustNewDecFromStr("0.34")) - - prices, err := suite.queryServer.Prices(sdk.WrapSDKContext(suite.ctx), &types.QueryPricesRequest{}) - suite.NoError(err) - - suite.Contains(prices.Prices, expectedPrice, "all prices should include the tstusd price") -} - -func (suite *grpcQueryTestSuite) TestGrpcPrices_NoPriceSet() { - params := types.NewParams([]types.Market{ - {MarketID: "tst:usd", BaseAsset: "tst", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "other:usd", BaseAsset: "other", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }) - suite.keeper.SetParams(suite.ctx, params) - - _, err := suite.keeper.SetPrice( - suite.ctx, suite.addrs[2], "tst:usd", - sdk.MustNewDecFromStr("0.34"), - suite.now.Add(time.Hour*1)) - suite.NoError(err) - - err = suite.keeper.SetCurrentPrices(suite.ctx, "tst:usd") - suite.NoError(err) - - // Set current price of "other:usd" with no individual prices in store - _ = suite.keeper.SetCurrentPrices(suite.ctx, "other:usd") - - expectedPrice := types.NewCurrentPriceResponse("tst:usd", sdk.MustNewDecFromStr("0.34")) - prices, err := suite.queryServer.Prices(sdk.WrapSDKContext(suite.ctx), &types.QueryPricesRequest{}) - suite.NoError(err) - - suite.Equal(len(prices.Prices), 1) - suite.Equal(prices.Prices, types.CurrentPriceResponses{expectedPrice}, "should only contain tst:usd price") -} - -func (suite *grpcQueryTestSuite) TestGrpcRawPrices() { - suite.setTestParams() - suite.setTstPrice() - - res, err := suite.queryServer.RawPrices(sdk.WrapSDKContext(suite.ctx), &types.QueryRawPricesRequest{MarketId: "tstusd"}) - suite.NoError(err) - - suite.Equal(3, len(res.RawPrices)) - - suite.ElementsMatch( - res.RawPrices, - []types.PostedPriceResponse{ - types.NewPostedPriceResponse( - "tstusd", - suite.addrs[0], - sdk.MustNewDecFromStr("0.33"), - suite.now.Add(time.Hour*1), - ), - types.NewPostedPriceResponse( - "tstusd", - suite.addrs[1], - sdk.MustNewDecFromStr("0.35"), - suite.now.Add(time.Hour*1), - ), - types.NewPostedPriceResponse( - "tstusd", - suite.addrs[2], - sdk.MustNewDecFromStr("0.34"), - suite.now.Add(time.Hour*1), - ), - }, - ) -} - -func (suite *grpcQueryTestSuite) TestGrpcRawPrices_InvalidMarket() { - suite.setTestParams() - suite.setTstPrice() - - _, err := suite.queryServer.RawPrices(sdk.WrapSDKContext(suite.ctx), &types.QueryRawPricesRequest{MarketId: "invalid"}) - suite.Equal("rpc error: code = NotFound desc = invalid market ID", err.Error()) -} - -func (suite *grpcQueryTestSuite) TestGrpcOracles_Empty() { - params := types.NewParams([]types.Market{ - {MarketID: "tstusd", BaseAsset: "tst", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }) - suite.keeper.SetParams(suite.ctx, params) - - res, err := suite.queryServer.Oracles(sdk.WrapSDKContext(suite.ctx), &types.QueryOraclesRequest{MarketId: "tstusd"}) - suite.NoError(err) - suite.Empty(res.Oracles) - - params = types.NewParams([]types.Market{ - {MarketID: "tstusd", BaseAsset: "tst", QuoteAsset: "usd", Oracles: suite.addrs, Active: true}, - }) - suite.keeper.SetParams(suite.ctx, params) - - res, err = suite.queryServer.Oracles(sdk.WrapSDKContext(suite.ctx), &types.QueryOraclesRequest{MarketId: "tstusd"}) - suite.NoError(err) - suite.ElementsMatch(suite.strAddrs, res.Oracles) - - _, err = suite.queryServer.Oracles(sdk.WrapSDKContext(suite.ctx), &types.QueryOraclesRequest{MarketId: "invalid"}) - suite.Equal("rpc error: code = NotFound desc = invalid market ID", err.Error()) -} - -func (suite *grpcQueryTestSuite) TestGrpcOracles() { - params := types.NewParams([]types.Market{ - {MarketID: "tstusd", BaseAsset: "tst", QuoteAsset: "usd", Oracles: suite.addrs, Active: true}, - }) - suite.keeper.SetParams(suite.ctx, params) - - res, err := suite.queryServer.Oracles(sdk.WrapSDKContext(suite.ctx), &types.QueryOraclesRequest{MarketId: "tstusd"}) - suite.NoError(err) - suite.ElementsMatch(suite.strAddrs, res.Oracles) -} - -func (suite *grpcQueryTestSuite) TestGrpcOracles_InvalidMarket() { - suite.setTestParams() - - _, err := suite.queryServer.Oracles(sdk.WrapSDKContext(suite.ctx), &types.QueryOraclesRequest{MarketId: "invalid"}) - suite.Equal("rpc error: code = NotFound desc = invalid market ID", err.Error()) -} - -func (suite *grpcQueryTestSuite) TestGrpcMarkets() { - params := types.NewParams([]types.Market{ - {MarketID: "tstusd", BaseAsset: "tst", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "btcusd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }) - suite.keeper.SetParams(suite.ctx, params) - - res, err := suite.queryServer.Markets(sdk.WrapSDKContext(suite.ctx), &types.QueryMarketsRequest{}) - suite.NoError(err) - suite.Len(res.Markets, 2) - suite.Equal(len(res.Markets), len(params.Markets)) - suite.NoError(res.Markets[0].VerboseEqual(params.Markets[0].ToMarketResponse())) - suite.NoError(res.Markets[1].VerboseEqual(params.Markets[1].ToMarketResponse())) -} - -func (suite *grpcQueryTestSuite) setTstPrice() { - _, err := suite.keeper.SetPrice( - suite.ctx, suite.addrs[0], "tstusd", - sdk.MustNewDecFromStr("0.33"), - suite.now.Add(time.Hour*1)) - suite.NoError(err) - - _, err = suite.keeper.SetPrice( - suite.ctx, suite.addrs[1], "tstusd", - sdk.MustNewDecFromStr("0.35"), - suite.now.Add(time.Hour*1)) - suite.NoError(err) - - _, err = suite.keeper.SetPrice( - suite.ctx, suite.addrs[2], "tstusd", - sdk.MustNewDecFromStr("0.34"), - suite.now.Add(time.Hour*1)) - suite.NoError(err) - - err = suite.keeper.SetCurrentPrices(suite.ctx, "tstusd") - suite.NoError(err) -} - -func TestGrpcQueryTestSuite(t *testing.T) { - suite.Run(t, new(grpcQueryTestSuite)) -} diff --git a/x/pricefeed/keeper/integration_test.go b/x/pricefeed/keeper/integration_test.go deleted file mode 100644 index e2c1cff6..00000000 --- a/x/pricefeed/keeper/integration_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package keeper_test - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/pricefeed/types" -) - -func NewPricefeedGenStateMulti() app.GenesisState { - pfGenesis := types.GenesisState{ - Params: types.Params{ - Markets: []types.Market{ - {MarketID: "btc:usd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "xrp:usd", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []types.PostedPrice{ - { - MarketID: "btc:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("8000.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "xrp:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("0.25"), - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - return app.GenesisState{types.ModuleName: types.ModuleCdc.LegacyAmino.MustMarshalJSON(pfGenesis)} -} diff --git a/x/pricefeed/keeper/keeper.go b/x/pricefeed/keeper/keeper.go deleted file mode 100644 index 95c65f7b..00000000 --- a/x/pricefeed/keeper/keeper.go +++ /dev/null @@ -1,297 +0,0 @@ -package keeper - -import ( - "fmt" - "sort" - "time" - - "github.com/cometbft/cometbft/libs/log" - - errorsmod "cosmossdk.io/errors" - "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/kava-labs/kava/x/pricefeed/types" -) - -// Keeper struct for pricefeed module -type Keeper struct { - // key used to access the stores from Context - key storetypes.StoreKey - // Codec for binary encoding/decoding - cdc codec.Codec - // The reference to the Paramstore to get and set pricefeed specific params - paramSubspace paramtypes.Subspace -} - -// NewKeeper returns a new keeper for the pricefeed module. -func NewKeeper( - cdc codec.Codec, key storetypes.StoreKey, paramstore paramtypes.Subspace, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - cdc: cdc, - key: key, - paramSubspace: paramstore, - } -} - -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) -} - -// SetPrice updates the posted price for a specific oracle -func (k Keeper) SetPrice( - ctx sdk.Context, - oracle sdk.AccAddress, - marketID string, - price sdk.Dec, - expiry time.Time, -) (types.PostedPrice, error) { - // If the expiry is less than or equal to the current blockheight, we consider the price valid - if !expiry.After(ctx.BlockTime()) { - return types.PostedPrice{}, types.ErrExpired - } - - store := ctx.KVStore(k.key) - - newRawPrice := types.NewPostedPrice(marketID, oracle, price, expiry) - - // Emit an event containing the oracle's new price - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeOracleUpdatedPrice, - sdk.NewAttribute(types.AttributeMarketID, marketID), - sdk.NewAttribute(types.AttributeOracle, oracle.String()), - sdk.NewAttribute(types.AttributeMarketPrice, price.String()), - sdk.NewAttribute(types.AttributeExpiry, expiry.UTC().String()), - ), - ) - - // Sets the raw price for a single oracle instead of an array of all oracle's raw prices - store.Set(types.RawPriceKey(marketID, oracle), k.cdc.MustMarshal(&newRawPrice)) - return newRawPrice, nil -} - -// SetCurrentPrices updates the price of an asset to the median of all valid oracle inputs -func (k Keeper) SetCurrentPrices(ctx sdk.Context, marketID string) error { - _, ok := k.GetMarket(ctx, marketID) - if !ok { - return errorsmod.Wrap(types.ErrInvalidMarket, marketID) - } - // store current price - validPrevPrice := true - prevPrice, err := k.GetCurrentPrice(ctx, marketID) - if err != nil { - validPrevPrice = false - } - - prices := k.GetRawPrices(ctx, marketID) - - var notExpiredPrices []types.CurrentPrice - // filter out expired prices - for _, v := range prices { - if v.Expiry.After(ctx.BlockTime()) { - notExpiredPrices = append(notExpiredPrices, types.NewCurrentPrice(v.MarketID, v.Price)) - } - } - - if len(notExpiredPrices) == 0 { - // NOTE: The current price stored will continue storing the most recent (expired) - // price if this is not set. - // This zero's out the current price stored value for that market and ensures - // that CDP methods that GetCurrentPrice will return error. - k.setCurrentPrice(ctx, marketID, types.CurrentPrice{}) - return types.ErrNoValidPrice - } - - medianPrice := k.CalculateMedianPrice(notExpiredPrices) - - // check case that market price was not set in genesis - if validPrevPrice && !medianPrice.Equal(prevPrice.Price) { - // only emit event if price has changed - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeMarketPriceUpdated, - sdk.NewAttribute(types.AttributeMarketID, marketID), - sdk.NewAttribute(types.AttributeMarketPrice, medianPrice.String()), - ), - ) - } - - currentPrice := types.NewCurrentPrice(marketID, medianPrice) - k.setCurrentPrice(ctx, marketID, currentPrice) - - return nil -} - -// SetCurrentPricesForAllMarkets updates the price of an asset to the median of all valid oracle inputs -func (k Keeper) SetCurrentPricesForAllMarkets(ctx sdk.Context) { - orderedMarkets := []string{} - marketPricesByID := make(map[string]types.CurrentPrices) - - for _, market := range k.GetMarkets(ctx) { - if market.Active { - orderedMarkets = append(orderedMarkets, market.MarketID) - marketPricesByID[market.MarketID] = types.CurrentPrices{} - } - } - - iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.key), types.RawPriceFeedPrefix) - for ; iterator.Valid(); iterator.Next() { - var postedPrice types.PostedPrice - k.cdc.MustUnmarshal(iterator.Value(), &postedPrice) - - prices, found := marketPricesByID[postedPrice.MarketID] - if !found { - continue - } - - // filter out expired prices - if postedPrice.Expiry.After(ctx.BlockTime()) { - marketPricesByID[postedPrice.MarketID] = append(prices, types.NewCurrentPrice(postedPrice.MarketID, postedPrice.Price)) - } - } - iterator.Close() - - for _, marketID := range orderedMarkets { - // store current price - validPrevPrice := true - prevPrice, err := k.GetCurrentPrice(ctx, marketID) - if err != nil { - validPrevPrice = false - } - - notExpiredPrices, _ := marketPricesByID[marketID] - - if len(notExpiredPrices) == 0 { - // NOTE: The current price stored will continue storing the most recent (expired) - // price if this is not set. - // This zero's out the current price stored value for that market and ensures - // that CDP methods that GetCurrentPrice will return error. - k.setCurrentPrice(ctx, marketID, types.CurrentPrice{}) - continue - } - - medianPrice := k.CalculateMedianPrice(notExpiredPrices) - - // check case that market price was not set in genesis - //if validPrevPrice && !medianPrice.Equal(prevPrice.Price) { - if validPrevPrice && !medianPrice.Equal(prevPrice.Price) { - // only emit event if price has changed - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeMarketPriceUpdated, - sdk.NewAttribute(types.AttributeMarketID, marketID), - sdk.NewAttribute(types.AttributeMarketPrice, medianPrice.String()), - ), - ) - } - - currentPrice := types.NewCurrentPrice(marketID, medianPrice) - k.setCurrentPrice(ctx, marketID, currentPrice) - } -} - -func (k Keeper) setCurrentPrice(ctx sdk.Context, marketID string, currentPrice types.CurrentPrice) { - store := ctx.KVStore(k.key) - store.Set(types.CurrentPriceKey(marketID), k.cdc.MustMarshal(¤tPrice)) -} - -// CalculateMedianPrice calculates the median prices for the input prices. -func (k Keeper) CalculateMedianPrice(prices []types.CurrentPrice) sdk.Dec { - l := len(prices) - - if l == 1 { - // Return immediately if there's only one price - return prices[0].Price - } - // sort the prices - sort.Slice(prices, func(i, j int) bool { - return prices[i].Price.LT(prices[j].Price) - }) - // for even numbers of prices, the median is calculated as the mean of the two middle prices - if l%2 == 0 { - median := k.calculateMeanPrice(prices[l/2-1], prices[l/2]) - return median - } - // for odd numbers of prices, return the middle element - return prices[l/2].Price -} - -func (k Keeper) calculateMeanPrice(priceA, priceB types.CurrentPrice) sdk.Dec { - sum := priceA.Price.Add(priceB.Price) - mean := sum.Quo(sdk.NewDec(2)) - return mean -} - -// GetCurrentPrice fetches the current median price of all oracles for a specific market -func (k Keeper) GetCurrentPrice(ctx sdk.Context, marketID string) (types.CurrentPrice, error) { - store := ctx.KVStore(k.key) - bz := store.Get(types.CurrentPriceKey(marketID)) - - if bz == nil { - return types.CurrentPrice{}, types.ErrNoValidPrice - } - var price types.CurrentPrice - err := k.cdc.Unmarshal(bz, &price) - if err != nil { - return types.CurrentPrice{}, err - } - if price.Price.Equal(sdk.ZeroDec()) { - return types.CurrentPrice{}, types.ErrNoValidPrice - } - return price, nil -} - -// IterateCurrentPrices iterates over all current price objects in the store and performs a callback function -func (k Keeper) IterateCurrentPrices(ctx sdk.Context, cb func(cp types.CurrentPrice) (stop bool)) { - iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.key), types.CurrentPricePrefix) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var cp types.CurrentPrice - k.cdc.MustUnmarshal(iterator.Value(), &cp) - if cb(cp) { - break - } - } -} - -// GetCurrentPrices returns all current price objects from the store -func (k Keeper) GetCurrentPrices(ctx sdk.Context) types.CurrentPrices { - var cps types.CurrentPrices - k.IterateCurrentPrices(ctx, func(cp types.CurrentPrice) (stop bool) { - cps = append(cps, cp) - return false - }) - return cps -} - -// GetRawPrices fetches the set of all prices posted by oracles for an asset -func (k Keeper) GetRawPrices(ctx sdk.Context, marketId string) types.PostedPrices { - var pps types.PostedPrices - k.IterateRawPricesByMarket(ctx, marketId, func(pp types.PostedPrice) (stop bool) { - pps = append(pps, pp) - return false - }) - return pps -} - -// IterateRawPrices iterates over all raw prices in the store and performs a callback function -func (k Keeper) IterateRawPricesByMarket(ctx sdk.Context, marketId string, cb func(record types.PostedPrice) (stop bool)) { - iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.key), types.RawPriceIteratorKey((marketId))) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var record types.PostedPrice - k.cdc.MustUnmarshal(iterator.Value(), &record) - if cb(record) { - break - } - } -} diff --git a/x/pricefeed/keeper/keeper_test.go b/x/pricefeed/keeper/keeper_test.go deleted file mode 100644 index ec7289a2..00000000 --- a/x/pricefeed/keeper/keeper_test.go +++ /dev/null @@ -1,271 +0,0 @@ -package keeper_test - -import ( - "errors" - "testing" - "time" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/pricefeed/keeper" - "github.com/kava-labs/kava/x/pricefeed/testutil" - "github.com/kava-labs/kava/x/pricefeed/types" -) - -// TestKeeper_SetGetMarket tests adding markets to the pricefeed, getting markets from the store -func TestKeeper_SetGetMarket(t *testing.T) { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmprototypes.Header{}) - keeper := tApp.GetPriceFeedKeeper() - - mp := types.Params{ - Markets: []types.Market{ - {MarketID: "tstusd", BaseAsset: "tst", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - } - keeper.SetParams(ctx, mp) - markets := keeper.GetMarkets(ctx) - require.Equal(t, len(markets), 1) - require.Equal(t, markets[0].MarketID, "tstusd") - - _, found := keeper.GetMarket(ctx, "tstusd") - require.True(t, found, "market should be found") - - _, found = keeper.GetMarket(ctx, "invalidmarket") - require.False(t, found, "invalidmarket should not be found") - - mp = types.Params{ - Markets: []types.Market{ - {MarketID: "tstusd", BaseAsset: "tst", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "tst2usd", BaseAsset: "tst2", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - } - keeper.SetParams(ctx, mp) - markets = keeper.GetMarkets(ctx) - require.Equal(t, len(markets), 2) - require.Equal(t, markets[0].MarketID, "tstusd") - require.Equal(t, markets[1].MarketID, "tst2usd") - - _, found = keeper.GetMarket(ctx, "nan") - require.Equal(t, found, false) -} - -// TestKeeper_GetSetPrice Test Posting the price by an oracle -func TestKeeper_GetSetPrice(t *testing.T) { - _, addrs := app.GeneratePrivKeyAddressPairs(2) - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmprototypes.Header{}) - keeper := tApp.GetPriceFeedKeeper() - - mp := types.Params{ - Markets: []types.Market{ - {MarketID: "tstusd", BaseAsset: "tst", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - } - keeper.SetParams(ctx, mp) - - prices := []struct { - oracle sdk.AccAddress - marketID string - price sdk.Dec - total int - }{ - {addrs[0], "tstusd", sdk.MustNewDecFromStr("0.33"), 1}, - {addrs[1], "tstusd", sdk.MustNewDecFromStr("0.35"), 2}, - {addrs[0], "tstusd", sdk.MustNewDecFromStr("0.37"), 2}, - } - - for _, p := range prices { - // Set price by oracle 1 - pp, err := keeper.SetPrice( - ctx, - p.oracle, - p.marketID, - p.price, - time.Now().UTC().Add(1*time.Hour), - ) - - require.NoError(t, err) - - // Get raw prices - rawPrices := keeper.GetRawPrices(ctx, "tstusd") - - require.Equal(t, p.total, len(rawPrices)) - require.Contains(t, rawPrices, pp) - - // Find the oracle and require price to be same - for _, rp := range rawPrices { - if p.oracle.Equals(rp.OracleAddress) { - require.Equal(t, p.price, rp.Price) - } - } - } -} - -// TestKeeper_GetSetCurrentPrice Test Setting the median price of an Asset -func TestKeeper_GetSetCurrentPrice(t *testing.T) { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmprototypes.Header{}). - WithBlockTime(time.Now().UTC()) - keeper := tApp.GetPriceFeedKeeper() - - mp := types.Params{ - Markets: []types.Market{ - {MarketID: "tstusd", BaseAsset: "tst", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - } - keeper.SetParams(ctx, mp) - - _, err := keeper.SetPrice( - ctx, addrs[0], "tstusd", - sdk.MustNewDecFromStr("0.33"), - time.Now().Add(time.Hour*1)) - require.NoError(t, err) - - _, err = keeper.SetPrice( - ctx, addrs[1], "tstusd", - sdk.MustNewDecFromStr("0.35"), - time.Now().Add(time.Hour*1)) - require.NoError(t, err) - - _, err = keeper.SetPrice( - ctx, addrs[2], "tstusd", - sdk.MustNewDecFromStr("0.34"), - time.Now().Add(time.Hour*1)) - require.NoError(t, err) - - // Add an expired one which should fail - _, err = keeper.SetPrice( - ctx, addrs[3], "tstusd", - sdk.MustNewDecFromStr("0.9"), - ctx.BlockTime().Add(-time.Hour*1)) - require.Error(t, err) - - // Add a non-expired price, but will not be counted when BlockTime is changed - _, err = keeper.SetPrice( - ctx, addrs[3], "tstusd", - sdk.MustNewDecFromStr("0.9"), - time.Now().Add(time.Minute*30)) - require.NoError(t, err) - - // Update block time such that first 3 prices valid but last one is expired - ctx = ctx.WithBlockTime(time.Now().Add(time.Minute * 45)) - - // Set current price - err = keeper.SetCurrentPrices(ctx, "tstusd") - require.NoError(t, err) - - // Get current price - price, err := keeper.GetCurrentPrice(ctx, "tstusd") - require.Nil(t, err) - - expCurPrice := sdk.MustNewDecFromStr("0.34") - require.Truef( - t, - price.Price.Equal(expCurPrice), - "expected current price to equal %v, actual %v", - expCurPrice, price.Price, - ) - - // Even number of oracles - _, err = keeper.SetPrice( - ctx, addrs[4], "tstusd", - sdk.MustNewDecFromStr("0.36"), - time.Now().Add(time.Hour*1)) - require.NoError(t, err) - - err = keeper.SetCurrentPrices(ctx, "tstusd") - require.NoError(t, err) - - price, err = keeper.GetCurrentPrice(ctx, "tstusd") - require.Nil(t, err) - - exp := sdk.MustNewDecFromStr("0.345") - require.Truef(t, price.Price.Equal(exp), - "current price %s should be %s", - price.Price.String(), - exp.String(), - ) - - prices := keeper.GetCurrentPrices(ctx) - require.Equal(t, 1, len(prices)) - require.Equal(t, price, prices[0]) -} - -func TestKeeper_ExpiredSetCurrentPrices(t *testing.T) { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmprototypes.Header{}). - WithBlockTime(time.Now().UTC()) - keeper := tApp.GetPriceFeedKeeper() - - mp := types.Params{ - Markets: []types.Market{ - {MarketID: "tstusd", BaseAsset: "tst", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - } - keeper.SetParams(ctx, mp) - - _, err := keeper.SetPrice( - ctx, addrs[0], "tstusd", - sdk.MustNewDecFromStr("0.33"), - time.Now().Add(time.Hour*1)) - require.NoError(t, err) - - _, err = keeper.SetPrice( - ctx, addrs[1], "tstusd", - sdk.MustNewDecFromStr("0.35"), - time.Now().Add(time.Hour*1)) - require.NoError(t, err) - - _, err = keeper.SetPrice( - ctx, addrs[2], "tstusd", - sdk.MustNewDecFromStr("0.34"), - time.Now().Add(time.Hour*1)) - require.NoError(t, err) - - // Update block time such that all prices expire - ctx = ctx.WithBlockTime(time.Now().UTC().Add(time.Hour * 2)) - - err = keeper.SetCurrentPrices(ctx, "tstusd") - require.ErrorIs(t, types.ErrNoValidPrice, err, "there should be no valid prices to be set") - - _, err = keeper.GetCurrentPrice(ctx, "tstusd") - require.ErrorIs(t, types.ErrNoValidPrice, err, "current prices should be invalid") -} - -func TestKeeper_SetCurrentPricesForAllMarkets_PriceUpdate(t *testing.T) { - testutil.SetCurrentPrices_PriceCalculations(t, func(ctx sdk.Context, keeper keeper.Keeper) { - keeper.SetCurrentPricesForAllMarkets(ctx) - }) -} - -func TestKeeper_SetCurrentPricesForAllMarkets_EventEmission(t *testing.T) { - testutil.SetCurrentPrices_EventEmission(t, func(ctx sdk.Context, keeper keeper.Keeper) { - keeper.SetCurrentPricesForAllMarkets(ctx) - }) -} - -func TestKeeper_SetCurrentPrices_MatchesAllMarketsBehavior(t *testing.T) { - testFunc := func(ctx sdk.Context, k keeper.Keeper) { - for _, market := range k.GetMarkets(ctx) { - if !market.Active { - continue - } - - err := k.SetCurrentPrices(ctx, market.MarketID) - if err != nil && !errors.Is(err, types.ErrNoValidPrice) { - panic(err) - } - } - } - - testutil.SetCurrentPrices_PriceCalculations(t, testFunc) - testutil.SetCurrentPrices_EventEmission(t, testFunc) -} diff --git a/x/pricefeed/keeper/msg_server.go b/x/pricefeed/keeper/msg_server.go deleted file mode 100644 index 67a10d1c..00000000 --- a/x/pricefeed/keeper/msg_server.go +++ /dev/null @@ -1,50 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/pricefeed/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the pricefeed MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -func (k msgServer) PostPrice(goCtx context.Context, msg *types.MsgPostPrice) (*types.MsgPostPriceResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - from, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - return nil, err - } - - _, err = k.keeper.GetOracle(ctx, msg.MarketID, from) - if err != nil { - return nil, err - } - - _, err = k.keeper.SetPrice(ctx, from, msg.MarketID, msg.Price, msg.Expiry) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.From), - ), - ) - - return &types.MsgPostPriceResponse{}, nil -} diff --git a/x/pricefeed/keeper/msg_server_test.go b/x/pricefeed/keeper/msg_server_test.go deleted file mode 100644 index 2ffcd8bb..00000000 --- a/x/pricefeed/keeper/msg_server_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/pricefeed/keeper" - "github.com/kava-labs/kava/x/pricefeed/types" - "github.com/stretchr/testify/require" -) - -func TestKeeper_PostPrice(t *testing.T) { - _, addrs := app.GeneratePrivKeyAddressPairs(4) - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmprototypes.Header{}). - WithBlockTime(time.Now().UTC()) - k := tApp.GetPriceFeedKeeper() - msgSrv := keeper.NewMsgServerImpl(k) - - authorizedOracles := addrs[:2] - unauthorizedAddrs := addrs[2:] - - mp := types.Params{ - Markets: []types.Market{ - {MarketID: "tstusd", BaseAsset: "tst", QuoteAsset: "usd", Oracles: authorizedOracles, Active: true}, - }, - } - k.SetParams(ctx, mp) - - now := time.Now().UTC() - - tests := []struct { - giveMsg string - giveOracle sdk.AccAddress - giveMarketId string - giveExpiry time.Time - wantAccepted bool - errorKind error - }{ - {"authorized", authorizedOracles[0], "tstusd", now.Add(time.Hour * 1), true, nil}, - {"expired", authorizedOracles[0], "tstusd", now.Add(-time.Hour * 1), false, types.ErrExpired}, - {"invalid", authorizedOracles[0], "invalid", now.Add(time.Hour * 1), false, types.ErrInvalidMarket}, - {"unauthorized", unauthorizedAddrs[0], "tstusd", now.Add(time.Hour * 1), false, types.ErrInvalidOracle}, - } - - for _, tt := range tests { - t.Run(tt.giveMsg, func(t *testing.T) { - // Use MsgServer over keeper methods directly to tests against valid oracles - msg := types.NewMsgPostPrice(tt.giveOracle.String(), tt.giveMarketId, sdk.MustNewDecFromStr("0.5"), tt.giveExpiry) - _, err := msgSrv.PostPrice(sdk.WrapSDKContext(ctx), msg) - - if tt.wantAccepted { - require.NoError(t, err) - } else { - require.Error(t, err) - require.ErrorIs(t, tt.errorKind, err) - } - }) - } -} diff --git a/x/pricefeed/keeper/params.go b/x/pricefeed/keeper/params.go deleted file mode 100644 index 5c167f1c..00000000 --- a/x/pricefeed/keeper/params.go +++ /dev/null @@ -1,79 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/pricefeed/types" -) - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - var p types.Params - k.paramSubspace.GetParamSet(ctx, &p) - return p -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} - -// GetMarkets returns the markets from params -func (k Keeper) GetMarkets(ctx sdk.Context) types.Markets { - return k.GetParams(ctx).Markets -} - -// GetOracles returns the oracles in the pricefeed store -func (k Keeper) GetOracles(ctx sdk.Context, marketID string) ([]sdk.AccAddress, error) { - for _, m := range k.GetMarkets(ctx) { - if marketID == m.MarketID { - return m.Oracles, nil - } - } - return nil, errorsmod.Wrap(types.ErrInvalidMarket, marketID) -} - -// GetOracle returns the oracle from the store or an error if not found -func (k Keeper) GetOracle(ctx sdk.Context, marketID string, address sdk.AccAddress) (sdk.AccAddress, error) { - oracles, err := k.GetOracles(ctx, marketID) - if err != nil { - // Error already wrapped - return nil, err - } - for _, addr := range oracles { - if addr.Equals(address) { - return addr, nil - } - } - return nil, errorsmod.Wrap(types.ErrInvalidOracle, address.String()) -} - -// GetMarket returns the market if it is in the pricefeed system -func (k Keeper) GetMarket(ctx sdk.Context, marketID string) (types.Market, bool) { - markets := k.GetMarkets(ctx) - - for i := range markets { - if markets[i].MarketID == marketID { - return markets[i], true - } - } - return types.Market{}, false -} - -// GetAuthorizedAddresses returns a list of addresses that have special authorization within this module, eg the oracles of all markets. -func (k Keeper) GetAuthorizedAddresses(ctx sdk.Context) []sdk.AccAddress { - var oracles []sdk.AccAddress - uniqueOracles := map[string]bool{} - - for _, m := range k.GetMarkets(ctx) { - for _, o := range m.Oracles { - // de-dup list of oracles - if _, found := uniqueOracles[o.String()]; !found { - oracles = append(oracles, o) - } - uniqueOracles[o.String()] = true - } - } - return oracles -} diff --git a/x/pricefeed/keeper/params_test.go b/x/pricefeed/keeper/params_test.go deleted file mode 100644 index ffad3c88..00000000 --- a/x/pricefeed/keeper/params_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/pricefeed/keeper" - "github.com/kava-labs/kava/x/pricefeed/types" -) - -type KeeperTestSuite struct { - suite.Suite - - keeper keeper.Keeper - addrs []sdk.AccAddress - ctx sdk.Context -} - -func (suite *KeeperTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmprototypes.Header{Height: 1, Time: tmtime.Now()}) - tApp.InitializeFromGenesisStates( - NewPricefeedGenStateMulti(), - ) - suite.keeper = tApp.GetPriceFeedKeeper() - suite.ctx = ctx - - _, addrs := app.GeneratePrivKeyAddressPairs(10) - suite.addrs = addrs -} - -func (suite *KeeperTestSuite) TestGetSetOracles() { - params := suite.keeper.GetParams(suite.ctx) - suite.Equal([]sdk.AccAddress(nil), params.Markets[0].Oracles) - - params.Markets[0].Oracles = suite.addrs - suite.NotPanics(func() { suite.keeper.SetParams(suite.ctx, params) }) - params = suite.keeper.GetParams(suite.ctx) - suite.Equal(suite.addrs, params.Markets[0].Oracles) - - addr, err := suite.keeper.GetOracle(suite.ctx, params.Markets[0].MarketID, suite.addrs[0]) - suite.NoError(err) - suite.Equal(suite.addrs[0], addr) -} - -func (suite *KeeperTestSuite) TestGetAuthorizedAddresses() { - _, oracles := app.GeneratePrivKeyAddressPairs(5) - - params := types.Params{ - Markets: []types.Market{ - {MarketID: "btc:usd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: oracles[:3], Active: true}, - {MarketID: "xrp:usd", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: oracles[2:], Active: true}, - {MarketID: "xrp:usd:30", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: nil, Active: true}, - }, - } - suite.keeper.SetParams(suite.ctx, params) - - actualOracles := suite.keeper.GetAuthorizedAddresses(suite.ctx) - - suite.Require().ElementsMatch(oracles, actualOracles) -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} diff --git a/x/pricefeed/legacy/v0_15/types.go b/x/pricefeed/legacy/v0_15/types.go deleted file mode 100644 index 0a9b6722..00000000 --- a/x/pricefeed/legacy/v0_15/types.go +++ /dev/null @@ -1,46 +0,0 @@ -package v0_15 - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName The name that will be used throughout the module - ModuleName = "pricefeed" -) - -// GenesisState - pricefeed state that must be provided at genesis -type GenesisState struct { - Params Params `json:"params" yaml:"params"` - PostedPrices PostedPrices `json:"posted_prices" yaml:"posted_prices"` -} - -// Params params for pricefeed. Can be altered via governance -type Params struct { - Markets Markets `json:"markets" yaml:"markets"` // Array containing the markets supported by the pricefeed -} - -// Markets array type for oracle -type Markets []Market - -// Market an asset in the pricefeed -type Market struct { - MarketID string `json:"market_id" yaml:"market_id"` - BaseAsset string `json:"base_asset" yaml:"base_asset"` - QuoteAsset string `json:"quote_asset" yaml:"quote_asset"` - Oracles []sdk.AccAddress `json:"oracles" yaml:"oracles"` - Active bool `json:"active" yaml:"active"` -} - -// PostedPrices type for an array of PostedPrice -type PostedPrices []PostedPrice - -// PostedPrice price for market posted by a specific oracle -type PostedPrice struct { - MarketID string `json:"market_id" yaml:"market_id"` - OracleAddress sdk.AccAddress `json:"oracle_address" yaml:"oracle_address"` - Price sdk.Dec `json:"price" yaml:"price"` - Expiry time.Time `json:"expiry" yaml:"expiry"` -} diff --git a/x/pricefeed/legacy/v0_16/migrate.go b/x/pricefeed/legacy/v0_16/migrate.go deleted file mode 100644 index 34cc8235..00000000 --- a/x/pricefeed/legacy/v0_16/migrate.go +++ /dev/null @@ -1,134 +0,0 @@ -package v0_16 - -import ( - "github.com/cosmos/cosmos-sdk/types" - v015pricefeed "github.com/kava-labs/kava/x/pricefeed/legacy/v0_15" - v016pricefeed "github.com/kava-labs/kava/x/pricefeed/types" -) - -var NewIBCMarkets = []v016pricefeed.Market{ - { - MarketID: "atom:usd", - BaseAsset: "atom", - QuoteAsset: "usd", - Oracles: nil, - Active: true, - }, - { - MarketID: "atom:usd:30", - BaseAsset: "atom", - QuoteAsset: "usd", - Oracles: nil, - Active: true, - }, - { - MarketID: "akt:usd", - BaseAsset: "akt", - QuoteAsset: "usd", - Oracles: nil, - Active: true, - }, - { - MarketID: "akt:usd:30", - BaseAsset: "akt", - QuoteAsset: "usd", - Oracles: nil, - Active: true, - }, - { - MarketID: "luna:usd", - BaseAsset: "luna", - QuoteAsset: "usd", - Oracles: nil, - Active: true, - }, - { - MarketID: "luna:usd:30", - BaseAsset: "luna", - QuoteAsset: "usd", - Oracles: nil, - Active: true, - }, - { - MarketID: "osmo:usd", - BaseAsset: "osmo", - QuoteAsset: "usd", - Oracles: nil, - Active: true, - }, - { - MarketID: "osmo:usd:30", - BaseAsset: "osmo", - QuoteAsset: "usd", - Oracles: nil, - Active: true, - }, - { - MarketID: "ust:usd", - BaseAsset: "ust", - QuoteAsset: "usd", - Oracles: nil, - Active: true, - }, - { - MarketID: "ust:usd:30", - BaseAsset: "ust", - QuoteAsset: "usd", - Oracles: nil, - Active: true, - }, -} - -func migrateParams(params v015pricefeed.Params) v016pricefeed.Params { - markets := make(v016pricefeed.Markets, len(params.Markets)) - for i, market := range params.Markets { - markets[i] = v016pricefeed.Market{ - MarketID: market.MarketID, - BaseAsset: market.BaseAsset, - QuoteAsset: market.QuoteAsset, - Oracles: market.Oracles, - Active: market.Active, - } - } - - markets = addIbcMarkets(markets) - - return v016pricefeed.Params{Markets: markets} -} - -func addIbcMarkets(markets v016pricefeed.Markets) v016pricefeed.Markets { - var oracles []types.AccAddress - - if len(markets) > 0 { - oracles = markets[0].Oracles - } - - for _, newMarket := range NewIBCMarkets { - // newMarket is a copy, should not affect other uses of NewIBCMarkets - newMarket.Oracles = oracles - markets = append(markets, newMarket) - } - - return markets -} - -func migratePostedPrices(oldPostedPrices v015pricefeed.PostedPrices) v016pricefeed.PostedPrices { - newPrices := make(v016pricefeed.PostedPrices, len(oldPostedPrices)) - for i, price := range oldPostedPrices { - newPrices[i] = v016pricefeed.PostedPrice{ - MarketID: price.MarketID, - OracleAddress: price.OracleAddress, - Price: price.Price, - Expiry: price.Expiry, - } - } - return newPrices -} - -// Migrate converts v0.15 pricefeed state and returns it in v0.16 format -func Migrate(oldState v015pricefeed.GenesisState) *v016pricefeed.GenesisState { - return &v016pricefeed.GenesisState{ - Params: migrateParams(oldState.Params), - PostedPrices: migratePostedPrices(oldState.PostedPrices), - } -} diff --git a/x/pricefeed/legacy/v0_16/migrate_test.go b/x/pricefeed/legacy/v0_16/migrate_test.go deleted file mode 100644 index 81f2e120..00000000 --- a/x/pricefeed/legacy/v0_16/migrate_test.go +++ /dev/null @@ -1,352 +0,0 @@ -package v0_16 - -import ( - "testing" - "time" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - app "github.com/kava-labs/kava/app" - v015pricefeed "github.com/kava-labs/kava/x/pricefeed/legacy/v0_15" - v016pricefeed "github.com/kava-labs/kava/x/pricefeed/types" -) - -type migrateTestSuite struct { - suite.Suite - - addresses []sdk.AccAddress - v15genstate v015pricefeed.GenesisState - cdc codec.Codec - legacyCdc *codec.LegacyAmino -} - -func (s *migrateTestSuite) SetupTest() { - app.SetSDKConfig() - - s.v15genstate = v015pricefeed.GenesisState{ - Params: v015pricefeed.Params{}, - PostedPrices: v015pricefeed.PostedPrices{}, - } - - config := app.MakeEncodingConfig() - s.cdc = config.Marshaler - - legacyCodec := codec.NewLegacyAmino() - s.legacyCdc = legacyCodec - - _, accAddresses := app.GeneratePrivKeyAddressPairs(10) - s.addresses = accAddresses -} - -func (s *migrateTestSuite) TestMigrate_JSON() { - // Migrate v15 pricefeed to v16 - v15Params := `{ - "params": { - "markets": [ - { - "active": true, - "base_asset": "bnb", - "market_id": "bnb:usd", - "oracles": ["kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em"], - "quote_asset": "usd" - }, - { - "active": true, - "base_asset": "bnb", - "market_id": "bnb:usd:30", - "oracles": ["kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em"], - "quote_asset": "usd" - } - ] - }, - "posted_prices": [ - { - "expiry": "2022-07-20T00:00:00Z", - "market_id": "bnb:usd", - "oracle_address": "kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em", - "price": "215.962650000000001782" - }, - { - "expiry": "2022-07-20T00:00:00Z", - "market_id": "bnb:usd:30", - "oracle_address": "kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em", - "price": "217.962650000000001782" - } - ] - }` - - expectedV16Params := `{ - "params": { - "markets": [ - { - "market_id": "bnb:usd", - "base_asset": "bnb", - "quote_asset": "usd", - "oracles": [ - "kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em" - ], - "active": true - }, - { - "market_id": "bnb:usd:30", - "base_asset": "bnb", - "quote_asset": "usd", - "oracles": [ - "kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em" - ], - "active": true - }, - { - "market_id": "atom:usd", - "base_asset": "atom", - "quote_asset": "usd", - "oracles": [ - "kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em" - ], - "active": true - }, - { - "market_id": "atom:usd:30", - "base_asset": "atom", - "quote_asset": "usd", - "oracles": [ - "kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em" - ], - "active": true - }, - { - "market_id": "akt:usd", - "base_asset": "akt", - "quote_asset": "usd", - "oracles": [ - "kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em" - ], - "active": true - }, - { - "market_id": "akt:usd:30", - "base_asset": "akt", - "quote_asset": "usd", - "oracles": [ - "kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em" - ], - "active": true - }, - { - "market_id": "luna:usd", - "base_asset": "luna", - "quote_asset": "usd", - "oracles": [ - "kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em" - ], - "active": true - }, - { - "market_id": "luna:usd:30", - "base_asset": "luna", - "quote_asset": "usd", - "oracles": [ - "kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em" - ], - "active": true - }, - { - "market_id": "osmo:usd", - "base_asset": "osmo", - "quote_asset": "usd", - "oracles": [ - "kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em" - ], - "active": true - }, - { - "market_id": "osmo:usd:30", - "base_asset": "osmo", - "quote_asset": "usd", - "oracles": [ - "kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em" - ], - "active": true - }, - { - "market_id": "ust:usd", - "base_asset": "ust", - "quote_asset": "usd", - "oracles": [ - "kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em" - ], - "active": true - }, - { - "market_id": "ust:usd:30", - "base_asset": "ust", - "quote_asset": "usd", - "oracles": [ - "kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em" - ], - "active": true - } - ] - }, - "posted_prices": [ - { - "market_id": "bnb:usd", - "oracle_address": "kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em", - "price": "215.962650000000001782", - "expiry": "2022-07-20T00:00:00Z" - }, - { - "market_id": "bnb:usd:30", - "oracle_address": "kava1acge4tcvhf3q6fh53fgwaa7vsq40wvx6wn50em", - "price": "217.962650000000001782", - "expiry": "2022-07-20T00:00:00Z" - } - ] - }` - - err := s.legacyCdc.UnmarshalJSON([]byte(v15Params), &s.v15genstate) - s.Require().NoError(err) - genstate := Migrate(s.v15genstate) - - // v16 pricefeed json should be the same as v15 but with IBC markets added - actual := s.cdc.MustMarshalJSON(genstate) - - s.Require().NoError(err) - s.Require().JSONEq(expectedV16Params, string(actual)) -} - -func (s *migrateTestSuite) TestMigrate_Params() { - s.v15genstate.Params = v015pricefeed.Params{ - Markets: v015pricefeed.Markets{ - { - MarketID: "market-1", - BaseAsset: "kava", - QuoteAsset: "usd", - Oracles: s.addresses, - Active: true, - }, - }, - } - expectedParams := v016pricefeed.Params{ - Markets: v016pricefeed.Markets{ - { - MarketID: "market-1", - BaseAsset: "kava", - QuoteAsset: "usd", - Oracles: s.addresses, - Active: true, - }, - { - MarketID: "atom:usd", - BaseAsset: "atom", - QuoteAsset: "usd", - Oracles: s.addresses, - Active: true, - }, - { - MarketID: "atom:usd:30", - BaseAsset: "atom", - QuoteAsset: "usd", - Oracles: s.addresses, - Active: true, - }, - { - MarketID: "akt:usd", - BaseAsset: "akt", - QuoteAsset: "usd", - Oracles: s.addresses, - Active: true, - }, - { - MarketID: "akt:usd:30", - BaseAsset: "akt", - QuoteAsset: "usd", - Oracles: s.addresses, - Active: true, - }, - { - MarketID: "luna:usd", - BaseAsset: "luna", - QuoteAsset: "usd", - Oracles: s.addresses, - Active: true, - }, - { - MarketID: "luna:usd:30", - BaseAsset: "luna", - QuoteAsset: "usd", - Oracles: s.addresses, - Active: true, - }, - { - MarketID: "osmo:usd", - BaseAsset: "osmo", - QuoteAsset: "usd", - Oracles: s.addresses, - Active: true, - }, - { - MarketID: "osmo:usd:30", - BaseAsset: "osmo", - QuoteAsset: "usd", - Oracles: s.addresses, - Active: true, - }, - { - MarketID: "ust:usd", - BaseAsset: "ust", - QuoteAsset: "usd", - Oracles: s.addresses, - Active: true, - }, - { - MarketID: "ust:usd:30", - BaseAsset: "ust", - QuoteAsset: "usd", - Oracles: s.addresses, - Active: true, - }, - }, - } - genState := Migrate(s.v15genstate) - s.Require().Equal(expectedParams, genState.Params) -} - -func (s *migrateTestSuite) TestMigrate_PostedPrices() { - s.v15genstate.PostedPrices = v015pricefeed.PostedPrices{ - { - MarketID: "market-1", - OracleAddress: s.addresses[0], - Price: sdk.MustNewDecFromStr("1.2"), - Expiry: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - { - MarketID: "market-2", - OracleAddress: s.addresses[1], - Price: sdk.MustNewDecFromStr("1.899"), - Expiry: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - } - expected := v016pricefeed.PostedPrices{ - { - MarketID: "market-1", - OracleAddress: s.addresses[0], - Price: sdk.MustNewDecFromStr("1.2"), - Expiry: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - { - MarketID: "market-2", - OracleAddress: s.addresses[1], - Price: sdk.MustNewDecFromStr("1.899"), - Expiry: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - } - genState := Migrate(s.v15genstate) - s.Require().Equal(expected, genState.PostedPrices) -} - -func TestPriceFeedMigrateTestSuite(t *testing.T) { - suite.Run(t, new(migrateTestSuite)) -} diff --git a/x/pricefeed/module.go b/x/pricefeed/module.go deleted file mode 100644 index 11ceb784..00000000 --- a/x/pricefeed/module.go +++ /dev/null @@ -1,144 +0,0 @@ -package pricefeed - -import ( - "context" - "encoding/json" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - sdkkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/kava-labs/kava/x/pricefeed/client/cli" - "github.com/kava-labs/kava/x/pricefeed/keeper" - "github.com/kava-labs/kava/x/pricefeed/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - gs := types.DefaultGenesisState() - return cdc.MustMarshalJSON(&gs) -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) - if err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the gov module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// GetTxCmd returns the root tx command for the swap module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the swap module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper sdkkeeper.AccountKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper sdkkeeper.AccountKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: accountKeeper, - } -} - -// Name module name -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// RegisterInvariants register module invariants -func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) {} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) -} - -// InitGenesis module init-genesis -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 module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(&gs) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) { -} - -// EndBlock module end-block -func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - EndBlocker(ctx, am.keeper) - - return []abci.ValidatorUpdate{} -} diff --git a/x/pricefeed/spec/01_concepts.md b/x/pricefeed/spec/01_concepts.md deleted file mode 100644 index aa3db8b5..00000000 --- a/x/pricefeed/spec/01_concepts.md +++ /dev/null @@ -1,7 +0,0 @@ - - -# Concepts - -Prices can be posted by any account which is added as an oracle. Oracles are specific to each market and can be updated via param change proposals. When an oracle posts a price, they submit a message to the blockchain that contains the current price for that market and a time when that price should be considered expired. If an oracle posts a new price, that price becomes the current price for that oracle, regardless of the previous price's expiry. A group of prices posted by a set of oracles for a particular market are referred to as 'raw prices' and the current median price of all valid oracle prices is referred to as the 'current price'. Each block, the current price for each market is determined by calculating the median of the raw prices. diff --git a/x/pricefeed/spec/02_state.md b/x/pricefeed/spec/02_state.md deleted file mode 100644 index 6fd95426..00000000 --- a/x/pricefeed/spec/02_state.md +++ /dev/null @@ -1,48 +0,0 @@ - - -# State - -## Parameters and genesis state - -`parameters` determine which markets are tracked by the pricefeed and which oracles are authorized to post prices for a given market. There is only one active parameter set at any given time. Updates to parameters can be made via on-chain parameter update proposals. - -```go -// Params params for pricefeed. Can be altered via governance -type Params struct { - Markets Markets `json:"markets" yaml:"markets"` // Array containing the markets supported by the pricefeed -} - -// Market an asset in the pricefeed -type Market struct { - MarketID string `json:"market_id" yaml:"market_id"` - BaseAsset string `json:"base_asset" yaml:"base_asset"` - QuoteAsset string `json:"quote_asset" yaml:"quote_asset"` - Oracles []sdk.AccAddress `json:"oracles" yaml:"oracles"` - Active bool `json:"active" yaml:"active"` -} - -type Markets []Market -``` - -`GenesisState` defines the state that must be persisted when the blockchain stops/stars in order for the normal function of the pricefeed to resume. - -```go -// GenesisState - pricefeed state that must be provided at genesis -type GenesisState struct { - Params Params `json:"params" yaml:"params"` - PostedPrices []PostedPrice `json:"posted_prices" yaml:"posted_prices"` -} - -// PostedPrice price for market posted by a specific oracle -type PostedPrice struct { - MarketID string `json:"market_id" yaml:"market_id"` - OracleAddress sdk.AccAddress `json:"oracle_address" yaml:"oracle_address"` - Price sdk.Dec `json:"price" yaml:"price"` - Expiry time.Time `json:"expiry" yaml:"expiry"` -} - -type PostedPrices []PostedPrice -``` - diff --git a/x/pricefeed/spec/03_messages.md b/x/pricefeed/spec/03_messages.md deleted file mode 100644 index fb26c47e..00000000 --- a/x/pricefeed/spec/03_messages.md +++ /dev/null @@ -1,24 +0,0 @@ - - -# Messages - -## Posting Prices - -An authorized oraclef for a particular market can post the current price for that market using the `MsgPostPrice` type. - -```go -// MsgPostPrice struct representing a posted price message. -// Used by oracles to input prices to the pricefeed -type MsgPostPrice struct { - From sdk.AccAddress `json:"from" yaml:"from"` // client that sent in this address - MarketID string `json:"market_id" yaml:"market_id"` // asset code used by exchanges/api - Price sdk.Dec `json:"price" yaml:"price"` // price in decimal (max precision 18) - Expiry time.Time `json:"expiry" yaml:"expiry"` // expiry time -} -``` - -### State Modifications - -* Update the raw price for the oracle for this market. This replaces any previous price for that oracle. diff --git a/x/pricefeed/spec/04_events.md b/x/pricefeed/spec/04_events.md deleted file mode 100644 index 7bf4865a..00000000 --- a/x/pricefeed/spec/04_events.md +++ /dev/null @@ -1,26 +0,0 @@ - - -# Events - -The `x/pricefeed` module emits the following events: - -## MsgPostPrice - -| Type | Attribute Key | Attribute Value | -|----------------------|---------------|--------------------| -| oracle_updated_price | market_id | `{market ID}` | -| oracle_updated_price | oracle | `{oracle}` | -| oracle_updated_price | market_price | `{price}` | -| oracle_updated_price | expiry | `{expiry}` | -| message | module | pricefeed | -| message | sender | `{sender address}` | - -## BeginBlock - -| Type | Attribute Key | Attribute Value | -|----------------------|-----------------|------------------| -| market_price_updated | market_id | `{market ID}` | -| market_price_updated | market_price | `{price}` | -| no_valid_prices | market_id | `{market ID}` | diff --git a/x/pricefeed/spec/05_params.md b/x/pricefeed/spec/05_params.md deleted file mode 100644 index 5eebda62..00000000 --- a/x/pricefeed/spec/05_params.md +++ /dev/null @@ -1,21 +0,0 @@ - - -# Parameters - -The pricefeed module has the following parameters: - -| Key | Type | Example | Description | -|------------|----------------|---------------|--------------------------------------------------| -| Markets | array (Market) | [{see below}] | array of params for each market in the pricefeed | - -Each `Market` has the following parameters - -| Key | Type | Example | Description | -|------------|--------------------|--------------------------|----------------------------------------------------------------| -| MarketID | string | "bnb:usd" | identifier for the market -- **must** be unique across markets | -| BaseAsset | string | "bnb" | the base asset for the market pair | -| QuoteAsset | string | "usd" | the quote asset for the market pair | -| Oracles | array (AccAddress) | ["kava1...", "kava1..."] | addresses which can post prices for the market | -| Active | bool | true | flag to disable oracle interactions with the module | diff --git a/x/pricefeed/spec/06_end_block.md b/x/pricefeed/spec/06_end_block.md deleted file mode 100644 index 4fc02525..00000000 --- a/x/pricefeed/spec/06_end_block.md +++ /dev/null @@ -1,30 +0,0 @@ - - -# End Block - -At the end of each block, the current price is calculated as the median of all raw prices for each market. The logic is as follows: - -```go -// EndBlocker updates the current pricefeed -func EndBlocker(ctx sdk.Context, k Keeper) { - // Update the current price of each asset. - for _, market := range k.GetMarkets(ctx) { - if market.Active { - err := k.SetCurrentPrices(ctx, market.MarketId) - if err != nil { - // In the event of failure, emit an event. - ctx.EventManager().EmitEvent( - sdk.NewEvent( - EventTypeNoValidPrices, - sdk.NewAttribute(AttributeMarketID, fmt.Sprintf("%s", market.MarketId)), - ), - ) - continue - } - } - } - return -} -``` diff --git a/x/pricefeed/spec/README.md b/x/pricefeed/spec/README.md deleted file mode 100644 index 7004f81d..00000000 --- a/x/pricefeed/spec/README.md +++ /dev/null @@ -1,20 +0,0 @@ - - -# `pricefeed` - - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** -5. **[Params](05_params.md)** -6. **[EndBlock](06_end_block.md)** - -## Abstract - -`x/pricefeed` is an implementation of a Cosmos SDK Module that handles the posting of prices for various markets by a group of whitelisted oracles. At the end of each block, the median price of all oracle posted prices is determined for each market and stored. diff --git a/x/pricefeed/testutil/helpers.go b/x/pricefeed/testutil/helpers.go deleted file mode 100644 index 76db45f1..00000000 --- a/x/pricefeed/testutil/helpers.go +++ /dev/null @@ -1,236 +0,0 @@ -package testutil - -import ( - "testing" - "time" - - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/pricefeed/keeper" - "github.com/kava-labs/kava/x/pricefeed/types" -) - -func SetCurrentPrices_PriceCalculations(t *testing.T, f func(ctx sdk.Context, keeper keeper.Keeper)) { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmprototypes.Header{}). - WithBlockTime(time.Now().UTC()) - keeper := tApp.GetPriceFeedKeeper() - - params := types.Params{ - Markets: []types.Market{ - // valid previous price, expired prices, price change, and active - {MarketID: "asset1:usd", BaseAsset: "asset1", QuoteAsset: "usd", Oracles: addrs, Active: true}, - // same data as asset1, but not active and should be ignored - {MarketID: "asset2:usd", BaseAsset: "asset2", QuoteAsset: "usd", Oracles: addrs, Active: false}, - // same data as asset1 except no valid previous price - {MarketID: "asset3:usd", BaseAsset: "asset3", QuoteAsset: "usd", Oracles: addrs, Active: true}, - // previous price set, but no valid prices - {MarketID: "asset4:usd", BaseAsset: "asset4", QuoteAsset: "usd", Oracles: addrs, Active: true}, - // same as market one except different prices - {MarketID: "asset5:usd", BaseAsset: "asset5", QuoteAsset: "usd", Oracles: addrs, Active: true}, - }, - } - keeper.SetParams(ctx, params) - - // need price equal to block time and after block time - blockTime := time.Now() - initialPriceExpiry := blockTime.Add(1 * time.Hour) - - _, err := keeper.SetPrice(ctx, addrs[0], "asset1:usd", sdk.MustNewDecFromStr("1"), initialPriceExpiry) - require.NoError(t, err) - _, err = keeper.SetPrice(ctx, addrs[0], "asset2:usd", sdk.MustNewDecFromStr("1"), initialPriceExpiry) - require.NoError(t, err) - _, err = keeper.SetPrice(ctx, addrs[0], "asset4:usd", sdk.MustNewDecFromStr("1"), initialPriceExpiry) - require.NoError(t, err) - _, err = keeper.SetPrice(ctx, addrs[0], "asset5:usd", sdk.MustNewDecFromStr("10"), initialPriceExpiry) - require.NoError(t, err) - - ctx = ctx.WithBlockTime(blockTime) - f(ctx, keeper) - - // price should be set - price, err := keeper.GetCurrentPrice(ctx, "asset1:usd") - require.NoError(t, err) - require.Equal(t, sdk.OneDec(), price.Price) - // not an active market, so price is not set - price, err = keeper.GetCurrentPrice(ctx, "asset2:usd") - require.Equal(t, types.ErrNoValidPrice, err) - // no price posted - price, err = keeper.GetCurrentPrice(ctx, "asset3:usd") - require.Equal(t, types.ErrNoValidPrice, err) - // price set initially - price, err = keeper.GetCurrentPrice(ctx, "asset4:usd") - require.NoError(t, err) - require.Equal(t, sdk.OneDec(), price.Price) - price, err = keeper.GetCurrentPrice(ctx, "asset5:usd") - require.NoError(t, err) - require.Equal(t, sdk.MustNewDecFromStr("10.0"), price.Price) - - _, err = keeper.SetPrice(ctx, addrs[1], "asset1:usd", sdk.MustNewDecFromStr("2"), initialPriceExpiry.Add(1*time.Hour)) - require.NoError(t, err) - _, err = keeper.SetPrice(ctx, addrs[1], "asset2:usd", sdk.MustNewDecFromStr("2"), initialPriceExpiry.Add(1*time.Hour)) - require.NoError(t, err) - _, err = keeper.SetPrice(ctx, addrs[1], "asset5:usd", sdk.MustNewDecFromStr("20"), initialPriceExpiry.Add(1*time.Hour)) - require.NoError(t, err) - - blockTime = blockTime.Add(30 * time.Minute) - ctx = ctx.WithBlockTime(blockTime) - f(ctx, keeper) - - // price should be set - price, err = keeper.GetCurrentPrice(ctx, "asset1:usd") - require.NoError(t, err) - require.Equal(t, sdk.MustNewDecFromStr("1.5"), price.Price) - // not an active market, so price is not set - price, err = keeper.GetCurrentPrice(ctx, "asset2:usd") - require.Equal(t, types.ErrNoValidPrice, err) - // no price posted - price, err = keeper.GetCurrentPrice(ctx, "asset3:usd") - require.Equal(t, types.ErrNoValidPrice, err) - // price set initially - price, err = keeper.GetCurrentPrice(ctx, "asset4:usd") - require.NoError(t, err) - require.Equal(t, sdk.OneDec(), price.Price) - price, err = keeper.GetCurrentPrice(ctx, "asset5:usd") - require.NoError(t, err) - require.Equal(t, sdk.MustNewDecFromStr("15.0"), price.Price) - - _, err = keeper.SetPrice(ctx, addrs[2], "asset1:usd", sdk.MustNewDecFromStr("30"), initialPriceExpiry.Add(1*time.Hour)) - require.NoError(t, err) - _, err = keeper.SetPrice(ctx, addrs[2], "asset2:usd", sdk.MustNewDecFromStr("30"), initialPriceExpiry.Add(1*time.Hour)) - require.NoError(t, err) - _, err = keeper.SetPrice(ctx, addrs[2], "asset5:usd", sdk.MustNewDecFromStr("30"), initialPriceExpiry.Add(1*time.Hour)) - require.NoError(t, err) - - blockTime = blockTime.Add(15 * time.Minute) - ctx = ctx.WithBlockTime(blockTime) - f(ctx, keeper) - - // price should be set - price, err = keeper.GetCurrentPrice(ctx, "asset1:usd") - require.NoError(t, err) - require.Equal(t, sdk.MustNewDecFromStr("2.0"), price.Price) - // not an active market, so price is not set - price, err = keeper.GetCurrentPrice(ctx, "asset2:usd") - require.Equal(t, types.ErrNoValidPrice, err) - // no price posted - price, err = keeper.GetCurrentPrice(ctx, "asset3:usd") - require.Equal(t, types.ErrNoValidPrice, err) - // price set initially - price, err = keeper.GetCurrentPrice(ctx, "asset4:usd") - require.NoError(t, err) - require.Equal(t, sdk.OneDec(), price.Price) - price, err = keeper.GetCurrentPrice(ctx, "asset5:usd") - require.NoError(t, err) - require.Equal(t, sdk.MustNewDecFromStr("20.0"), price.Price) - - blockTime = blockTime.Add(15 * time.Minute) - ctx = ctx.WithBlockTime(blockTime) - f(ctx, keeper) - - // price should be set - price, err = keeper.GetCurrentPrice(ctx, "asset1:usd") - require.NoError(t, err) - require.Equal(t, sdk.MustNewDecFromStr("16"), price.Price) - // not an active market, so price is not set - price, err = keeper.GetCurrentPrice(ctx, "asset2:usd") - require.Equal(t, types.ErrNoValidPrice, err) - // no price posted - price, err = keeper.GetCurrentPrice(ctx, "asset3:usd") - require.Equal(t, types.ErrNoValidPrice, err) - // price set initially, now expired - price, err = keeper.GetCurrentPrice(ctx, "asset4:usd") - require.Equal(t, types.ErrNoValidPrice, err) - price, err = keeper.GetCurrentPrice(ctx, "asset5:usd") - require.NoError(t, err) - require.Equal(t, sdk.MustNewDecFromStr("25.0"), price.Price) - - blockTime = blockTime.Add(10 * time.Hour) - ctx = ctx.WithBlockTime(blockTime) - f(ctx, keeper) - - // all prices expired now - price, err = keeper.GetCurrentPrice(ctx, "asset1:usd") - require.Equal(t, types.ErrNoValidPrice, err) - price, err = keeper.GetCurrentPrice(ctx, "asset2:usd") - require.Equal(t, types.ErrNoValidPrice, err) - price, err = keeper.GetCurrentPrice(ctx, "asset3:usd") - require.Equal(t, types.ErrNoValidPrice, err) - price, err = keeper.GetCurrentPrice(ctx, "asset4:usd") - require.Equal(t, types.ErrNoValidPrice, err) - price, err = keeper.GetCurrentPrice(ctx, "asset5:usd") - require.Equal(t, types.ErrNoValidPrice, err) -} - -func SetCurrentPrices_EventEmission(t *testing.T, f func(ctx sdk.Context, keeper keeper.Keeper)) { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmprototypes.Header{}). - WithBlockTime(time.Now().UTC()) - keeper := tApp.GetPriceFeedKeeper() - - params := types.Params{ - Markets: []types.Market{ - {MarketID: "asset1:usd", BaseAsset: "asset1", QuoteAsset: "usd", Oracles: addrs, Active: true}, - }, - } - keeper.SetParams(ctx, params) - - blockTime := time.Now() - initialPriceExpiry := blockTime.Add(1 * time.Hour) - - // post a price - _, err := keeper.SetPrice(ctx, addrs[0], "asset1:usd", sdk.MustNewDecFromStr("1"), initialPriceExpiry) - require.NoError(t, err) - - // reset context with fresh event manager - ctx = ctx.WithBlockTime(blockTime).WithEventManager(sdk.NewEventManager()) - f(ctx, keeper) - - // no previous price so no event - require.Equal(t, 0, len(ctx.EventManager().Events())) - - // post same price from another oracle - _, err = keeper.SetPrice(ctx, addrs[1], "asset1:usd", sdk.MustNewDecFromStr("1"), initialPriceExpiry) - require.NoError(t, err) - - blockTime = blockTime.Add(10 * time.Second) - ctx = ctx.WithBlockTime(blockTime).WithEventManager(sdk.NewEventManager()) - f(ctx, keeper) - - // no price change so no event - require.Equal(t, 0, len(ctx.EventManager().Events())) - - // post price changes - _, err = keeper.SetPrice(ctx, addrs[2], "asset1:usd", sdk.MustNewDecFromStr("2"), initialPriceExpiry) - require.NoError(t, err) - _, err = keeper.SetPrice(ctx, addrs[3], "asset1:usd", sdk.MustNewDecFromStr("10"), initialPriceExpiry) - require.NoError(t, err) - _, err = keeper.SetPrice(ctx, addrs[4], "asset1:usd", sdk.MustNewDecFromStr("10"), initialPriceExpiry) - require.NoError(t, err) - - blockTime = blockTime.Add(10 * time.Second) - ctx = ctx.WithBlockTime(blockTime).WithEventManager(sdk.NewEventManager()) - f(ctx, keeper) - - // price is changes so event should be emitted - require.Equal(t, 1, len(ctx.EventManager().Events())) - - event := ctx.EventManager().Events()[0] - - // has correct event type - assert.Equal(t, types.EventTypeMarketPriceUpdated, event.Type) - // has correct attributes - marketID, found := event.GetAttribute(types.AttributeMarketID) - require.True(t, found) - marketPrice, found := event.GetAttribute(types.AttributeMarketPrice) - require.True(t, found) - // attributes have correct values - assert.Equal(t, "asset1:usd", marketID.Value) - assert.Equal(t, sdk.MustNewDecFromStr("2").String(), marketPrice.Value) -} diff --git a/x/pricefeed/types/codec.go b/x/pricefeed/types/codec.go deleted file mode 100644 index 2ac8f712..00000000 --- a/x/pricefeed/types/codec.go +++ /dev/null @@ -1,38 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the -// governance module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgPostPrice{}, "pricefeed/MsgPostPrice", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgPostPrice{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/pricefeed/types/errors.go b/x/pricefeed/types/errors.go deleted file mode 100644 index 0d25cf67..00000000 --- a/x/pricefeed/types/errors.go +++ /dev/null @@ -1,20 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// DONTCOVER - -var ( - // ErrEmptyInput error for empty input - ErrEmptyInput = errorsmod.Register(ModuleName, 2, "input must not be empty") - // ErrExpired error for posted price messages with expired price - ErrExpired = errorsmod.Register(ModuleName, 3, "price is expired") - // ErrNoValidPrice error for posted price messages with expired price - ErrNoValidPrice = errorsmod.Register(ModuleName, 4, "all input prices are expired") - // ErrInvalidMarket error for posted price messages for invalid markets - ErrInvalidMarket = errorsmod.Register(ModuleName, 5, "market does not exist") - // ErrInvalidOracle error for posted price messages for invalid oracles - ErrInvalidOracle = errorsmod.Register(ModuleName, 6, "oracle does not exist or not authorized") - // ErrAssetNotFound error for not found asset - ErrAssetNotFound = errorsmod.Register(ModuleName, 7, "asset not found") -) diff --git a/x/pricefeed/types/events.go b/x/pricefeed/types/events.go deleted file mode 100644 index 683a379b..00000000 --- a/x/pricefeed/types/events.go +++ /dev/null @@ -1,14 +0,0 @@ -package types - -// Pricefeed module event types -const ( - EventTypeMarketPriceUpdated = "market_price_updated" - EventTypeOracleUpdatedPrice = "oracle_updated_price" - EventTypeNoValidPrices = "no_valid_prices" - - AttributeValueCategory = ModuleName - AttributeMarketID = "market_id" - AttributeMarketPrice = "market_price" - AttributeOracle = "oracle" - AttributeExpiry = "expiry" -) diff --git a/x/pricefeed/types/genesis.go b/x/pricefeed/types/genesis.go deleted file mode 100644 index c9eba7be..00000000 --- a/x/pricefeed/types/genesis.go +++ /dev/null @@ -1,27 +0,0 @@ -package types - -// NewGenesisState creates a new genesis state for the pricefeed module -func NewGenesisState(p Params, pp []PostedPrice) GenesisState { - return GenesisState{ - Params: p, - PostedPrices: pp, - } -} - -// DefaultGenesisState defines default GenesisState for pricefeed -func DefaultGenesisState() GenesisState { - return NewGenesisState( - DefaultParams(), - []PostedPrice{}, - ) -} - -// Validate performs basic validation of genesis data returning an -// error for any failed validation criteria. -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - - return gs.PostedPrices.Validate() -} diff --git a/x/pricefeed/types/genesis.pb.go b/x/pricefeed/types/genesis.pb.go deleted file mode 100644 index 3b2d8074..00000000 --- a/x/pricefeed/types/genesis.pb.go +++ /dev/null @@ -1,460 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/pricefeed/v1beta1/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 pricefeed module's genesis state. -type GenesisState struct { - // params defines all the parameters of the module. - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - PostedPrices PostedPrices `protobuf:"bytes,2,rep,name=posted_prices,json=postedPrices,proto3,castrepeated=PostedPrices" json:"posted_prices"` -} - -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_fffec798191784d2, []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) GetPostedPrices() PostedPrices { - if m != nil { - return m.PostedPrices - } - return nil -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.pricefeed.v1beta1.GenesisState") -} - -func init() { - proto.RegisterFile("kava/pricefeed/v1beta1/genesis.proto", fileDescriptor_fffec798191784d2) -} - -var fileDescriptor_fffec798191784d2 = []byte{ - // 262 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xc9, 0x4e, 0x2c, 0x4b, - 0xd4, 0x2f, 0x28, 0xca, 0x4c, 0x4e, 0x4d, 0x4b, 0x4d, 0x4d, 0xd1, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, - 0x49, 0x34, 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, - 0x17, 0x12, 0x03, 0xa9, 0xd2, 0x83, 0xab, 0xd2, 0x83, 0xaa, 0x92, 0x12, 0x49, 0xcf, 0x4f, 0xcf, - 0x07, 0x2b, 0xd1, 0x07, 0xb1, 0x20, 0xaa, 0xa5, 0x94, 0x70, 0x98, 0x59, 0x5c, 0x92, 0x5f, 0x94, - 0x0a, 0x51, 0xa3, 0xb4, 0x86, 0x91, 0x8b, 0xc7, 0x1d, 0x62, 0x47, 0x70, 0x49, 0x62, 0x49, 0xaa, - 0x90, 0x0d, 0x17, 0x5b, 0x41, 0x62, 0x51, 0x62, 0x6e, 0xb1, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0xb7, - 0x91, 0x9c, 0x1e, 0x76, 0x3b, 0xf5, 0x02, 0xc0, 0xaa, 0x9c, 0x58, 0x4e, 0xdc, 0x93, 0x67, 0x08, - 0x82, 0xea, 0x11, 0x8a, 0xe3, 0xe2, 0x2d, 0xc8, 0x2f, 0x2e, 0x49, 0x4d, 0x89, 0x07, 0x6b, 0x28, - 0x96, 0x60, 0x52, 0x60, 0xd6, 0xe0, 0x36, 0x52, 0xc6, 0x69, 0x08, 0x58, 0x71, 0x00, 0x48, 0xdc, - 0x49, 0x04, 0x64, 0xd2, 0xaa, 0xfb, 0xf2, 0x3c, 0x48, 0x82, 0xc5, 0x41, 0x3c, 0x05, 0x48, 0x3c, - 0x27, 0xdf, 0x07, 0x0f, 0xe5, 0x18, 0x57, 0x3c, 0x92, 0x63, 0x3c, 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, 0xed, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, - 0x7d, 0x90, 0xa5, 0xba, 0x39, 0x89, 0x49, 0xc5, 0x60, 0x96, 0x7e, 0x05, 0x52, 0x58, 0x94, 0x54, - 0x16, 0xa4, 0x16, 0x27, 0xb1, 0x81, 0x03, 0xc1, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xcf, 0xf3, - 0x1e, 0xef, 0x7e, 0x01, 0x00, 0x00, -} - -func (this *GenesisState) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*GenesisState) - if !ok { - that2, ok := that.(GenesisState) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *GenesisState") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *GenesisState but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *GenesisState but is not nil && this == nil") - } - if !this.Params.Equal(&that1.Params) { - return fmt.Errorf("Params this(%v) Not Equal that(%v)", this.Params, that1.Params) - } - if len(this.PostedPrices) != len(that1.PostedPrices) { - return fmt.Errorf("PostedPrices this(%v) Not Equal that(%v)", len(this.PostedPrices), len(that1.PostedPrices)) - } - for i := range this.PostedPrices { - if !this.PostedPrices[i].Equal(&that1.PostedPrices[i]) { - return fmt.Errorf("PostedPrices this[%v](%v) Not Equal that[%v](%v)", i, this.PostedPrices[i], i, that1.PostedPrices[i]) - } - } - return nil -} -func (this *GenesisState) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*GenesisState) - if !ok { - that2, ok := that.(GenesisState) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if !this.Params.Equal(&that1.Params) { - return false - } - if len(this.PostedPrices) != len(that1.PostedPrices) { - return false - } - for i := range this.PostedPrices { - if !this.PostedPrices[i].Equal(&that1.PostedPrices[i]) { - return false - } - } - return true -} -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.PostedPrices) > 0 { - for iNdEx := len(m.PostedPrices) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.PostedPrices[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.PostedPrices) > 0 { - for _, e := range m.PostedPrices { - 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 PostedPrices", 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.PostedPrices = append(m.PostedPrices, PostedPrice{}) - if err := m.PostedPrices[len(m.PostedPrices)-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/pricefeed/types/genesis_test.go b/x/pricefeed/types/genesis_test.go deleted file mode 100644 index acdc45b3..00000000 --- a/x/pricefeed/types/genesis_test.go +++ /dev/null @@ -1,93 +0,0 @@ -package types - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - tmtypes "github.com/cometbft/cometbft/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestGenesisStateValidate(t *testing.T) { - now := time.Now() - mockPrivKey := tmtypes.NewMockPV() - pubkey, err := mockPrivKey.GetPubKey() - require.NoError(t, err) - addr := sdk.AccAddress(pubkey.Address()) - - testCases := []struct { - msg string - genesisState GenesisState - expPass bool - }{ - { - msg: "default", - genesisState: DefaultGenesisState(), - expPass: true, - }, - { - msg: "valid genesis", - genesisState: NewGenesisState( - NewParams([]Market{ - {"market", "xrp", "bnb", []sdk.AccAddress{addr}, true}, - }), - []PostedPrice{NewPostedPrice("xrp", addr, sdk.OneDec(), now)}, - ), - expPass: true, - }, - { - msg: "invalid param", - genesisState: NewGenesisState( - NewParams([]Market{ - {"", "xrp", "bnb", []sdk.AccAddress{addr}, true}, - }), - []PostedPrice{NewPostedPrice("xrp", addr, sdk.OneDec(), now)}, - ), - expPass: false, - }, - { - msg: "dup market param", - genesisState: NewGenesisState( - NewParams([]Market{ - {"market", "xrp", "bnb", []sdk.AccAddress{addr}, true}, - {"market", "xrp", "bnb", []sdk.AccAddress{addr}, true}, - }), - []PostedPrice{NewPostedPrice("xrp", addr, sdk.OneDec(), now)}, - ), - expPass: false, - }, - { - msg: "invalid posted price", - genesisState: NewGenesisState( - NewParams([]Market{}), - []PostedPrice{NewPostedPrice("xrp", nil, sdk.OneDec(), now)}, - ), - expPass: false, - }, - { - msg: "duplicated posted price", - genesisState: NewGenesisState( - NewParams([]Market{}), - []PostedPrice{ - NewPostedPrice("xrp", addr, sdk.OneDec(), now), - NewPostedPrice("xrp", addr, sdk.OneDec(), now), - }, - ), - expPass: false, - }, - } - - for _, tc := range testCases { - t.Run(tc.msg, func(t *testing.T) { - err := tc.genesisState.Validate() - if tc.expPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } -} diff --git a/x/pricefeed/types/key.go b/x/pricefeed/types/key.go deleted file mode 100644 index 13168977..00000000 --- a/x/pricefeed/types/key.go +++ /dev/null @@ -1,58 +0,0 @@ -package types - -import sdk "github.com/cosmos/cosmos-sdk/types" - -const ( - // ModuleName The name that will be used throughout the module - ModuleName = "pricefeed" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default namestore - DefaultParamspace = ModuleName -) - -var ( - // CurrentPricePrefix prefix for the current price of an asset - CurrentPricePrefix = []byte{0x00} - - // RawPriceFeedPrefix prefix for the raw pricefeed of an asset - RawPriceFeedPrefix = []byte{0x01} -) - -// CurrentPriceKey returns the prefix for the current price -func CurrentPriceKey(marketID string) []byte { - return append(CurrentPricePrefix, []byte(marketID)...) -} - -// RawPriceIteratorKey returns the prefix for the raw price for a single market -func RawPriceIteratorKey(marketID string) []byte { - return append( - RawPriceFeedPrefix, - lengthPrefixWithByte([]byte(marketID))..., - ) -} - -// RawPriceKey returns the prefix for the raw price -func RawPriceKey(marketID string, oracleAddr sdk.AccAddress) []byte { - return append( - RawPriceIteratorKey(marketID), - lengthPrefixWithByte(oracleAddr)..., - ) -} - -// lengthPrefixWithByte returns the input bytes prefixes with one byte containing its length. -// It panics if the input is greater than 255 in length. -func lengthPrefixWithByte(bz []byte) []byte { - length := len(bz) - - if length > 255 { - panic("cannot length prefix more than 255 bytes with single byte") - } - - return append([]byte{byte(length)}, bz...) -} diff --git a/x/pricefeed/types/key_test.go b/x/pricefeed/types/key_test.go deleted file mode 100644 index a18e1740..00000000 --- a/x/pricefeed/types/key_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package types - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestRawPriceKey_Iteration(t *testing.T) { - // An iterator key should only match price keys with the same market - iteratorKey := RawPriceIteratorKey("kava:usd") - - addr := sdk.AccAddress("test addr") - - testCases := []struct { - name string - priceKey []byte - expectErr bool - }{ - { - name: "equal marketID is included in iteration", - priceKey: RawPriceKey("kava:usd", addr), - expectErr: false, - }, - { - name: "prefix overlapping marketID excluded from iteration", - priceKey: RawPriceKey("kava:usd:30", addr), - expectErr: true, - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - matchedSubKey := tc.priceKey[:len(iteratorKey)] - if tc.expectErr { - require.NotEqual(t, iteratorKey, matchedSubKey) - } else { - require.Equal(t, iteratorKey, matchedSubKey) - } - }) - } -} diff --git a/x/pricefeed/types/market.go b/x/pricefeed/types/market.go deleted file mode 100644 index 923260fa..00000000 --- a/x/pricefeed/types/market.go +++ /dev/null @@ -1,172 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "strings" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewMarket returns a new Market -func NewMarket(id, base, quote string, oracles []sdk.AccAddress, active bool) Market { - return Market{ - MarketID: id, - BaseAsset: base, - QuoteAsset: quote, - Oracles: oracles, - Active: active, - } -} - -// Validate performs a basic validation of the market params -func (m Market) Validate() error { - if strings.TrimSpace(m.MarketID) == "" { - return errors.New("market id cannot be blank") - } - if err := sdk.ValidateDenom(m.BaseAsset); err != nil { - return fmt.Errorf("invalid base asset: %w", err) - } - if err := sdk.ValidateDenom(m.QuoteAsset); err != nil { - return fmt.Errorf("invalid quote asset: %w", err) - } - seenOracles := make(map[string]bool) - for i, oracle := range m.Oracles { - if len(oracle) == 0 { - return fmt.Errorf("oracle %d is empty", i) - } - if seenOracles[oracle.String()] { - return fmt.Errorf("duplicated oracle %s", oracle) - } - seenOracles[oracle.String()] = true - } - return nil -} - -// ToMarketResponse returns a new MarketResponse from a Market -func (m Market) ToMarketResponse() MarketResponse { - return NewMarketResponse(m.MarketID, m.BaseAsset, m.QuoteAsset, m.Oracles, m.Active) -} - -// Markets is a slice of Market -type Markets []Market - -// Validate checks if all the markets are valid and there are no duplicated -// entries. -func (ms Markets) Validate() error { - seenMarkets := make(map[string]bool) - for _, m := range ms { - if seenMarkets[m.MarketID] { - return fmt.Errorf("duplicated market %s", m.MarketID) - } - if err := m.Validate(); err != nil { - return err - } - seenMarkets[m.MarketID] = true - } - return nil -} - -// NewMarketResponse returns a new MarketResponse -func NewMarketResponse(id, base, quote string, oracles []sdk.AccAddress, active bool) MarketResponse { - var strOracles []string - for _, oracle := range oracles { - strOracles = append(strOracles, oracle.String()) - } - - return MarketResponse{ - MarketID: id, - BaseAsset: base, - QuoteAsset: quote, - Oracles: strOracles, - Active: active, - } -} - -// MarketResponses is a slice of MarketResponse -type MarketResponses []MarketResponse - -// NewCurrentPrice returns an instance of CurrentPrice -func NewCurrentPrice(marketID string, price sdk.Dec) CurrentPrice { - return CurrentPrice{MarketID: marketID, Price: price} -} - -// CurrentPrices is a slice of CurrentPrice -type CurrentPrices []CurrentPrice - -// NewCurrentPriceResponse returns an instance of CurrentPriceResponse -func NewCurrentPriceResponse(marketID string, price sdk.Dec) CurrentPriceResponse { - return CurrentPriceResponse{MarketID: marketID, Price: price} -} - -// CurrentPriceResponses is a slice of CurrentPriceResponse -type CurrentPriceResponses []CurrentPriceResponse - -// NewPostedPrice returns a new PostedPrice -func NewPostedPrice(marketID string, oracle sdk.AccAddress, price sdk.Dec, expiry time.Time) PostedPrice { - return PostedPrice{ - MarketID: marketID, - OracleAddress: oracle, - Price: price, - Expiry: expiry, - } -} - -// Validate performs a basic check of a PostedPrice params. -func (pp PostedPrice) Validate() error { - if strings.TrimSpace(pp.MarketID) == "" { - return errors.New("market id cannot be blank") - } - if len(pp.OracleAddress) == 0 { - return errors.New("oracle address cannot be empty") - } - if pp.Price.IsNegative() { - return fmt.Errorf("posted price cannot be negative %s", pp.Price) - } - if pp.Expiry.Unix() <= 0 { - return errors.New("expiry time cannot be zero") - } - return nil -} - -// PostedPrices is a slice of PostedPrice -type PostedPrices []PostedPrice - -// Validate checks if all the posted prices are valid and there are no -// duplicated entries. -func (pps PostedPrices) Validate() error { - seenPrices := make(map[string]bool) - for _, pp := range pps { - if !pp.OracleAddress.Empty() && seenPrices[pp.MarketID+pp.OracleAddress.String()] { - return fmt.Errorf("duplicated posted price for marked id %s and oracle address %s", pp.MarketID, pp.OracleAddress) - } - - if err := pp.Validate(); err != nil { - return err - } - seenPrices[pp.MarketID+pp.OracleAddress.String()] = true - } - - return nil -} - -// NewPostedPrice returns a new PostedPrice -func NewPostedPriceResponse(marketID string, oracle sdk.AccAddress, price sdk.Dec, expiry time.Time) PostedPriceResponse { - return PostedPriceResponse{ - MarketID: marketID, - OracleAddress: oracle.String(), - Price: price, - Expiry: expiry, - } -} - -// PostedPriceResponses is a slice of PostedPriceResponse -type PostedPriceResponses []PostedPriceResponse - -// SortDecs provides the interface needed to sort sdk.Dec slices -type SortDecs []sdk.Dec - -func (a SortDecs) Len() int { return len(a) } -func (a SortDecs) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a SortDecs) Less(i, j int) bool { return a[i].LT(a[j]) } diff --git a/x/pricefeed/types/market_test.go b/x/pricefeed/types/market_test.go deleted file mode 100644 index 1dbcae87..00000000 --- a/x/pricefeed/types/market_test.go +++ /dev/null @@ -1,163 +0,0 @@ -package types - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - tmtypes "github.com/cometbft/cometbft/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestMarketValidate(t *testing.T) { - mockPrivKey := tmtypes.NewMockPV() - pubkey, err := mockPrivKey.GetPubKey() - require.NoError(t, err) - addr := sdk.AccAddress(pubkey.Address()) - - testCases := []struct { - msg string - market Market - expPass bool - }{ - { - "valid market", - Market{ - MarketID: "market", - BaseAsset: "xrp", - QuoteAsset: "bnb", - Oracles: []sdk.AccAddress{addr}, - Active: true, - }, - true, - }, - { - "invalid id", - Market{ - MarketID: " ", - }, - false, - }, - { - "invalid base asset", - Market{ - MarketID: "market", - BaseAsset: "XRP", - }, - false, - }, - { - "invalid market", - Market{ - MarketID: "market", - BaseAsset: "xrp", - // Denoms can be uppercase in v0.44 - QuoteAsset: "BNB~", - }, - false, - }, - { - "empty oracle address ", - Market{ - MarketID: "market", - BaseAsset: "xrp", - QuoteAsset: "bnb", - Oracles: []sdk.AccAddress{nil}, - }, - false, - }, - { - "empty oracle address ", - Market{ - MarketID: "market", - BaseAsset: "xrp", - QuoteAsset: "bnb", - Oracles: []sdk.AccAddress{addr, addr}, - }, - false, - }, - } - - for _, tc := range testCases { - t.Run(tc.msg, func(t *testing.T) { - err := tc.market.Validate() - if tc.expPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } -} - -func TestPostedPriceValidate(t *testing.T) { - now := time.Now() - mockPrivKey := tmtypes.NewMockPV() - pubkey, err := mockPrivKey.GetPubKey() - require.NoError(t, err) - addr := sdk.AccAddress(pubkey.Address()) - - testCases := []struct { - msg string - postedPrice PostedPrice - expPass bool - }{ - { - "valid posted price", - PostedPrice{ - MarketID: "market", - OracleAddress: addr, - Price: sdk.OneDec(), - Expiry: now, - }, - true, - }, - { - "invalid id", - PostedPrice{ - MarketID: " ", - }, - false, - }, - { - "invalid oracle", - PostedPrice{ - MarketID: "market", - OracleAddress: sdk.AccAddress{}, - }, - false, - }, - { - "invalid price", - PostedPrice{ - MarketID: "market", - OracleAddress: addr, - Price: sdk.NewDec(-1), - }, - false, - }, - { - "zero expiry time ", - PostedPrice{ - MarketID: "market", - OracleAddress: addr, - Price: sdk.OneDec(), - Expiry: time.Time{}, - }, - false, - }, - } - - for _, tc := range testCases { - t.Run(tc.msg, func(t *testing.T) { - err := tc.postedPrice.Validate() - if tc.expPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } -} diff --git a/x/pricefeed/types/msgs.go b/x/pricefeed/types/msgs.go deleted file mode 100644 index 57e3e8c3..00000000 --- a/x/pricefeed/types/msgs.go +++ /dev/null @@ -1,71 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "strings" - time "time" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -const ( - // TypeMsgPostPrice type of PostPrice msg - TypeMsgPostPrice = "post_price" - - // MaxExpiry defines the max expiry time defined as UNIX time (9999-12-31 23:59:59 +0000 UTC) - MaxExpiry = 253402300799 -) - -// ensure Msg interface compliance at compile time -var _ sdk.Msg = &MsgPostPrice{} - -// NewMsgPostPrice returns a new MsgPostPrice -func NewMsgPostPrice(from string, marketID string, price sdk.Dec, expiry time.Time) *MsgPostPrice { - return &MsgPostPrice{ - From: from, - MarketID: marketID, - Price: price, - Expiry: expiry, - } -} - -// Route Implements Msg. -func (msg MsgPostPrice) Route() string { return RouterKey } - -// Type Implements Msg -func (msg MsgPostPrice) Type() string { return TypeMsgPostPrice } - -// GetSignBytes Implements Msg. -func (msg MsgPostPrice) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners Implements Msg. -func (msg MsgPostPrice) GetSigners() []sdk.AccAddress { - from, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - panic(err) - } - return []sdk.AccAddress{from} -} - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgPostPrice) ValidateBasic() error { - if len(msg.From) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty") - } - if strings.TrimSpace(msg.MarketID) == "" { - return errors.New("market id cannot be blank") - } - if msg.Price.IsNegative() { - return fmt.Errorf("price cannot be negative: %s", msg.Price.String()) - } - if msg.Expiry.Unix() <= 0 { - return errors.New("must set an expiration time") - } - return nil -} diff --git a/x/pricefeed/types/msgs_test.go b/x/pricefeed/types/msgs_test.go deleted file mode 100644 index 9bbb84c7..00000000 --- a/x/pricefeed/types/msgs_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - - tmtime "github.com/cometbft/cometbft/types/time" -) - -func TestMsgPlaceBid_ValidateBasic(t *testing.T) { - addr := sdk.AccAddress([]byte("someName")) - price, _ := sdk.NewDecFromStr("0.3005") - expiry := tmtime.Now() - negativePrice, _ := sdk.NewDecFromStr("-3.05") - - tests := []struct { - name string - msg MsgPostPrice - expectPass bool - }{ - {"normal", MsgPostPrice{addr.String(), "xrp", price, expiry}, true}, - {"emptyAddr", MsgPostPrice{"", "xrp", price, expiry}, false}, - {"emptyAsset", MsgPostPrice{addr.String(), "", price, expiry}, false}, - {"negativePrice", MsgPostPrice{addr.String(), "xrp", negativePrice, expiry}, false}, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - if tc.expectPass { - require.Nil(t, tc.msg.ValidateBasic()) - } else { - require.NotNil(t, tc.msg.ValidateBasic()) - } - }) - } -} diff --git a/x/pricefeed/types/params.go b/x/pricefeed/types/params.go deleted file mode 100644 index 96716df2..00000000 --- a/x/pricefeed/types/params.go +++ /dev/null @@ -1,52 +0,0 @@ -package types - -import ( - "fmt" - - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// Parameter keys -var ( - KeyMarkets = []byte("Markets") - DefaultMarkets = []Market{} -) - -// NewParams creates a new AssetParams object -func NewParams(markets []Market) Params { - return Params{ - Markets: markets, - } -} - -// DefaultParams default params for pricefeed -func DefaultParams() Params { - return NewParams(DefaultMarkets) -} - -// ParamKeyTable Key declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements the ParamSet interface and returns all the key/value pairs -// pairs of pricefeed module's parameters. -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyMarkets, &p.Markets, validateMarketParams), - } -} - -// Validate ensure that params have valid values -func (p Params) Validate() error { - return validateMarketParams(p.Markets) -} - -func validateMarketParams(i interface{}) error { - markets, ok := i.(Markets) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return markets.Validate() -} diff --git a/x/pricefeed/types/query.pb.go b/x/pricefeed/types/query.pb.go deleted file mode 100644 index a4111a2d..00000000 --- a/x/pricefeed/types/query.pb.go +++ /dev/null @@ -1,4157 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/pricefeed/v1beta1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 defines the request type for querying x/pricefeed -// parameters. -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_84567be3085e4c6c, []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 defines the response type for querying x/pricefeed -// parameters. -type QueryParamsResponse struct { - 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_84567be3085e4c6c, []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 - -// QueryPriceRequest is the request type for the Query/PriceRequest RPC method. -type QueryPriceRequest struct { - MarketId string `protobuf:"bytes,1,opt,name=market_id,json=marketId,proto3" json:"market_id,omitempty"` -} - -func (m *QueryPriceRequest) Reset() { *m = QueryPriceRequest{} } -func (m *QueryPriceRequest) String() string { return proto.CompactTextString(m) } -func (*QueryPriceRequest) ProtoMessage() {} -func (*QueryPriceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_84567be3085e4c6c, []int{2} -} -func (m *QueryPriceRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPriceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPriceRequest.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 *QueryPriceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPriceRequest.Merge(m, src) -} -func (m *QueryPriceRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryPriceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPriceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPriceRequest proto.InternalMessageInfo - -// QueryPriceResponse is the response type for the Query/Prices RPC method. -type QueryPriceResponse struct { - Price CurrentPriceResponse `protobuf:"bytes,1,opt,name=price,proto3" json:"price"` -} - -func (m *QueryPriceResponse) Reset() { *m = QueryPriceResponse{} } -func (m *QueryPriceResponse) String() string { return proto.CompactTextString(m) } -func (*QueryPriceResponse) ProtoMessage() {} -func (*QueryPriceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_84567be3085e4c6c, []int{3} -} -func (m *QueryPriceResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPriceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPriceResponse.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 *QueryPriceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPriceResponse.Merge(m, src) -} -func (m *QueryPriceResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryPriceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPriceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPriceResponse proto.InternalMessageInfo - -// QueryPricesRequest is the request type for the Query/Prices RPC method. -type QueryPricesRequest struct { -} - -func (m *QueryPricesRequest) Reset() { *m = QueryPricesRequest{} } -func (m *QueryPricesRequest) String() string { return proto.CompactTextString(m) } -func (*QueryPricesRequest) ProtoMessage() {} -func (*QueryPricesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_84567be3085e4c6c, []int{4} -} -func (m *QueryPricesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPricesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPricesRequest.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 *QueryPricesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPricesRequest.Merge(m, src) -} -func (m *QueryPricesRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryPricesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPricesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPricesRequest proto.InternalMessageInfo - -// QueryPricesResponse is the response type for the Query/Prices RPC method. -type QueryPricesResponse struct { - Prices CurrentPriceResponses `protobuf:"bytes,1,rep,name=prices,proto3,castrepeated=CurrentPriceResponses" json:"prices"` -} - -func (m *QueryPricesResponse) Reset() { *m = QueryPricesResponse{} } -func (m *QueryPricesResponse) String() string { return proto.CompactTextString(m) } -func (*QueryPricesResponse) ProtoMessage() {} -func (*QueryPricesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_84567be3085e4c6c, []int{5} -} -func (m *QueryPricesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPricesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPricesResponse.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 *QueryPricesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPricesResponse.Merge(m, src) -} -func (m *QueryPricesResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryPricesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPricesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPricesResponse proto.InternalMessageInfo - -// QueryRawPricesRequest is the request type for the Query/RawPrices RPC method. -type QueryRawPricesRequest struct { - MarketId string `protobuf:"bytes,1,opt,name=market_id,json=marketId,proto3" json:"market_id,omitempty"` -} - -func (m *QueryRawPricesRequest) Reset() { *m = QueryRawPricesRequest{} } -func (m *QueryRawPricesRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRawPricesRequest) ProtoMessage() {} -func (*QueryRawPricesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_84567be3085e4c6c, []int{6} -} -func (m *QueryRawPricesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRawPricesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRawPricesRequest.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 *QueryRawPricesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRawPricesRequest.Merge(m, src) -} -func (m *QueryRawPricesRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryRawPricesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRawPricesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRawPricesRequest proto.InternalMessageInfo - -// QueryRawPricesResponse is the response type for the Query/RawPrices RPC -// method. -type QueryRawPricesResponse struct { - RawPrices PostedPriceResponses `protobuf:"bytes,1,rep,name=raw_prices,json=rawPrices,proto3,castrepeated=PostedPriceResponses" json:"raw_prices"` -} - -func (m *QueryRawPricesResponse) Reset() { *m = QueryRawPricesResponse{} } -func (m *QueryRawPricesResponse) String() string { return proto.CompactTextString(m) } -func (*QueryRawPricesResponse) ProtoMessage() {} -func (*QueryRawPricesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_84567be3085e4c6c, []int{7} -} -func (m *QueryRawPricesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRawPricesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRawPricesResponse.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 *QueryRawPricesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRawPricesResponse.Merge(m, src) -} -func (m *QueryRawPricesResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryRawPricesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRawPricesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRawPricesResponse proto.InternalMessageInfo - -// QueryOraclesRequest is the request type for the Query/Oracles RPC method. -type QueryOraclesRequest struct { - MarketId string `protobuf:"bytes,1,opt,name=market_id,json=marketId,proto3" json:"market_id,omitempty"` -} - -func (m *QueryOraclesRequest) Reset() { *m = QueryOraclesRequest{} } -func (m *QueryOraclesRequest) String() string { return proto.CompactTextString(m) } -func (*QueryOraclesRequest) ProtoMessage() {} -func (*QueryOraclesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_84567be3085e4c6c, []int{8} -} -func (m *QueryOraclesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryOraclesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryOraclesRequest.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 *QueryOraclesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryOraclesRequest.Merge(m, src) -} -func (m *QueryOraclesRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryOraclesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryOraclesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryOraclesRequest proto.InternalMessageInfo - -// QueryOraclesResponse is the response type for the Query/Oracles RPC method. -type QueryOraclesResponse struct { - // List of oracle addresses - Oracles []string `protobuf:"bytes,1,rep,name=oracles,proto3" json:"oracles,omitempty"` -} - -func (m *QueryOraclesResponse) Reset() { *m = QueryOraclesResponse{} } -func (m *QueryOraclesResponse) String() string { return proto.CompactTextString(m) } -func (*QueryOraclesResponse) ProtoMessage() {} -func (*QueryOraclesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_84567be3085e4c6c, []int{9} -} -func (m *QueryOraclesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryOraclesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryOraclesResponse.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 *QueryOraclesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryOraclesResponse.Merge(m, src) -} -func (m *QueryOraclesResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryOraclesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryOraclesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryOraclesResponse proto.InternalMessageInfo - -// QueryMarketsRequest is the request type for the Query/Markets RPC method. -type QueryMarketsRequest struct { -} - -func (m *QueryMarketsRequest) Reset() { *m = QueryMarketsRequest{} } -func (m *QueryMarketsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryMarketsRequest) ProtoMessage() {} -func (*QueryMarketsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_84567be3085e4c6c, []int{10} -} -func (m *QueryMarketsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryMarketsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryMarketsRequest.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 *QueryMarketsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryMarketsRequest.Merge(m, src) -} -func (m *QueryMarketsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryMarketsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryMarketsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryMarketsRequest proto.InternalMessageInfo - -// QueryMarketsResponse is the response type for the Query/Markets RPC method. -type QueryMarketsResponse struct { - // List of markets - Markets MarketResponses `protobuf:"bytes,1,rep,name=markets,proto3,castrepeated=MarketResponses" json:"markets"` -} - -func (m *QueryMarketsResponse) Reset() { *m = QueryMarketsResponse{} } -func (m *QueryMarketsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryMarketsResponse) ProtoMessage() {} -func (*QueryMarketsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_84567be3085e4c6c, []int{11} -} -func (m *QueryMarketsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryMarketsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryMarketsResponse.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 *QueryMarketsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryMarketsResponse.Merge(m, src) -} -func (m *QueryMarketsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryMarketsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryMarketsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryMarketsResponse proto.InternalMessageInfo - -// PostedPriceResponse defines a price for market posted by a specific oracle. -type PostedPriceResponse struct { - MarketID string `protobuf:"bytes,1,opt,name=market_id,json=marketId,proto3" json:"market_id,omitempty"` - OracleAddress string `protobuf:"bytes,2,opt,name=oracle_address,json=oracleAddress,proto3" json:"oracle_address,omitempty"` - Price github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=price,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"price"` - Expiry time.Time `protobuf:"bytes,4,opt,name=expiry,proto3,stdtime" json:"expiry"` -} - -func (m *PostedPriceResponse) Reset() { *m = PostedPriceResponse{} } -func (m *PostedPriceResponse) String() string { return proto.CompactTextString(m) } -func (*PostedPriceResponse) ProtoMessage() {} -func (*PostedPriceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_84567be3085e4c6c, []int{12} -} -func (m *PostedPriceResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *PostedPriceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PostedPriceResponse.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 *PostedPriceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_PostedPriceResponse.Merge(m, src) -} -func (m *PostedPriceResponse) XXX_Size() int { - return m.Size() -} -func (m *PostedPriceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_PostedPriceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_PostedPriceResponse proto.InternalMessageInfo - -func (m *PostedPriceResponse) GetMarketID() string { - if m != nil { - return m.MarketID - } - return "" -} - -func (m *PostedPriceResponse) GetOracleAddress() string { - if m != nil { - return m.OracleAddress - } - return "" -} - -func (m *PostedPriceResponse) GetExpiry() time.Time { - if m != nil { - return m.Expiry - } - return time.Time{} -} - -// CurrentPriceResponse defines a current price for a particular market in the pricefeed -// module. -type CurrentPriceResponse struct { - MarketID string `protobuf:"bytes,1,opt,name=market_id,json=marketId,proto3" json:"market_id,omitempty"` - Price github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=price,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"price"` -} - -func (m *CurrentPriceResponse) Reset() { *m = CurrentPriceResponse{} } -func (m *CurrentPriceResponse) String() string { return proto.CompactTextString(m) } -func (*CurrentPriceResponse) ProtoMessage() {} -func (*CurrentPriceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_84567be3085e4c6c, []int{13} -} -func (m *CurrentPriceResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CurrentPriceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CurrentPriceResponse.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 *CurrentPriceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_CurrentPriceResponse.Merge(m, src) -} -func (m *CurrentPriceResponse) XXX_Size() int { - return m.Size() -} -func (m *CurrentPriceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_CurrentPriceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_CurrentPriceResponse proto.InternalMessageInfo - -func (m *CurrentPriceResponse) GetMarketID() string { - if m != nil { - return m.MarketID - } - return "" -} - -// MarketResponse defines an asset in the pricefeed. -type MarketResponse struct { - MarketID string `protobuf:"bytes,1,opt,name=market_id,json=marketId,proto3" json:"market_id,omitempty"` - BaseAsset string `protobuf:"bytes,2,opt,name=base_asset,json=baseAsset,proto3" json:"base_asset,omitempty"` - QuoteAsset string `protobuf:"bytes,3,opt,name=quote_asset,json=quoteAsset,proto3" json:"quote_asset,omitempty"` - Oracles []string `protobuf:"bytes,4,rep,name=oracles,proto3" json:"oracles,omitempty"` - Active bool `protobuf:"varint,5,opt,name=active,proto3" json:"active,omitempty"` -} - -func (m *MarketResponse) Reset() { *m = MarketResponse{} } -func (m *MarketResponse) String() string { return proto.CompactTextString(m) } -func (*MarketResponse) ProtoMessage() {} -func (*MarketResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_84567be3085e4c6c, []int{14} -} -func (m *MarketResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MarketResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MarketResponse.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 *MarketResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MarketResponse.Merge(m, src) -} -func (m *MarketResponse) XXX_Size() int { - return m.Size() -} -func (m *MarketResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MarketResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MarketResponse proto.InternalMessageInfo - -func (m *MarketResponse) GetMarketID() string { - if m != nil { - return m.MarketID - } - return "" -} - -func (m *MarketResponse) GetBaseAsset() string { - if m != nil { - return m.BaseAsset - } - return "" -} - -func (m *MarketResponse) GetQuoteAsset() string { - if m != nil { - return m.QuoteAsset - } - return "" -} - -func (m *MarketResponse) GetOracles() []string { - if m != nil { - return m.Oracles - } - return nil -} - -func (m *MarketResponse) GetActive() bool { - if m != nil { - return m.Active - } - return false -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.pricefeed.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.pricefeed.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryPriceRequest)(nil), "kava.pricefeed.v1beta1.QueryPriceRequest") - proto.RegisterType((*QueryPriceResponse)(nil), "kava.pricefeed.v1beta1.QueryPriceResponse") - proto.RegisterType((*QueryPricesRequest)(nil), "kava.pricefeed.v1beta1.QueryPricesRequest") - proto.RegisterType((*QueryPricesResponse)(nil), "kava.pricefeed.v1beta1.QueryPricesResponse") - proto.RegisterType((*QueryRawPricesRequest)(nil), "kava.pricefeed.v1beta1.QueryRawPricesRequest") - proto.RegisterType((*QueryRawPricesResponse)(nil), "kava.pricefeed.v1beta1.QueryRawPricesResponse") - proto.RegisterType((*QueryOraclesRequest)(nil), "kava.pricefeed.v1beta1.QueryOraclesRequest") - proto.RegisterType((*QueryOraclesResponse)(nil), "kava.pricefeed.v1beta1.QueryOraclesResponse") - proto.RegisterType((*QueryMarketsRequest)(nil), "kava.pricefeed.v1beta1.QueryMarketsRequest") - proto.RegisterType((*QueryMarketsResponse)(nil), "kava.pricefeed.v1beta1.QueryMarketsResponse") - proto.RegisterType((*PostedPriceResponse)(nil), "kava.pricefeed.v1beta1.PostedPriceResponse") - proto.RegisterType((*CurrentPriceResponse)(nil), "kava.pricefeed.v1beta1.CurrentPriceResponse") - proto.RegisterType((*MarketResponse)(nil), "kava.pricefeed.v1beta1.MarketResponse") -} - -func init() { - proto.RegisterFile("kava/pricefeed/v1beta1/query.proto", fileDescriptor_84567be3085e4c6c) -} - -var fileDescriptor_84567be3085e4c6c = []byte{ - // 884 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x95, 0xcf, 0x6f, 0x1b, 0x45, - 0x14, 0xc7, 0x3d, 0xa9, 0x7f, 0x4e, 0xa1, 0x88, 0xa9, 0x13, 0x2c, 0xd3, 0xee, 0x86, 0x95, 0x08, - 0x6d, 0x1c, 0xef, 0xaa, 0xa9, 0xa8, 0x50, 0xc5, 0xa5, 0x26, 0x07, 0x7a, 0xa8, 0x80, 0x15, 0x97, - 0x72, 0xb1, 0xc6, 0xde, 0xa9, 0xbb, 0x4a, 0xec, 0xd9, 0xec, 0x8c, 0xe3, 0x46, 0x08, 0x09, 0x21, - 0x24, 0xca, 0x01, 0x29, 0x82, 0x13, 0x37, 0xb8, 0x21, 0x24, 0xfe, 0x8f, 0x1c, 0x23, 0x71, 0x41, - 0x1c, 0x92, 0xe0, 0x70, 0xe3, 0x9f, 0x40, 0x3b, 0xf3, 0x76, 0xf1, 0x26, 0xde, 0x64, 0x2d, 0x4e, - 0xc9, 0xbe, 0x7d, 0x3f, 0x3e, 0xef, 0xbb, 0x33, 0x5f, 0x63, 0x6b, 0x9b, 0xee, 0x51, 0x27, 0x08, - 0xfd, 0x3e, 0x7b, 0xc6, 0x98, 0xe7, 0xec, 0xdd, 0xeb, 0x31, 0x49, 0xef, 0x39, 0xbb, 0x63, 0x16, - 0xee, 0xdb, 0x41, 0xc8, 0x25, 0x27, 0x2b, 0x51, 0x8e, 0x9d, 0xe4, 0xd8, 0x90, 0xd3, 0xac, 0x0f, - 0xf8, 0x80, 0xab, 0x14, 0x27, 0xfa, 0x4f, 0x67, 0x37, 0x6f, 0x0d, 0x38, 0x1f, 0xec, 0x30, 0x87, - 0x06, 0xbe, 0x43, 0x47, 0x23, 0x2e, 0xa9, 0xf4, 0xf9, 0x48, 0xc0, 0x5b, 0x13, 0xde, 0xaa, 0xa7, - 0xde, 0xf8, 0x99, 0x23, 0xfd, 0x21, 0x13, 0x92, 0x0e, 0x03, 0x48, 0xc8, 0x02, 0x12, 0x92, 0x87, - 0x4c, 0xe7, 0x58, 0x75, 0x4c, 0x3e, 0x89, 0xf8, 0x3e, 0xa6, 0x21, 0x1d, 0x0a, 0x97, 0xed, 0x8e, - 0x99, 0x90, 0xd6, 0x53, 0x7c, 0x33, 0x15, 0x15, 0x01, 0x1f, 0x09, 0x46, 0xde, 0xc7, 0xe5, 0x40, - 0x45, 0x1a, 0x68, 0x15, 0xdd, 0xb9, 0xbe, 0x69, 0xd8, 0xf3, 0xd7, 0xb1, 0x75, 0x5d, 0xa7, 0x78, - 0x78, 0x6c, 0x16, 0x5c, 0xa8, 0x79, 0x58, 0x7c, 0xf9, 0x93, 0x59, 0xb0, 0x1e, 0xe0, 0xd7, 0x75, - 0xeb, 0xa8, 0x08, 0xe6, 0x91, 0x37, 0x71, 0x6d, 0x48, 0xc3, 0x6d, 0x26, 0xbb, 0xbe, 0xa7, 0x7a, - 0xd7, 0xdc, 0xaa, 0x0e, 0x3c, 0xf6, 0xa0, 0xce, 0x8b, 0x41, 0x75, 0x1d, 0x10, 0x7d, 0x88, 0x4b, - 0x6a, 0x3a, 0x00, 0x6d, 0x64, 0x01, 0x7d, 0x30, 0x0e, 0x43, 0x36, 0x92, 0xa9, 0x62, 0xc0, 0xd3, - 0x0d, 0x60, 0x4a, 0x7d, 0x76, 0x4a, 0x22, 0xc7, 0x97, 0x28, 0xd6, 0x03, 0xc2, 0x30, 0xbd, 0x8f, - 0xcb, 0xaa, 0x38, 0xd2, 0xe3, 0xda, 0xc2, 0xe3, 0x6f, 0x47, 0xe3, 0x7f, 0x3d, 0x31, 0x97, 0xe7, - 0xbd, 0x15, 0x2e, 0xb4, 0x06, 0xb0, 0x87, 0x78, 0x59, 0x11, 0xb8, 0x74, 0x92, 0x62, 0xcb, 0x23, - 0xdd, 0x4b, 0x84, 0x57, 0xce, 0x17, 0xc3, 0x06, 0xcf, 0x31, 0x0e, 0xe9, 0xa4, 0x9b, 0xda, 0xa2, - 0x95, 0xf9, 0x55, 0xb9, 0x90, 0xcc, 0x4b, 0x2f, 0x71, 0x0b, 0x96, 0xa8, 0xcf, 0x79, 0x29, 0xdc, - 0x5a, 0x18, 0x4f, 0x04, 0x94, 0xf7, 0x40, 0xc8, 0x8f, 0x42, 0xda, 0xdf, 0x59, 0x68, 0x89, 0x07, - 0xb8, 0x9e, 0xae, 0x84, 0x0d, 0x1a, 0xb8, 0xc2, 0x75, 0x48, 0xe1, 0xd7, 0xdc, 0xf8, 0x11, 0xea, - 0x96, 0x61, 0xe2, 0x13, 0xd5, 0x2e, 0xf9, 0xa4, 0x13, 0x68, 0x97, 0x84, 0xa1, 0xdd, 0x53, 0x5c, - 0xd1, 0x83, 0x63, 0x35, 0xd6, 0xb2, 0xd4, 0xd0, 0x95, 0x89, 0x10, 0x6f, 0x80, 0x10, 0xaf, 0xa5, - 0xe3, 0xc2, 0x8d, 0xfb, 0x01, 0xcf, 0x3f, 0x08, 0xdf, 0x9c, 0xa3, 0x15, 0xb9, 0x7b, 0x41, 0x82, - 0xce, 0x2b, 0xd3, 0x63, 0xb3, 0xaa, 0xdb, 0x3d, 0xde, 0xfa, 0x4f, 0x10, 0xf2, 0x36, 0xbe, 0xa1, - 0x77, 0xec, 0x52, 0xcf, 0x0b, 0x99, 0x10, 0x8d, 0x25, 0x25, 0xd9, 0xab, 0x3a, 0xfa, 0x48, 0x07, - 0xc9, 0x56, 0x7c, 0x37, 0xae, 0xa9, 0x6e, 0x76, 0x04, 0xf8, 0xe7, 0xb1, 0xb9, 0x36, 0xf0, 0xe5, - 0xf3, 0x71, 0xcf, 0xee, 0xf3, 0xa1, 0xd3, 0xe7, 0x62, 0xc8, 0x05, 0xfc, 0x69, 0x0b, 0x6f, 0xdb, - 0x91, 0xfb, 0x01, 0x13, 0xf6, 0x16, 0xeb, 0xc3, 0xbd, 0x88, 0xee, 0x3c, 0x7b, 0x11, 0xf8, 0xe1, - 0x7e, 0xa3, 0xa8, 0xae, 0x58, 0xd3, 0xd6, 0xb6, 0x63, 0xc7, 0xb6, 0x63, 0x7f, 0x1a, 0xdb, 0x4e, - 0xa7, 0x1a, 0x8d, 0x38, 0x38, 0x31, 0x91, 0x0b, 0x35, 0xd6, 0x37, 0x08, 0xd7, 0xe7, 0x1d, 0xef, - 0x45, 0xd6, 0x4d, 0xf6, 0x58, 0xfa, 0x1f, 0x7b, 0x58, 0xbf, 0x21, 0x7c, 0x23, 0xfd, 0x69, 0x16, - 0x61, 0xb8, 0x8d, 0x71, 0x8f, 0x0a, 0xd6, 0xa5, 0x42, 0x30, 0x09, 0x72, 0xd7, 0xa2, 0xc8, 0xa3, - 0x28, 0x40, 0x4c, 0x7c, 0x7d, 0x77, 0xcc, 0x65, 0xfc, 0x5e, 0x09, 0xee, 0x62, 0x15, 0xd2, 0x09, - 0x33, 0xa7, 0xb4, 0x98, 0x3a, 0xa5, 0x64, 0x05, 0x97, 0x69, 0x5f, 0xfa, 0x7b, 0xac, 0x51, 0x5a, - 0x45, 0x77, 0xaa, 0x2e, 0x3c, 0x6d, 0x7e, 0x5d, 0xc1, 0x25, 0x75, 0x42, 0xc9, 0xb7, 0x08, 0x97, - 0xb5, 0xa1, 0x92, 0xf5, 0xac, 0xc3, 0x78, 0xd1, 0xc3, 0x9b, 0xad, 0x5c, 0xb9, 0x5a, 0x0a, 0x6b, - 0xed, 0xab, 0xdf, 0xff, 0xfe, 0x61, 0x69, 0x95, 0x18, 0x4e, 0xc6, 0x6f, 0x86, 0xf6, 0x70, 0xf2, - 0x3d, 0xc2, 0x25, 0xf5, 0x21, 0xc9, 0xdd, 0xcb, 0xdb, 0xcf, 0xb8, 0x7b, 0x73, 0x3d, 0x4f, 0x2a, - 0x80, 0x6c, 0x2a, 0x90, 0x0d, 0xb2, 0x9e, 0x09, 0xa2, 0xec, 0xc4, 0xf9, 0x3c, 0xf9, 0x72, 0x5f, - 0x68, 0x81, 0x54, 0x98, 0xe4, 0x18, 0x95, 0x57, 0xa0, 0x94, 0x51, 0xe6, 0x10, 0x48, 0x03, 0xfc, - 0x8c, 0x70, 0x2d, 0xb1, 0x59, 0xd2, 0xbe, 0x74, 0xc4, 0x79, 0x2f, 0x6f, 0xda, 0x79, 0xd3, 0x01, - 0xea, 0x5d, 0x05, 0xe5, 0x90, 0x76, 0x16, 0x54, 0x48, 0x27, 0x73, 0xf4, 0xfa, 0x11, 0xe1, 0x0a, - 0xd8, 0x28, 0xb9, 0x5c, 0x84, 0xb4, 0x4d, 0x37, 0x37, 0xf2, 0x25, 0x03, 0xdd, 0x7d, 0x45, 0xd7, - 0x26, 0xad, 0x2c, 0x3a, 0xb8, 0x02, 0x29, 0xb6, 0xef, 0x10, 0xae, 0x80, 0x27, 0x5f, 0xc1, 0x96, - 0x36, 0xf4, 0x2b, 0xd8, 0xce, 0xd9, 0xbc, 0xf5, 0x8e, 0x62, 0x7b, 0x8b, 0x98, 0x59, 0x6c, 0x60, - 0xda, 0x9d, 0x27, 0xa7, 0x7f, 0x19, 0xe8, 0x97, 0xa9, 0x81, 0x0e, 0xa7, 0x06, 0x3a, 0x9a, 0x1a, - 0xe8, 0x74, 0x6a, 0xa0, 0x83, 0x33, 0xa3, 0x70, 0x74, 0x66, 0x14, 0xfe, 0x38, 0x33, 0x0a, 0x9f, - 0xb5, 0x66, 0x7c, 0x28, 0x6a, 0xd6, 0xde, 0xa1, 0x3d, 0xa1, 0xdb, 0xbe, 0x98, 0x69, 0xac, 0x0c, - 0xa9, 0x57, 0x56, 0xae, 0x79, 0xff, 0xdf, 0x00, 0x00, 0x00, 0xff, 0xff, 0xd8, 0x99, 0x27, 0xa2, - 0x2c, 0x0a, 0x00, 0x00, -} - -func (this *QueryParamsRequest) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*QueryParamsRequest) - if !ok { - that2, ok := that.(QueryParamsRequest) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *QueryParamsRequest") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *QueryParamsRequest but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *QueryParamsRequest but is not nil && this == nil") - } - return nil -} -func (this *QueryParamsRequest) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*QueryParamsRequest) - if !ok { - that2, ok := that.(QueryParamsRequest) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - return true -} -func (this *QueryParamsResponse) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*QueryParamsResponse) - if !ok { - that2, ok := that.(QueryParamsResponse) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *QueryParamsResponse") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *QueryParamsResponse but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *QueryParamsResponse but is not nil && this == nil") - } - if !this.Params.Equal(&that1.Params) { - return fmt.Errorf("Params this(%v) Not Equal that(%v)", this.Params, that1.Params) - } - return nil -} -func (this *QueryParamsResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*QueryParamsResponse) - if !ok { - that2, ok := that.(QueryParamsResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if !this.Params.Equal(&that1.Params) { - return false - } - return true -} -func (this *QueryPriceRequest) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*QueryPriceRequest) - if !ok { - that2, ok := that.(QueryPriceRequest) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *QueryPriceRequest") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *QueryPriceRequest but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *QueryPriceRequest but is not nil && this == nil") - } - if this.MarketId != that1.MarketId { - return fmt.Errorf("MarketId this(%v) Not Equal that(%v)", this.MarketId, that1.MarketId) - } - return nil -} -func (this *QueryPriceRequest) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*QueryPriceRequest) - if !ok { - that2, ok := that.(QueryPriceRequest) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.MarketId != that1.MarketId { - return false - } - return true -} -func (this *QueryPriceResponse) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*QueryPriceResponse) - if !ok { - that2, ok := that.(QueryPriceResponse) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *QueryPriceResponse") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *QueryPriceResponse but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *QueryPriceResponse but is not nil && this == nil") - } - if !this.Price.Equal(&that1.Price) { - return fmt.Errorf("Price this(%v) Not Equal that(%v)", this.Price, that1.Price) - } - return nil -} -func (this *QueryPriceResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*QueryPriceResponse) - if !ok { - that2, ok := that.(QueryPriceResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if !this.Price.Equal(&that1.Price) { - return false - } - return true -} -func (this *QueryPricesRequest) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*QueryPricesRequest) - if !ok { - that2, ok := that.(QueryPricesRequest) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *QueryPricesRequest") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *QueryPricesRequest but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *QueryPricesRequest but is not nil && this == nil") - } - return nil -} -func (this *QueryPricesRequest) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*QueryPricesRequest) - if !ok { - that2, ok := that.(QueryPricesRequest) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - return true -} -func (this *QueryPricesResponse) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*QueryPricesResponse) - if !ok { - that2, ok := that.(QueryPricesResponse) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *QueryPricesResponse") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *QueryPricesResponse but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *QueryPricesResponse but is not nil && this == nil") - } - if len(this.Prices) != len(that1.Prices) { - return fmt.Errorf("Prices this(%v) Not Equal that(%v)", len(this.Prices), len(that1.Prices)) - } - for i := range this.Prices { - if !this.Prices[i].Equal(&that1.Prices[i]) { - return fmt.Errorf("Prices this[%v](%v) Not Equal that[%v](%v)", i, this.Prices[i], i, that1.Prices[i]) - } - } - return nil -} -func (this *QueryPricesResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*QueryPricesResponse) - if !ok { - that2, ok := that.(QueryPricesResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if len(this.Prices) != len(that1.Prices) { - return false - } - for i := range this.Prices { - if !this.Prices[i].Equal(&that1.Prices[i]) { - return false - } - } - return true -} -func (this *QueryRawPricesRequest) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*QueryRawPricesRequest) - if !ok { - that2, ok := that.(QueryRawPricesRequest) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *QueryRawPricesRequest") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *QueryRawPricesRequest but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *QueryRawPricesRequest but is not nil && this == nil") - } - if this.MarketId != that1.MarketId { - return fmt.Errorf("MarketId this(%v) Not Equal that(%v)", this.MarketId, that1.MarketId) - } - return nil -} -func (this *QueryRawPricesRequest) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*QueryRawPricesRequest) - if !ok { - that2, ok := that.(QueryRawPricesRequest) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.MarketId != that1.MarketId { - return false - } - return true -} -func (this *QueryRawPricesResponse) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*QueryRawPricesResponse) - if !ok { - that2, ok := that.(QueryRawPricesResponse) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *QueryRawPricesResponse") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *QueryRawPricesResponse but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *QueryRawPricesResponse but is not nil && this == nil") - } - if len(this.RawPrices) != len(that1.RawPrices) { - return fmt.Errorf("RawPrices this(%v) Not Equal that(%v)", len(this.RawPrices), len(that1.RawPrices)) - } - for i := range this.RawPrices { - if !this.RawPrices[i].Equal(&that1.RawPrices[i]) { - return fmt.Errorf("RawPrices this[%v](%v) Not Equal that[%v](%v)", i, this.RawPrices[i], i, that1.RawPrices[i]) - } - } - return nil -} -func (this *QueryRawPricesResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*QueryRawPricesResponse) - if !ok { - that2, ok := that.(QueryRawPricesResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if len(this.RawPrices) != len(that1.RawPrices) { - return false - } - for i := range this.RawPrices { - if !this.RawPrices[i].Equal(&that1.RawPrices[i]) { - return false - } - } - return true -} -func (this *QueryOraclesRequest) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*QueryOraclesRequest) - if !ok { - that2, ok := that.(QueryOraclesRequest) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *QueryOraclesRequest") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *QueryOraclesRequest but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *QueryOraclesRequest but is not nil && this == nil") - } - if this.MarketId != that1.MarketId { - return fmt.Errorf("MarketId this(%v) Not Equal that(%v)", this.MarketId, that1.MarketId) - } - return nil -} -func (this *QueryOraclesRequest) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*QueryOraclesRequest) - if !ok { - that2, ok := that.(QueryOraclesRequest) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.MarketId != that1.MarketId { - return false - } - return true -} -func (this *QueryOraclesResponse) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*QueryOraclesResponse) - if !ok { - that2, ok := that.(QueryOraclesResponse) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *QueryOraclesResponse") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *QueryOraclesResponse but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *QueryOraclesResponse but is not nil && this == nil") - } - if len(this.Oracles) != len(that1.Oracles) { - return fmt.Errorf("Oracles this(%v) Not Equal that(%v)", len(this.Oracles), len(that1.Oracles)) - } - for i := range this.Oracles { - if this.Oracles[i] != that1.Oracles[i] { - return fmt.Errorf("Oracles this[%v](%v) Not Equal that[%v](%v)", i, this.Oracles[i], i, that1.Oracles[i]) - } - } - return nil -} -func (this *QueryOraclesResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*QueryOraclesResponse) - if !ok { - that2, ok := that.(QueryOraclesResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if len(this.Oracles) != len(that1.Oracles) { - return false - } - for i := range this.Oracles { - if this.Oracles[i] != that1.Oracles[i] { - return false - } - } - return true -} -func (this *QueryMarketsRequest) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*QueryMarketsRequest) - if !ok { - that2, ok := that.(QueryMarketsRequest) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *QueryMarketsRequest") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *QueryMarketsRequest but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *QueryMarketsRequest but is not nil && this == nil") - } - return nil -} -func (this *QueryMarketsRequest) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*QueryMarketsRequest) - if !ok { - that2, ok := that.(QueryMarketsRequest) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - return true -} -func (this *QueryMarketsResponse) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*QueryMarketsResponse) - if !ok { - that2, ok := that.(QueryMarketsResponse) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *QueryMarketsResponse") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *QueryMarketsResponse but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *QueryMarketsResponse but is not nil && this == nil") - } - if len(this.Markets) != len(that1.Markets) { - return fmt.Errorf("Markets this(%v) Not Equal that(%v)", len(this.Markets), len(that1.Markets)) - } - for i := range this.Markets { - if !this.Markets[i].Equal(&that1.Markets[i]) { - return fmt.Errorf("Markets this[%v](%v) Not Equal that[%v](%v)", i, this.Markets[i], i, that1.Markets[i]) - } - } - return nil -} -func (this *QueryMarketsResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*QueryMarketsResponse) - if !ok { - that2, ok := that.(QueryMarketsResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if len(this.Markets) != len(that1.Markets) { - return false - } - for i := range this.Markets { - if !this.Markets[i].Equal(&that1.Markets[i]) { - return false - } - } - return true -} -func (this *PostedPriceResponse) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*PostedPriceResponse) - if !ok { - that2, ok := that.(PostedPriceResponse) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *PostedPriceResponse") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *PostedPriceResponse but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *PostedPriceResponse but is not nil && this == nil") - } - if this.MarketID != that1.MarketID { - return fmt.Errorf("MarketID this(%v) Not Equal that(%v)", this.MarketID, that1.MarketID) - } - if this.OracleAddress != that1.OracleAddress { - return fmt.Errorf("OracleAddress this(%v) Not Equal that(%v)", this.OracleAddress, that1.OracleAddress) - } - if !this.Price.Equal(that1.Price) { - return fmt.Errorf("Price this(%v) Not Equal that(%v)", this.Price, that1.Price) - } - if !this.Expiry.Equal(that1.Expiry) { - return fmt.Errorf("Expiry this(%v) Not Equal that(%v)", this.Expiry, that1.Expiry) - } - return nil -} -func (this *PostedPriceResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*PostedPriceResponse) - if !ok { - that2, ok := that.(PostedPriceResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.MarketID != that1.MarketID { - return false - } - if this.OracleAddress != that1.OracleAddress { - return false - } - if !this.Price.Equal(that1.Price) { - return false - } - if !this.Expiry.Equal(that1.Expiry) { - return false - } - return true -} -func (this *CurrentPriceResponse) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*CurrentPriceResponse) - if !ok { - that2, ok := that.(CurrentPriceResponse) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *CurrentPriceResponse") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *CurrentPriceResponse but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *CurrentPriceResponse but is not nil && this == nil") - } - if this.MarketID != that1.MarketID { - return fmt.Errorf("MarketID this(%v) Not Equal that(%v)", this.MarketID, that1.MarketID) - } - if !this.Price.Equal(that1.Price) { - return fmt.Errorf("Price this(%v) Not Equal that(%v)", this.Price, that1.Price) - } - return nil -} -func (this *CurrentPriceResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*CurrentPriceResponse) - if !ok { - that2, ok := that.(CurrentPriceResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.MarketID != that1.MarketID { - return false - } - if !this.Price.Equal(that1.Price) { - return false - } - return true -} -func (this *MarketResponse) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*MarketResponse) - if !ok { - that2, ok := that.(MarketResponse) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *MarketResponse") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *MarketResponse but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *MarketResponse but is not nil && this == nil") - } - if this.MarketID != that1.MarketID { - return fmt.Errorf("MarketID this(%v) Not Equal that(%v)", this.MarketID, that1.MarketID) - } - if this.BaseAsset != that1.BaseAsset { - return fmt.Errorf("BaseAsset this(%v) Not Equal that(%v)", this.BaseAsset, that1.BaseAsset) - } - if this.QuoteAsset != that1.QuoteAsset { - return fmt.Errorf("QuoteAsset this(%v) Not Equal that(%v)", this.QuoteAsset, that1.QuoteAsset) - } - if len(this.Oracles) != len(that1.Oracles) { - return fmt.Errorf("Oracles this(%v) Not Equal that(%v)", len(this.Oracles), len(that1.Oracles)) - } - for i := range this.Oracles { - if this.Oracles[i] != that1.Oracles[i] { - return fmt.Errorf("Oracles this[%v](%v) Not Equal that[%v](%v)", i, this.Oracles[i], i, that1.Oracles[i]) - } - } - if this.Active != that1.Active { - return fmt.Errorf("Active this(%v) Not Equal that(%v)", this.Active, that1.Active) - } - return nil -} -func (this *MarketResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MarketResponse) - if !ok { - that2, ok := that.(MarketResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.MarketID != that1.MarketID { - return false - } - if this.BaseAsset != that1.BaseAsset { - return false - } - if this.QuoteAsset != that1.QuoteAsset { - return false - } - if len(this.Oracles) != len(that1.Oracles) { - return false - } - for i := range this.Oracles { - if this.Oracles[i] != that1.Oracles[i] { - return false - } - } - if this.Active != that1.Active { - return false - } - return true -} - -// 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 { - // Params queries all parameters of the pricefeed module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Price queries price details based on a market - Price(ctx context.Context, in *QueryPriceRequest, opts ...grpc.CallOption) (*QueryPriceResponse, error) - // Prices queries all prices - Prices(ctx context.Context, in *QueryPricesRequest, opts ...grpc.CallOption) (*QueryPricesResponse, error) - // RawPrices queries all raw prices based on a market - RawPrices(ctx context.Context, in *QueryRawPricesRequest, opts ...grpc.CallOption) (*QueryRawPricesResponse, error) - // Oracles queries all oracles based on a market - Oracles(ctx context.Context, in *QueryOraclesRequest, opts ...grpc.CallOption) (*QueryOraclesResponse, error) - // Markets queries all markets - Markets(ctx context.Context, in *QueryMarketsRequest, opts ...grpc.CallOption) (*QueryMarketsResponse, 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, "/kava.pricefeed.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Price(ctx context.Context, in *QueryPriceRequest, opts ...grpc.CallOption) (*QueryPriceResponse, error) { - out := new(QueryPriceResponse) - err := c.cc.Invoke(ctx, "/kava.pricefeed.v1beta1.Query/Price", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Prices(ctx context.Context, in *QueryPricesRequest, opts ...grpc.CallOption) (*QueryPricesResponse, error) { - out := new(QueryPricesResponse) - err := c.cc.Invoke(ctx, "/kava.pricefeed.v1beta1.Query/Prices", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) RawPrices(ctx context.Context, in *QueryRawPricesRequest, opts ...grpc.CallOption) (*QueryRawPricesResponse, error) { - out := new(QueryRawPricesResponse) - err := c.cc.Invoke(ctx, "/kava.pricefeed.v1beta1.Query/RawPrices", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Oracles(ctx context.Context, in *QueryOraclesRequest, opts ...grpc.CallOption) (*QueryOraclesResponse, error) { - out := new(QueryOraclesResponse) - err := c.cc.Invoke(ctx, "/kava.pricefeed.v1beta1.Query/Oracles", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Markets(ctx context.Context, in *QueryMarketsRequest, opts ...grpc.CallOption) (*QueryMarketsResponse, error) { - out := new(QueryMarketsResponse) - err := c.cc.Invoke(ctx, "/kava.pricefeed.v1beta1.Query/Markets", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries all parameters of the pricefeed module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Price queries price details based on a market - Price(context.Context, *QueryPriceRequest) (*QueryPriceResponse, error) - // Prices queries all prices - Prices(context.Context, *QueryPricesRequest) (*QueryPricesResponse, error) - // RawPrices queries all raw prices based on a market - RawPrices(context.Context, *QueryRawPricesRequest) (*QueryRawPricesResponse, error) - // Oracles queries all oracles based on a market - Oracles(context.Context, *QueryOraclesRequest) (*QueryOraclesResponse, error) - // Markets queries all markets - Markets(context.Context, *QueryMarketsRequest) (*QueryMarketsResponse, 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) Price(ctx context.Context, req *QueryPriceRequest) (*QueryPriceResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Price not implemented") -} -func (*UnimplementedQueryServer) Prices(ctx context.Context, req *QueryPricesRequest) (*QueryPricesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Prices not implemented") -} -func (*UnimplementedQueryServer) RawPrices(ctx context.Context, req *QueryRawPricesRequest) (*QueryRawPricesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RawPrices not implemented") -} -func (*UnimplementedQueryServer) Oracles(ctx context.Context, req *QueryOraclesRequest) (*QueryOraclesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Oracles not implemented") -} -func (*UnimplementedQueryServer) Markets(ctx context.Context, req *QueryMarketsRequest) (*QueryMarketsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Markets 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: "/kava.pricefeed.v1beta1.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_Price_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryPriceRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Price(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.pricefeed.v1beta1.Query/Price", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Price(ctx, req.(*QueryPriceRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Prices_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryPricesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Prices(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.pricefeed.v1beta1.Query/Prices", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Prices(ctx, req.(*QueryPricesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_RawPrices_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRawPricesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).RawPrices(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.pricefeed.v1beta1.Query/RawPrices", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).RawPrices(ctx, req.(*QueryRawPricesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Oracles_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryOraclesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Oracles(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.pricefeed.v1beta1.Query/Oracles", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Oracles(ctx, req.(*QueryOraclesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Markets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryMarketsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Markets(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.pricefeed.v1beta1.Query/Markets", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Markets(ctx, req.(*QueryMarketsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.pricefeed.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Price", - Handler: _Query_Price_Handler, - }, - { - MethodName: "Prices", - Handler: _Query_Prices_Handler, - }, - { - MethodName: "RawPrices", - Handler: _Query_RawPrices_Handler, - }, - { - MethodName: "Oracles", - Handler: _Query_Oracles_Handler, - }, - { - MethodName: "Markets", - Handler: _Query_Markets_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/pricefeed/v1beta1/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 *QueryPriceRequest) 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 *QueryPriceRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPriceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.MarketId) > 0 { - i -= len(m.MarketId) - copy(dAtA[i:], m.MarketId) - i = encodeVarintQuery(dAtA, i, uint64(len(m.MarketId))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryPriceResponse) 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 *QueryPriceResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPriceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Price.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 *QueryPricesRequest) 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 *QueryPricesRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPricesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryPricesResponse) 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 *QueryPricesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPricesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Prices) > 0 { - for iNdEx := len(m.Prices) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Prices[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 (m *QueryRawPricesRequest) 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 *QueryRawPricesRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRawPricesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.MarketId) > 0 { - i -= len(m.MarketId) - copy(dAtA[i:], m.MarketId) - i = encodeVarintQuery(dAtA, i, uint64(len(m.MarketId))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryRawPricesResponse) 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 *QueryRawPricesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRawPricesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RawPrices) > 0 { - for iNdEx := len(m.RawPrices) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RawPrices[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 (m *QueryOraclesRequest) 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 *QueryOraclesRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryOraclesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.MarketId) > 0 { - i -= len(m.MarketId) - copy(dAtA[i:], m.MarketId) - i = encodeVarintQuery(dAtA, i, uint64(len(m.MarketId))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryOraclesResponse) 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 *QueryOraclesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryOraclesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Oracles) > 0 { - for iNdEx := len(m.Oracles) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Oracles[iNdEx]) - copy(dAtA[i:], m.Oracles[iNdEx]) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Oracles[iNdEx]))) - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryMarketsRequest) 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 *QueryMarketsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryMarketsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryMarketsResponse) 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 *QueryMarketsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryMarketsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Markets) > 0 { - for iNdEx := len(m.Markets) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Markets[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 (m *PostedPriceResponse) 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 *PostedPriceResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PostedPriceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - n3, err3 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Expiry, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Expiry):]) - if err3 != nil { - return 0, err3 - } - i -= n3 - i = encodeVarintQuery(dAtA, i, uint64(n3)) - i-- - dAtA[i] = 0x22 - { - size := m.Price.Size() - i -= size - if _, err := m.Price.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.OracleAddress) > 0 { - i -= len(m.OracleAddress) - copy(dAtA[i:], m.OracleAddress) - i = encodeVarintQuery(dAtA, i, uint64(len(m.OracleAddress))) - i-- - dAtA[i] = 0x12 - } - if len(m.MarketID) > 0 { - i -= len(m.MarketID) - copy(dAtA[i:], m.MarketID) - i = encodeVarintQuery(dAtA, i, uint64(len(m.MarketID))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CurrentPriceResponse) 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 *CurrentPriceResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CurrentPriceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Price.Size() - i -= size - if _, err := m.Price.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.MarketID) > 0 { - i -= len(m.MarketID) - copy(dAtA[i:], m.MarketID) - i = encodeVarintQuery(dAtA, i, uint64(len(m.MarketID))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MarketResponse) 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 *MarketResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MarketResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Active { - i-- - if m.Active { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x28 - } - if len(m.Oracles) > 0 { - for iNdEx := len(m.Oracles) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Oracles[iNdEx]) - copy(dAtA[i:], m.Oracles[iNdEx]) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Oracles[iNdEx]))) - i-- - dAtA[i] = 0x22 - } - } - if len(m.QuoteAsset) > 0 { - i -= len(m.QuoteAsset) - copy(dAtA[i:], m.QuoteAsset) - i = encodeVarintQuery(dAtA, i, uint64(len(m.QuoteAsset))) - i-- - dAtA[i] = 0x1a - } - if len(m.BaseAsset) > 0 { - i -= len(m.BaseAsset) - copy(dAtA[i:], m.BaseAsset) - i = encodeVarintQuery(dAtA, i, uint64(len(m.BaseAsset))) - i-- - dAtA[i] = 0x12 - } - if len(m.MarketID) > 0 { - i -= len(m.MarketID) - copy(dAtA[i:], m.MarketID) - i = encodeVarintQuery(dAtA, i, uint64(len(m.MarketID))) - 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 *QueryPriceRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.MarketId) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryPriceResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Price.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryPricesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryPricesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Prices) > 0 { - for _, e := range m.Prices { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryRawPricesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.MarketId) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryRawPricesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.RawPrices) > 0 { - for _, e := range m.RawPrices { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryOraclesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.MarketId) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryOraclesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Oracles) > 0 { - for _, s := range m.Oracles { - l = len(s) - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryMarketsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryMarketsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Markets) > 0 { - for _, e := range m.Markets { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *PostedPriceResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.MarketID) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.OracleAddress) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = m.Price.Size() - n += 1 + l + sovQuery(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Expiry) - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *CurrentPriceResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.MarketID) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = m.Price.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *MarketResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.MarketID) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.BaseAsset) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.QuoteAsset) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.Oracles) > 0 { - for _, s := range m.Oracles { - l = len(s) - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Active { - n += 2 - } - 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 *QueryPriceRequest) 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: QueryPriceRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPriceRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarketId", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MarketId = string(dAtA[iNdEx:postIndex]) - 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 *QueryPriceResponse) 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: QueryPriceResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPriceResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Price", 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.Price.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 *QueryPricesRequest) 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: QueryPricesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPricesRequest: 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 *QueryPricesResponse) 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: QueryPricesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPricesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Prices", 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.Prices = append(m.Prices, CurrentPriceResponse{}) - if err := m.Prices[len(m.Prices)-1].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 *QueryRawPricesRequest) 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: QueryRawPricesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRawPricesRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarketId", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MarketId = string(dAtA[iNdEx:postIndex]) - 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 *QueryRawPricesResponse) 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: QueryRawPricesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRawPricesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RawPrices", 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.RawPrices = append(m.RawPrices, PostedPriceResponse{}) - if err := m.RawPrices[len(m.RawPrices)-1].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 *QueryOraclesRequest) 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: QueryOraclesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryOraclesRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarketId", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MarketId = string(dAtA[iNdEx:postIndex]) - 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 *QueryOraclesResponse) 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: QueryOraclesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryOraclesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Oracles", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Oracles = append(m.Oracles, string(dAtA[iNdEx:postIndex])) - 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 *QueryMarketsRequest) 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: QueryMarketsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryMarketsRequest: 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 *QueryMarketsResponse) 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: QueryMarketsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryMarketsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Markets", 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.Markets = append(m.Markets, MarketResponse{}) - if err := m.Markets[len(m.Markets)-1].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 *PostedPriceResponse) 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: PostedPriceResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PostedPriceResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarketID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MarketID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OracleAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.OracleAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Price", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Price.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Expiry", 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 := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Expiry, 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 *CurrentPriceResponse) 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: CurrentPriceResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CurrentPriceResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarketID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MarketID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Price", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Price.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 *MarketResponse) 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: MarketResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MarketResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarketID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MarketID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseAsset", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.BaseAsset = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field QuoteAsset", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.QuoteAsset = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Oracles", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Oracles = append(m.Oracles, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Active", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Active = bool(v != 0) - 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/pricefeed/types/query.pb.gw.go b/x/pricefeed/types/query.pb.gw.go deleted file mode 100644 index f6db726a..00000000 --- a/x/pricefeed/types/query.pb.gw.go +++ /dev/null @@ -1,586 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/pricefeed/v1beta1/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_Price_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPriceRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["market_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "market_id") - } - - protoReq.MarketId, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "market_id", err) - } - - msg, err := client.Price(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Price_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPriceRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["market_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "market_id") - } - - protoReq.MarketId, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "market_id", err) - } - - msg, err := server.Price(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Prices_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPricesRequest - var metadata runtime.ServerMetadata - - msg, err := client.Prices(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Prices_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPricesRequest - var metadata runtime.ServerMetadata - - msg, err := server.Prices(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_RawPrices_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRawPricesRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["market_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "market_id") - } - - protoReq.MarketId, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "market_id", err) - } - - msg, err := client.RawPrices(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_RawPrices_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRawPricesRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["market_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "market_id") - } - - protoReq.MarketId, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "market_id", err) - } - - msg, err := server.RawPrices(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Oracles_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryOraclesRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["market_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "market_id") - } - - protoReq.MarketId, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "market_id", err) - } - - msg, err := client.Oracles(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Oracles_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryOraclesRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["market_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "market_id") - } - - protoReq.MarketId, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "market_id", err) - } - - msg, err := server.Oracles(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Markets_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryMarketsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Markets(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Markets_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryMarketsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Markets(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_Price_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_Price_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_Price_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Prices_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_Prices_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_Prices_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_RawPrices_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_RawPrices_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_RawPrices_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Oracles_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_Oracles_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_Oracles_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Markets_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_Markets_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_Markets_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_Price_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_Price_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_Price_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Prices_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_Prices_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_Prices_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_RawPrices_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_RawPrices_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_RawPrices_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Oracles_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_Oracles_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_Oracles_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Markets_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_Markets_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_Markets_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{"kava", "pricefeed", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Price_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"kava", "pricefeed", "v1beta1", "prices", "market_id"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Prices_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "pricefeed", "v1beta1", "prices"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_RawPrices_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"kava", "pricefeed", "v1beta1", "rawprices", "market_id"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Oracles_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"kava", "pricefeed", "v1beta1", "oracles", "market_id"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Markets_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "pricefeed", "v1beta1", "markets"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Price_0 = runtime.ForwardResponseMessage - - forward_Query_Prices_0 = runtime.ForwardResponseMessage - - forward_Query_RawPrices_0 = runtime.ForwardResponseMessage - - forward_Query_Oracles_0 = runtime.ForwardResponseMessage - - forward_Query_Markets_0 = runtime.ForwardResponseMessage -) diff --git a/x/pricefeed/types/store.pb.go b/x/pricefeed/types/store.pb.go deleted file mode 100644 index 6b8f2ae2..00000000 --- a/x/pricefeed/types/store.pb.go +++ /dev/null @@ -1,1552 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/pricefeed/v1beta1/store.proto - -package types - -import ( - bytes "bytes" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 pricefeed module. -type Params struct { - Markets Markets `protobuf:"bytes,1,rep,name=markets,proto3,castrepeated=Markets" json:"markets"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_9df40639f5e16f9a, []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 (m *Params) GetMarkets() Markets { - if m != nil { - return m.Markets - } - return nil -} - -// Market defines an asset in the pricefeed. -type Market struct { - MarketID string `protobuf:"bytes,1,opt,name=market_id,json=marketId,proto3" json:"market_id,omitempty"` - BaseAsset string `protobuf:"bytes,2,opt,name=base_asset,json=baseAsset,proto3" json:"base_asset,omitempty"` - QuoteAsset string `protobuf:"bytes,3,opt,name=quote_asset,json=quoteAsset,proto3" json:"quote_asset,omitempty"` - Oracles []github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,4,rep,name=oracles,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"oracles,omitempty"` - Active bool `protobuf:"varint,5,opt,name=active,proto3" json:"active,omitempty"` -} - -func (m *Market) Reset() { *m = Market{} } -func (m *Market) String() string { return proto.CompactTextString(m) } -func (*Market) ProtoMessage() {} -func (*Market) Descriptor() ([]byte, []int) { - return fileDescriptor_9df40639f5e16f9a, []int{1} -} -func (m *Market) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Market) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Market.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 *Market) XXX_Merge(src proto.Message) { - xxx_messageInfo_Market.Merge(m, src) -} -func (m *Market) XXX_Size() int { - return m.Size() -} -func (m *Market) XXX_DiscardUnknown() { - xxx_messageInfo_Market.DiscardUnknown(m) -} - -var xxx_messageInfo_Market proto.InternalMessageInfo - -func (m *Market) GetMarketID() string { - if m != nil { - return m.MarketID - } - return "" -} - -func (m *Market) GetBaseAsset() string { - if m != nil { - return m.BaseAsset - } - return "" -} - -func (m *Market) GetQuoteAsset() string { - if m != nil { - return m.QuoteAsset - } - return "" -} - -func (m *Market) GetOracles() []github_com_cosmos_cosmos_sdk_types.AccAddress { - if m != nil { - return m.Oracles - } - return nil -} - -func (m *Market) GetActive() bool { - if m != nil { - return m.Active - } - return false -} - -// PostedPrice defines a price for market posted by a specific oracle. -type PostedPrice struct { - MarketID string `protobuf:"bytes,1,opt,name=market_id,json=marketId,proto3" json:"market_id,omitempty"` - OracleAddress github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,2,opt,name=oracle_address,json=oracleAddress,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"oracle_address,omitempty"` - Price github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=price,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"price"` - Expiry time.Time `protobuf:"bytes,4,opt,name=expiry,proto3,stdtime" json:"expiry"` -} - -func (m *PostedPrice) Reset() { *m = PostedPrice{} } -func (m *PostedPrice) String() string { return proto.CompactTextString(m) } -func (*PostedPrice) ProtoMessage() {} -func (*PostedPrice) Descriptor() ([]byte, []int) { - return fileDescriptor_9df40639f5e16f9a, []int{2} -} -func (m *PostedPrice) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *PostedPrice) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PostedPrice.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 *PostedPrice) XXX_Merge(src proto.Message) { - xxx_messageInfo_PostedPrice.Merge(m, src) -} -func (m *PostedPrice) XXX_Size() int { - return m.Size() -} -func (m *PostedPrice) XXX_DiscardUnknown() { - xxx_messageInfo_PostedPrice.DiscardUnknown(m) -} - -var xxx_messageInfo_PostedPrice proto.InternalMessageInfo - -func (m *PostedPrice) GetMarketID() string { - if m != nil { - return m.MarketID - } - return "" -} - -func (m *PostedPrice) GetOracleAddress() github_com_cosmos_cosmos_sdk_types.AccAddress { - if m != nil { - return m.OracleAddress - } - return nil -} - -func (m *PostedPrice) GetExpiry() time.Time { - if m != nil { - return m.Expiry - } - return time.Time{} -} - -// CurrentPrice defines a current price for a particular market in the pricefeed -// module. -type CurrentPrice struct { - MarketID string `protobuf:"bytes,1,opt,name=market_id,json=marketId,proto3" json:"market_id,omitempty"` - Price github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=price,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"price"` -} - -func (m *CurrentPrice) Reset() { *m = CurrentPrice{} } -func (m *CurrentPrice) String() string { return proto.CompactTextString(m) } -func (*CurrentPrice) ProtoMessage() {} -func (*CurrentPrice) Descriptor() ([]byte, []int) { - return fileDescriptor_9df40639f5e16f9a, []int{3} -} -func (m *CurrentPrice) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CurrentPrice) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CurrentPrice.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 *CurrentPrice) XXX_Merge(src proto.Message) { - xxx_messageInfo_CurrentPrice.Merge(m, src) -} -func (m *CurrentPrice) XXX_Size() int { - return m.Size() -} -func (m *CurrentPrice) XXX_DiscardUnknown() { - xxx_messageInfo_CurrentPrice.DiscardUnknown(m) -} - -var xxx_messageInfo_CurrentPrice proto.InternalMessageInfo - -func (m *CurrentPrice) GetMarketID() string { - if m != nil { - return m.MarketID - } - return "" -} - -func init() { - proto.RegisterType((*Params)(nil), "kava.pricefeed.v1beta1.Params") - proto.RegisterType((*Market)(nil), "kava.pricefeed.v1beta1.Market") - proto.RegisterType((*PostedPrice)(nil), "kava.pricefeed.v1beta1.PostedPrice") - proto.RegisterType((*CurrentPrice)(nil), "kava.pricefeed.v1beta1.CurrentPrice") -} - -func init() { - proto.RegisterFile("kava/pricefeed/v1beta1/store.proto", fileDescriptor_9df40639f5e16f9a) -} - -var fileDescriptor_9df40639f5e16f9a = []byte{ - // 508 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x53, 0x3f, 0x6f, 0xd3, 0x40, - 0x14, 0xcf, 0x25, 0x6d, 0xfe, 0x5c, 0x02, 0x48, 0x06, 0x55, 0x26, 0x12, 0x76, 0x94, 0x01, 0x19, - 0xa1, 0x9c, 0xd5, 0xb2, 0xb2, 0xc4, 0x64, 0x20, 0x43, 0xa5, 0xc8, 0x30, 0xb1, 0x44, 0x67, 0xfb, - 0xd5, 0x58, 0x89, 0x39, 0x73, 0x77, 0x89, 0x9a, 0x89, 0xaf, 0xd0, 0x8f, 0x81, 0x90, 0xd8, 0xf8, - 0x10, 0x1d, 0x2b, 0x26, 0xc4, 0x90, 0x16, 0xe7, 0x03, 0xb0, 0x33, 0x21, 0xdf, 0xd9, 0x55, 0x07, - 0x06, 0x2a, 0x98, 0xee, 0xde, 0xef, 0xfd, 0xde, 0xbf, 0xdf, 0xbd, 0xc3, 0xc3, 0x05, 0x5d, 0x53, - 0x37, 0xe3, 0x49, 0x08, 0x27, 0x00, 0x91, 0xbb, 0x3e, 0x0c, 0x40, 0xd2, 0x43, 0x57, 0x48, 0xc6, - 0x81, 0x64, 0x9c, 0x49, 0x66, 0x1c, 0x14, 0x1c, 0x72, 0xcd, 0x21, 0x25, 0xa7, 0xff, 0x30, 0x64, - 0x22, 0x65, 0x62, 0xae, 0x58, 0xae, 0x36, 0x74, 0x48, 0xff, 0x41, 0xcc, 0x62, 0xa6, 0xf1, 0xe2, - 0x56, 0xa2, 0x76, 0xcc, 0x58, 0xbc, 0x04, 0x57, 0x59, 0xc1, 0xea, 0xc4, 0x95, 0x49, 0x0a, 0x42, - 0xd2, 0x34, 0xd3, 0x84, 0xe1, 0x2b, 0xdc, 0x9c, 0x51, 0x4e, 0x53, 0x61, 0x4c, 0x71, 0x2b, 0xa5, - 0x7c, 0x01, 0x52, 0x98, 0x68, 0xd0, 0x70, 0xba, 0x47, 0x16, 0xf9, 0x73, 0x17, 0xe4, 0x58, 0xd1, - 0xbc, 0x7b, 0xe7, 0x5b, 0xbb, 0xf6, 0xe9, 0xd2, 0x6e, 0x69, 0x5b, 0xf8, 0x55, 0xfc, 0xf0, 0x27, - 0xc2, 0x4d, 0x0d, 0x1a, 0x4f, 0x70, 0x47, 0xa3, 0xf3, 0x24, 0x32, 0xd1, 0x00, 0x39, 0x1d, 0xaf, - 0x97, 0x6f, 0xed, 0xb6, 0x76, 0x4f, 0x27, 0x7e, 0x5b, 0xbb, 0xa7, 0x91, 0xf1, 0x08, 0xe3, 0x80, - 0x0a, 0x98, 0x53, 0x21, 0x40, 0x9a, 0xf5, 0x82, 0xeb, 0x77, 0x0a, 0x64, 0x5c, 0x00, 0x86, 0x8d, - 0xbb, 0xef, 0x57, 0x4c, 0x56, 0xfe, 0x86, 0xf2, 0x63, 0x05, 0x69, 0x42, 0x80, 0x5b, 0x8c, 0xd3, - 0x70, 0x09, 0xc2, 0xdc, 0x1b, 0x34, 0x9c, 0x9e, 0xf7, 0xf2, 0xd7, 0xd6, 0x1e, 0xc5, 0x89, 0x7c, - 0xbb, 0x0a, 0x48, 0xc8, 0xd2, 0x52, 0xaf, 0xf2, 0x18, 0x89, 0x68, 0xe1, 0xca, 0x4d, 0x06, 0x82, - 0x8c, 0xc3, 0x70, 0x1c, 0x45, 0x1c, 0x84, 0xf8, 0xfa, 0x65, 0x74, 0xbf, 0x54, 0xb5, 0x44, 0xbc, - 0x8d, 0x04, 0xe1, 0x57, 0x89, 0x8d, 0x03, 0xdc, 0xa4, 0xa1, 0x4c, 0xd6, 0x60, 0xee, 0x0f, 0x90, - 0xd3, 0xf6, 0x4b, 0x6b, 0xf8, 0xb9, 0x8e, 0xbb, 0x33, 0x26, 0x24, 0x44, 0xb3, 0x42, 0xae, 0xdb, - 0x8c, 0xcd, 0xf0, 0x5d, 0x9d, 0x7d, 0x4e, 0x75, 0x49, 0x35, 0xfa, 0xff, 0xec, 0xfe, 0x8e, 0xce, - 0x5f, 0x62, 0xc6, 0x04, 0xef, 0xab, 0x37, 0xd5, 0x12, 0x7a, 0xa4, 0x78, 0xc6, 0xef, 0x5b, 0xfb, - 0xf1, 0x5f, 0xd4, 0x9a, 0x40, 0xe8, 0xeb, 0x60, 0xe3, 0x39, 0x6e, 0xc2, 0x69, 0x96, 0xf0, 0x8d, - 0xb9, 0x37, 0x40, 0x4e, 0xf7, 0xa8, 0x4f, 0xf4, 0xaa, 0x91, 0x6a, 0xd5, 0xc8, 0xeb, 0x6a, 0xd5, - 0xbc, 0x76, 0x51, 0xe2, 0xec, 0xd2, 0x46, 0x7e, 0x19, 0x33, 0xfc, 0x80, 0x7b, 0x2f, 0x56, 0x9c, - 0xc3, 0x3b, 0x79, 0x6b, 0xbd, 0xae, 0xdb, 0xaf, 0xff, 0x43, 0xfb, 0xde, 0xf1, 0xd5, 0x0f, 0x0b, - 0x7d, 0xcc, 0x2d, 0x74, 0x9e, 0x5b, 0xe8, 0x22, 0xb7, 0xd0, 0x55, 0x6e, 0xa1, 0xb3, 0x9d, 0x55, - 0xbb, 0xd8, 0x59, 0xb5, 0x6f, 0x3b, 0xab, 0xf6, 0xe6, 0xe9, 0x8d, 0x84, 0xc5, 0x47, 0x18, 0x2d, - 0x69, 0x20, 0xd4, 0xcd, 0x3d, 0xbd, 0xf1, 0x7d, 0x55, 0xe6, 0xa0, 0xa9, 0xa6, 0x7e, 0xf6, 0x3b, - 0x00, 0x00, 0xff, 0xff, 0x18, 0xb5, 0x5b, 0xc1, 0xdd, 0x03, 0x00, 0x00, -} - -func (this *Params) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*Params) - if !ok { - that2, ok := that.(Params) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *Params") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *Params but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *Params but is not nil && this == nil") - } - if len(this.Markets) != len(that1.Markets) { - return fmt.Errorf("Markets this(%v) Not Equal that(%v)", len(this.Markets), len(that1.Markets)) - } - for i := range this.Markets { - if !this.Markets[i].Equal(&that1.Markets[i]) { - return fmt.Errorf("Markets this[%v](%v) Not Equal that[%v](%v)", i, this.Markets[i], i, that1.Markets[i]) - } - } - return nil -} -func (this *Params) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*Params) - if !ok { - that2, ok := that.(Params) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if len(this.Markets) != len(that1.Markets) { - return false - } - for i := range this.Markets { - if !this.Markets[i].Equal(&that1.Markets[i]) { - return false - } - } - return true -} -func (this *Market) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*Market) - if !ok { - that2, ok := that.(Market) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *Market") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *Market but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *Market but is not nil && this == nil") - } - if this.MarketID != that1.MarketID { - return fmt.Errorf("MarketID this(%v) Not Equal that(%v)", this.MarketID, that1.MarketID) - } - if this.BaseAsset != that1.BaseAsset { - return fmt.Errorf("BaseAsset this(%v) Not Equal that(%v)", this.BaseAsset, that1.BaseAsset) - } - if this.QuoteAsset != that1.QuoteAsset { - return fmt.Errorf("QuoteAsset this(%v) Not Equal that(%v)", this.QuoteAsset, that1.QuoteAsset) - } - if len(this.Oracles) != len(that1.Oracles) { - return fmt.Errorf("Oracles this(%v) Not Equal that(%v)", len(this.Oracles), len(that1.Oracles)) - } - for i := range this.Oracles { - if !bytes.Equal(this.Oracles[i], that1.Oracles[i]) { - return fmt.Errorf("Oracles this[%v](%v) Not Equal that[%v](%v)", i, this.Oracles[i], i, that1.Oracles[i]) - } - } - if this.Active != that1.Active { - return fmt.Errorf("Active this(%v) Not Equal that(%v)", this.Active, that1.Active) - } - return nil -} -func (this *Market) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*Market) - if !ok { - that2, ok := that.(Market) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.MarketID != that1.MarketID { - return false - } - if this.BaseAsset != that1.BaseAsset { - return false - } - if this.QuoteAsset != that1.QuoteAsset { - return false - } - if len(this.Oracles) != len(that1.Oracles) { - return false - } - for i := range this.Oracles { - if !bytes.Equal(this.Oracles[i], that1.Oracles[i]) { - return false - } - } - if this.Active != that1.Active { - return false - } - return true -} -func (this *PostedPrice) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*PostedPrice) - if !ok { - that2, ok := that.(PostedPrice) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *PostedPrice") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *PostedPrice but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *PostedPrice but is not nil && this == nil") - } - if this.MarketID != that1.MarketID { - return fmt.Errorf("MarketID this(%v) Not Equal that(%v)", this.MarketID, that1.MarketID) - } - if !bytes.Equal(this.OracleAddress, that1.OracleAddress) { - return fmt.Errorf("OracleAddress this(%v) Not Equal that(%v)", this.OracleAddress, that1.OracleAddress) - } - if !this.Price.Equal(that1.Price) { - return fmt.Errorf("Price this(%v) Not Equal that(%v)", this.Price, that1.Price) - } - if !this.Expiry.Equal(that1.Expiry) { - return fmt.Errorf("Expiry this(%v) Not Equal that(%v)", this.Expiry, that1.Expiry) - } - return nil -} -func (this *PostedPrice) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*PostedPrice) - if !ok { - that2, ok := that.(PostedPrice) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.MarketID != that1.MarketID { - return false - } - if !bytes.Equal(this.OracleAddress, that1.OracleAddress) { - return false - } - if !this.Price.Equal(that1.Price) { - return false - } - if !this.Expiry.Equal(that1.Expiry) { - return false - } - return true -} -func (this *CurrentPrice) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*CurrentPrice) - if !ok { - that2, ok := that.(CurrentPrice) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *CurrentPrice") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *CurrentPrice but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *CurrentPrice but is not nil && this == nil") - } - if this.MarketID != that1.MarketID { - return fmt.Errorf("MarketID this(%v) Not Equal that(%v)", this.MarketID, that1.MarketID) - } - if !this.Price.Equal(that1.Price) { - return fmt.Errorf("Price this(%v) Not Equal that(%v)", this.Price, that1.Price) - } - return nil -} -func (this *CurrentPrice) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*CurrentPrice) - if !ok { - that2, ok := that.(CurrentPrice) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.MarketID != that1.MarketID { - return false - } - if !this.Price.Equal(that1.Price) { - return false - } - return true -} -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 - if len(m.Markets) > 0 { - for iNdEx := len(m.Markets) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Markets[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintStore(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *Market) 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 *Market) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Market) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Active { - i-- - if m.Active { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x28 - } - if len(m.Oracles) > 0 { - for iNdEx := len(m.Oracles) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Oracles[iNdEx]) - copy(dAtA[i:], m.Oracles[iNdEx]) - i = encodeVarintStore(dAtA, i, uint64(len(m.Oracles[iNdEx]))) - i-- - dAtA[i] = 0x22 - } - } - if len(m.QuoteAsset) > 0 { - i -= len(m.QuoteAsset) - copy(dAtA[i:], m.QuoteAsset) - i = encodeVarintStore(dAtA, i, uint64(len(m.QuoteAsset))) - i-- - dAtA[i] = 0x1a - } - if len(m.BaseAsset) > 0 { - i -= len(m.BaseAsset) - copy(dAtA[i:], m.BaseAsset) - i = encodeVarintStore(dAtA, i, uint64(len(m.BaseAsset))) - i-- - dAtA[i] = 0x12 - } - if len(m.MarketID) > 0 { - i -= len(m.MarketID) - copy(dAtA[i:], m.MarketID) - i = encodeVarintStore(dAtA, i, uint64(len(m.MarketID))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *PostedPrice) 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 *PostedPrice) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PostedPrice) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Expiry, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Expiry):]) - if err1 != nil { - return 0, err1 - } - i -= n1 - i = encodeVarintStore(dAtA, i, uint64(n1)) - i-- - dAtA[i] = 0x22 - { - size := m.Price.Size() - i -= size - if _, err := m.Price.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintStore(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.OracleAddress) > 0 { - i -= len(m.OracleAddress) - copy(dAtA[i:], m.OracleAddress) - i = encodeVarintStore(dAtA, i, uint64(len(m.OracleAddress))) - i-- - dAtA[i] = 0x12 - } - if len(m.MarketID) > 0 { - i -= len(m.MarketID) - copy(dAtA[i:], m.MarketID) - i = encodeVarintStore(dAtA, i, uint64(len(m.MarketID))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CurrentPrice) 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 *CurrentPrice) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CurrentPrice) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Price.Size() - i -= size - if _, err := m.Price.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintStore(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.MarketID) > 0 { - i -= len(m.MarketID) - copy(dAtA[i:], m.MarketID) - i = encodeVarintStore(dAtA, i, uint64(len(m.MarketID))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintStore(dAtA []byte, offset int, v uint64) int { - offset -= sovStore(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 - if len(m.Markets) > 0 { - for _, e := range m.Markets { - l = e.Size() - n += 1 + l + sovStore(uint64(l)) - } - } - return n -} - -func (m *Market) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.MarketID) - if l > 0 { - n += 1 + l + sovStore(uint64(l)) - } - l = len(m.BaseAsset) - if l > 0 { - n += 1 + l + sovStore(uint64(l)) - } - l = len(m.QuoteAsset) - if l > 0 { - n += 1 + l + sovStore(uint64(l)) - } - if len(m.Oracles) > 0 { - for _, b := range m.Oracles { - l = len(b) - n += 1 + l + sovStore(uint64(l)) - } - } - if m.Active { - n += 2 - } - return n -} - -func (m *PostedPrice) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.MarketID) - if l > 0 { - n += 1 + l + sovStore(uint64(l)) - } - l = len(m.OracleAddress) - if l > 0 { - n += 1 + l + sovStore(uint64(l)) - } - l = m.Price.Size() - n += 1 + l + sovStore(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Expiry) - n += 1 + l + sovStore(uint64(l)) - return n -} - -func (m *CurrentPrice) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.MarketID) - if l > 0 { - n += 1 + l + sovStore(uint64(l)) - } - l = m.Price.Size() - n += 1 + l + sovStore(uint64(l)) - return n -} - -func sovStore(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozStore(x uint64) (n int) { - return sovStore(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 ErrIntOverflowStore - } - 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 { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Markets", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthStore - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthStore - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Markets = append(m.Markets, Market{}) - if err := m.Markets[len(m.Markets)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipStore(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthStore - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Market) 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 ErrIntOverflowStore - } - 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: Market: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Market: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarketID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - 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 ErrInvalidLengthStore - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthStore - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MarketID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseAsset", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - 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 ErrInvalidLengthStore - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthStore - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.BaseAsset = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field QuoteAsset", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - 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 ErrInvalidLengthStore - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthStore - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.QuoteAsset = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Oracles", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthStore - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthStore - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Oracles = append(m.Oracles, make([]byte, postIndex-iNdEx)) - copy(m.Oracles[len(m.Oracles)-1], dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Active", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Active = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipStore(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthStore - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *PostedPrice) 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 ErrIntOverflowStore - } - 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: PostedPrice: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PostedPrice: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarketID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - 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 ErrInvalidLengthStore - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthStore - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MarketID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OracleAddress", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthStore - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthStore - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.OracleAddress = append(m.OracleAddress[:0], dAtA[iNdEx:postIndex]...) - if m.OracleAddress == nil { - m.OracleAddress = []byte{} - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Price", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - 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 ErrInvalidLengthStore - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthStore - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Price.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Expiry", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthStore - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthStore - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Expiry, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipStore(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthStore - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CurrentPrice) 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 ErrIntOverflowStore - } - 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: CurrentPrice: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CurrentPrice: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarketID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - 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 ErrInvalidLengthStore - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthStore - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MarketID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Price", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - 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 ErrInvalidLengthStore - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthStore - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Price.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipStore(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthStore - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipStore(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, ErrIntOverflowStore - } - 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, ErrIntOverflowStore - } - 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, ErrIntOverflowStore - } - 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, ErrInvalidLengthStore - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupStore - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthStore - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthStore = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowStore = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupStore = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/pricefeed/types/tx.pb.go b/x/pricefeed/types/tx.pb.go deleted file mode 100644 index 358f29a7..00000000 --- a/x/pricefeed/types/tx.pb.go +++ /dev/null @@ -1,792 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/pricefeed/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// 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 - -// MsgPostPrice represents a method for creating a new post price -type MsgPostPrice struct { - // address of client - From string `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` - MarketID string `protobuf:"bytes,2,opt,name=market_id,json=marketId,proto3" json:"market_id,omitempty"` - Price github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=price,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"price"` - Expiry time.Time `protobuf:"bytes,4,opt,name=expiry,proto3,stdtime" json:"expiry"` -} - -func (m *MsgPostPrice) Reset() { *m = MsgPostPrice{} } -func (m *MsgPostPrice) String() string { return proto.CompactTextString(m) } -func (*MsgPostPrice) ProtoMessage() {} -func (*MsgPostPrice) Descriptor() ([]byte, []int) { - return fileDescriptor_afd93c8e4685da16, []int{0} -} -func (m *MsgPostPrice) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgPostPrice) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgPostPrice.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 *MsgPostPrice) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgPostPrice.Merge(m, src) -} -func (m *MsgPostPrice) XXX_Size() int { - return m.Size() -} -func (m *MsgPostPrice) XXX_DiscardUnknown() { - xxx_messageInfo_MsgPostPrice.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgPostPrice proto.InternalMessageInfo - -// MsgPostPriceResponse defines the Msg/PostPrice response type. -type MsgPostPriceResponse struct { -} - -func (m *MsgPostPriceResponse) Reset() { *m = MsgPostPriceResponse{} } -func (m *MsgPostPriceResponse) String() string { return proto.CompactTextString(m) } -func (*MsgPostPriceResponse) ProtoMessage() {} -func (*MsgPostPriceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_afd93c8e4685da16, []int{1} -} -func (m *MsgPostPriceResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgPostPriceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgPostPriceResponse.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 *MsgPostPriceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgPostPriceResponse.Merge(m, src) -} -func (m *MsgPostPriceResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgPostPriceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgPostPriceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgPostPriceResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgPostPrice)(nil), "kava.pricefeed.v1beta1.MsgPostPrice") - proto.RegisterType((*MsgPostPriceResponse)(nil), "kava.pricefeed.v1beta1.MsgPostPriceResponse") -} - -func init() { proto.RegisterFile("kava/pricefeed/v1beta1/tx.proto", fileDescriptor_afd93c8e4685da16) } - -var fileDescriptor_afd93c8e4685da16 = []byte{ - // 370 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x92, 0xbd, 0x6e, 0xea, 0x30, - 0x14, 0x80, 0xe3, 0x0b, 0x17, 0x81, 0x2f, 0x53, 0x84, 0x50, 0x94, 0xc1, 0x41, 0xe8, 0xaa, 0xa2, - 0x6a, 0xb1, 0x05, 0xdd, 0xaa, 0x4e, 0x88, 0x85, 0x21, 0x12, 0x8a, 0x3a, 0x75, 0x41, 0xf9, 0x71, - 0xd2, 0x08, 0x52, 0x47, 0xb1, 0x41, 0xf0, 0x06, 0x1d, 0x79, 0x84, 0x8e, 0x7d, 0x14, 0x46, 0xb6, - 0x56, 0x1d, 0x28, 0x0d, 0x2f, 0x52, 0xc5, 0x81, 0x36, 0x43, 0x87, 0x4e, 0x39, 0xf1, 0xf9, 0xce, - 0x39, 0xfe, 0x8e, 0x0c, 0x8d, 0xa9, 0xbd, 0xb0, 0x49, 0x9c, 0x84, 0x2e, 0xf5, 0x29, 0xf5, 0xc8, - 0xa2, 0xe7, 0x50, 0x61, 0xf7, 0x88, 0x58, 0xe2, 0x38, 0x61, 0x82, 0xa9, 0xcd, 0x0c, 0xc0, 0x5f, - 0x00, 0x3e, 0x02, 0x7a, 0x23, 0x60, 0x01, 0x93, 0x08, 0xc9, 0xa2, 0x9c, 0xd6, 0x8d, 0x80, 0xb1, - 0x60, 0x46, 0x89, 0xfc, 0x73, 0xe6, 0x3e, 0x11, 0x61, 0x44, 0xb9, 0xb0, 0xa3, 0x38, 0x07, 0xda, - 0x2f, 0x00, 0xd6, 0x4d, 0x1e, 0x8c, 0x19, 0x17, 0xe3, 0xac, 0xa7, 0xaa, 0xc2, 0xb2, 0x9f, 0xb0, - 0x48, 0x03, 0x2d, 0xd0, 0xa9, 0x59, 0x32, 0x56, 0xcf, 0x61, 0x2d, 0xb2, 0x93, 0x29, 0x15, 0x93, - 0xd0, 0xd3, 0xfe, 0x64, 0x89, 0x41, 0x3d, 0xdd, 0x19, 0x55, 0x53, 0x1e, 0x8e, 0x86, 0x56, 0x35, - 0x4f, 0x8f, 0x3c, 0x75, 0x08, 0xff, 0xca, 0xbb, 0x69, 0x25, 0x89, 0xe1, 0xcd, 0xce, 0x50, 0xde, - 0x76, 0xc6, 0x59, 0x10, 0x8a, 0xfb, 0xb9, 0x83, 0x5d, 0x16, 0x11, 0x97, 0xf1, 0x88, 0xf1, 0xe3, - 0xa7, 0xcb, 0xbd, 0x29, 0x11, 0xab, 0x98, 0x72, 0x3c, 0xa4, 0xae, 0x95, 0x17, 0xab, 0x37, 0xb0, - 0x42, 0x97, 0x71, 0x98, 0xac, 0xb4, 0x72, 0x0b, 0x74, 0xfe, 0xf5, 0x75, 0x9c, 0x7b, 0xe0, 0x93, - 0x07, 0xbe, 0x3d, 0x79, 0x0c, 0xaa, 0xd9, 0x88, 0xf5, 0xbb, 0x01, 0xac, 0x63, 0xcd, 0x75, 0xf9, - 0xf1, 0xc9, 0x50, 0xda, 0x4d, 0xd8, 0x28, 0x8a, 0x59, 0x94, 0xc7, 0xec, 0x81, 0xd3, 0xbe, 0x0f, - 0x4b, 0x26, 0x0f, 0xd4, 0x09, 0xac, 0x7d, 0x4b, 0xff, 0xc7, 0x3f, 0x6f, 0x15, 0x17, 0x3b, 0xe8, - 0x97, 0xbf, 0xa1, 0x4e, 0x73, 0x06, 0xe6, 0xfe, 0x03, 0x81, 0xe7, 0x14, 0x81, 0x4d, 0x8a, 0xc0, - 0x36, 0x45, 0x60, 0x9f, 0x22, 0xb0, 0x3e, 0x20, 0x65, 0x7b, 0x40, 0xca, 0xeb, 0x01, 0x29, 0x77, - 0x17, 0x85, 0xa5, 0x64, 0x9d, 0xbb, 0x33, 0xdb, 0xe1, 0x32, 0x22, 0xcb, 0xc2, 0x13, 0x90, 0xdb, - 0x71, 0x2a, 0x52, 0xfd, 0xea, 0x33, 0x00, 0x00, 0xff, 0xff, 0x6f, 0x4a, 0x12, 0x82, 0x21, 0x02, - 0x00, 0x00, -} - -func (this *MsgPostPrice) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*MsgPostPrice) - if !ok { - that2, ok := that.(MsgPostPrice) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *MsgPostPrice") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *MsgPostPrice but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *MsgPostPrice but is not nil && this == nil") - } - if this.From != that1.From { - return fmt.Errorf("From this(%v) Not Equal that(%v)", this.From, that1.From) - } - if this.MarketID != that1.MarketID { - return fmt.Errorf("MarketID this(%v) Not Equal that(%v)", this.MarketID, that1.MarketID) - } - if !this.Price.Equal(that1.Price) { - return fmt.Errorf("Price this(%v) Not Equal that(%v)", this.Price, that1.Price) - } - if !this.Expiry.Equal(that1.Expiry) { - return fmt.Errorf("Expiry this(%v) Not Equal that(%v)", this.Expiry, that1.Expiry) - } - return nil -} -func (this *MsgPostPrice) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgPostPrice) - if !ok { - that2, ok := that.(MsgPostPrice) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.From != that1.From { - return false - } - if this.MarketID != that1.MarketID { - return false - } - if !this.Price.Equal(that1.Price) { - return false - } - if !this.Expiry.Equal(that1.Expiry) { - return false - } - return true -} -func (this *MsgPostPriceResponse) VerboseEqual(that interface{}) error { - if that == nil { - if this == nil { - return nil - } - return fmt.Errorf("that == nil && this != nil") - } - - that1, ok := that.(*MsgPostPriceResponse) - if !ok { - that2, ok := that.(MsgPostPriceResponse) - if ok { - that1 = &that2 - } else { - return fmt.Errorf("that is not of type *MsgPostPriceResponse") - } - } - if that1 == nil { - if this == nil { - return nil - } - return fmt.Errorf("that is type *MsgPostPriceResponse but is nil && this != nil") - } else if this == nil { - return fmt.Errorf("that is type *MsgPostPriceResponse but is not nil && this == nil") - } - return nil -} -func (this *MsgPostPriceResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgPostPriceResponse) - if !ok { - that2, ok := that.(MsgPostPriceResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - return true -} - -// 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 { - // PostPrice defines a method for creating a new post price - PostPrice(ctx context.Context, in *MsgPostPrice, opts ...grpc.CallOption) (*MsgPostPriceResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) PostPrice(ctx context.Context, in *MsgPostPrice, opts ...grpc.CallOption) (*MsgPostPriceResponse, error) { - out := new(MsgPostPriceResponse) - err := c.cc.Invoke(ctx, "/kava.pricefeed.v1beta1.Msg/PostPrice", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // PostPrice defines a method for creating a new post price - PostPrice(context.Context, *MsgPostPrice) (*MsgPostPriceResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) PostPrice(ctx context.Context, req *MsgPostPrice) (*MsgPostPriceResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method PostPrice not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_PostPrice_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgPostPrice) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).PostPrice(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.pricefeed.v1beta1.Msg/PostPrice", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).PostPrice(ctx, req.(*MsgPostPrice)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.pricefeed.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "PostPrice", - Handler: _Msg_PostPrice_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/pricefeed/v1beta1/tx.proto", -} - -func (m *MsgPostPrice) 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 *MsgPostPrice) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgPostPrice) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Expiry, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Expiry):]) - if err1 != nil { - return 0, err1 - } - i -= n1 - i = encodeVarintTx(dAtA, i, uint64(n1)) - i-- - dAtA[i] = 0x22 - { - size := m.Price.Size() - i -= size - if _, err := m.Price.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.MarketID) > 0 { - i -= len(m.MarketID) - copy(dAtA[i:], m.MarketID) - i = encodeVarintTx(dAtA, i, uint64(len(m.MarketID))) - i-- - dAtA[i] = 0x12 - } - if len(m.From) > 0 { - i -= len(m.From) - copy(dAtA[i:], m.From) - i = encodeVarintTx(dAtA, i, uint64(len(m.From))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgPostPriceResponse) 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 *MsgPostPriceResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgPostPriceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgPostPrice) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.From) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.MarketID) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Price.Size() - n += 1 + l + sovTx(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Expiry) - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgPostPriceResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgPostPrice) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgPostPrice: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgPostPrice: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.From = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarketID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MarketID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Price", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Price.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Expiry", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Expiry, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgPostPriceResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgPostPriceResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgPostPriceResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/router/client/cli/tx.go b/x/router/client/cli/tx.go deleted file mode 100644 index 894378fe..00000000 --- a/x/router/client/cli/tx.go +++ /dev/null @@ -1,175 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/spf13/cobra" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/kava-labs/kava/x/router/types" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - liquidTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "router transactions subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - getCmdMintDeposit(), - getCmdDelegateMintDeposit(), - getCmdWithdrawBurn(), - getCmdWithdrawBurnUndelegate(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - liquidTxCmd.AddCommand(cmds...) - - return liquidTxCmd -} - -func getCmdMintDeposit() *cobra.Command { - return &cobra.Command{ - Use: "mint-deposit [validator-addr] [amount]", - Short: "mints staking derivative from a delegation and deposits them to earn", - Args: cobra.ExactArgs(2), - Example: fmt.Sprintf( - `%s tx %s mint-deposit kavavaloper16lnfpgn6llvn4fstg5nfrljj6aaxyee9z59jqd 10000000ukava --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - valAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - coin, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - msg := types.NewMsgMintDeposit(clientCtx.GetFromAddress(), valAddr, coin) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} - -func getCmdDelegateMintDeposit() *cobra.Command { - return &cobra.Command{ - Use: "delegate-mint-deposit [validator-addr] [amount]", - Short: "delegates tokens, mints staking derivative from a them, and deposits them to earn", - Args: cobra.ExactArgs(2), - Example: fmt.Sprintf( - `%s tx %s delegate-mint-deposit kavavaloper16lnfpgn6llvn4fstg5nfrljj6aaxyee9z59jqd 10000000ukava --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - valAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - coin, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - msg := types.NewMsgDelegateMintDeposit(clientCtx.GetFromAddress(), valAddr, coin) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} - -func getCmdWithdrawBurn() *cobra.Command { - return &cobra.Command{ - Use: "withdraw-burn [validator-addr] [amount]", - Short: "withdraws staking derivatives from earn and burns them to redeem a delegation", - Example: fmt.Sprintf( - `%s tx %s withdraw-burn kavavaloper16lnfpgn6llvn4fstg5nfrljj6aaxyee9z59jqd 10000000ukava --from `, version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - valAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - amount, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - msg := types.NewMsgWithdrawBurn(clientCtx.GetFromAddress(), valAddr, amount) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} - -func getCmdWithdrawBurnUndelegate() *cobra.Command { - return &cobra.Command{ - Use: "withdraw-burn-undelegate [validator-addr] [amount]", - Short: "withdraws staking derivatives from earn, burns them to redeem a delegation, then unstakes the delegation", - Example: fmt.Sprintf( - `%s tx %s withdraw-burn-undelegate kavavaloper16lnfpgn6llvn4fstg5nfrljj6aaxyee9z59jqd 10000000ukava --from `, version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - valAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - amount, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - msg := types.NewMsgWithdrawBurnUndelegate(clientCtx.GetFromAddress(), valAddr, amount) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} diff --git a/x/router/keeper/keeper.go b/x/router/keeper/keeper.go deleted file mode 100644 index a509ad97..00000000 --- a/x/router/keeper/keeper.go +++ /dev/null @@ -1,26 +0,0 @@ -package keeper - -import ( - "github.com/kava-labs/kava/x/router/types" -) - -// Keeper is the keeper for the module -type Keeper struct { - earnKeeper types.EarnKeeper - liquidKeeper types.LiquidKeeper - stakingKeeper types.StakingKeeper -} - -// NewKeeper creates a new keeper -func NewKeeper( - earnKeeper types.EarnKeeper, - liquidKeeper types.LiquidKeeper, - stakingKeeper types.StakingKeeper, -) Keeper { - - return Keeper{ - earnKeeper: earnKeeper, - liquidKeeper: liquidKeeper, - stakingKeeper: stakingKeeper, - } -} diff --git a/x/router/keeper/msg_server.go b/x/router/keeper/msg_server.go deleted file mode 100644 index ba18c6d0..00000000 --- a/x/router/keeper/msg_server.go +++ /dev/null @@ -1,202 +0,0 @@ -package keeper - -import ( - "context" - "time" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - earntypes "github.com/kava-labs/kava/x/earn/types" - "github.com/kava-labs/kava/x/router/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the module's MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -// MintDeposit converts a delegation into staking derivatives and deposits it all into an earn vault -func (m msgServer) MintDeposit(goCtx context.Context, msg *types.MsgMintDeposit) (*types.MsgMintDepositResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - val, err := sdk.ValAddressFromBech32(msg.Validator) - if err != nil { - return nil, err - } - - derivative, err := m.keeper.liquidKeeper.MintDerivative(ctx, depositor, val, msg.Amount) - if err != nil { - return nil, err - } - err = m.keeper.earnKeeper.Deposit(ctx, depositor, derivative, earntypes.STRATEGY_TYPE_SAVINGS) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.String()), - ), - ) - return &types.MsgMintDepositResponse{}, nil -} - -// DelegateMintDeposit delegates tokens to a validator, then converts them into staking derivatives, -// then deposits to an earn vault. -func (m msgServer) DelegateMintDeposit(goCtx context.Context, msg *types.MsgDelegateMintDeposit) (*types.MsgDelegateMintDepositResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - valAddr, err := sdk.ValAddressFromBech32(msg.Validator) - if err != nil { - return nil, err - } - validator, found := m.keeper.stakingKeeper.GetValidator(ctx, valAddr) - if !found { - return nil, stakingtypes.ErrNoValidatorFound - } - bondDenom := m.keeper.stakingKeeper.BondDenom(ctx) - if msg.Amount.Denom != bondDenom { - return nil, errorsmod.Wrapf( - sdkerrors.ErrInvalidRequest, "invalid coin denomination: got %s, expected %s", msg.Amount.Denom, bondDenom, - ) - } - newShares, err := m.keeper.stakingKeeper.Delegate(ctx, depositor, msg.Amount.Amount, stakingtypes.Unbonded, validator, true) - if err != nil { - return nil, err - } - - derivativeMinted, err := m.keeper.liquidKeeper.MintDerivative(ctx, depositor, valAddr, msg.Amount) - if err != nil { - return nil, err - } - - err = m.keeper.earnKeeper.Deposit(ctx, depositor, derivativeMinted, earntypes.STRATEGY_TYPE_SAVINGS) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - stakingtypes.EventTypeDelegate, - sdk.NewAttribute(stakingtypes.AttributeKeyValidator, valAddr.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), - sdk.NewAttribute(stakingtypes.AttributeKeyNewShares, newShares.String()), - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.String()), - ), - }) - - return &types.MsgDelegateMintDepositResponse{}, nil -} - -// WithdrawBurn removes staking derivatives from an earn vault and converts them back to a staking delegation. -func (m msgServer) WithdrawBurn(goCtx context.Context, msg *types.MsgWithdrawBurn) (*types.MsgWithdrawBurnResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - return nil, err - } - val, err := sdk.ValAddressFromBech32(msg.Validator) - if err != nil { - return nil, err - } - - tokenAmount, err := m.keeper.liquidKeeper.DerivativeFromTokens(ctx, val, msg.Amount) - if err != nil { - return nil, err - } - - withdrawnAmount, err := m.keeper.earnKeeper.Withdraw(ctx, depositor, tokenAmount, earntypes.STRATEGY_TYPE_SAVINGS) - if err != nil { - return nil, err - } - - _, err = m.keeper.liquidKeeper.BurnDerivative(ctx, depositor, val, withdrawnAmount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.String()), - ), - ) - - return &types.MsgWithdrawBurnResponse{}, nil -} - -// WithdrawBurnUndelegate removes staking derivatives from an earn vault, converts them to a staking delegation, -// then undelegates them from their validator. -func (m msgServer) WithdrawBurnUndelegate(goCtx context.Context, msg *types.MsgWithdrawBurnUndelegate) (*types.MsgWithdrawBurnUndelegateResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - return nil, err - } - val, err := sdk.ValAddressFromBech32(msg.Validator) - if err != nil { - return nil, err - } - - tokenAmount, err := m.keeper.liquidKeeper.DerivativeFromTokens(ctx, val, msg.Amount) - if err != nil { - return nil, err - } - - withdrawnAmount, err := m.keeper.earnKeeper.Withdraw(ctx, depositor, tokenAmount, earntypes.STRATEGY_TYPE_SAVINGS) - if err != nil { - return nil, err - } - - sharesReturned, err := m.keeper.liquidKeeper.BurnDerivative(ctx, depositor, val, withdrawnAmount) - if err != nil { - return nil, err - } - - completionTime, err := m.keeper.stakingKeeper.Undelegate(ctx, depositor, val, sharesReturned) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - stakingtypes.EventTypeUnbond, - sdk.NewAttribute(stakingtypes.AttributeKeyValidator, val.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), - sdk.NewAttribute(stakingtypes.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)), - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.String()), - ), - }) - return &types.MsgWithdrawBurnUndelegateResponse{}, nil -} diff --git a/x/router/keeper/msg_server_test.go b/x/router/keeper/msg_server_test.go deleted file mode 100644 index a53b6852..00000000 --- a/x/router/keeper/msg_server_test.go +++ /dev/null @@ -1,322 +0,0 @@ -package keeper_test - -import ( - "fmt" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - earntypes "github.com/kava-labs/kava/x/earn/types" - "github.com/kava-labs/kava/x/router/keeper" - "github.com/kava-labs/kava/x/router/testutil" - "github.com/kava-labs/kava/x/router/types" -) - -type msgServerTestSuite struct { - testutil.Suite - - msgServer types.MsgServer -} - -func (suite *msgServerTestSuite) SetupTest() { - suite.Suite.SetupTest() - - suite.msgServer = keeper.NewMsgServerImpl(suite.Keeper) -} - -func TestMsgServerTestSuite(t *testing.T) { - suite.Run(t, new(msgServerTestSuite)) -} - -func (suite *msgServerTestSuite) TestMintDeposit_Events() { - user, valAddr, delegation := suite.setupValidatorAndDelegation() - suite.setupEarnForDeposits(valAddr) - - msg := types.NewMsgMintDeposit( - user, - valAddr, - suite.NewBondCoin(delegation), - ) - _, err := suite.msgServer.MintDeposit(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - suite.EventsContains(suite.Ctx.EventManager().Events(), - sdk.NewEvent(sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, user.String()), - ), - ) -} - -func (suite *msgServerTestSuite) TestDelegateMintDeposit_Events() { - user, valAddr, balance := suite.setupValidator() - suite.setupEarnForDeposits(valAddr) - - msg := types.NewMsgDelegateMintDeposit( - user, - valAddr, - suite.NewBondCoin(balance), - ) - _, err := suite.msgServer.DelegateMintDeposit(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - suite.EventsContains(suite.Ctx.EventManager().Events(), - sdk.NewEvent(sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, user.String()), - ), - ) - expectedShares := sdk.NewDecFromInt(msg.Amount.Amount) // no slashes so shares equal staked tokens - suite.EventsContains(suite.Ctx.EventManager().Events(), - sdk.NewEvent( - stakingtypes.EventTypeDelegate, - sdk.NewAttribute(stakingtypes.AttributeKeyValidator, msg.Validator), - sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), - sdk.NewAttribute(stakingtypes.AttributeKeyNewShares, expectedShares.String()), - ), - ) -} - -func (suite *msgServerTestSuite) TestWithdrawBurn_Events() { - user, valAddr, delegated := suite.setupDerivatives() - // clear events from setup - suite.Ctx = suite.Ctx.WithEventManager(sdk.NewEventManager()) - - msg := types.NewMsgWithdrawBurn( - user, - valAddr, - // in this setup where the validator is not slashed, the derivative amount is equal to the staked balance - suite.NewBondCoin(delegated.Amount), - ) - _, err := suite.msgServer.WithdrawBurn(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - suite.EventsContains(suite.Ctx.EventManager().Events(), - sdk.NewEvent(sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, user.String()), - ), - ) -} - -func (suite *msgServerTestSuite) TestWithdrawBurnUndelegate_Events() { - user, valAddr, delegated := suite.setupDerivatives() - // clear events from setup - suite.Ctx = suite.Ctx.WithEventManager(sdk.NewEventManager()) - - msg := types.NewMsgWithdrawBurnUndelegate( - user, - valAddr, - // in this setup where the validator is not slashed, the derivative amount is equal to the staked balance - suite.NewBondCoin(delegated.Amount), - ) - _, err := suite.msgServer.WithdrawBurnUndelegate(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - suite.EventsContains(suite.Ctx.EventManager().Events(), - sdk.NewEvent(sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, user.String()), - ), - ) - unbondingTime := suite.StakingKeeper.UnbondingTime(suite.Ctx) - completionTime := suite.Ctx.BlockTime().Add(unbondingTime) - suite.EventsContains(suite.Ctx.EventManager().Events(), - sdk.NewEvent( - stakingtypes.EventTypeUnbond, - sdk.NewAttribute(stakingtypes.AttributeKeyValidator, msg.Validator), - sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), - sdk.NewAttribute(stakingtypes.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)), - ), - ) -} - -func (suite *msgServerTestSuite) TestMintDepositAndWithdrawBurn_TransferEntireBalance() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, user := addrs[0], addrs[1] - valAddr := sdk.ValAddress(valAccAddr) - - derivativeDenom := suite.setupEarnForDeposits(valAddr) - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(sdkmath.NewInt(1e9))) - vesting := sdkmath.NewInt(1000) - suite.CreateVestingAccountWithAddress(user, - suite.NewBondCoins(sdkmath.NewInt(1e9).Add(vesting)), - suite.NewBondCoins(vesting), - ) - - // Create a slashed validator, where the delegator owns fractional tokens. - suite.CreateNewUnbondedValidator(valAddr, sdkmath.NewInt(1e9)) - suite.CreateDelegation(valAddr, user, sdkmath.NewInt(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - suite.SlashValidator(valAddr, sdk.MustNewDecFromStr("0.666666666666666667")) - - // Query the full staked balance and convert it all to derivatives - // user technically 333_333_333.333333333333333333 staked tokens without rounding - delegation := suite.QueryStaking_Delegation(valAddr, user) - suite.Equal(sdkmath.NewInt(333_333_333), delegation.Balance.Amount) - - msgDeposit := types.NewMsgMintDeposit( - user, - valAddr, - delegation.Balance, - ) - _, err := suite.msgServer.MintDeposit(sdk.WrapSDKContext(suite.Ctx), msgDeposit) - suite.Require().NoError(err) - - // There should be no extractable balance left in delegation - suite.DelegationBalanceLessThan(valAddr, user, sdkmath.NewInt(1)) - // All derivative coins should be deposited to earn - suite.AccountBalanceOfEqual(user, derivativeDenom, sdk.ZeroInt()) - // Earn vault has all minted derivatives - suite.VaultAccountValueEqual(user, sdk.NewInt64Coin(derivativeDenom, 999_999_998)) // 2 lost in conversion - - // Query the full kava balance of the earn deposit and convert all to a delegation - deposit := suite.QueryEarn_VaultValue(user, "bkava") - suite.Equal(suite.NewBondCoins(sdkmath.NewInt(333_333_332)), deposit.Value) // 1 lost due to lost shares - - msgWithdraw := types.NewMsgWithdrawBurn( - user, - valAddr, - deposit.Value[0], - ) - _, err = suite.msgServer.WithdrawBurn(sdk.WrapSDKContext(suite.Ctx), msgWithdraw) - suite.Require().NoError(err) - - // There should be no earn deposit left (earn removes dust amounts) - suite.VaultAccountSharesEqual(user, nil) - // All derivative coins should be converted to a delegation - suite.AccountBalanceOfEqual(user, derivativeDenom, sdk.ZeroInt()) - // The user should get back most of their original deposited balance - suite.DelegationBalanceInDeltaBelow(valAddr, user, sdkmath.NewInt(333_333_332), sdkmath.NewInt(2)) -} - -func (suite *msgServerTestSuite) TestDelegateMintDepositAndWithdrawBurnUndelegate_TransferEntireBalance() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, user := addrs[0], addrs[1] - valAddr := sdk.ValAddress(valAccAddr) - - derivativeDenom := suite.setupEarnForDeposits(valAddr) - - valBalance := sdkmath.NewInt(1e9) - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(valBalance)) - - // Create a slashed validator, where a future delegator will own fractional tokens. - suite.CreateNewUnbondedValidator(valAddr, valBalance) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - suite.SlashValidator(valAddr, sdk.MustNewDecFromStr("0.4")) // tokens remaining 600_000_000 - - userBalance := sdkmath.NewInt(100e6) - vesting := sdkmath.NewInt(1000) - suite.CreateVestingAccountWithAddress(user, - suite.NewBondCoins(userBalance.Add(vesting)), - suite.NewBondCoins(vesting), - ) - - // Query the full vested balance and convert it all to derivatives - balance := suite.QueryBank_SpendableBalance(user) - suite.Equal(suite.NewBondCoins(userBalance), balance) - - // When delegation is created it will have 166_666_666.666666666666666666 shares - // newShares = validatorShares * newTokens/validatorTokens, truncated to 18 decimals - msgDeposit := types.NewMsgDelegateMintDeposit( - user, - valAddr, - balance[0], - ) - _, err := suite.msgServer.DelegateMintDeposit(sdk.WrapSDKContext(suite.Ctx), msgDeposit) - suite.Require().NoError(err) - - // All spendable balance should be withdrawn - suite.AccountSpendableBalanceEqual(user, sdk.NewCoins()) - // Since shares are newly created, the exact amount should be converted to derivatives, leaving none behind - suite.DelegationSharesEqual(valAddr, user, sdk.ZeroDec()) - // All derivative coins should be deposited to earn - suite.AccountBalanceOfEqual(user, derivativeDenom, sdk.ZeroInt()) - - suite.VaultAccountValueEqual(user, sdk.NewInt64Coin(derivativeDenom, 166_666_666)) - - // Query the full kava balance of the earn deposit and convert all to a delegation - deposit := suite.QueryEarn_VaultValue(user, "bkava") - suite.Equal(suite.NewBondCoins(sdkmath.NewInt(99_999_999)), deposit.Value) // 1 lost due to truncating shares to derivatives - - msgWithdraw := types.NewMsgWithdrawBurnUndelegate( - user, - valAddr, - deposit.Value[0], - ) - _, err = suite.msgServer.WithdrawBurnUndelegate(sdk.WrapSDKContext(suite.Ctx), msgWithdraw) - suite.Require().NoError(err) - - // There should be no earn deposit left (earn removes dust amounts) - suite.VaultAccountSharesEqual(user, nil) - // All derivative coins should be converted to a delegation - suite.AccountBalanceOfEqual(user, derivativeDenom, sdk.ZeroInt()) - // There should be zero shares left because undelegate removes all created by burn. - suite.AccountBalanceOfEqual(user, derivativeDenom, sdk.ZeroInt()) - // User should have most of their original balance back in an unbonding delegation - suite.UnbondingDelegationInDeltaBelow(valAddr, user, userBalance, sdkmath.NewInt(2)) -} - -func (suite *msgServerTestSuite) setupValidator() (sdk.AccAddress, sdk.ValAddress, sdkmath.Int) { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, user := addrs[0], addrs[1] - valAddr := sdk.ValAddress(valAccAddr) - - balance := sdkmath.NewInt(1e9) - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(balance)) - suite.CreateAccountWithAddress(user, suite.NewBondCoins(balance)) - - suite.CreateNewUnbondedValidator(valAddr, balance) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - return user, valAddr, balance -} - -func (suite *msgServerTestSuite) setupValidatorAndDelegation() (sdk.AccAddress, sdk.ValAddress, sdkmath.Int) { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, user := addrs[0], addrs[1] - valAddr := sdk.ValAddress(valAccAddr) - - balance := sdkmath.NewInt(1e9) - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(balance)) - suite.CreateAccountWithAddress(user, suite.NewBondCoins(balance)) - - suite.CreateNewUnbondedValidator(valAddr, balance) - suite.CreateDelegation(valAddr, user, balance) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - return user, valAddr, balance -} - -func (suite *msgServerTestSuite) setupEarnForDeposits(valAddr sdk.ValAddress) string { - suite.CreateVault("bkava", earntypes.StrategyTypes{earntypes.STRATEGY_TYPE_SAVINGS}, false, nil) - derivativeDenom := fmt.Sprintf("bkava-%s", valAddr) - suite.SetSavingsSupportedDenoms([]string{derivativeDenom}) - return derivativeDenom -} - -func (suite *msgServerTestSuite) setupDerivatives() (sdk.AccAddress, sdk.ValAddress, sdk.Coin) { - user, valAddr, delegation := suite.setupValidatorAndDelegation() - suite.setupEarnForDeposits(valAddr) - - msg := types.NewMsgMintDeposit( - user, - valAddr, - suite.NewBondCoin(delegation), - ) - _, err := suite.msgServer.MintDeposit(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - derivativeDenom := fmt.Sprintf("bkava-%s", valAddr) - derivatives, err := suite.EarnKeeper.GetVaultAccountValue(suite.Ctx, derivativeDenom, user) - suite.Require().NoError(err) - - return user, valAddr, derivatives -} diff --git a/x/router/module.go b/x/router/module.go deleted file mode 100644 index 41be3f30..00000000 --- a/x/router/module.go +++ /dev/null @@ -1,118 +0,0 @@ -package router - -import ( - "encoding/json" - - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/kava-labs/kava/x/router/client/cli" - "github.com/kava-labs/kava/x/router/keeper" - "github.com/kava-labs/kava/x/router/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { - return []byte("{}") -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, _ client.TxEncodingConfig, _ json.RawMessage) error { - return nil -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(_ client.Context, _ *runtime.ServeMux) { -} - -// GetTxCmd returns the root tx command for the module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return nil -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - } -} - -// Name module name -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// RegisterInvariants register module invariants -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) -} - -// InitGenesis module init-genesis -func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONCodec, _ json.RawMessage) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} - -// ExportGenesis module export genesis -func (am AppModule) ExportGenesis(_ sdk.Context, cdc codec.JSONCodec) json.RawMessage { - return am.DefaultGenesis(cdc) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - -// EndBlock module end-block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/router/testutil/suite.go b/x/router/testutil/suite.go deleted file mode 100644 index 8bbbfdd1..00000000 --- a/x/router/testutil/suite.go +++ /dev/null @@ -1,365 +0,0 @@ -package testutil - -import ( - "fmt" - "reflect" - - sdkmath "cosmossdk.io/math" - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - - "github.com/kava-labs/kava/app" - earnkeeper "github.com/kava-labs/kava/x/earn/keeper" - earntypes "github.com/kava-labs/kava/x/earn/types" - "github.com/kava-labs/kava/x/router/keeper" - savingstypes "github.com/kava-labs/kava/x/savings/types" -) - -// Test suite used for all keeper tests -type Suite struct { - suite.Suite - App app.TestApp - Ctx sdk.Context - Keeper keeper.Keeper - BankKeeper bankkeeper.Keeper - StakingKeeper *stakingkeeper.Keeper - EarnKeeper earnkeeper.Keeper -} - -// The default state used by each test -func (suite *Suite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - tApp.InitializeFromGenesisStates() - - suite.App = tApp - suite.Ctx = ctx - suite.Keeper = tApp.GetRouterKeeper() - suite.StakingKeeper = tApp.GetStakingKeeper() - suite.BankKeeper = tApp.GetBankKeeper() - suite.EarnKeeper = tApp.GetEarnKeeper() -} - -// CreateAccount creates a new account from the provided balance and address -func (suite *Suite) CreateAccountWithAddress(addr sdk.AccAddress, initialBalance sdk.Coins) authtypes.AccountI { - ak := suite.App.GetAccountKeeper() - - acc := ak.NewAccountWithAddress(suite.Ctx, addr) - ak.SetAccount(suite.Ctx, acc) - - err := suite.App.FundAccount(suite.Ctx, acc.GetAddress(), initialBalance) - suite.Require().NoError(err) - - return acc -} - -// CreateVestingAccount creates a new vesting account. `vestingBalance` should be a fraction of `initialBalance`. -func (suite *Suite) CreateVestingAccountWithAddress(addr sdk.AccAddress, initialBalance sdk.Coins, vestingBalance sdk.Coins) authtypes.AccountI { - if vestingBalance.IsAnyGT(initialBalance) { - panic("vesting balance must be less than initial balance") - } - acc := suite.CreateAccountWithAddress(addr, initialBalance) - bacc := acc.(*authtypes.BaseAccount) - - periods := vestingtypes.Periods{ - vestingtypes.Period{ - Length: 31556952, - Amount: vestingBalance, - }, - } - vacc := vestingtypes.NewPeriodicVestingAccount(bacc, vestingBalance, suite.Ctx.BlockTime().Unix(), periods) - suite.App.GetAccountKeeper().SetAccount(suite.Ctx, vacc) - return vacc -} - -// AddCoinsToModule adds coins to the a module account, creating it if it doesn't exist. -func (suite *Suite) AddCoinsToModule(module string, amount sdk.Coins) { - err := suite.App.FundModuleAccount(suite.Ctx, module, amount) - suite.Require().NoError(err) -} - -// AccountBalanceEqual checks if an account has the specified coins. -func (suite *Suite) AccountBalanceEqual(addr sdk.AccAddress, coins sdk.Coins) { - balance := suite.BankKeeper.GetAllBalances(suite.Ctx, addr) - suite.Equalf(coins, balance, "expected account balance to equal coins %s, but got %s", coins, balance) -} - -// AccountBalanceOfEqual checks if an account has the specified amount of one denom. -func (suite *Suite) AccountBalanceOfEqual(addr sdk.AccAddress, denom string, amount sdkmath.Int) { - balance := suite.BankKeeper.GetBalance(suite.Ctx, addr, denom).Amount - suite.Equalf(amount, balance, "expected account balance to have %[1]s%[2]s, but got %[3]s%[2]s", amount, denom, balance) -} - -// AccountSpendableBalanceEqual checks if an account has the specified coins unlocked. -func (suite *Suite) AccountSpendableBalanceEqual(addr sdk.AccAddress, amount sdk.Coins) { - balance := suite.BankKeeper.SpendableCoins(suite.Ctx, addr) - expectedAmt := amount - if expectedAmt == nil { - expectedAmt = sdk.NewCoins() - } - suite.Equalf(expectedAmt, balance, "expected account spendable balance to equal coins %s, but got %s", amount, balance) -} - -func (suite *Suite) QueryBank_SpendableBalance(user sdk.AccAddress) sdk.Coins { - res, err := suite.BankKeeper.SpendableBalances( - sdk.WrapSDKContext(suite.Ctx), - &banktypes.QuerySpendableBalancesRequest{ - Address: user.String(), - }, - ) - suite.Require().NoError(err) - return *&res.Balances -} - -func (suite *Suite) deliverMsgCreateValidator(ctx sdk.Context, address sdk.ValAddress, selfDelegation sdk.Coin) error { - msg, err := stakingtypes.NewMsgCreateValidator( - address, - ed25519.GenPrivKey().PubKey(), - selfDelegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - sdkmath.NewInt(1e6), - ) - if err != nil { - return err - } - - msgServer := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.Ctx), msg) - return err -} - -// NewBondCoin creates a Coin with the current staking denom. -func (suite *Suite) NewBondCoin(amount sdkmath.Int) sdk.Coin { - stakingDenom := suite.StakingKeeper.BondDenom(suite.Ctx) - return sdk.NewCoin(stakingDenom, amount) -} - -// NewBondCoins creates Coins with the current staking denom. -func (suite *Suite) NewBondCoins(amount sdkmath.Int) sdk.Coins { - return sdk.NewCoins(suite.NewBondCoin(amount)) -} - -// CreateNewUnbondedValidator creates a new validator in the staking module. -// New validators are unbonded until the end blocker is run. -func (suite *Suite) CreateNewUnbondedValidator(addr sdk.ValAddress, selfDelegation sdkmath.Int) stakingtypes.Validator { - // Create a validator - err := suite.deliverMsgCreateValidator(suite.Ctx, addr, suite.NewBondCoin(selfDelegation)) - suite.Require().NoError(err) - - // New validators are created in an unbonded state. Note if the end blocker is run later this validator could become bonded. - - validator, found := suite.StakingKeeper.GetValidator(suite.Ctx, addr) - suite.Require().True(found) - return validator -} - -// SlashValidator burns tokens staked in a validator. new_tokens = old_tokens * (1-slashFraction) -func (suite *Suite) SlashValidator(addr sdk.ValAddress, slashFraction sdk.Dec) { - validator, found := suite.StakingKeeper.GetValidator(suite.Ctx, addr) - suite.Require().True(found) - consAddr, err := validator.GetConsAddr() - suite.Require().NoError(err) - - // Assume infraction was at current height. Note unbonding delegations and redelegations are only slashed if created after - // the infraction height so none will be slashed. - infractionHeight := suite.Ctx.BlockHeight() - - power := suite.StakingKeeper.TokensToConsensusPower(suite.Ctx, validator.GetTokens()) - - suite.StakingKeeper.Slash(suite.Ctx, consAddr, infractionHeight, power, slashFraction) -} - -// CreateDelegation delegates tokens to a validator. -func (suite *Suite) CreateDelegation(valAddr sdk.ValAddress, delegator sdk.AccAddress, amount sdkmath.Int) sdk.Dec { - stakingDenom := suite.StakingKeeper.BondDenom(suite.Ctx) - msg := stakingtypes.NewMsgDelegate( - delegator, - valAddr, - sdk.NewCoin(stakingDenom, amount), - ) - - msgServer := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - _, err := msgServer.Delegate(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - del, found := suite.StakingKeeper.GetDelegation(suite.Ctx, delegator, valAddr) - suite.Require().True(found) - return del.Shares -} - -// DelegationSharesEqual checks if a delegation has the specified shares. -// It expects delegations with zero shares to not be stored in state. -func (suite *Suite) DelegationSharesEqual(valAddr sdk.ValAddress, delegator sdk.AccAddress, shares sdk.Dec) bool { - del, found := suite.StakingKeeper.GetDelegation(suite.Ctx, delegator, valAddr) - - if shares.IsZero() { - return suite.Falsef(found, "expected delegator to not be found, got %s shares", del.Shares) - } else { - res := suite.True(found, "expected delegator to be found") - return res && suite.Truef(shares.Equal(del.Shares), "expected %s delegator shares but got %s", shares, del.Shares) - } -} - -// DelegationBalanceLessThan checks if a delegation's staked token balance is less the specified amount. -// It treats not found delegations as having zero shares. -func (suite *Suite) DelegationBalanceLessThan(valAddr sdk.ValAddress, delegator sdk.AccAddress, max sdkmath.Int) bool { - shares := sdk.ZeroDec() - del, found := suite.StakingKeeper.GetDelegation(suite.Ctx, delegator, valAddr) - if found { - shares = del.Shares - } - - val, found := suite.StakingKeeper.GetValidator(suite.Ctx, valAddr) - suite.Require().Truef(found, "expected validator to be found") - - tokens := val.TokensFromShares(shares).TruncateInt() - - return suite.Truef(tokens.LT(max), "expected delegation balance to be less than %s, got %s", max, tokens) -} - -// DelegationBalanceInDeltaBelow checks if a delegation's staked token balance is between `expected` and `expected - delta` inclusive. -// It treats not found delegations as having zero shares. -func (suite *Suite) DelegationBalanceInDeltaBelow(valAddr sdk.ValAddress, delegator sdk.AccAddress, expected, delta sdkmath.Int) bool { - shares := sdk.ZeroDec() - del, found := suite.StakingKeeper.GetDelegation(suite.Ctx, delegator, valAddr) - if found { - shares = del.Shares - } - - val, found := suite.StakingKeeper.GetValidator(suite.Ctx, valAddr) - suite.Require().Truef(found, "expected validator to be found") - - tokens := val.TokensFromShares(shares).TruncateInt() - - lte := suite.Truef(tokens.LTE(expected), "expected delegation balance to be less than or equal to %s, got %s", expected, tokens) - gte := suite.Truef(tokens.GTE(expected.Sub(delta)), "expected delegation balance to be greater than or equal to %s, got %s", expected.Sub(delta), tokens) - return lte && gte -} - -// UnbondingDelegationInDeltaBelow checks if the total balance in an unbonding delegation is between `expected` and `expected - delta` inclusive. -func (suite *Suite) UnbondingDelegationInDeltaBelow(valAddr sdk.ValAddress, delegator sdk.AccAddress, expected, delta sdkmath.Int) bool { - tokens := sdk.ZeroInt() - ubd, found := suite.StakingKeeper.GetUnbondingDelegation(suite.Ctx, delegator, valAddr) - if found { - for _, entry := range ubd.Entries { - tokens = tokens.Add(entry.Balance) - } - } - - lte := suite.Truef(tokens.LTE(expected), "expected unbonding delegation balance to be less than or equal to %s, got %s", expected, tokens) - gte := suite.Truef(tokens.GTE(expected.Sub(delta)), "expected unbonding delegation balance to be greater than or equal to %s, got %s", expected.Sub(delta), tokens) - return lte && gte -} - -func (suite *Suite) QueryStaking_Delegation(valAddr sdk.ValAddress, delegator sdk.AccAddress) stakingtypes.DelegationResponse { - stakingQuery := stakingkeeper.Querier{Keeper: suite.StakingKeeper} - res, err := stakingQuery.Delegation( - sdk.WrapSDKContext(suite.Ctx), - &stakingtypes.QueryDelegationRequest{ - DelegatorAddr: delegator.String(), - ValidatorAddr: valAddr.String(), - }, - ) - suite.Require().NoError(err) - return *res.DelegationResponse -} - -// EventsContains asserts that the expected event is in the provided events -func (suite *Suite) EventsContains(events sdk.Events, expectedEvent sdk.Event) { - foundMatch := false - for _, event := range events { - if event.Type == expectedEvent.Type { - if reflect.DeepEqual(attrsToMap(expectedEvent.Attributes), attrsToMap(event.Attributes)) { - foundMatch = true - } - } - } - - suite.True(foundMatch, fmt.Sprintf("event of type %s not found or did not match", expectedEvent.Type)) -} - -func attrsToMap(attrs []abci.EventAttribute) []sdk.Attribute { - out := []sdk.Attribute{} - - for _, attr := range attrs { - out = append(out, sdk.NewAttribute(string(attr.Key), string(attr.Value))) - } - - return out -} - -// CreateVault adds a new earn vault to the earn keeper parameters -func (suite *Suite) CreateVault( - vaultDenom string, - vaultStrategies earntypes.StrategyTypes, - isPrivateVault bool, - allowedDepositors []sdk.AccAddress, -) { - vault := earntypes.NewAllowedVault(vaultDenom, vaultStrategies, isPrivateVault, allowedDepositors) - - allowedVaults := suite.EarnKeeper.GetAllowedVaults(suite.Ctx) - allowedVaults = append(allowedVaults, vault) - - params := earntypes.NewParams(allowedVaults) - - suite.EarnKeeper.SetParams( - suite.Ctx, - params, - ) -} - -// SetSavingsSupportedDenoms overwrites the list of supported denoms in the savings module params. -func (suite *Suite) SetSavingsSupportedDenoms(denoms []string) { - sk := suite.App.GetSavingsKeeper() - sk.SetParams(suite.Ctx, savingstypes.NewParams(denoms)) -} - -// VaultAccountValueEqual asserts that the vault account value matches the provided coin amount. -func (suite *Suite) VaultAccountValueEqual(acc sdk.AccAddress, coin sdk.Coin) { - - accVaultBal, err := suite.EarnKeeper.GetVaultAccountValue(suite.Ctx, coin.Denom, acc) - suite.Require().NoError(err) - - suite.Require().Truef( - coin.Equal(accVaultBal), - "expected account vault balance to equal %s, but got %s", - coin, accVaultBal, - ) -} - -// VaultAccountSharesEqual asserts that the vault account shares match the provided values. -func (suite *Suite) VaultAccountSharesEqual(acc sdk.AccAddress, shares earntypes.VaultShares) { // TODO - - accVaultShares, found := suite.EarnKeeper.GetVaultAccountShares(suite.Ctx, acc) - if !found { - suite.Empty(shares) - } else { - suite.Equal(shares, accVaultShares) - } -} - -func (suite *Suite) QueryEarn_VaultValue(depositor sdk.AccAddress, vaultDenom string) earntypes.DepositResponse { - earnQuery := earnkeeper.NewQueryServerImpl(suite.EarnKeeper) - res, err := earnQuery.Deposits( - sdk.WrapSDKContext(suite.Ctx), - &earntypes.QueryDepositsRequest{ - Depositor: depositor.String(), - Denom: vaultDenom, - }, - ) - suite.Require().NoError(err) - suite.Require().Equalf(1, len(res.Deposits), "while earn supports one vault per denom, deposits response should be length 1") - return res.Deposits[0] -} diff --git a/x/router/types/codec.go b/x/router/types/codec.go deleted file mode 100644 index dfd5046c..00000000 --- a/x/router/types/codec.go +++ /dev/null @@ -1,46 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgMintDeposit{}, "router/MsgMintDeposit", nil) - cdc.RegisterConcrete(&MsgDelegateMintDeposit{}, "router/MsgDelegateMintDeposit", nil) - cdc.RegisterConcrete(&MsgWithdrawBurn{}, "router/MsgWithdrawBurn", nil) - cdc.RegisterConcrete(&MsgWithdrawBurnUndelegate{}, "router/MsgWithdrawBurnUndelegate", nil) -} - -// RegisterInterfaces registers proto messages under their interfaces for unmarshalling, -// in addition to registering the msg service for handling tx msgs -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgMintDeposit{}, - &MsgDelegateMintDeposit{}, - &MsgWithdrawBurn{}, - &MsgWithdrawBurnUndelegate{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - // ModuleCdc represents the legacy amino codec for the module - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/router/types/common_test.go b/x/router/types/common_test.go deleted file mode 100644 index e88e1d5e..00000000 --- a/x/router/types/common_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package types_test - -import ( - "os" - "testing" - - "github.com/kava-labs/kava/app" -) - -func TestMain(m *testing.M) { - app.SetSDKConfig() - os.Exit(m.Run()) -} diff --git a/x/router/types/expected_keepers.go b/x/router/types/expected_keepers.go deleted file mode 100644 index 927160bb..00000000 --- a/x/router/types/expected_keepers.go +++ /dev/null @@ -1,35 +0,0 @@ -package types - -import ( - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - earntypes "github.com/kava-labs/kava/x/earn/types" -) - -type StakingKeeper interface { - BondDenom(ctx sdk.Context) (res string) - GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool) - - Delegate( - ctx sdk.Context, delAddr sdk.AccAddress, bondAmt sdkmath.Int, tokenSrc stakingtypes.BondStatus, - validator stakingtypes.Validator, subtractAccount bool, - ) (newShares sdk.Dec, err error) - Undelegate( - ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, sharesAmount sdk.Dec, - ) (time.Time, error) -} - -type LiquidKeeper interface { - DerivativeFromTokens(ctx sdk.Context, valAddr sdk.ValAddress, amount sdk.Coin) (sdk.Coin, error) - MintDerivative(ctx sdk.Context, delegatorAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) (sdk.Coin, error) - BurnDerivative(ctx sdk.Context, delegatorAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) (sdk.Dec, error) -} - -type EarnKeeper interface { - Deposit(ctx sdk.Context, depositor sdk.AccAddress, amount sdk.Coin, depositStrategy earntypes.StrategyType) error - Withdraw(ctx sdk.Context, from sdk.AccAddress, wantAmount sdk.Coin, withdrawStrategy earntypes.StrategyType) (sdk.Coin, error) -} diff --git a/x/router/types/keys.go b/x/router/types/keys.go deleted file mode 100644 index dbde25a7..00000000 --- a/x/router/types/keys.go +++ /dev/null @@ -1,9 +0,0 @@ -package types - -const ( - // ModuleName name that will be used throughout the module - ModuleName = "router" - - // RouterKey top level router key - RouterKey = ModuleName -) diff --git a/x/router/types/msg.go b/x/router/types/msg.go deleted file mode 100644 index 93170853..00000000 --- a/x/router/types/msg.go +++ /dev/null @@ -1,202 +0,0 @@ -package types - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" -) - -const ( - // TypeMsgMintDeposit defines the type for MsgMintDeposit - TypeMsgMintDeposit = "mint_deposit" - // TypeMsgDelegateMintDeposit defines the type for MsgDelegateMintDeposit - TypeMsgDelegateMintDeposit = "delegate_mint_deposit" - // TypeMsgWithdrawBurn defines the type for MsgWithdrawBurn - TypeMsgWithdrawBurn = "withdraw_burn" - // TypeMsgWithdrawBurnUndelegate defines the type for MsgWithdrawBurnUndelegate - TypeMsgWithdrawBurnUndelegate = "withdraw_burn_undelegate" -) - -var ( - _ sdk.Msg = &MsgMintDeposit{} - _ legacytx.LegacyMsg = &MsgMintDeposit{} - _ sdk.Msg = &MsgDelegateMintDeposit{} - _ legacytx.LegacyMsg = &MsgDelegateMintDeposit{} - _ sdk.Msg = &MsgWithdrawBurn{} - _ legacytx.LegacyMsg = &MsgWithdrawBurn{} - _ sdk.Msg = &MsgWithdrawBurnUndelegate{} - _ legacytx.LegacyMsg = &MsgWithdrawBurnUndelegate{} -) - -// NewMsgMintDeposit returns a new MsgMintDeposit. -func NewMsgMintDeposit(depositor sdk.AccAddress, validator sdk.ValAddress, amount sdk.Coin) *MsgMintDeposit { - return &MsgMintDeposit{ - Depositor: depositor.String(), - Validator: validator.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgMintDeposit) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgMintDeposit) Type() string { return TypeMsgMintDeposit } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgMintDeposit) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Depositor); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid depositor address: %s", err) - } - - if _, err := sdk.ValAddressFromBech32(msg.Validator); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid validator address: %s", err) - } - - if msg.Amount.IsNil() || !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "'%s'", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgMintDeposit) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgMintDeposit) GetSigners() []sdk.AccAddress { - depositor, _ := sdk.AccAddressFromBech32(msg.Depositor) - return []sdk.AccAddress{depositor} -} - -// NewMsgDelegateMintDeposit returns a new MsgDelegateMintDeposit. -func NewMsgDelegateMintDeposit(depositor sdk.AccAddress, validator sdk.ValAddress, amount sdk.Coin) *MsgDelegateMintDeposit { - return &MsgDelegateMintDeposit{ - Depositor: depositor.String(), - Validator: validator.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgDelegateMintDeposit) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgDelegateMintDeposit) Type() string { return TypeMsgDelegateMintDeposit } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgDelegateMintDeposit) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Depositor); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid depositor address: %s", err) - } - - if _, err := sdk.ValAddressFromBech32(msg.Validator); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid validator address: %s", err) - } - - if msg.Amount.IsNil() || !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "'%s'", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgDelegateMintDeposit) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgDelegateMintDeposit) GetSigners() []sdk.AccAddress { - depositor, _ := sdk.AccAddressFromBech32(msg.Depositor) - return []sdk.AccAddress{depositor} -} - -// NewMsgWithdrawBurn returns a new MsgWithdrawBurn. -func NewMsgWithdrawBurn(from sdk.AccAddress, validator sdk.ValAddress, amount sdk.Coin) *MsgWithdrawBurn { - return &MsgWithdrawBurn{ - From: from.String(), - Validator: validator.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgWithdrawBurn) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgWithdrawBurn) Type() string { return TypeMsgWithdrawBurn } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgWithdrawBurn) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.From); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid from address: %s", err) - } - - if _, err := sdk.ValAddressFromBech32(msg.Validator); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid validator address: %s", err) - } - - if msg.Amount.IsNil() || !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "'%s'", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgWithdrawBurn) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgWithdrawBurn) GetSigners() []sdk.AccAddress { - from, _ := sdk.AccAddressFromBech32(msg.From) - return []sdk.AccAddress{from} -} - -// NewMsgWithdrawBurnUndelegate returns a new MsgWithdrawBurnUndelegate. -func NewMsgWithdrawBurnUndelegate(from sdk.AccAddress, validator sdk.ValAddress, amount sdk.Coin) *MsgWithdrawBurnUndelegate { - return &MsgWithdrawBurnUndelegate{ - From: from.String(), - Validator: validator.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgWithdrawBurnUndelegate) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgWithdrawBurnUndelegate) Type() string { return TypeMsgWithdrawBurnUndelegate } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgWithdrawBurnUndelegate) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.From); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid from address: %s", err) - } - - if _, err := sdk.ValAddressFromBech32(msg.Validator); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid validator address: %s", err) - } - - if msg.Amount.IsNil() || !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "'%s'", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgWithdrawBurnUndelegate) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgWithdrawBurnUndelegate) GetSigners() []sdk.AccAddress { - from, _ := sdk.AccAddressFromBech32(msg.From) - return []sdk.AccAddress{from} -} diff --git a/x/router/types/msg_test.go b/x/router/types/msg_test.go deleted file mode 100644 index 2f7b10fd..00000000 --- a/x/router/types/msg_test.go +++ /dev/null @@ -1,208 +0,0 @@ -package types_test - -import ( - fmt "fmt" - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/kava-labs/kava/x/router/types" -) - -func TestMsgMintDeposit_Signing(t *testing.T) { - address := mustAccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - validatorAddress := mustValAddressFromBech32("kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42") - - msg := types.NewMsgMintDeposit( - address, - validatorAddress, - sdk.NewCoin("ukava", sdkmath.NewInt(1e9)), - ) - - // checking for the "type" field ensures the msg is registered on the amino codec - signBytes := []byte( - `{"type":"router/MsgMintDeposit","value":{"amount":{"amount":"1000000000","denom":"ukava"},"depositor":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","validator":"kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42"}}`, - ) - - assert.Equal(t, []sdk.AccAddress{address}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsgDelegateMintDeposit_Signing(t *testing.T) { - address := mustAccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - validatorAddress := mustValAddressFromBech32("kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42") - - msg := types.NewMsgDelegateMintDeposit( - address, - validatorAddress, - sdk.NewCoin("ukava", sdkmath.NewInt(1e9)), - ) - - // checking for the "type" field ensures the msg is registered on the amino codec - signBytes := []byte( - `{"type":"router/MsgDelegateMintDeposit","value":{"amount":{"amount":"1000000000","denom":"ukava"},"depositor":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","validator":"kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42"}}`, - ) - - assert.Equal(t, []sdk.AccAddress{address}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsgWithdrawBurn_Signing(t *testing.T) { - address := mustAccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - validatorAddress := mustValAddressFromBech32("kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42") - - msg := types.NewMsgWithdrawBurn( - address, - validatorAddress, - sdk.NewCoin("ukava", sdkmath.NewInt(1e9)), - ) - - // checking for the "type" field ensures the msg is registered on the amino codec - signBytes := []byte( - `{"type":"router/MsgWithdrawBurn","value":{"amount":{"amount":"1000000000","denom":"ukava"},"from":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","validator":"kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42"}}`, - ) - - assert.Equal(t, []sdk.AccAddress{address}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsgWithdrawBurnUndelegate_Signing(t *testing.T) { - address := mustAccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - validatorAddress := mustValAddressFromBech32("kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42") - - msg := types.NewMsgWithdrawBurnUndelegate( - address, - validatorAddress, - sdk.NewCoin("ukava", sdkmath.NewInt(1e9)), - ) - - // checking for the "type" field ensures the msg is registered on the amino codec - signBytes := []byte( - `{"type":"router/MsgWithdrawBurnUndelegate","value":{"amount":{"amount":"1000000000","denom":"ukava"},"from":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","validator":"kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42"}}`, - ) - - assert.Equal(t, []sdk.AccAddress{address}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsg_Validate(t *testing.T) { - validAddress := "kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d" - validValidatorAddress := "kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42" - validCoin := sdk.NewInt64Coin("ukava", 1e9) - - type msgArgs struct { - depositor string - validator string - amount sdk.Coin - } - tests := []struct { - name string - msgArgs msgArgs - expectedErr error - }{ - { - name: "normal multiplier is valid", - msgArgs: msgArgs{ - depositor: validAddress, - validator: validValidatorAddress, - amount: validCoin, - }, - }, - { - name: "invalid depositor", - msgArgs: msgArgs{ - depositor: "invalid", - validator: validValidatorAddress, - amount: validCoin, - }, - expectedErr: sdkerrors.ErrInvalidAddress, - }, - { - name: "empty depositor", - msgArgs: msgArgs{ - depositor: "", - validator: validValidatorAddress, - amount: validCoin, - }, - expectedErr: sdkerrors.ErrInvalidAddress, - }, - { - name: "invalid validator", - msgArgs: msgArgs{ - depositor: validAddress, - validator: "invalid", - amount: validCoin, - }, - expectedErr: sdkerrors.ErrInvalidAddress, - }, - { - name: "nil coin", - msgArgs: msgArgs{ - depositor: validAddress, - validator: validValidatorAddress, - amount: sdk.Coin{}, - }, - expectedErr: sdkerrors.ErrInvalidCoins, - }, - { - name: "zero coin", - msgArgs: msgArgs{ - depositor: validAddress, - validator: validValidatorAddress, - amount: sdk.NewCoin("ukava", sdk.ZeroInt()), - }, - expectedErr: sdkerrors.ErrInvalidCoins, - }, - { - name: "negative coin", - msgArgs: msgArgs{ - depositor: validAddress, - validator: validValidatorAddress, - amount: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - }, - expectedErr: sdkerrors.ErrInvalidCoins, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - msgMintDeposit := types.MsgMintDeposit{tc.msgArgs.depositor, tc.msgArgs.validator, tc.msgArgs.amount} - msgDelegateMintDeposit := types.MsgDelegateMintDeposit{tc.msgArgs.depositor, tc.msgArgs.validator, tc.msgArgs.amount} - - msgWithdrawBurn := types.MsgWithdrawBurn{tc.msgArgs.depositor, tc.msgArgs.validator, tc.msgArgs.amount} - msgWithdrawBurnUndelegate := types.MsgWithdrawBurnUndelegate{tc.msgArgs.depositor, tc.msgArgs.validator, tc.msgArgs.amount} - - msgs := []sdk.Msg{&msgMintDeposit, &msgDelegateMintDeposit, &msgWithdrawBurn, &msgWithdrawBurnUndelegate} - for _, msg := range msgs { - t.Run(fmt.Sprintf("%T", msg), func(t *testing.T) { - err := msg.ValidateBasic() - if tc.expectedErr == nil { - require.NoError(t, err) - } else { - require.ErrorIs(t, err, tc.expectedErr, "expected error '%s' not found in actual '%s'", tc.expectedErr, err) - } - }) - } - }) - } -} - -func mustAccAddressFromBech32(address string) sdk.AccAddress { - addr, err := sdk.AccAddressFromBech32(address) - if err != nil { - panic(err) - } - return addr -} - -func mustValAddressFromBech32(address string) sdk.ValAddress { - addr, err := sdk.ValAddressFromBech32(address) - if err != nil { - panic(err) - } - return addr -} diff --git a/x/router/types/tx.pb.go b/x/router/types/tx.pb.go deleted file mode 100644 index 5f0dc219..00000000 --- a/x/router/types/tx.pb.go +++ /dev/null @@ -1,1882 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/router/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - 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 - -// MsgMintDeposit converts a delegation into staking derivatives and deposits it all into an earn vault. -type MsgMintDeposit struct { - // depositor represents the owner of the delegation to convert - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - // validator is the validator for the depositor's delegation - Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` - // amount is the delegation balance to convert - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *MsgMintDeposit) Reset() { *m = MsgMintDeposit{} } -func (m *MsgMintDeposit) String() string { return proto.CompactTextString(m) } -func (*MsgMintDeposit) ProtoMessage() {} -func (*MsgMintDeposit) Descriptor() ([]byte, []int) { - return fileDescriptor_63015631bbbf9425, []int{0} -} -func (m *MsgMintDeposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgMintDeposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMintDeposit.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 *MsgMintDeposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMintDeposit.Merge(m, src) -} -func (m *MsgMintDeposit) XXX_Size() int { - return m.Size() -} -func (m *MsgMintDeposit) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMintDeposit.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMintDeposit proto.InternalMessageInfo - -// MsgMintDepositResponse defines the Msg/MsgMintDeposit response type. -type MsgMintDepositResponse struct { -} - -func (m *MsgMintDepositResponse) Reset() { *m = MsgMintDepositResponse{} } -func (m *MsgMintDepositResponse) String() string { return proto.CompactTextString(m) } -func (*MsgMintDepositResponse) ProtoMessage() {} -func (*MsgMintDepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63015631bbbf9425, []int{1} -} -func (m *MsgMintDepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgMintDepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMintDepositResponse.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 *MsgMintDepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMintDepositResponse.Merge(m, src) -} -func (m *MsgMintDepositResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgMintDepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMintDepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMintDepositResponse proto.InternalMessageInfo - -// MsgDelegateMintDeposit delegates tokens to a validator, then converts them into staking derivatives, -// then deposits to an earn vault. -type MsgDelegateMintDeposit struct { - // depositor represents the owner of the tokens to delegate - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - // validator is the address of the validator to delegate to - Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` - // amount is the tokens to delegate - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *MsgDelegateMintDeposit) Reset() { *m = MsgDelegateMintDeposit{} } -func (m *MsgDelegateMintDeposit) String() string { return proto.CompactTextString(m) } -func (*MsgDelegateMintDeposit) ProtoMessage() {} -func (*MsgDelegateMintDeposit) Descriptor() ([]byte, []int) { - return fileDescriptor_63015631bbbf9425, []int{2} -} -func (m *MsgDelegateMintDeposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDelegateMintDeposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDelegateMintDeposit.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 *MsgDelegateMintDeposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDelegateMintDeposit.Merge(m, src) -} -func (m *MsgDelegateMintDeposit) XXX_Size() int { - return m.Size() -} -func (m *MsgDelegateMintDeposit) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDelegateMintDeposit.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDelegateMintDeposit proto.InternalMessageInfo - -// MsgDelegateMintDepositResponse defines the Msg/MsgDelegateMintDeposit response type. -type MsgDelegateMintDepositResponse struct { -} - -func (m *MsgDelegateMintDepositResponse) Reset() { *m = MsgDelegateMintDepositResponse{} } -func (m *MsgDelegateMintDepositResponse) String() string { return proto.CompactTextString(m) } -func (*MsgDelegateMintDepositResponse) ProtoMessage() {} -func (*MsgDelegateMintDepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63015631bbbf9425, []int{3} -} -func (m *MsgDelegateMintDepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDelegateMintDepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDelegateMintDepositResponse.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 *MsgDelegateMintDepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDelegateMintDepositResponse.Merge(m, src) -} -func (m *MsgDelegateMintDepositResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgDelegateMintDepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDelegateMintDepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDelegateMintDepositResponse proto.InternalMessageInfo - -// MsgWithdrawBurn removes staking derivatives from an earn vault and converts them back to a staking delegation. -type MsgWithdrawBurn struct { - // from is the owner of the earn vault to withdraw from - From string `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` - // validator is the address to select the derivative denom to withdraw - Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` - // amount is the staked token equivalent to withdraw - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *MsgWithdrawBurn) Reset() { *m = MsgWithdrawBurn{} } -func (m *MsgWithdrawBurn) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawBurn) ProtoMessage() {} -func (*MsgWithdrawBurn) Descriptor() ([]byte, []int) { - return fileDescriptor_63015631bbbf9425, []int{4} -} -func (m *MsgWithdrawBurn) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawBurn) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawBurn.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 *MsgWithdrawBurn) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawBurn.Merge(m, src) -} -func (m *MsgWithdrawBurn) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawBurn) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawBurn.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawBurn proto.InternalMessageInfo - -// MsgWithdrawBurnResponse defines the Msg/MsgWithdrawBurn response type. -type MsgWithdrawBurnResponse struct { -} - -func (m *MsgWithdrawBurnResponse) Reset() { *m = MsgWithdrawBurnResponse{} } -func (m *MsgWithdrawBurnResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawBurnResponse) ProtoMessage() {} -func (*MsgWithdrawBurnResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63015631bbbf9425, []int{5} -} -func (m *MsgWithdrawBurnResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawBurnResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawBurnResponse.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 *MsgWithdrawBurnResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawBurnResponse.Merge(m, src) -} -func (m *MsgWithdrawBurnResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawBurnResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawBurnResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawBurnResponse proto.InternalMessageInfo - -// MsgWithdrawBurnUndelegate removes staking derivatives from an earn vault, converts them to a staking delegation, -// then undelegates them from their validator. -type MsgWithdrawBurnUndelegate struct { - // from is the owner of the earn vault to withdraw from - From string `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` - // validator is the address to select the derivative denom to withdraw - Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` - // amount is the staked token equivalent to withdraw - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *MsgWithdrawBurnUndelegate) Reset() { *m = MsgWithdrawBurnUndelegate{} } -func (m *MsgWithdrawBurnUndelegate) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawBurnUndelegate) ProtoMessage() {} -func (*MsgWithdrawBurnUndelegate) Descriptor() ([]byte, []int) { - return fileDescriptor_63015631bbbf9425, []int{6} -} -func (m *MsgWithdrawBurnUndelegate) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawBurnUndelegate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawBurnUndelegate.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 *MsgWithdrawBurnUndelegate) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawBurnUndelegate.Merge(m, src) -} -func (m *MsgWithdrawBurnUndelegate) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawBurnUndelegate) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawBurnUndelegate.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawBurnUndelegate proto.InternalMessageInfo - -// MsgWithdrawBurnUndelegateResponse defines the Msg/MsgWithdrawBurnUndelegate response type. -type MsgWithdrawBurnUndelegateResponse struct { -} - -func (m *MsgWithdrawBurnUndelegateResponse) Reset() { *m = MsgWithdrawBurnUndelegateResponse{} } -func (m *MsgWithdrawBurnUndelegateResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawBurnUndelegateResponse) ProtoMessage() {} -func (*MsgWithdrawBurnUndelegateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63015631bbbf9425, []int{7} -} -func (m *MsgWithdrawBurnUndelegateResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawBurnUndelegateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawBurnUndelegateResponse.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 *MsgWithdrawBurnUndelegateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawBurnUndelegateResponse.Merge(m, src) -} -func (m *MsgWithdrawBurnUndelegateResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawBurnUndelegateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawBurnUndelegateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawBurnUndelegateResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgMintDeposit)(nil), "kava.router.v1beta1.MsgMintDeposit") - proto.RegisterType((*MsgMintDepositResponse)(nil), "kava.router.v1beta1.MsgMintDepositResponse") - proto.RegisterType((*MsgDelegateMintDeposit)(nil), "kava.router.v1beta1.MsgDelegateMintDeposit") - proto.RegisterType((*MsgDelegateMintDepositResponse)(nil), "kava.router.v1beta1.MsgDelegateMintDepositResponse") - proto.RegisterType((*MsgWithdrawBurn)(nil), "kava.router.v1beta1.MsgWithdrawBurn") - proto.RegisterType((*MsgWithdrawBurnResponse)(nil), "kava.router.v1beta1.MsgWithdrawBurnResponse") - proto.RegisterType((*MsgWithdrawBurnUndelegate)(nil), "kava.router.v1beta1.MsgWithdrawBurnUndelegate") - proto.RegisterType((*MsgWithdrawBurnUndelegateResponse)(nil), "kava.router.v1beta1.MsgWithdrawBurnUndelegateResponse") -} - -func init() { proto.RegisterFile("kava/router/v1beta1/tx.proto", fileDescriptor_63015631bbbf9425) } - -var fileDescriptor_63015631bbbf9425 = []byte{ - // 472 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x54, 0xcf, 0x6b, 0x13, 0x41, - 0x14, 0xde, 0x31, 0xa5, 0x90, 0x57, 0x51, 0xd8, 0x96, 0x9a, 0x2c, 0x65, 0x8c, 0xa9, 0x87, 0x80, - 0xed, 0x2c, 0x6d, 0xa1, 0x9e, 0x8d, 0xc5, 0x5b, 0x2e, 0x11, 0x11, 0xbc, 0x94, 0xd9, 0xec, 0x38, - 0x1d, 0x4c, 0x66, 0xc2, 0xcc, 0x6c, 0x5a, 0x6f, 0xfe, 0x09, 0x9e, 0xbc, 0xea, 0xcd, 0x7f, 0xc0, - 0xbf, 0x41, 0x72, 0x2c, 0x9e, 0x3c, 0x89, 0x26, 0xff, 0x88, 0xec, 0xcf, 0x34, 0x65, 0x17, 0xd3, - 0x83, 0xd0, 0xdb, 0xdb, 0xf7, 0x7d, 0xef, 0x7b, 0xdf, 0x07, 0x6f, 0x07, 0x76, 0xde, 0xd1, 0x09, - 0xf5, 0xb5, 0x8a, 0x2c, 0xd3, 0xfe, 0xe4, 0x20, 0x60, 0x96, 0x1e, 0xf8, 0xf6, 0x82, 0x8c, 0xb5, - 0xb2, 0xca, 0xdd, 0x8c, 0x51, 0x92, 0xa2, 0x24, 0x43, 0x3d, 0x3c, 0x50, 0x66, 0xa4, 0x8c, 0x1f, - 0x50, 0xc3, 0x8a, 0x91, 0x81, 0x12, 0x32, 0x1d, 0xf2, 0x9a, 0x29, 0x7e, 0x9a, 0x7c, 0xf9, 0xe9, - 0x47, 0x06, 0x6d, 0x71, 0xc5, 0x55, 0xda, 0x8f, 0xab, 0xb4, 0xdb, 0xfe, 0x8c, 0xe0, 0x5e, 0xcf, - 0xf0, 0x9e, 0x90, 0xf6, 0x84, 0x8d, 0x95, 0x11, 0xd6, 0x3d, 0x86, 0x7a, 0x98, 0x96, 0x4a, 0x37, - 0x50, 0x0b, 0x75, 0xea, 0xdd, 0xc6, 0x8f, 0x6f, 0xfb, 0x5b, 0x99, 0xda, 0xb3, 0x30, 0xd4, 0xcc, - 0x98, 0x97, 0x56, 0x0b, 0xc9, 0xfb, 0x0b, 0xaa, 0xbb, 0x03, 0xf5, 0x09, 0x1d, 0x8a, 0x90, 0xc6, - 0x73, 0x77, 0xe2, 0xb9, 0xfe, 0xa2, 0xe1, 0x3e, 0x85, 0x75, 0x3a, 0x52, 0x91, 0xb4, 0x8d, 0x5a, - 0x0b, 0x75, 0x36, 0x0e, 0x9b, 0x24, 0xd3, 0x8b, 0xa3, 0xe4, 0xf9, 0xc8, 0x73, 0x25, 0x64, 0x77, - 0x6d, 0xfa, 0xeb, 0xa1, 0xd3, 0xcf, 0xe8, 0xed, 0x06, 0x6c, 0x2f, 0x1b, 0xec, 0x33, 0x33, 0x56, - 0xd2, 0xb0, 0xf6, 0x57, 0x94, 0x40, 0x27, 0x6c, 0xc8, 0x38, 0xb5, 0xec, 0x16, 0x67, 0x68, 0x01, - 0x2e, 0x37, 0x5a, 0x64, 0xf9, 0x84, 0xe0, 0x7e, 0xcf, 0xf0, 0xd7, 0xc2, 0x9e, 0x85, 0x9a, 0x9e, - 0x77, 0x23, 0x2d, 0xdd, 0x3d, 0x58, 0x7b, 0xab, 0xd5, 0xe8, 0x9f, 0xfe, 0x13, 0xd6, 0xff, 0xb2, - 0xde, 0x84, 0x07, 0xd7, 0x7c, 0x15, 0x9e, 0xbf, 0x20, 0x68, 0x5e, 0xc3, 0x5e, 0xc9, 0x30, 0x0b, - 0x79, 0x3b, 0xdc, 0xef, 0xc2, 0xa3, 0x4a, 0x87, 0x79, 0x8e, 0xc3, 0xef, 0x35, 0xa8, 0xf5, 0x0c, - 0x77, 0x4f, 0x61, 0xe3, 0xea, 0x0d, 0xed, 0x92, 0x92, 0x3f, 0x90, 0x2c, 0xdf, 0xa2, 0xf7, 0x64, - 0x05, 0x52, 0xbe, 0xc8, 0x3d, 0x87, 0xcd, 0xb2, 0x63, 0xad, 0xd4, 0x28, 0x21, 0x7b, 0x47, 0x37, - 0x20, 0x17, 0x8b, 0x03, 0xb8, 0xbb, 0x74, 0x59, 0x8f, 0xab, 0x44, 0xae, 0xb2, 0xbc, 0xbd, 0x55, - 0x58, 0xc5, 0x8e, 0x0f, 0x08, 0xb6, 0x2b, 0x4e, 0x81, 0xac, 0x22, 0xb4, 0xe0, 0x7b, 0xc7, 0x37, - 0xe3, 0xe7, 0x16, 0xba, 0x2f, 0xa6, 0x7f, 0xb0, 0x33, 0x9d, 0x61, 0x74, 0x39, 0xc3, 0xe8, 0xf7, - 0x0c, 0xa3, 0x8f, 0x73, 0xec, 0x5c, 0xce, 0xb1, 0xf3, 0x73, 0x8e, 0x9d, 0x37, 0x1d, 0x2e, 0xec, - 0x59, 0x14, 0x90, 0x81, 0x1a, 0xf9, 0xb1, 0xfe, 0xfe, 0x90, 0x06, 0x26, 0xa9, 0xfc, 0x8b, 0xfc, - 0x15, 0xb6, 0xef, 0xc7, 0xcc, 0x04, 0xeb, 0xc9, 0xdb, 0x78, 0xf4, 0x37, 0x00, 0x00, 0xff, 0xff, - 0x14, 0x23, 0x1c, 0x49, 0xa1, 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 - -// 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 { - // MintDeposit converts a delegation into staking derivatives and deposits it all into an earn vault. - MintDeposit(ctx context.Context, in *MsgMintDeposit, opts ...grpc.CallOption) (*MsgMintDepositResponse, error) - // DelegateMintDeposit delegates tokens to a validator, then converts them into staking derivatives, - // then deposits to an earn vault. - DelegateMintDeposit(ctx context.Context, in *MsgDelegateMintDeposit, opts ...grpc.CallOption) (*MsgDelegateMintDepositResponse, error) - // WithdrawBurn removes staking derivatives from an earn vault and converts them back to a staking delegation. - WithdrawBurn(ctx context.Context, in *MsgWithdrawBurn, opts ...grpc.CallOption) (*MsgWithdrawBurnResponse, error) - // WithdrawBurnUndelegate removes staking derivatives from an earn vault, converts them to a staking delegation, - // then undelegates them from their validator. - WithdrawBurnUndelegate(ctx context.Context, in *MsgWithdrawBurnUndelegate, opts ...grpc.CallOption) (*MsgWithdrawBurnUndelegateResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) MintDeposit(ctx context.Context, in *MsgMintDeposit, opts ...grpc.CallOption) (*MsgMintDepositResponse, error) { - out := new(MsgMintDepositResponse) - err := c.cc.Invoke(ctx, "/kava.router.v1beta1.Msg/MintDeposit", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) DelegateMintDeposit(ctx context.Context, in *MsgDelegateMintDeposit, opts ...grpc.CallOption) (*MsgDelegateMintDepositResponse, error) { - out := new(MsgDelegateMintDepositResponse) - err := c.cc.Invoke(ctx, "/kava.router.v1beta1.Msg/DelegateMintDeposit", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) WithdrawBurn(ctx context.Context, in *MsgWithdrawBurn, opts ...grpc.CallOption) (*MsgWithdrawBurnResponse, error) { - out := new(MsgWithdrawBurnResponse) - err := c.cc.Invoke(ctx, "/kava.router.v1beta1.Msg/WithdrawBurn", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) WithdrawBurnUndelegate(ctx context.Context, in *MsgWithdrawBurnUndelegate, opts ...grpc.CallOption) (*MsgWithdrawBurnUndelegateResponse, error) { - out := new(MsgWithdrawBurnUndelegateResponse) - err := c.cc.Invoke(ctx, "/kava.router.v1beta1.Msg/WithdrawBurnUndelegate", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // MintDeposit converts a delegation into staking derivatives and deposits it all into an earn vault. - MintDeposit(context.Context, *MsgMintDeposit) (*MsgMintDepositResponse, error) - // DelegateMintDeposit delegates tokens to a validator, then converts them into staking derivatives, - // then deposits to an earn vault. - DelegateMintDeposit(context.Context, *MsgDelegateMintDeposit) (*MsgDelegateMintDepositResponse, error) - // WithdrawBurn removes staking derivatives from an earn vault and converts them back to a staking delegation. - WithdrawBurn(context.Context, *MsgWithdrawBurn) (*MsgWithdrawBurnResponse, error) - // WithdrawBurnUndelegate removes staking derivatives from an earn vault, converts them to a staking delegation, - // then undelegates them from their validator. - WithdrawBurnUndelegate(context.Context, *MsgWithdrawBurnUndelegate) (*MsgWithdrawBurnUndelegateResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) MintDeposit(ctx context.Context, req *MsgMintDeposit) (*MsgMintDepositResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method MintDeposit not implemented") -} -func (*UnimplementedMsgServer) DelegateMintDeposit(ctx context.Context, req *MsgDelegateMintDeposit) (*MsgDelegateMintDepositResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DelegateMintDeposit not implemented") -} -func (*UnimplementedMsgServer) WithdrawBurn(ctx context.Context, req *MsgWithdrawBurn) (*MsgWithdrawBurnResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method WithdrawBurn not implemented") -} -func (*UnimplementedMsgServer) WithdrawBurnUndelegate(ctx context.Context, req *MsgWithdrawBurnUndelegate) (*MsgWithdrawBurnUndelegateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method WithdrawBurnUndelegate not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_MintDeposit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgMintDeposit) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).MintDeposit(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.router.v1beta1.Msg/MintDeposit", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).MintDeposit(ctx, req.(*MsgMintDeposit)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_DelegateMintDeposit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgDelegateMintDeposit) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).DelegateMintDeposit(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.router.v1beta1.Msg/DelegateMintDeposit", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).DelegateMintDeposit(ctx, req.(*MsgDelegateMintDeposit)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_WithdrawBurn_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdrawBurn) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).WithdrawBurn(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.router.v1beta1.Msg/WithdrawBurn", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).WithdrawBurn(ctx, req.(*MsgWithdrawBurn)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_WithdrawBurnUndelegate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdrawBurnUndelegate) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).WithdrawBurnUndelegate(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.router.v1beta1.Msg/WithdrawBurnUndelegate", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).WithdrawBurnUndelegate(ctx, req.(*MsgWithdrawBurnUndelegate)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.router.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "MintDeposit", - Handler: _Msg_MintDeposit_Handler, - }, - { - MethodName: "DelegateMintDeposit", - Handler: _Msg_DelegateMintDeposit_Handler, - }, - { - MethodName: "WithdrawBurn", - Handler: _Msg_WithdrawBurn_Handler, - }, - { - MethodName: "WithdrawBurnUndelegate", - Handler: _Msg_WithdrawBurnUndelegate_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/router/v1beta1/tx.proto", -} - -func (m *MsgMintDeposit) 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 *MsgMintDeposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMintDeposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Validator) > 0 { - i -= len(m.Validator) - copy(dAtA[i:], m.Validator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Validator))) - i-- - dAtA[i] = 0x12 - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgMintDepositResponse) 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 *MsgMintDepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMintDepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgDelegateMintDeposit) 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 *MsgDelegateMintDeposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDelegateMintDeposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Validator) > 0 { - i -= len(m.Validator) - copy(dAtA[i:], m.Validator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Validator))) - i-- - dAtA[i] = 0x12 - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgDelegateMintDepositResponse) 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 *MsgDelegateMintDepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDelegateMintDepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawBurn) 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 *MsgWithdrawBurn) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawBurn) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Validator) > 0 { - i -= len(m.Validator) - copy(dAtA[i:], m.Validator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Validator))) - i-- - dAtA[i] = 0x12 - } - if len(m.From) > 0 { - i -= len(m.From) - copy(dAtA[i:], m.From) - i = encodeVarintTx(dAtA, i, uint64(len(m.From))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawBurnResponse) 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 *MsgWithdrawBurnResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawBurnResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawBurnUndelegate) 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 *MsgWithdrawBurnUndelegate) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawBurnUndelegate) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Validator) > 0 { - i -= len(m.Validator) - copy(dAtA[i:], m.Validator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Validator))) - i-- - dAtA[i] = 0x12 - } - if len(m.From) > 0 { - i -= len(m.From) - copy(dAtA[i:], m.From) - i = encodeVarintTx(dAtA, i, uint64(len(m.From))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawBurnUndelegateResponse) 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 *MsgWithdrawBurnUndelegateResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawBurnUndelegateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgMintDeposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Validator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgMintDepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgDelegateMintDeposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Validator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgDelegateMintDepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgWithdrawBurn) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.From) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Validator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgWithdrawBurnResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgWithdrawBurnUndelegate) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.From) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Validator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgWithdrawBurnUndelegateResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgMintDeposit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgMintDeposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMintDeposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Validator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgMintDepositResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgMintDepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMintDepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDelegateMintDeposit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDelegateMintDeposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDelegateMintDeposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Validator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDelegateMintDepositResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDelegateMintDepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDelegateMintDepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawBurn) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawBurn: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawBurn: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.From = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Validator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawBurnResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawBurnResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawBurnResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawBurnUndelegate) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawBurnUndelegate: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawBurnUndelegate: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.From = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Validator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawBurnUndelegateResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawBurnUndelegateResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawBurnUndelegateResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/savings/client/cli/query.go b/x/savings/client/cli/query.go deleted file mode 100644 index be39f98f..00000000 --- a/x/savings/client/cli/query.go +++ /dev/null @@ -1,158 +0,0 @@ -package cli - -import ( - "context" - "fmt" - - "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/cosmos/cosmos-sdk/version" - - "github.com/kava-labs/kava/x/savings/types" -) - -// flags for cli queries -const ( - flagDenom = "denom" - flagOwner = "owner" -) - -// GetQueryCmd returns the cli query commands for this module -func GetQueryCmd() *cobra.Command { - savingsQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the savings module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - GetCmdQueryParams(), - queryDepositsCmd(), - GetCmdTotalSupply(), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - savingsQueryCmd.AddCommand(cmds...) - - return savingsQueryCmd -} - -// GetCmdQueryParams queries the savings module parameters -func GetCmdQueryParams() *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: "get the savings module parameters", - Long: "Get the current global savings module parameters.", - 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(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } -} - -func queryDepositsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "deposits", - Short: "query savings module deposits with optional filters", - Long: "query for all savings module deposits or a specific deposit using flags", - Example: fmt.Sprintf(`%[1]s q %[2]s deposits -%[1]s q %[2]s deposits --owner kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny --denom bnb -%[1]s q %[2]s deposits --denom ukava -%[1]s q %[2]s deposits --denom btcb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - ownerBech, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - req := &types.QueryDepositsRequest{ - Denom: denom, - Pagination: pageReq, - } - - if len(ownerBech) != 0 { - depositOwner, err := sdk.AccAddressFromBech32(ownerBech) - if err != nil { - return err - } - req.Owner = depositOwner.String() - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Deposits(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, "deposits") - - cmd.Flags().String(flagOwner, "", "(optional) filter for deposits by owner address") - cmd.Flags().String(flagDenom, "", "(optional) filter for deposits by denom") - - return cmd -} - -// GetCmdTotalSupply returns the command that queries total supply locked into savings module -func GetCmdTotalSupply() *cobra.Command { - return &cobra.Command{ - Use: "total-supply", - Short: "get total supply locked into savings module", - Long: "Get the sum of all denoms locked into the savings 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.TotalSupply(context.Background(), &types.QueryTotalSupplyRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} diff --git a/x/savings/client/cli/tx.go b/x/savings/client/cli/tx.go deleted file mode 100644 index 469a9936..00000000 --- a/x/savings/client/cli/tx.go +++ /dev/null @@ -1,91 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/kava-labs/kava/x/savings/types" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - savingsTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "savings transactions subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - getCmdDeposit(), - getCmdWithdraw(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - savingsTxCmd.AddCommand(cmds...) - - return savingsTxCmd -} - -func getCmdDeposit() *cobra.Command { - return &cobra.Command{ - Use: "deposit [amount]", - Short: "deposit coins to savings", - Example: fmt.Sprintf( - `%s tx %s deposit 10000000ukava,100000000usdx --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - amount, err := sdk.ParseCoinsNormalized(args[0]) - if err != nil { - return err - } - msg := types.NewMsgDeposit(clientCtx.GetFromAddress(), amount) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -func getCmdWithdraw() *cobra.Command { - return &cobra.Command{ - Use: "withdraw [amount]", - Short: "withdraw coins from savings", - Example: fmt.Sprintf( - `%s tx %s withdraw 10000000ukava,100000000usdx --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - amount, err := sdk.ParseCoinsNormalized(args[0]) - if err != nil { - return err - } - msg := types.NewMsgWithdraw(clientCtx.GetFromAddress(), amount) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} diff --git a/x/savings/genesis.go b/x/savings/genesis.go deleted file mode 100644 index 9f67544f..00000000 --- a/x/savings/genesis.go +++ /dev/null @@ -1,36 +0,0 @@ -package savings - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/savings/keeper" - "github.com/kava-labs/kava/x/savings/types" -) - -// InitGenesis initializes genesis state -func InitGenesis(ctx sdk.Context, k keeper.Keeper, ak types.AccountKeeper, gs types.GenesisState) { - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - k.SetParams(ctx, gs.Params) - - for _, deposit := range gs.Deposits { - k.SetDeposit(ctx, deposit) - } - - // check if the module account exists - SavingsModuleAccount := ak.GetModuleAccount(ctx, types.ModuleAccountName) - if SavingsModuleAccount == nil { - panic(fmt.Sprintf("%s module account has not been set", SavingsModuleAccount)) - } -} - -// ExportGenesis returns a GenesisState for a given context and keeper -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { - params := k.GetParams(ctx) - deposits := k.GetAllDeposits(ctx) - return types.NewGenesisState(params, deposits) -} diff --git a/x/savings/genesis_test.go b/x/savings/genesis_test.go deleted file mode 100644 index d2becb56..00000000 --- a/x/savings/genesis_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package savings_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/savings" - "github.com/kava-labs/kava/x/savings/keeper" - "github.com/kava-labs/kava/x/savings/types" -) - -type GenesisTestSuite struct { - suite.Suite - - app app.TestApp - genTime time.Time - ctx sdk.Context - keeper keeper.Keeper - addrs []sdk.AccAddress -} - -func (suite *GenesisTestSuite) SetupTest() { - tApp := app.NewTestApp() - suite.genTime = tmtime.Canonical(time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC)) - suite.ctx = tApp.NewContext(true, tmproto.Header{Height: 1, Time: suite.genTime}) - suite.keeper = tApp.GetSavingsKeeper() - suite.app = tApp - - _, addrs := app.GeneratePrivKeyAddressPairs(3) - suite.addrs = addrs -} - -func (suite *GenesisTestSuite) TestInitExportGenesis() { - params := types.NewParams( - []string{"btc", "ukava", "bnb"}, - ) - - depositAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e8))) - - deposits := types.Deposits{ - types.NewDeposit( - suite.addrs[0], - depositAmt, // 100 ukava - ), - } - savingsGenesis := types.NewGenesisState(params, deposits) - - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleModuleAccount(types.ModuleAccountName, depositAmt) - - cdc := suite.app.AppCodec() - suite.NotPanics( - func() { - suite.app.InitializeFromGenesisStatesWithTime( - suite.genTime, - authBuilder.BuildMarshalled(cdc), - app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&savingsGenesis)}, - ) - }, - ) - - expectedDeposits := suite.keeper.GetAllDeposits(suite.ctx) - expectedGenesis := savingsGenesis - expectedGenesis.Deposits = expectedDeposits - exportedGenesis := savings.ExportGenesis(suite.ctx, suite.keeper) - suite.Equal(expectedGenesis, exportedGenesis) -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(GenesisTestSuite)) -} diff --git a/x/savings/keeper/deposit.go b/x/savings/keeper/deposit.go deleted file mode 100644 index 3bb92265..00000000 --- a/x/savings/keeper/deposit.go +++ /dev/null @@ -1,89 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/savings/types" -) - -// Deposit deposit -func (k Keeper) Deposit(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error { - err := k.ValidateDeposit(ctx, coins) - if err != nil { - return err - } - - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, depositor, types.ModuleAccountName, coins) - if err != nil { - return err - } - - currDeposit, foundDeposit := k.GetDeposit(ctx, depositor) - - deposit := types.NewDeposit(depositor, coins) - if foundDeposit { - deposit.Amount = deposit.Amount.Add(currDeposit.Amount...) - k.BeforeSavingsDepositModified(ctx, deposit, setDifference(getDenoms(coins), getDenoms(deposit.Amount))) - - } - - k.SetDeposit(ctx, deposit) - - if !foundDeposit { - k.AfterSavingsDepositCreated(ctx, deposit) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeSavingsDeposit, - sdk.NewAttribute(sdk.AttributeKeyAmount, coins.String()), - sdk.NewAttribute(types.AttributeKeyDepositor, deposit.Depositor.String()), - ), - ) - - return nil -} - -// ValidateDeposit validates a deposit -func (k Keeper) ValidateDeposit(ctx sdk.Context, coins sdk.Coins) error { - for _, coin := range coins { - supported := k.IsDenomSupported(ctx, coin.Denom) - if !supported { - return errorsmod.Wrapf(types.ErrInvalidDepositDenom, ": %s", coin.Denom) - } - } - - return nil -} - -// GetTotalDeposited returns the total amount deposited for the deposit denom -func (k Keeper) GetTotalDeposited(ctx sdk.Context, depositDenom string) (total sdkmath.Int) { - macc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - return k.bankKeeper.GetBalance(ctx, macc.GetAddress(), depositDenom).Amount -} - -// Set setDifference: A - B -func setDifference(a, b []string) (diff []string) { - m := make(map[string]bool) - - for _, item := range b { - m[item] = true - } - - for _, item := range a { - if _, ok := m[item]; !ok { - diff = append(diff, item) - } - } - return -} - -func getDenoms(coins sdk.Coins) []string { - denoms := []string{} - for _, coin := range coins { - denoms = append(denoms, coin.Denom) - } - return denoms -} diff --git a/x/savings/keeper/deposit_test.go b/x/savings/keeper/deposit_test.go deleted file mode 100644 index c6e4e2ca..00000000 --- a/x/savings/keeper/deposit_test.go +++ /dev/null @@ -1,214 +0,0 @@ -package keeper_test - -import ( - "fmt" - "strings" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/savings/types" -) - -func (suite *KeeperTestSuite) TestDeposit() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, delegator := addrs[0], addrs[1] - - valAddr := sdk.ValAddress(valAccAddr) - initialBalance := sdkmath.NewInt(1e9) - - bkavaDenom := fmt.Sprintf("bkava-%s", valAddr.String()) - invalidBkavaDenom := fmt.Sprintf("bkava-%s", sdk.ValAddress(addrs[2]).String()) - - type args struct { - allowedDenoms []string - depositor sdk.AccAddress - initialDepositorBalance sdk.Coins - depositAmount sdk.Coins - numberDeposits int - expectedAccountBalance sdk.Coins - expectedModAccountBalance sdk.Coins - expectedDepositCoins sdk.Coins - } - type errArgs struct { - expectPass bool - contains string - } - type depositTest struct { - name string - args args - errArgs errArgs - } - testCases := []depositTest{ - { - "valid", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - numberDeposits: 1, - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(900)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - expectedDepositCoins: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid multi deposit", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - numberDeposits: 2, - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(800)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - expectedDepositCoins: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid bkava", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava", "bkava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(100))), - numberDeposits: 1, - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(900)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(100))), - expectedDepositCoins: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(100))), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid deposit denom", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin("fake", sdkmath.NewInt(100))), - numberDeposits: 1, - expectedAccountBalance: sdk.Coins{}, - expectedModAccountBalance: sdk.Coins{}, - expectedDepositCoins: sdk.Coins{}, - }, - errArgs{ - expectPass: false, - contains: "invalid deposit denom", - }, - }, - { - "invalid bkava", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava", "bkava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin(invalidBkavaDenom, sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin(invalidBkavaDenom, sdkmath.NewInt(100))), - numberDeposits: 1, - expectedAccountBalance: sdk.Coins{}, - expectedModAccountBalance: sdk.Coins{}, - expectedDepositCoins: sdk.Coins{}, - }, - errArgs{ - expectPass: false, - contains: "invalid deposit denom", - }, - }, - { - "insufficient funds", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10000))), - numberDeposits: 1, - expectedAccountBalance: sdk.Coins{}, - expectedModAccountBalance: sdk.Coins{}, - expectedDepositCoins: sdk.Coins{}, - }, - errArgs{ - expectPass: false, - contains: "insufficient funds", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // create new app with one funded account - - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{tc.args.initialDepositorBalance}, - []sdk.AccAddress{tc.args.depositor}, - ) - savingsGS := types.NewGenesisState( - types.NewParams(tc.args.allowedDenoms), - types.Deposits{}, - ) - - stakingParams := stakingtypes.DefaultParams() - stakingParams.BondDenom = "ukava" - - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&savingsGS)}, - app.GenesisState{stakingtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(stakingtypes.NewGenesisState(stakingParams, nil, nil))}, - ) - keeper := tApp.GetSavingsKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - - // Create validator and delegate for bkava - suite.CreateAccountWithAddress(valAccAddr, cs(c("ukava", 100e10))) - suite.CreateAccountWithAddress(delegator, cs(c("ukava", 100e10))) - - suite.CreateNewUnbondedValidator(valAddr, initialBalance) - suite.CreateDelegation(valAddr, delegator, initialBalance) - staking.EndBlocker(suite.ctx, suite.app.GetStakingKeeper()) - - // run the test - var err error - for i := 0; i < tc.args.numberDeposits; i++ { - err = suite.keeper.Deposit(suite.ctx, tc.args.depositor, tc.args.depositAmount) - } - - // verify results - if tc.errArgs.expectPass { - suite.Require().NoError(err) - acc := suite.getAccount(tc.args.depositor) - suite.Require().Equal(tc.args.expectedAccountBalance, suite.getAccountCoins(acc)) - mAcc := suite.getModuleAccount(types.ModuleAccountName) - suite.Require().Equal(tc.args.expectedModAccountBalance, suite.getAccountCoins(mAcc)) - dep, f := suite.keeper.GetDeposit(suite.ctx, tc.args.depositor) - suite.Require().True(f) - suite.Require().Equal(tc.args.expectedDepositCoins, dep.Amount) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } diff --git a/x/savings/keeper/diff_test.go b/x/savings/keeper/diff_test.go deleted file mode 100644 index a032a06c..00000000 --- a/x/savings/keeper/diff_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestSetDiff(t *testing.T) { - tests := []struct { - name string - setA []string - setB []string - expected []string - }{ - {"empty", []string{}, []string{}, []string(nil)}, - {"diff equal sets", []string{"busd", "usdx"}, []string{"busd", "usdx"}, []string(nil)}, - {"diff set empty", []string{"bnb", "ukava", "usdx"}, []string{}, []string{"bnb", "ukava", "usdx"}}, - {"input set empty", []string{}, []string{"bnb", "ukava", "usdx"}, []string(nil)}, - {"diff set with common elements", []string{"bnb", "btcb", "usdx", "xrpb"}, []string{"bnb", "usdx"}, []string{"btcb", "xrpb"}}, - {"diff set with all common elements", []string{"bnb", "usdx"}, []string{"bnb", "btcb", "usdx", "xrpb"}, []string(nil)}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - require.Equal(t, tt.expected, setDifference(tt.setA, tt.setB)) - }) - } -} diff --git a/x/savings/keeper/grpc_query.go b/x/savings/keeper/grpc_query.go deleted file mode 100644 index f99c82af..00000000 --- a/x/savings/keeper/grpc_query.go +++ /dev/null @@ -1,142 +0,0 @@ -package keeper - -import ( - "context" - "strings" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/types/query" - - "github.com/kava-labs/kava/x/savings/types" -) - -type queryServer struct { - keeper Keeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -var _ types.QueryServer = queryServer{} - -// Params implements the gRPC service handler for querying x/savings parameters. -func (s queryServer) Params(c context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(c) - params := s.keeper.GetParams(sdkCtx) - - return &types.QueryParamsResponse{Params: params}, nil -} - -func (s queryServer) Deposits(ctx context.Context, req *types.QueryDepositsRequest) (*types.QueryDepositsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - hasDenom := len(req.Denom) > 0 - hasOwner := len(req.Owner) > 0 - - var owner sdk.AccAddress - var err error - if hasOwner { - owner, err = sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - } - - var deposits types.Deposits - switch { - case hasOwner && hasDenom: - deposit, found := s.keeper.GetDeposit(sdkCtx, owner) - if found { - for _, coin := range deposit.Amount { - if coin.Denom == req.Denom { - deposits = append(deposits, deposit) - } - } - } - case hasOwner: - deposit, found := s.keeper.GetDeposit(sdkCtx, owner) - if found { - deposits = append(deposits, deposit) - } - case hasDenom: - s.keeper.IterateDeposits(sdkCtx, func(deposit types.Deposit) (stop bool) { - if deposit.Amount.AmountOf(req.Denom).IsPositive() { - deposits = append(deposits, deposit) - } - return false - }) - default: - s.keeper.IterateDeposits(sdkCtx, func(deposit types.Deposit) (stop bool) { - deposits = append(deposits, deposit) - return false - }) - } - - page, limit, err := query.ParsePagination(req.Pagination) - if err != nil { - return nil, err - } - - start, end := client.Paginate(len(deposits), page, limit, 100) - if start < 0 || end < 0 { - deposits = types.Deposits{} - } else { - deposits = deposits[start:end] - } - - return &types.QueryDepositsResponse{ - Deposits: deposits, - Pagination: nil, - }, nil -} - -func (s queryServer) TotalSupply(ctx context.Context, req *types.QueryTotalSupplyRequest) (*types.QueryTotalSupplyResponse, error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) - totalSupply := sdk.NewCoins() - liquidStakedDerivatives := sdk.NewCoins() - - s.keeper.IterateDeposits(sdkCtx, func(deposit types.Deposit) (stop bool) { - for _, c := range deposit.Amount { - // separate out bkava denoms - if strings.HasPrefix(c.Denom, bkavaPrefix) { - liquidStakedDerivatives = liquidStakedDerivatives.Add(c) - } else { - totalSupply = totalSupply.Add(c) - } - } - return false - }) - - // determine underlying value of bkava denoms - if len(liquidStakedDerivatives) > 0 { - underlyingValue, err := s.keeper.liquidKeeper.GetStakedTokensForDerivatives( - sdkCtx, - liquidStakedDerivatives, - ) - if err != nil { - return nil, err - } - totalSupply = totalSupply.Add(sdk.NewCoin(bkavaDenom, underlyingValue.Amount)) - } - - return &types.QueryTotalSupplyResponse{ - Height: sdkCtx.BlockHeight(), - Result: totalSupply, - }, nil -} diff --git a/x/savings/keeper/grpcquery_test.go b/x/savings/keeper/grpcquery_test.go deleted file mode 100644 index 87081302..00000000 --- a/x/savings/keeper/grpcquery_test.go +++ /dev/null @@ -1,354 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/kava-labs/kava/app" - liquidtypes "github.com/kava-labs/kava/x/liquid/types" - "github.com/kava-labs/kava/x/savings/keeper" - "github.com/kava-labs/kava/x/savings/types" -) - -var dep = types.NewDeposit - -const ( - bkava1 = "bkava-kavavaloper15gqc744d05xacn4n6w2furuads9fu4pqn6zxlu" - bkava2 = "bkava-kavavaloper15qdefkmwswysgg4qxgqpqr35k3m49pkx8yhpte" -) - -type grpcQueryTestSuite struct { - suite.Suite - - tApp app.TestApp - ctx sdk.Context - keeper keeper.Keeper - queryServer types.QueryServer - addrs []sdk.AccAddress -} - -func (suite *grpcQueryTestSuite) SetupTest() { - suite.tApp = app.NewTestApp() - _, addrs := app.GeneratePrivKeyAddressPairs(2) - - suite.addrs = addrs - - suite.ctx = suite.tApp.NewContext(true, tmprototypes.Header{}). - WithBlockTime(time.Now().UTC()) - suite.keeper = suite.tApp.GetSavingsKeeper() - suite.queryServer = keeper.NewQueryServerImpl(suite.keeper) - - err := suite.tApp.FundModuleAccount( - suite.ctx, - types.ModuleAccountName, - cs( - c("usdx", 10000000000), - c("busd", 10000000000), - ), - ) - suite.Require().NoError(err) - - savingsGenesis := types.GenesisState{ - Params: types.NewParams([]string{"bnb", "busd", bkava1, bkava2}), - } - savingsGenState := app.GenesisState{types.ModuleName: suite.tApp.AppCodec().MustMarshalJSON(&savingsGenesis)} - - suite.tApp.InitializeFromGenesisStates( - savingsGenState, - app.NewFundedGenStateWithSameCoins( - suite.tApp.AppCodec(), - cs( - c("bnb", 10000000000), - c("busd", 20000000000), - ), - addrs, - ), - ) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryParams() { - res, err := suite.queryServer.Params(sdk.WrapSDKContext(suite.ctx), &types.QueryParamsRequest{}) - suite.Require().NoError(err) - - var expected types.GenesisState - savingsGenesis := types.GenesisState{ - Params: types.NewParams([]string{"bnb", "busd", bkava1, bkava2}), - } - savingsGenState := app.GenesisState{types.ModuleName: suite.tApp.AppCodec().MustMarshalJSON(&savingsGenesis)} - suite.tApp.AppCodec().MustUnmarshalJSON(savingsGenState[types.ModuleName], &expected) - - suite.Equal(expected.Params, res.Params, "params should equal test genesis state") -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryDeposits() { - suite.addDeposits([]types.Deposit{ - dep(suite.addrs[0], cs(c("bnb", 100000000))), - dep(suite.addrs[1], cs(c("bnb", 20000000))), - dep(suite.addrs[0], cs(c("busd", 20000000))), - dep(suite.addrs[0], cs(c("busd", 8000000))), - }) - - tests := []struct { - giveName string - giveRequest *types.QueryDepositsRequest - wantDepositCounts int - shouldError bool - errorSubstr string - }{ - { - "empty query", - &types.QueryDepositsRequest{}, - 2, - false, - "", - }, - { - "owner", - &types.QueryDepositsRequest{ - Owner: suite.addrs[0].String(), - }, - // Excludes the second address - 1, - false, - "", - }, - { - "invalid owner", - &types.QueryDepositsRequest{ - Owner: "invalid address", - }, - // No deposits - 0, - true, - "decoding bech32 failed", - }, - { - "owner and denom", - &types.QueryDepositsRequest{ - Owner: suite.addrs[0].String(), - Denom: "bnb", - }, - // Only the first one - 1, - false, - "", - }, - { - "owner and invalid denom empty response", - &types.QueryDepositsRequest{ - Owner: suite.addrs[0].String(), - Denom: "invalid denom", - }, - 0, - false, - "", - }, - { - "denom", - &types.QueryDepositsRequest{ - Denom: "bnb", - }, - 2, - false, - "", - }, - } - - for _, tt := range tests { - suite.Run(tt.giveName, func() { - res, err := suite.queryServer.Deposits(sdk.WrapSDKContext(suite.ctx), tt.giveRequest) - - if tt.shouldError { - suite.Error(err) - suite.Contains(err.Error(), tt.errorSubstr) - } else { - suite.NoError(err) - suite.Equal(tt.wantDepositCounts, len(res.Deposits)) - } - }) - } -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalSupply() { - testCases := []struct { - name string - deposits types.Deposits - expectedSupply sdk.Coins - }{ - { - name: "returns zeros when there's no supply", - deposits: []types.Deposit{}, - expectedSupply: sdk.NewCoins(), - }, - { - name: "returns supply of one denom deposited from multiple accounts", - deposits: []types.Deposit{ - dep(suite.addrs[0], sdk.NewCoins(c("busd", 1e6))), - dep(suite.addrs[1], sdk.NewCoins(c("busd", 1e6))), - }, - expectedSupply: sdk.NewCoins(c("busd", 2e6)), - }, - { - name: "returns supply of multiple denoms deposited from single account", - deposits: []types.Deposit{ - dep(suite.addrs[0], sdk.NewCoins(c("busd", 1e6), c("bnb", 1e6))), - }, - expectedSupply: sdk.NewCoins(c("busd", 1e6), c("bnb", 1e6)), - }, - { - name: "returns supply of multiple denoms deposited from multiple accounts", - deposits: []types.Deposit{ - dep(suite.addrs[0], sdk.NewCoins(c("busd", 1e6), c("bnb", 1e6))), - dep(suite.addrs[1], sdk.NewCoins(c("busd", 1e6), c("bnb", 1e6))), - }, - expectedSupply: sdk.NewCoins(c("busd", 2e6), c("bnb", 2e6)), - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - // setup deposits - suite.addDeposits(tc.deposits) - - res, err := suite.queryServer.TotalSupply( - sdk.WrapSDKContext(suite.ctx), - &types.QueryTotalSupplyRequest{}, - ) - suite.Require().NoError(err) - suite.Require().Equal(tc.expectedSupply, res.Result) - }) - } - - suite.Run("aggregates bkava denoms, accounting for slashing", func() { - suite.SetupTest() - - address1, derivatives1, _ := suite.createAccountWithDerivatives(bkava1, sdkmath.NewInt(1e9)) - address2, derivatives2, _ := suite.createAccountWithDerivatives(bkava2, sdkmath.NewInt(1e9)) - - // bond validators - staking.EndBlocker(suite.ctx, suite.tApp.GetStakingKeeper()) - // slash val2 - its shares are now 80% as valuable! - err := suite.slashValidator(sdk.ValAddress(address2), sdk.MustNewDecFromStr("0.2")) - suite.Require().NoError(err) - - suite.addDeposits( - types.Deposits{ - dep(address1, cs(derivatives1)), - dep(address2, cs(derivatives2)), - }, - ) - - expectedSupply := sdk.NewCoins( - sdk.NewCoin( - "bkava", - sdkmath.NewIntFromUint64(1e9). // derivative 1 - Add(sdkmath.NewInt(1e9).MulRaw(80).QuoRaw(100))), // derivative 2: original value * 80% - ) - - res, err := suite.queryServer.TotalSupply( - sdk.WrapSDKContext(suite.ctx), - &types.QueryTotalSupplyRequest{}, - ) - suite.Require().NoError(err) - suite.Require().Equal(expectedSupply, res.Result) - }) -} - -func (suite *grpcQueryTestSuite) addDeposits(deposits types.Deposits) { - for _, dep := range deposits { - suite.NotPanics(func() { - err := suite.keeper.Deposit(suite.ctx, dep.Depositor, dep.Amount) - suite.Require().NoError(err) - }) - } -} - -// createUnbondedValidator creates an unbonded validator with the given amount of self-delegation. -func (suite *grpcQueryTestSuite) createUnbondedValidator(address sdk.ValAddress, selfDelegation sdk.Coin, minSelfDelegation sdkmath.Int) error { - msg, err := stakingtypes.NewMsgCreateValidator( - address, - ed25519.GenPrivKey().PubKey(), - selfDelegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - minSelfDelegation, - ) - if err != nil { - return err - } - - msgServer := stakingkeeper.NewMsgServerImpl(suite.tApp.GetStakingKeeper()) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.ctx), msg) - return err -} - -// createAccountWithDerivatives creates an account with the given amount and denom of derivative token. -// Internally, it creates a validator account and mints derivatives from the validator's self delegation. -func (suite *grpcQueryTestSuite) createAccountWithDerivatives(denom string, amount sdkmath.Int) (sdk.AccAddress, sdk.Coin, sdk.Coins) { - bondDenom := suite.tApp.GetStakingKeeper().BondDenom(suite.ctx) - valAddress, err := liquidtypes.ParseLiquidStakingTokenDenom(denom) - suite.Require().NoError(err) - address := sdk.AccAddress(valAddress) - - remainingSelfDelegation := sdkmath.NewInt(1e6) - selfDelegation := sdk.NewCoin( - bondDenom, - amount.Add(remainingSelfDelegation), - ) - - // create & fund account - // ak := suite.tApp.GetAccountKeeper() - // acc := ak.NewAccountWithAddress(suite.ctx, address) - // ak.SetAccount(suite.ctx, acc) - err = suite.tApp.FundAccount(suite.ctx, address, sdk.NewCoins(selfDelegation)) - suite.Require().NoError(err) - - err = suite.createUnbondedValidator(valAddress, selfDelegation, remainingSelfDelegation) - suite.Require().NoError(err) - - toConvert := sdk.NewCoin(bondDenom, amount) - derivatives, err := suite.tApp.GetLiquidKeeper().MintDerivative(suite.ctx, - address, - valAddress, - toConvert, - ) - suite.Require().NoError(err) - - fullBalance := suite.tApp.GetBankKeeper().GetAllBalances(suite.ctx, address) - - return address, derivatives, fullBalance -} - -// slashValidator slashes the validator with the given address by the given percentage. -func (suite *grpcQueryTestSuite) slashValidator(address sdk.ValAddress, slashFraction sdk.Dec) error { - stakingKeeper := suite.tApp.GetStakingKeeper() - - validator, found := stakingKeeper.GetValidator(suite.ctx, address) - suite.Require().True(found) - consAddr, err := validator.GetConsAddr() - suite.Require().NoError(err) - - // Assume infraction was at current height. Note unbonding delegations and redelegations are only slashed if created after - // the infraction height so none will be slashed. - infractionHeight := suite.ctx.BlockHeight() - - power := stakingKeeper.TokensToConsensusPower(suite.ctx, validator.GetTokens()) - - stakingKeeper.Slash(suite.ctx, consAddr, infractionHeight, power, slashFraction) - return nil -} - -func TestGrpcQueryTestSuite(t *testing.T) { - suite.Run(t, new(grpcQueryTestSuite)) -} diff --git a/x/savings/keeper/hooks.go b/x/savings/keeper/hooks.go deleted file mode 100644 index 9bc577de..00000000 --- a/x/savings/keeper/hooks.go +++ /dev/null @@ -1,24 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/savings/types" -) - -// Implements StakingHooks interface -var _ types.SavingsHooks = Keeper{} - -// AfterSavingsDepositCreated - call hook if registered -func (k Keeper) AfterSavingsDepositCreated(ctx sdk.Context, deposit types.Deposit) { - if k.hooks != nil { - k.hooks.AfterSavingsDepositCreated(ctx, deposit) - } -} - -// BeforeSavingsDepositModified - call hook if registered -func (k Keeper) BeforeSavingsDepositModified(ctx sdk.Context, deposit types.Deposit, incomingDenoms []string) { - if k.hooks != nil { - k.hooks.BeforeSavingsDepositModified(ctx, deposit, incomingDenoms) - } -} diff --git a/x/savings/keeper/invariants.go b/x/savings/keeper/invariants.go deleted file mode 100644 index e963b597..00000000 --- a/x/savings/keeper/invariants.go +++ /dev/null @@ -1,67 +0,0 @@ -package keeper - -import ( - "github.com/kava-labs/kava/x/savings/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// RegisterInvariants registers the savings module invariants -func RegisterInvariants(ir sdk.InvariantRegistry, k Keeper) { - ir.RegisterRoute(types.ModuleName, "deposits", DepositsInvariant(k)) - ir.RegisterRoute(types.ModuleName, "solvency", SolvencyInvariant(k)) -} - -// AllInvariants runs all invariants of the savings module -func AllInvariants(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - if res, stop := DepositsInvariant(k)(ctx); stop { - return res, stop - } - - res, stop := SolvencyInvariant(k)(ctx) - return res, stop - } -} - -// DepositsInvariant iterates all deposits and asserts that they are valid -func DepositsInvariant(k Keeper) sdk.Invariant { - broken := false - message := sdk.FormatInvariant(types.ModuleName, "validate deposits broken", "deposit invalid") - - return func(ctx sdk.Context) (string, bool) { - k.IterateDeposits(ctx, func(deposit types.Deposit) bool { - if err := deposit.Validate(); err != nil { - broken = true - return true - } - if !deposit.Amount.IsAllPositive() { - broken = true - return true - } - return false - }) - - return message, broken - } -} - -// SolvencyInvariant iterates all deposits and ensures the total amount matches the module account coins -func SolvencyInvariant(k Keeper) sdk.Invariant { - message := sdk.FormatInvariant(types.ModuleName, "module solvency broken", "total deposited amount does not match module account") - - return func(ctx sdk.Context) (string, bool) { - balance := k.GetSavingsModuleAccountBalances(ctx) - - deposited := sdk.Coins{} - k.IterateDeposits(ctx, func(deposit types.Deposit) bool { - for _, coin := range deposit.Amount { - deposited = deposited.Add(coin) - } - return false - }) - - broken := !deposited.IsEqual(balance) - return message, broken - } -} diff --git a/x/savings/keeper/invariants_test.go b/x/savings/keeper/invariants_test.go deleted file mode 100644 index 866a5aed..00000000 --- a/x/savings/keeper/invariants_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package keeper_test - -import ( - "testing" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/savings/keeper" - "github.com/kava-labs/kava/x/savings/types" -) - -type invariantTestSuite struct { - suite.Suite - - tApp app.TestApp - ctx sdk.Context - keeper keeper.Keeper - bankKeeper bankkeeper.Keeper - addrs []sdk.AccAddress - invariants map[string]map[string]sdk.Invariant -} - -func (suite *invariantTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - _, addrs := app.GeneratePrivKeyAddressPairs(1) - suite.addrs = addrs - - suite.tApp = tApp - suite.ctx = ctx - suite.keeper = tApp.GetSavingsKeeper() - suite.bankKeeper = tApp.GetBankKeeper() - - suite.invariants = make(map[string]map[string]sdk.Invariant) - keeper.RegisterInvariants(suite, suite.keeper) -} - -func (suite *invariantTestSuite) RegisterRoute(moduleName string, route string, invariant sdk.Invariant) { - _, exists := suite.invariants[moduleName] - - if !exists { - suite.invariants[moduleName] = make(map[string]sdk.Invariant) - } - - suite.invariants[moduleName][route] = invariant -} - -func (suite *invariantTestSuite) SetupValidState() { - depositAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(2e8))) - - suite.keeper.SetDeposit(suite.ctx, types.NewDeposit( - suite.addrs[0], - depositAmt, - )) - - err := suite.tApp.FundModuleAccount(suite.ctx, types.ModuleName, depositAmt) - suite.Require().NoError(err) -} - -func (suite *invariantTestSuite) runInvariant(route string, invariant func(k keeper.Keeper) sdk.Invariant) (string, bool) { - ctx := suite.ctx - registeredInvariant := suite.invariants[types.ModuleName][route] - suite.Require().NotNil(registeredInvariant) - - // direct call - dMessage, dBroken := invariant(suite.keeper)(ctx) - // registered call - rMessage, rBroken := registeredInvariant(ctx) - // all call - aMessage, aBroken := keeper.AllInvariants(suite.keeper)(ctx) - - // require matching values for direct call and registered call - suite.Require().Equal(dMessage, rMessage, "expected registered invariant message to match") - suite.Require().Equal(dBroken, rBroken, "expected registered invariant broken to match") - // require matching values for direct call and all invariants call if broken - suite.Require().Equal(dBroken, aBroken, "expected all invariant broken to match") - if dBroken { - suite.Require().Equal(dMessage, aMessage, "expected all invariant message to match") - } - - // return message, broken - return dMessage, dBroken -} - -func (suite *invariantTestSuite) TestDepositsInvariant() { - message, broken := suite.runInvariant("deposits", keeper.DepositsInvariant) - suite.Equal("savings: validate deposits broken invariant\ndeposit invalid\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("deposits", keeper.DepositsInvariant) - suite.Equal("savings: validate deposits broken invariant\ndeposit invalid\n", message) - suite.Equal(false, broken) - - // broken with invalid deposit - suite.keeper.SetDeposit(suite.ctx, types.NewDeposit( - suite.addrs[0], - sdk.Coins{}, - )) - - message, broken = suite.runInvariant("deposits", keeper.DepositsInvariant) - suite.Equal("savings: validate deposits broken invariant\ndeposit invalid\n", message) - suite.Equal(true, broken) -} - -func (suite *invariantTestSuite) TestSolvencyInvariant() { - message, broken := suite.runInvariant("solvency", keeper.SolvencyInvariant) - suite.Equal("savings: module solvency broken invariant\ntotal deposited amount does not match module account\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("solvency", keeper.SolvencyInvariant) - suite.Equal("savings: module solvency broken invariant\ntotal deposited amount does not match module account\n", message) - suite.Equal(false, broken) - - // broken when deposits are greater than module balance - suite.keeper.SetDeposit(suite.ctx, types.NewDeposit( - suite.addrs[0], - sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(3e8))), - )) - - message, broken = suite.runInvariant("solvency", keeper.SolvencyInvariant) - suite.Equal("savings: module solvency broken invariant\ntotal deposited amount does not match module account\n", message) - suite.Equal(true, broken) - - // broken when deposits are less than the module balance - suite.keeper.SetDeposit(suite.ctx, types.NewDeposit( - suite.addrs[0], - sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e8))), - )) - - message, broken = suite.runInvariant("solvency", keeper.SolvencyInvariant) - suite.Equal("savings: module solvency broken invariant\ntotal deposited amount does not match module account\n", message) - suite.Equal(true, broken) -} - -func TestInvariantTestSuite(t *testing.T) { - suite.Run(t, new(invariantTestSuite)) -} diff --git a/x/savings/keeper/keeper.go b/x/savings/keeper/keeper.go deleted file mode 100644 index 76ca0caa..00000000 --- a/x/savings/keeper/keeper.go +++ /dev/null @@ -1,113 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store/prefix" - 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/kava-labs/kava/x/savings/types" -) - -// Keeper struct for savings module -type Keeper struct { - key storetypes.StoreKey - cdc codec.Codec - paramSubspace paramtypes.Subspace - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - liquidKeeper types.LiquidKeeper - hooks types.SavingsHooks -} - -// NewKeeper returns a new keeper for the savings module. -func NewKeeper( - cdc codec.Codec, key storetypes.StoreKey, paramstore paramtypes.Subspace, - ak types.AccountKeeper, bk types.BankKeeper, lk types.LiquidKeeper, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - cdc: cdc, - key: key, - paramSubspace: paramstore, - accountKeeper: ak, - bankKeeper: bk, - liquidKeeper: lk, - hooks: nil, - } -} - -// SetHooks adds hooks to the keeper. -func (k *Keeper) SetHooks(hooks types.MultiSavingsHooks) *Keeper { - if k.hooks != nil { - panic("cannot set savings hooks twice") - } - k.hooks = hooks - return k -} - -// GetSavingsModuleAccountBalances returns the savings module account balances -func (k Keeper) GetSavingsModuleAccountBalances(ctx sdk.Context) sdk.Coins { - savingMacc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - return k.bankKeeper.GetAllBalances(ctx, savingMacc.GetAddress()) -} - -// GetDeposit returns a deposit from the store for a particular depositor address, deposit denom -func (k Keeper) GetDeposit(ctx sdk.Context, depositor sdk.AccAddress) (types.Deposit, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositsKeyPrefix) - bz := store.Get(depositor.Bytes()) - if len(bz) == 0 { - return types.Deposit{}, false - } - var deposit types.Deposit - k.cdc.MustUnmarshal(bz, &deposit) - return deposit, true -} - -// SetDeposit sets the input deposit in the store -func (k Keeper) SetDeposit(ctx sdk.Context, deposit types.Deposit) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositsKeyPrefix) - bz := k.cdc.MustMarshal(&deposit) - store.Set(deposit.Depositor.Bytes(), bz) -} - -// DeleteDeposit deletes a deposit from the store -func (k Keeper) DeleteDeposit(ctx sdk.Context, deposit types.Deposit) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositsKeyPrefix) - store.Delete(deposit.Depositor.Bytes()) -} - -// IterateDeposits iterates over all deposit objects in the store and performs a callback function -func (k Keeper) IterateDeposits(ctx sdk.Context, cb func(deposit types.Deposit) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositsKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var deposit types.Deposit - k.cdc.MustUnmarshal(iterator.Value(), &deposit) - if cb(deposit) { - break - } - } -} - -// GetAllDeposits returns all Deposits from the store -func (k Keeper) GetAllDeposits(ctx sdk.Context) (deposits types.Deposits) { - k.IterateDeposits(ctx, func(deposit types.Deposit) bool { - deposits = append(deposits, deposit) - return false - }) - return -} - -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) -} diff --git a/x/savings/keeper/keeper_test.go b/x/savings/keeper/keeper_test.go deleted file mode 100644 index 5b862fa5..00000000 --- a/x/savings/keeper/keeper_test.go +++ /dev/null @@ -1,194 +0,0 @@ -package keeper_test - -import ( - "fmt" - "testing" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/savings/keeper" - "github.com/kava-labs/kava/x/savings/types" -) - -// Test suite used for all keeper tests -type KeeperTestSuite struct { - suite.Suite - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context - addrs []sdk.AccAddress -} - -// The default state used by each test -func (suite *KeeperTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - tApp.InitializeFromGenesisStates() - _, addrs := app.GeneratePrivKeyAddressPairs(1) - keeper := tApp.GetSavingsKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - suite.addrs = addrs - - stakingParams := stakingtypes.DefaultParams() - stakingParams.BondDenom = "ukava" - suite.app.GetStakingKeeper().SetParams(suite.ctx, stakingParams) -} - -func (suite *KeeperTestSuite) TestGetSetDeleteDeposit() { - dep := types.NewDeposit(sdk.AccAddress("test"), sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100)))) - - _, f := suite.keeper.GetDeposit(suite.ctx, sdk.AccAddress("test")) - suite.Require().False(f) - - suite.keeper.SetDeposit(suite.ctx, dep) - - testDeposit, f := suite.keeper.GetDeposit(suite.ctx, sdk.AccAddress("test")) - suite.Require().True(f) - suite.Require().Equal(dep, testDeposit) - - suite.Require().NotPanics(func() { suite.keeper.DeleteDeposit(suite.ctx, dep) }) - _, f = suite.keeper.GetDeposit(suite.ctx, sdk.AccAddress("test")) - suite.Require().False(f) -} - -func (suite *KeeperTestSuite) TestIterateDeposits() { - for i := 0; i < 5; i++ { - dep := types.NewDeposit(sdk.AccAddress("test"+fmt.Sprint(i)), sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100)))) - suite.Require().NotPanics(func() { suite.keeper.SetDeposit(suite.ctx, dep) }) - } - var deposits []types.Deposit - suite.keeper.IterateDeposits(suite.ctx, func(d types.Deposit) bool { - deposits = append(deposits, d) - return false - }) - suite.Require().Equal(5, len(deposits)) -} - -func (suite *KeeperTestSuite) getAccountCoins(acc authtypes.AccountI) sdk.Coins { - bk := suite.app.GetBankKeeper() - return bk.GetAllBalances(suite.ctx, acc.GetAddress()) -} - -func (suite *KeeperTestSuite) getAccount(addr sdk.AccAddress) authtypes.AccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetAccount(suite.ctx, addr) -} - -func (suite *KeeperTestSuite) getAccountAtCtx(addr sdk.AccAddress, ctx sdk.Context) authtypes.AccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetAccount(ctx, addr) -} - -func (suite *KeeperTestSuite) getModuleAccount(name string) authtypes.ModuleAccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetModuleAccount(suite.ctx, name) -} - -func (suite *KeeperTestSuite) getModuleAccountAtCtx(name string, ctx sdk.Context) authtypes.ModuleAccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetModuleAccount(ctx, name) -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} - -// CreateAccount creates a new account from the provided balance and address -func (suite *KeeperTestSuite) CreateAccountWithAddress(addr sdk.AccAddress, initialBalance sdk.Coins) authtypes.AccountI { - ak := suite.app.GetAccountKeeper() - - acc := ak.NewAccountWithAddress(suite.ctx, addr) - ak.SetAccount(suite.ctx, acc) - - err := suite.app.FundAccount(suite.ctx, acc.GetAddress(), initialBalance) - suite.Require().NoError(err) - - return acc -} - -// CreateVestingAccount creates a new vesting account. `vestingBalance` should be a fraction of `initialBalance`. -func (suite *KeeperTestSuite) CreateVestingAccountWithAddress(addr sdk.AccAddress, initialBalance sdk.Coins, vestingBalance sdk.Coins) authtypes.AccountI { - if vestingBalance.IsAnyGT(initialBalance) { - panic("vesting balance must be less than initial balance") - } - acc := suite.CreateAccountWithAddress(addr, initialBalance) - bacc := acc.(*authtypes.BaseAccount) - - periods := vestingtypes.Periods{ - vestingtypes.Period{ - Length: 31556952, - Amount: vestingBalance, - }, - } - vacc := vestingtypes.NewPeriodicVestingAccount(bacc, vestingBalance, suite.ctx.BlockTime().Unix(), periods) - suite.app.GetAccountKeeper().SetAccount(suite.ctx, vacc) - return vacc -} - -func (suite *KeeperTestSuite) deliverMsgCreateValidator(ctx sdk.Context, address sdk.ValAddress, selfDelegation sdk.Coin) error { - msg, err := stakingtypes.NewMsgCreateValidator( - address, - ed25519.GenPrivKey().PubKey(), - selfDelegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - sdkmath.NewInt(1e6), - ) - if err != nil { - return err - } - - msgServer := stakingkeeper.NewMsgServerImpl(suite.app.GetStakingKeeper()) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.ctx), msg) - return err -} - -// CreateNewUnbondedValidator creates a new validator in the staking module. -// New validators are unbonded until the end blocker is run. -func (suite *KeeperTestSuite) CreateNewUnbondedValidator(addr sdk.ValAddress, selfDelegation sdkmath.Int) stakingtypes.Validator { - // Create a validator - err := suite.deliverMsgCreateValidator(suite.ctx, addr, sdk.NewCoin("ukava", selfDelegation)) - suite.Require().NoError(err) - - // New validators are created in an unbonded state. Note if the end blocker is run later this validator could become bonded. - - validator, found := suite.app.GetStakingKeeper().GetValidator(suite.ctx, addr) - suite.Require().True(found) - return validator -} - -// CreateDelegation delegates tokens to a validator. -func (suite *KeeperTestSuite) CreateDelegation(valAddr sdk.ValAddress, delegator sdk.AccAddress, amount sdkmath.Int) sdk.Dec { - sk := suite.app.GetStakingKeeper() - - stakingDenom := sk.BondDenom(suite.ctx) - msg := stakingtypes.NewMsgDelegate( - delegator, - valAddr, - sdk.NewCoin(stakingDenom, amount), - ) - - msgServer := stakingkeeper.NewMsgServerImpl(sk) - _, err := msgServer.Delegate(sdk.WrapSDKContext(suite.ctx), msg) - suite.Require().NoError(err) - - del, found := sk.GetDelegation(suite.ctx, delegator, valAddr) - suite.Require().True(found) - return del.Shares -} diff --git a/x/savings/keeper/msg_server.go b/x/savings/keeper/msg_server.go deleted file mode 100644 index 1f081a66..00000000 --- a/x/savings/keeper/msg_server.go +++ /dev/null @@ -1,67 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/savings/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the savings MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -func (k msgServer) Deposit(goCtx context.Context, msg *types.MsgDeposit) (*types.MsgDepositResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - - err = k.keeper.Deposit(ctx, depositor, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Depositor), - ), - ) - return &types.MsgDepositResponse{}, nil -} - -func (k msgServer) Withdraw(goCtx context.Context, msg *types.MsgWithdraw) (*types.MsgWithdrawResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - - err = k.keeper.Withdraw(ctx, depositor, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Depositor), - ), - ) - return &types.MsgWithdrawResponse{}, nil -} diff --git a/x/savings/keeper/params.go b/x/savings/keeper/params.go deleted file mode 100644 index ad786130..00000000 --- a/x/savings/keeper/params.go +++ /dev/null @@ -1,43 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - liquidtypes "github.com/kava-labs/kava/x/liquid/types" - "github.com/kava-labs/kava/x/savings/types" -) - -const ( - bkavaDenom = "bkava" - bkavaPrefix = bkavaDenom + "-" -) - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - var p types.Params - k.paramSubspace.GetParamSet(ctx, &p) - return p -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} - -// IsDenomSupported returns a boolean indicating if a denom is supported -func (k Keeper) IsDenomSupported(ctx sdk.Context, denom string) bool { - p := k.GetParams(ctx) - for _, supportedDenom := range p.SupportedDenoms { - if supportedDenom == denom { - return true - } - - if supportedDenom == liquidtypes.DefaultDerivativeDenom { - if k.liquidKeeper.IsDerivativeDenom(ctx, denom) { - return true - } - } - } - - return false -} diff --git a/x/savings/keeper/params_test.go b/x/savings/keeper/params_test.go deleted file mode 100644 index 23ecfc22..00000000 --- a/x/savings/keeper/params_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package keeper_test - -import ( - "github.com/kava-labs/kava/x/savings/types" -) - -func (suite *KeeperTestSuite) TestGetSetParams() { - params := suite.keeper.GetParams(suite.ctx) - suite.Require().Equal( - types.Params{SupportedDenoms: []string(nil)}, - params, - ) - - newParams := types.NewParams([]string{"btc", "test"}) - suite.keeper.SetParams(suite.ctx, newParams) - - fetchedParams := suite.keeper.GetParams(suite.ctx) - suite.Require().Equal(newParams, fetchedParams) -} diff --git a/x/savings/keeper/withdraw.go b/x/savings/keeper/withdraw.go deleted file mode 100644 index bdb57bb4..00000000 --- a/x/savings/keeper/withdraw.go +++ /dev/null @@ -1,63 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/savings/types" -) - -// Withdraw returns some or all of a deposit back to original depositor -func (k Keeper) Withdraw(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error { - deposit, found := k.GetDeposit(ctx, depositor) - if !found { - return errorsmod.Wrap(types.ErrNoDepositFound, fmt.Sprintf(" for address: %s", depositor.String())) - } - - amount, err := k.CalculateWithdrawAmount(deposit.Amount, coins) - if err != nil { - return err - } - - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, depositor, amount) - if err != nil { - return err - } - - deposit.Amount = deposit.Amount.Sub(amount...) - if deposit.Amount.Empty() { - k.DeleteDeposit(ctx, deposit) - } else { - k.SetDeposit(ctx, deposit) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeSavingsWithdrawal, - sdk.NewAttribute(sdk.AttributeKeyAmount, amount.String()), - sdk.NewAttribute(types.AttributeKeyDepositor, depositor.String()), - ), - ) - return nil -} - -// CalculateWithdrawAmount enables full withdraw of deposited coins by adjusting withdraw amount -// to equal total deposit amount if the requested withdraw amount > current deposit amount -func (k Keeper) CalculateWithdrawAmount(available sdk.Coins, request sdk.Coins) (sdk.Coins, error) { - result := sdk.Coins{} - - if !request.DenomsSubsetOf(available) { - return result, types.ErrInvalidWithdrawDenom - } - - for _, coin := range request { - if coin.Amount.GT(available.AmountOf(coin.Denom)) { - result = append(result, sdk.NewCoin(coin.Denom, available.AmountOf(coin.Denom))) - } else { - result = append(result, coin) - } - } - return result, nil -} diff --git a/x/savings/keeper/withdraw_test.go b/x/savings/keeper/withdraw_test.go deleted file mode 100644 index b4f61f98..00000000 --- a/x/savings/keeper/withdraw_test.go +++ /dev/null @@ -1,202 +0,0 @@ -package keeper_test - -import ( - "fmt" - "strings" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/savings/types" -) - -func (suite *KeeperTestSuite) TestWithdraw() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, delegator := addrs[0], addrs[1] - - valAddr := sdk.ValAddress(valAccAddr) - initialBalance := sdkmath.NewInt(1e9) - - bkavaDenom := fmt.Sprintf("bkava-%s", valAddr.String()) - - type args struct { - allowedDenoms []string - depositor sdk.AccAddress - initialDepositorBalance sdk.Coins - depositAmount sdk.Coins - withdrawAmount sdk.Coins - expectedAccountBalance sdk.Coins - expectedModAccountBalance sdk.Coins - expectedDepositCoins sdk.Coins - } - type errArgs struct { - expectPass bool - expectDelete bool - contains string - } - type withdrawTest struct { - name string - args args - errArgs errArgs - } - testCases := []withdrawTest{ - { - "valid: partial withdraw", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(900)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - expectedDepositCoins: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - }, - errArgs{ - expectPass: true, - expectDelete: false, - contains: "", - }, - }, - { - "valid: partial bkava", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava", "bkava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(100))), - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(900)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(100))), - expectedDepositCoins: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(100))), - }, - errArgs{ - expectPass: true, - expectDelete: false, - contains: "", - }, - }, - { - "valid: full withdraw", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava"}, - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.Coins{}, - expectedDepositCoins: sdk.Coins{}, - }, - errArgs{ - expectPass: true, - expectDelete: true, - contains: "", - }, - }, - { - "valid: withdraw exceeds deposit but is adjusted to match max deposit", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava"}, - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(300))), - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.Coins{}, - expectedDepositCoins: sdk.Coins{}, - }, - errArgs{ - expectPass: true, - expectDelete: true, - contains: "", - }, - }, - { - "invalid: withdraw non-supplied coin type", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin("btcb", sdkmath.NewInt(200))), - expectedAccountBalance: sdk.Coins{}, - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - expectedDepositCoins: sdk.Coins{}, - }, - errArgs{ - expectPass: false, - expectDelete: false, - contains: "invalid withdraw denom", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{tc.args.initialDepositorBalance}, - []sdk.AccAddress{tc.args.depositor}, - ) - savingsGS := types.NewGenesisState( - types.NewParams(tc.args.allowedDenoms), - types.Deposits{}, - ) - - stakingParams := stakingtypes.DefaultParams() - stakingParams.BondDenom = "ukava" - - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&savingsGS)}, - app.GenesisState{stakingtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(stakingtypes.NewGenesisState(stakingParams, nil, nil))}, - ) - keeper := tApp.GetSavingsKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - bankKeeper := tApp.GetBankKeeper() - - // Create validator and delegate for bkava - suite.CreateAccountWithAddress(valAccAddr, cs(c("ukava", 100e10))) - suite.CreateAccountWithAddress(delegator, cs(c("ukava", 100e10))) - - suite.CreateNewUnbondedValidator(valAddr, initialBalance) - suite.CreateDelegation(valAddr, delegator, initialBalance) - staking.EndBlocker(suite.ctx, suite.app.GetStakingKeeper()) - - err := suite.keeper.Deposit(suite.ctx, tc.args.depositor, tc.args.depositAmount) - suite.Require().NoError(err) - - err = suite.keeper.Withdraw(suite.ctx, tc.args.depositor, tc.args.withdrawAmount) - if tc.errArgs.expectPass { - suite.Require().NoError(err) - // Check depositor's account balance - acc := suite.getAccount(tc.args.depositor) - suite.Require().Equal(tc.args.expectedAccountBalance, bankKeeper.GetAllBalances(ctx, acc.GetAddress())) - // Check savings module account balance - mAcc := suite.getModuleAccount(types.ModuleAccountName) - suite.Require().True(tc.args.expectedModAccountBalance.IsEqual(bankKeeper.GetAllBalances(ctx, mAcc.GetAddress()))) - // Check deposit - testDeposit, f := suite.keeper.GetDeposit(suite.ctx, tc.args.depositor) - if tc.errArgs.expectDelete { - suite.Require().False(f) - } else { - suite.Require().True(f) - suite.Require().Equal(tc.args.expectedDepositCoins, testDeposit.Amount) - } - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} diff --git a/x/savings/module.go b/x/savings/module.go deleted file mode 100644 index f7649ec3..00000000 --- a/x/savings/module.go +++ /dev/null @@ -1,146 +0,0 @@ -package savings - -import ( - "context" - "encoding/json" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/kava-labs/kava/x/savings/client/cli" - "github.com/kava-labs/kava/x/savings/keeper" - "github.com/kava-labs/kava/x/savings/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - gs := types.DefaultGenesisState() - return cdc.MustMarshalJSON(&gs) -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) - if err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the gov module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// GetTxCmd returns the root tx command for the module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper authkeeper.AccountKeeper - bankKeeper types.BankKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper authkeeper.AccountKeeper, bankKeeper types.BankKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - } -} - -// Name module name -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// RegisterInvariants register module invariants -func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { - keeper.RegisterInvariants(ir, am.keeper) -} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) -} - -// InitGenesis module init-genesis -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, am.accountKeeper, genState) - - return []abci.ValidatorUpdate{} -} - -// ExportGenesis module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(&gs) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) { -} - -// EndBlock module end-block -func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/savings/types/codec.go b/x/savings/types/codec.go deleted file mode 100644 index 44048a87..00000000 --- a/x/savings/types/codec.go +++ /dev/null @@ -1,40 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the -// savings module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgDeposit{}, "savings/MsgDeposit", nil) - cdc.RegisterConcrete(&MsgWithdraw{}, "savings/MsgWithdraw", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgDeposit{}, - &MsgWithdraw{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/savings/types/deposit.go b/x/savings/types/deposit.go deleted file mode 100644 index a7632c8c..00000000 --- a/x/savings/types/deposit.go +++ /dev/null @@ -1,46 +0,0 @@ -package types - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewDeposit returns a new deposit -func NewDeposit(depositor sdk.AccAddress, amount sdk.Coins) Deposit { - return Deposit{ - Depositor: depositor, - Amount: amount, - } -} - -// Validate deposit validation -func (d Deposit) Validate() error { - if d.Depositor.Empty() { - return fmt.Errorf("depositor cannot be empty") - } - if !d.Amount.IsValid() { - return fmt.Errorf("invalid deposit coins: %s", d.Amount) - } - - return nil -} - -// Deposits is a slice of Deposit -type Deposits []Deposit - -// Validate validates Deposits -func (ds Deposits) Validate() error { - depositDupMap := make(map[string]Deposit) - for _, d := range ds { - if err := d.Validate(); err != nil { - return err - } - dup, ok := depositDupMap[d.Depositor.String()] - if ok { - return fmt.Errorf("duplicate depositor: %s\n%s", d, dup) - } - depositDupMap[d.Depositor.String()] = d - } - return nil -} diff --git a/x/savings/types/errors.go b/x/savings/types/errors.go deleted file mode 100644 index bcaa8efb..00000000 --- a/x/savings/types/errors.go +++ /dev/null @@ -1,16 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// DONTCOVER - -var ( - // ErrEmptyInput error for empty input - ErrEmptyInput = errorsmod.Register(ModuleName, 2, "input must not be empty") - // ErrNoDepositFound error when no deposit is found for an address - ErrNoDepositFound = errorsmod.Register(ModuleName, 3, "no deposit found") - // ErrInvalidDepositDenom error for invalid deposit denom - ErrInvalidDepositDenom = errorsmod.Register(ModuleName, 4, "invalid deposit denom") - // ErrInvalidWithdrawDenom error for invalid withdraw denoms - ErrInvalidWithdrawDenom = errorsmod.Register(ModuleName, 5, "invalid withdraw denom") -) diff --git a/x/savings/types/events.go b/x/savings/types/events.go deleted file mode 100644 index 2f30ebe1..00000000 --- a/x/savings/types/events.go +++ /dev/null @@ -1,10 +0,0 @@ -package types - -const ( - EventTypeSavingsDeposit = "deposit_savings" - EventTypeSavingsWithdrawal = "withdraw_savings" - - AttributeValueCategory = ModuleName - AttributeKeyAmount = "amount" - AttributeKeyDepositor = "depositor" -) diff --git a/x/savings/types/expected_keepers.go b/x/savings/types/expected_keepers.go deleted file mode 100644 index 7072936c..00000000 --- a/x/savings/types/expected_keepers.go +++ /dev/null @@ -1,38 +0,0 @@ -package types // noalias - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// BankKeeper defines the expected bank keeper -type BankKeeper interface { - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - - GetSupply(ctx sdk.Context, denom string) sdk.Coin - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins -} - -// AccountKeeper defines the expected keeper interface for interacting with account -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI - SetAccount(ctx sdk.Context, acc authtypes.AccountI) - - GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, name string) authtypes.ModuleAccountI -} - -// SavingsHooks event hooks for other keepers to run code in response to Savings modifications -type SavingsHooks interface { - AfterSavingsDepositCreated(ctx sdk.Context, deposit Deposit) - BeforeSavingsDepositModified(ctx sdk.Context, deposit Deposit, incomingDenoms []string) -} - -type LiquidKeeper interface { - GetStakedTokensForDerivatives(ctx sdk.Context, derivatives sdk.Coins) (sdk.Coin, error) - IsDerivativeDenom(ctx sdk.Context, denom string) bool -} diff --git a/x/savings/types/genesis.go b/x/savings/types/genesis.go deleted file mode 100644 index c0027ad0..00000000 --- a/x/savings/types/genesis.go +++ /dev/null @@ -1,27 +0,0 @@ -package types - -// NewGenesisState creates a new genesis state for the savings module -func NewGenesisState(p Params, deposits Deposits) GenesisState { - return GenesisState{ - Params: p, - Deposits: deposits, - } -} - -// DefaultGenesisState defines default GenesisState for savings -func DefaultGenesisState() GenesisState { - return NewGenesisState( - DefaultParams(), - Deposits{}, - ) -} - -// Validate performs basic validation of genesis data returning an -// error for any failed validation criteria. -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - - return gs.Deposits.Validate() -} diff --git a/x/savings/types/genesis.pb.go b/x/savings/types/genesis.pb.go deleted file mode 100644 index 5c2f1f55..00000000 --- a/x/savings/types/genesis.pb.go +++ /dev/null @@ -1,389 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/savings/v1beta1/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 savings module's genesis state. -type GenesisState struct { - // params defines all the parameters of the module. - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - Deposits Deposits `protobuf:"bytes,2,rep,name=deposits,proto3,castrepeated=Deposits" json:"deposits"` -} - -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_f5dcde4d417fcec8, []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) GetDeposits() Deposits { - if m != nil { - return m.Deposits - } - return nil -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.savings.v1beta1.GenesisState") -} - -func init() { - proto.RegisterFile("kava/savings/v1beta1/genesis.proto", fileDescriptor_f5dcde4d417fcec8) -} - -var fileDescriptor_f5dcde4d417fcec8 = []byte{ - // 245 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xca, 0x4e, 0x2c, 0x4b, - 0xd4, 0x2f, 0x4e, 0x2c, 0xcb, 0xcc, 0x4b, 0x2f, 0xd6, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, - 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, - 0x01, 0xa9, 0xd1, 0x83, 0xaa, 0xd1, 0x83, 0xaa, 0x91, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x2b, - 0xd0, 0x07, 0xb1, 0x20, 0x6a, 0xa5, 0x14, 0xb0, 0x9a, 0x57, 0x5c, 0x92, 0x5f, 0x94, 0x0a, 0x51, - 0xa1, 0x34, 0x9d, 0x91, 0x8b, 0xc7, 0x1d, 0x62, 0x7e, 0x70, 0x49, 0x62, 0x49, 0xaa, 0x90, 0x15, - 0x17, 0x5b, 0x41, 0x62, 0x51, 0x62, 0x6e, 0xb1, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0xb7, 0x91, 0x8c, - 0x1e, 0x36, 0xfb, 0xf4, 0x02, 0xc0, 0x6a, 0x9c, 0x58, 0x4e, 0xdc, 0x93, 0x67, 0x08, 0x82, 0xea, - 0x10, 0xf2, 0xe6, 0xe2, 0x48, 0x49, 0x2d, 0xc8, 0x2f, 0xce, 0x2c, 0x29, 0x96, 0x60, 0x52, 0x60, - 0xd6, 0xe0, 0x36, 0x92, 0xc5, 0xae, 0xdb, 0x05, 0xa2, 0xca, 0x49, 0x00, 0xa4, 0x7d, 0xd5, 0x7d, - 0x79, 0x0e, 0xa8, 0x40, 0x71, 0x10, 0xdc, 0x00, 0x27, 0xe7, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, - 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, 0x0b, 0x8f, 0xe5, 0x18, 0x6e, - 0x3c, 0x96, 0x63, 0x88, 0xd2, 0x4c, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, - 0x07, 0x19, 0xaf, 0x9b, 0x93, 0x98, 0x54, 0x0c, 0x66, 0xe9, 0x57, 0xc0, 0x3d, 0x5b, 0x52, 0x59, - 0x90, 0x5a, 0x9c, 0xc4, 0x06, 0xf6, 0xa5, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0xb9, 0x68, 0xf5, - 0x36, 0x59, 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.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[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.Deposits) > 0 { - for _, e := range m.Deposits { - 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 Deposits", 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.Deposits = append(m.Deposits, Deposit{}) - if err := m.Deposits[len(m.Deposits)-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/savings/types/hooks.go b/x/savings/types/hooks.go deleted file mode 100644 index b4441b59..00000000 --- a/x/savings/types/hooks.go +++ /dev/null @@ -1,25 +0,0 @@ -package types - -import sdk "github.com/cosmos/cosmos-sdk/types" - -// MultiSavingsHooks combine multiple Savings hooks, all hook functions are run in array sequence -type MultiSavingsHooks []SavingsHooks - -// NewMultiSavingsHooks returns a new MultiSavingsHooks -func NewMultiSavingsHooks(hooks ...SavingsHooks) MultiSavingsHooks { - return hooks -} - -// AfterSavingsDepositCreated runs after a deposit is created -func (s MultiSavingsHooks) AfterSavingsDepositCreated(ctx sdk.Context, deposit Deposit) { - for i := range s { - s[i].AfterSavingsDepositCreated(ctx, deposit) - } -} - -// BeforeSavingsDepositModified runs before a deposit is modified -func (s MultiSavingsHooks) BeforeSavingsDepositModified(ctx sdk.Context, deposit Deposit, incomingDenoms []string) { - for i := range s { - s[i].BeforeSavingsDepositModified(ctx, deposit, incomingDenoms) - } -} diff --git a/x/savings/types/key.go b/x/savings/types/key.go deleted file mode 100644 index 6bf64608..00000000 --- a/x/savings/types/key.go +++ /dev/null @@ -1,20 +0,0 @@ -package types - -const ( - // ModuleName The name that will be used throughout the module - ModuleName = "savings" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default namestore - DefaultParamspace = ModuleName - - // ModuleAccountName is the module account's name - ModuleAccountName = ModuleName -) - -var DepositsKeyPrefix = []byte{0x01} diff --git a/x/savings/types/msg.go b/x/savings/types/msg.go deleted file mode 100644 index f6dae871..00000000 --- a/x/savings/types/msg.go +++ /dev/null @@ -1,97 +0,0 @@ -package types - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// ensure Msg interface compliance at compile time -var ( - _ sdk.Msg = &MsgDeposit{} - _ sdk.Msg = &MsgWithdraw{} -) - -// NewMsgDeposit returns a new MsgDeposit -func NewMsgDeposit(depositor sdk.AccAddress, amount sdk.Coins) MsgDeposit { - return MsgDeposit{ - Depositor: depositor.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgDeposit) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgDeposit) Type() string { return "savings_deposit" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgDeposit) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "deposit amount %s", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgDeposit) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgDeposit) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - panic(err) - } - return []sdk.AccAddress{depositor} -} - -// NewMsgWithdraw returns a new MsgWithdraw -func NewMsgWithdraw(depositor sdk.AccAddress, amount sdk.Coins) MsgWithdraw { - return MsgWithdraw{ - Depositor: depositor.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgWithdraw) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgWithdraw) Type() string { return "savings_withdraw" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgWithdraw) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "withdraw amount %s", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgWithdraw) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgWithdraw) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - panic(err) - } - return []sdk.AccAddress{depositor} -} diff --git a/x/savings/types/params.go b/x/savings/types/params.go deleted file mode 100644 index a22a3d2e..00000000 --- a/x/savings/types/params.go +++ /dev/null @@ -1,59 +0,0 @@ -package types - -import ( - "fmt" - - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// Parameter keys -var ( - KeySupportedDenoms = []byte("SupportedDenoms") - DefaultSupportedDenoms = []string{} -) - -// NewParams creates a new Params object -func NewParams(supportedDenoms []string) Params { - return Params{ - SupportedDenoms: supportedDenoms, - } -} - -// DefaultParams default params for savings -func DefaultParams() Params { - return NewParams(DefaultSupportedDenoms) -} - -// ParamKeyTable Key declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements the ParamSet interface and returns all the key/value pairs -// pairs of savings module's parameters. -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeySupportedDenoms, &p.SupportedDenoms, validateSupportedDenoms), - } -} - -// Validate ensure that params have valid values -func (p Params) Validate() error { - return validateSupportedDenoms(p.SupportedDenoms) -} - -func validateSupportedDenoms(i interface{}) error { - supportedDenoms, ok := i.([]string) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - seenDenoms := make(map[string]bool) - for _, denom := range supportedDenoms { - if seenDenoms[denom] { - return fmt.Errorf("duplicated denom %s", denom) - } - seenDenoms[denom] = true - } - return nil -} diff --git a/x/savings/types/query.pb.go b/x/savings/types/query.pb.go deleted file mode 100644 index 5e1340de..00000000 --- a/x/savings/types/query.pb.go +++ /dev/null @@ -1,1495 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/savings/v1beta1/query.proto - -package types - -import ( - context "context" - 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" - 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 defines the request type for querying x/savings -// parameters. -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_f78c91efc5db144f, []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 defines the response type for querying x/savings -// parameters. -type QueryParamsResponse struct { - 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_f78c91efc5db144f, []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 - -// QueryDepositsRequest defines the request type for querying x/savings -// deposits. -type QueryDepositsRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Pagination *query.PageRequest `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDepositsRequest) Reset() { *m = QueryDepositsRequest{} } -func (m *QueryDepositsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsRequest) ProtoMessage() {} -func (*QueryDepositsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_f78c91efc5db144f, []int{2} -} -func (m *QueryDepositsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsRequest.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 *QueryDepositsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsRequest.Merge(m, src) -} -func (m *QueryDepositsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsRequest proto.InternalMessageInfo - -func (m *QueryDepositsRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *QueryDepositsRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *QueryDepositsRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryDepositsResponse defines the response type for querying x/savings -// deposits. -type QueryDepositsResponse struct { - Deposits Deposits `protobuf:"bytes,1,rep,name=deposits,proto3,castrepeated=Deposits" json:"deposits"` - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDepositsResponse) Reset() { *m = QueryDepositsResponse{} } -func (m *QueryDepositsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsResponse) ProtoMessage() {} -func (*QueryDepositsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_f78c91efc5db144f, []int{3} -} -func (m *QueryDepositsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsResponse.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 *QueryDepositsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsResponse.Merge(m, src) -} -func (m *QueryDepositsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsResponse proto.InternalMessageInfo - -func (m *QueryDepositsResponse) GetDeposits() Deposits { - if m != nil { - return m.Deposits - } - return nil -} - -func (m *QueryDepositsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryTotalSupplyRequest defines the request type for Query/TotalSupply method. -type QueryTotalSupplyRequest struct { -} - -func (m *QueryTotalSupplyRequest) Reset() { *m = QueryTotalSupplyRequest{} } -func (m *QueryTotalSupplyRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalSupplyRequest) ProtoMessage() {} -func (*QueryTotalSupplyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_f78c91efc5db144f, []int{4} -} -func (m *QueryTotalSupplyRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalSupplyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalSupplyRequest.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 *QueryTotalSupplyRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalSupplyRequest.Merge(m, src) -} -func (m *QueryTotalSupplyRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalSupplyRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalSupplyRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalSupplyRequest proto.InternalMessageInfo - -// TotalSupplyResponse defines the response type for the Query/TotalSupply method. -type QueryTotalSupplyResponse struct { - // Height is the block height at which these totals apply - Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` - // Result is a list of coins supplied to savings - Result github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=result,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"result"` -} - -func (m *QueryTotalSupplyResponse) Reset() { *m = QueryTotalSupplyResponse{} } -func (m *QueryTotalSupplyResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalSupplyResponse) ProtoMessage() {} -func (*QueryTotalSupplyResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_f78c91efc5db144f, []int{5} -} -func (m *QueryTotalSupplyResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalSupplyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalSupplyResponse.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 *QueryTotalSupplyResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalSupplyResponse.Merge(m, src) -} -func (m *QueryTotalSupplyResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalSupplyResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalSupplyResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalSupplyResponse proto.InternalMessageInfo - -func (m *QueryTotalSupplyResponse) GetHeight() int64 { - if m != nil { - return m.Height - } - return 0 -} - -func (m *QueryTotalSupplyResponse) GetResult() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Result - } - return nil -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.savings.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.savings.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryDepositsRequest)(nil), "kava.savings.v1beta1.QueryDepositsRequest") - proto.RegisterType((*QueryDepositsResponse)(nil), "kava.savings.v1beta1.QueryDepositsResponse") - proto.RegisterType((*QueryTotalSupplyRequest)(nil), "kava.savings.v1beta1.QueryTotalSupplyRequest") - proto.RegisterType((*QueryTotalSupplyResponse)(nil), "kava.savings.v1beta1.QueryTotalSupplyResponse") -} - -func init() { proto.RegisterFile("kava/savings/v1beta1/query.proto", fileDescriptor_f78c91efc5db144f) } - -var fileDescriptor_f78c91efc5db144f = []byte{ - // 619 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x94, 0xb1, 0x8f, 0x12, 0x41, - 0x14, 0xc6, 0x19, 0x38, 0xc8, 0x39, 0x34, 0x66, 0x5c, 0x75, 0x21, 0xb8, 0x90, 0xcd, 0xe5, 0xe4, - 0x30, 0xec, 0x7a, 0xd8, 0x5d, 0x27, 0x67, 0xb4, 0xb0, 0xd1, 0x3d, 0x13, 0x13, 0x9b, 0xcb, 0x00, - 0x93, 0x65, 0x73, 0xb0, 0xb3, 0xb7, 0x33, 0x8b, 0xd2, 0x6a, 0x63, 0x62, 0x63, 0x62, 0xa1, 0xa5, - 0x85, 0x95, 0x89, 0x9d, 0xf1, 0x6f, 0xb8, 0xf2, 0xa2, 0x8d, 0x95, 0x1a, 0xf0, 0x0f, 0x31, 0x3b, - 0x33, 0xbb, 0x07, 0xc7, 0xe6, 0xa4, 0x82, 0x79, 0xf3, 0x7d, 0xdf, 0xfc, 0xe6, 0xcd, 0x03, 0xd8, - 0x38, 0xc2, 0x13, 0x6c, 0x33, 0x3c, 0xf1, 0x7c, 0x97, 0xd9, 0x93, 0xdd, 0x1e, 0xe1, 0x78, 0xd7, - 0x3e, 0x8e, 0x48, 0x38, 0xb5, 0x82, 0x90, 0x72, 0x8a, 0xb4, 0x58, 0x61, 0x29, 0x85, 0xa5, 0x14, - 0xd5, 0x56, 0x9f, 0xb2, 0x31, 0x65, 0x76, 0x0f, 0x33, 0x22, 0xe5, 0xa9, 0x39, 0xc0, 0xae, 0xe7, - 0x63, 0xee, 0x51, 0x5f, 0x26, 0x54, 0x8d, 0x45, 0x6d, 0xa2, 0xea, 0x53, 0x2f, 0xd9, 0xaf, 0xc8, - 0xfd, 0x43, 0xb1, 0xb2, 0xe5, 0x42, 0x6d, 0x69, 0x2e, 0x75, 0xa9, 0xac, 0xc7, 0xdf, 0x54, 0xb5, - 0xe6, 0x52, 0xea, 0x8e, 0x88, 0x8d, 0x03, 0xcf, 0xc6, 0xbe, 0x4f, 0xb9, 0x38, 0x2d, 0xf1, 0x64, - 0x5f, 0x89, 0x71, 0x1a, 0x12, 0xa9, 0x30, 0x35, 0x88, 0x1e, 0xc7, 0xc8, 0x8f, 0x70, 0x88, 0xc7, - 0xcc, 0x21, 0xc7, 0x11, 0x61, 0xdc, 0x7c, 0x0a, 0xaf, 0x2c, 0x55, 0x59, 0x40, 0x7d, 0x46, 0xd0, - 0x1e, 0x2c, 0x05, 0xa2, 0xa2, 0x83, 0x06, 0x68, 0x96, 0x3b, 0x35, 0x2b, 0xab, 0x21, 0x96, 0x74, - 0x75, 0x37, 0x4e, 0x7e, 0xd5, 0x73, 0x8e, 0x72, 0xec, 0x6d, 0xbc, 0xfe, 0x58, 0xcf, 0x99, 0x9f, - 0x00, 0xd4, 0x44, 0xf2, 0x3d, 0x12, 0x50, 0xe6, 0xf1, 0xe4, 0x44, 0xa4, 0xc1, 0xe2, 0x80, 0xf8, - 0x74, 0x2c, 0x92, 0x2f, 0x39, 0x72, 0x81, 0x2c, 0x58, 0xa4, 0xcf, 0x7d, 0x12, 0xea, 0xf9, 0xb8, - 0xda, 0xd5, 0xbf, 0x7f, 0x6d, 0x6b, 0xaa, 0x29, 0x77, 0x07, 0x83, 0x90, 0x30, 0x76, 0xc0, 0x43, - 0xcf, 0x77, 0x1d, 0x29, 0x43, 0xf7, 0x21, 0x3c, 0x6b, 0xb9, 0x5e, 0x10, 0x90, 0xdb, 0x96, 0x72, - 0xc4, 0x3d, 0xb7, 0xe4, 0x73, 0x9e, 0x91, 0xba, 0x44, 0x11, 0x38, 0x0b, 0x4e, 0xf3, 0x0b, 0x80, - 0x57, 0xcf, 0x61, 0xaa, 0x16, 0x3c, 0x84, 0x9b, 0x03, 0x55, 0xd3, 0x41, 0xa3, 0xd0, 0x2c, 0x77, - 0x6e, 0x64, 0x37, 0x41, 0x39, 0xbb, 0x97, 0xe3, 0x2e, 0x7c, 0xfe, 0x5d, 0xdf, 0x4c, 0xa3, 0xd2, - 0x00, 0xf4, 0x60, 0x09, 0x37, 0x2f, 0x70, 0x6f, 0xfe, 0x17, 0x57, 0x92, 0x2c, 0xf1, 0x56, 0xe0, - 0x75, 0x81, 0xfb, 0x84, 0x72, 0x3c, 0x3a, 0x88, 0x82, 0x60, 0x34, 0x4d, 0x9e, 0xf2, 0x3d, 0x80, - 0xfa, 0xea, 0x9e, 0xba, 0xcd, 0x35, 0x58, 0x1a, 0x12, 0xcf, 0x1d, 0x72, 0xd1, 0xf6, 0x82, 0xa3, - 0x56, 0xa8, 0x0f, 0x4b, 0x21, 0x61, 0xd1, 0x88, 0xeb, 0x79, 0x71, 0xc7, 0xca, 0x12, 0x54, 0x82, - 0xb3, 0x4f, 0x3d, 0xbf, 0x7b, 0x5b, 0xdd, 0xaf, 0xe9, 0x7a, 0x7c, 0x18, 0xf5, 0xac, 0x3e, 0x1d, - 0xab, 0xb9, 0x55, 0x1f, 0x6d, 0x36, 0x38, 0xb2, 0xf9, 0x34, 0x20, 0x4c, 0x18, 0x98, 0xa3, 0xa2, - 0x3b, 0xdf, 0x0a, 0xb0, 0x28, 0xc8, 0xd0, 0x2b, 0x00, 0x4b, 0x72, 0x68, 0x50, 0x33, 0xbb, 0x9b, - 0xab, 0x33, 0x5a, 0xdd, 0x59, 0x43, 0x29, 0xaf, 0x69, 0x6e, 0xbd, 0xfc, 0xf1, 0xf7, 0x5d, 0xde, - 0x40, 0x35, 0x3b, 0xf3, 0xf7, 0x20, 0x27, 0x14, 0xbd, 0x01, 0x30, 0x7d, 0x24, 0xd4, 0xba, 0x20, - 0xfd, 0xdc, 0xec, 0x56, 0x6f, 0xad, 0xa5, 0x55, 0x2c, 0xdb, 0x82, 0xa5, 0x81, 0x8c, 0x6c, 0x96, - 0x74, 0x36, 0x3e, 0x00, 0x58, 0x5e, 0x78, 0x32, 0xd4, 0xbe, 0xe0, 0x90, 0xd5, 0x67, 0xaf, 0x5a, - 0xeb, 0xca, 0x15, 0x56, 0x4b, 0x60, 0x6d, 0x21, 0x33, 0x1b, 0x8b, 0xc7, 0x96, 0x43, 0x26, 0x3c, - 0xdd, 0xfd, 0x93, 0x99, 0x01, 0x4e, 0x67, 0x06, 0xf8, 0x33, 0x33, 0xc0, 0xdb, 0xb9, 0x91, 0x3b, - 0x9d, 0x1b, 0xb9, 0x9f, 0x73, 0x23, 0xf7, 0x6c, 0x67, 0x61, 0x08, 0xe2, 0x9c, 0xf6, 0x08, 0xf7, - 0x98, 0x4c, 0x7c, 0x91, 0x66, 0x8a, 0x59, 0xe8, 0x95, 0xc4, 0xff, 0xcf, 0x9d, 0x7f, 0x01, 0x00, - 0x00, 0xff, 0xff, 0xa9, 0x76, 0x1d, 0x1f, 0x76, 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 { - // Params queries all parameters of the savings module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Deposits queries savings deposits. - Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) - // TotalSupply returns the total sum of all coins currently locked into the savings module. - TotalSupply(ctx context.Context, in *QueryTotalSupplyRequest, opts ...grpc.CallOption) (*QueryTotalSupplyResponse, 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, "/kava.savings.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) { - out := new(QueryDepositsResponse) - err := c.cc.Invoke(ctx, "/kava.savings.v1beta1.Query/Deposits", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalSupply(ctx context.Context, in *QueryTotalSupplyRequest, opts ...grpc.CallOption) (*QueryTotalSupplyResponse, error) { - out := new(QueryTotalSupplyResponse) - err := c.cc.Invoke(ctx, "/kava.savings.v1beta1.Query/TotalSupply", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries all parameters of the savings module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Deposits queries savings deposits. - Deposits(context.Context, *QueryDepositsRequest) (*QueryDepositsResponse, error) - // TotalSupply returns the total sum of all coins currently locked into the savings module. - TotalSupply(context.Context, *QueryTotalSupplyRequest) (*QueryTotalSupplyResponse, 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) Deposits(ctx context.Context, req *QueryDepositsRequest) (*QueryDepositsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposits not implemented") -} -func (*UnimplementedQueryServer) TotalSupply(ctx context.Context, req *QueryTotalSupplyRequest) (*QueryTotalSupplyResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalSupply 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: "/kava.savings.v1beta1.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_Deposits_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDepositsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Deposits(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.savings.v1beta1.Query/Deposits", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Deposits(ctx, req.(*QueryDepositsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalSupply_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalSupplyRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalSupply(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.savings.v1beta1.Query/TotalSupply", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalSupply(ctx, req.(*QueryTotalSupplyRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.savings.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Deposits", - Handler: _Query_Deposits_Handler, - }, - { - MethodName: "TotalSupply", - Handler: _Query_TotalSupply_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/savings/v1beta1/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 *QueryDepositsRequest) 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 *QueryDepositsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsRequest) 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] = 0x1a - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDepositsResponse) 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 *QueryDepositsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsResponse) 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.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[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 (m *QueryTotalSupplyRequest) 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 *QueryTotalSupplyRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalSupplyRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryTotalSupplyResponse) 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 *QueryTotalSupplyResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalSupplyResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Result) > 0 { - for iNdEx := len(m.Result) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Result[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if m.Height != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.Height)) - i-- - dAtA[i] = 0x8 - } - 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 *QueryDepositsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDepositsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Deposits) > 0 { - for _, e := range m.Deposits { - 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 (m *QueryTotalSupplyRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryTotalSupplyResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Height != 0 { - n += 1 + sovQuery(uint64(m.Height)) - } - if len(m.Result) > 0 { - for _, e := range m.Result { - l = e.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 *QueryDepositsRequest) 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: QueryDepositsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - 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 *QueryDepositsResponse) 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: QueryDepositsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposits", 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.Deposits = append(m.Deposits, Deposit{}) - if err := m.Deposits[len(m.Deposits)-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 (m *QueryTotalSupplyRequest) 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: QueryTotalSupplyRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalSupplyRequest: 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 *QueryTotalSupplyResponse) 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: QueryTotalSupplyResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalSupplyResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) - } - m.Height = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Height |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Result", 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.Result = append(m.Result, types.Coin{}) - if err := m.Result[len(m.Result)-1].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/savings/types/query.pb.gw.go b/x/savings/types/query.pb.gw.go deleted file mode 100644 index 8a59f3da..00000000 --- a/x/savings/types/query.pb.gw.go +++ /dev/null @@ -1,301 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/savings/v1beta1/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 - -} - -var ( - filter_Query_Deposits_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - 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_Deposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Deposits(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - 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_Deposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Deposits(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_TotalSupply_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalSupplyRequest - var metadata runtime.ServerMetadata - - msg, err := client.TotalSupply(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalSupply_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalSupplyRequest - var metadata runtime.ServerMetadata - - msg, err := server.TotalSupply(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_Deposits_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_Deposits_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_Deposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalSupply_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_TotalSupply_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_TotalSupply_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_Deposits_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_Deposits_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_Deposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalSupply_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_TotalSupply_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_TotalSupply_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{"kava", "savings", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Deposits_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "savings", "v1beta1", "deposits"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalSupply_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "savings", "v1beta1", "total_supply"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Deposits_0 = runtime.ForwardResponseMessage - - forward_Query_TotalSupply_0 = runtime.ForwardResponseMessage -) diff --git a/x/savings/types/store.pb.go b/x/savings/types/store.pb.go deleted file mode 100644 index 02ee9143..00000000 --- a/x/savings/types/store.pb.go +++ /dev/null @@ -1,546 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/savings/v1beta1/store.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" - 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 savings module. -type Params struct { - SupportedDenoms []string `protobuf:"bytes,1,rep,name=supported_denoms,json=supportedDenoms,proto3" json:"supported_denoms,omitempty"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_f7110366fa182786, []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 - -// Deposit defines an amount of coins deposited into a savings module account. -type Deposit struct { - Depositor github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=depositor,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"depositor,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *Deposit) Reset() { *m = Deposit{} } -func (m *Deposit) String() string { return proto.CompactTextString(m) } -func (*Deposit) ProtoMessage() {} -func (*Deposit) Descriptor() ([]byte, []int) { - return fileDescriptor_f7110366fa182786, []int{1} -} -func (m *Deposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Deposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Deposit.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 *Deposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_Deposit.Merge(m, src) -} -func (m *Deposit) XXX_Size() int { - return m.Size() -} -func (m *Deposit) XXX_DiscardUnknown() { - xxx_messageInfo_Deposit.DiscardUnknown(m) -} - -var xxx_messageInfo_Deposit proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Params)(nil), "kava.savings.v1beta1.Params") - proto.RegisterType((*Deposit)(nil), "kava.savings.v1beta1.Deposit") -} - -func init() { proto.RegisterFile("kava/savings/v1beta1/store.proto", fileDescriptor_f7110366fa182786) } - -var fileDescriptor_f7110366fa182786 = []byte{ - // 335 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x51, 0xc1, 0x4e, 0xc2, 0x40, - 0x14, 0xec, 0x4a, 0x82, 0xa1, 0x1e, 0x34, 0x95, 0x03, 0x70, 0x58, 0x1a, 0x4e, 0xe5, 0xd0, 0x5d, - 0x91, 0x2f, 0xa0, 0x92, 0xe8, 0xd1, 0x70, 0xf4, 0x42, 0xb6, 0xed, 0x5a, 0x1b, 0x6c, 0x5f, 0xd3, - 0xb7, 0x10, 0xf9, 0x0b, 0xbf, 0xc3, 0xb3, 0x1f, 0xc1, 0x91, 0x78, 0x30, 0x9e, 0x50, 0xe1, 0x2f, - 0x3c, 0x99, 0xb6, 0x2b, 0x7a, 0xf4, 0xb4, 0x6f, 0xe7, 0xcd, 0x4c, 0x26, 0xf3, 0x4c, 0x7b, 0x26, - 0x16, 0x82, 0xa3, 0x58, 0xc4, 0x69, 0x84, 0x7c, 0x31, 0xf0, 0xa5, 0x12, 0x03, 0x8e, 0x0a, 0x72, - 0xc9, 0xb2, 0x1c, 0x14, 0x58, 0xcd, 0x82, 0xc1, 0x34, 0x83, 0x69, 0x46, 0x87, 0x06, 0x80, 0x09, - 0x20, 0xf7, 0x05, 0xca, 0xbd, 0x2c, 0x80, 0x38, 0xad, 0x54, 0x9d, 0x76, 0xb5, 0x9f, 0x96, 0x3f, - 0x5e, 0x7d, 0xf4, 0xaa, 0x19, 0x41, 0x04, 0x15, 0x5e, 0x4c, 0x15, 0xda, 0x1b, 0x9a, 0xf5, 0x6b, - 0x91, 0x8b, 0x04, 0xad, 0xbe, 0x79, 0x82, 0xf3, 0x2c, 0x83, 0x5c, 0xc9, 0x70, 0x1a, 0xca, 0x14, - 0x12, 0x6c, 0x11, 0xbb, 0xe6, 0x34, 0x26, 0xc7, 0x7b, 0x7c, 0x5c, 0xc2, 0xbd, 0x57, 0x62, 0x1e, - 0x8e, 0x65, 0x06, 0x18, 0x2b, 0xeb, 0xd6, 0x6c, 0x84, 0xd5, 0x08, 0x79, 0x8b, 0xd8, 0xc4, 0x69, - 0x78, 0x57, 0x5f, 0x9b, 0xae, 0x1b, 0xc5, 0xea, 0x6e, 0xee, 0xb3, 0x00, 0x12, 0x1d, 0x43, 0x3f, - 0x2e, 0x86, 0x33, 0xae, 0x96, 0x99, 0x44, 0x36, 0x0a, 0x82, 0x51, 0x18, 0xe6, 0x12, 0xf1, 0xe5, - 0xd9, 0x3d, 0xd5, 0x61, 0x35, 0xe2, 0x2d, 0x95, 0xc4, 0xc9, 0xaf, 0xb5, 0x15, 0x98, 0x75, 0x91, - 0xc0, 0x3c, 0x55, 0xad, 0x03, 0xbb, 0xe6, 0x1c, 0x9d, 0xb7, 0x99, 0x16, 0x14, 0x55, 0xfc, 0xf4, - 0xc3, 0x2e, 0x20, 0x4e, 0xbd, 0xb3, 0xd5, 0xa6, 0x6b, 0x3c, 0xbd, 0x77, 0x9d, 0x7f, 0x64, 0x28, - 0x04, 0x38, 0xd1, 0xd6, 0xde, 0xe5, 0xea, 0x93, 0x1a, 0xab, 0x2d, 0x25, 0xeb, 0x2d, 0x25, 0x1f, - 0x5b, 0x4a, 0x1e, 0x77, 0xd4, 0x58, 0xef, 0xa8, 0xf1, 0xb6, 0xa3, 0xc6, 0x4d, 0xff, 0x8f, 0x5f, - 0x71, 0x1d, 0xf7, 0x5e, 0xf8, 0x58, 0x4e, 0xfc, 0x61, 0x7f, 0xcb, 0xd2, 0xd6, 0xaf, 0x97, 0xed, - 0x0e, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0xef, 0x42, 0x46, 0x9e, 0xe8, 0x01, 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 - if len(m.SupportedDenoms) > 0 { - for iNdEx := len(m.SupportedDenoms) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.SupportedDenoms[iNdEx]) - copy(dAtA[i:], m.SupportedDenoms[iNdEx]) - i = encodeVarintStore(dAtA, i, uint64(len(m.SupportedDenoms[iNdEx]))) - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *Deposit) 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 *Deposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Deposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintStore(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintStore(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintStore(dAtA []byte, offset int, v uint64) int { - offset -= sovStore(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 - if len(m.SupportedDenoms) > 0 { - for _, s := range m.SupportedDenoms { - l = len(s) - n += 1 + l + sovStore(uint64(l)) - } - } - return n -} - -func (m *Deposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovStore(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovStore(uint64(l)) - } - } - return n -} - -func sovStore(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozStore(x uint64) (n int) { - return sovStore(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 ErrIntOverflowStore - } - 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 { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SupportedDenoms", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - 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 ErrInvalidLengthStore - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthStore - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SupportedDenoms = append(m.SupportedDenoms, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipStore(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthStore - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Deposit) 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 ErrIntOverflowStore - } - 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: Deposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Deposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - 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 ErrInvalidLengthStore - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthStore - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = github_com_cosmos_cosmos_sdk_types.AccAddress(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthStore - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthStore - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipStore(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthStore - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipStore(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, ErrIntOverflowStore - } - 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, ErrIntOverflowStore - } - 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, ErrIntOverflowStore - } - 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, ErrInvalidLengthStore - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupStore - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthStore - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthStore = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowStore = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupStore = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/savings/types/tx.pb.go b/x/savings/types/tx.pb.go deleted file mode 100644 index 392172d5..00000000 --- a/x/savings/types/tx.pb.go +++ /dev/null @@ -1,992 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/savings/v1beta1/tx.proto - -package types - -import ( - context "context" - 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" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - 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 - -// MsgDeposit defines the Msg/Deposit request type. -type MsgDeposit struct { - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MsgDeposit) Reset() { *m = MsgDeposit{} } -func (m *MsgDeposit) String() string { return proto.CompactTextString(m) } -func (*MsgDeposit) ProtoMessage() {} -func (*MsgDeposit) Descriptor() ([]byte, []int) { - return fileDescriptor_c0bf8679b144267a, []int{0} -} -func (m *MsgDeposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDeposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDeposit.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 *MsgDeposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDeposit.Merge(m, src) -} -func (m *MsgDeposit) XXX_Size() int { - return m.Size() -} -func (m *MsgDeposit) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDeposit.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDeposit proto.InternalMessageInfo - -func (m *MsgDeposit) GetDepositor() string { - if m != nil { - return m.Depositor - } - return "" -} - -func (m *MsgDeposit) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -// MsgDepositResponse defines the Msg/Deposit response type. -type MsgDepositResponse struct { -} - -func (m *MsgDepositResponse) Reset() { *m = MsgDepositResponse{} } -func (m *MsgDepositResponse) String() string { return proto.CompactTextString(m) } -func (*MsgDepositResponse) ProtoMessage() {} -func (*MsgDepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_c0bf8679b144267a, []int{1} -} -func (m *MsgDepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDepositResponse.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 *MsgDepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDepositResponse.Merge(m, src) -} -func (m *MsgDepositResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgDepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDepositResponse proto.InternalMessageInfo - -// MsgWithdraw defines the Msg/Withdraw request type. -type MsgWithdraw struct { - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MsgWithdraw) Reset() { *m = MsgWithdraw{} } -func (m *MsgWithdraw) String() string { return proto.CompactTextString(m) } -func (*MsgWithdraw) ProtoMessage() {} -func (*MsgWithdraw) Descriptor() ([]byte, []int) { - return fileDescriptor_c0bf8679b144267a, []int{2} -} -func (m *MsgWithdraw) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdraw) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdraw.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 *MsgWithdraw) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdraw.Merge(m, src) -} -func (m *MsgWithdraw) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdraw) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdraw.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdraw proto.InternalMessageInfo - -func (m *MsgWithdraw) GetDepositor() string { - if m != nil { - return m.Depositor - } - return "" -} - -func (m *MsgWithdraw) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -type MsgWithdrawResponse struct { -} - -func (m *MsgWithdrawResponse) Reset() { *m = MsgWithdrawResponse{} } -func (m *MsgWithdrawResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawResponse) ProtoMessage() {} -func (*MsgWithdrawResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_c0bf8679b144267a, []int{3} -} -func (m *MsgWithdrawResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawResponse.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 *MsgWithdrawResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawResponse.Merge(m, src) -} -func (m *MsgWithdrawResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgDeposit)(nil), "kava.savings.v1beta1.MsgDeposit") - proto.RegisterType((*MsgDepositResponse)(nil), "kava.savings.v1beta1.MsgDepositResponse") - proto.RegisterType((*MsgWithdraw)(nil), "kava.savings.v1beta1.MsgWithdraw") - proto.RegisterType((*MsgWithdrawResponse)(nil), "kava.savings.v1beta1.MsgWithdrawResponse") -} - -func init() { proto.RegisterFile("kava/savings/v1beta1/tx.proto", fileDescriptor_c0bf8679b144267a) } - -var fileDescriptor_c0bf8679b144267a = []byte{ - // 368 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x52, 0xcd, 0x4e, 0xea, 0x40, - 0x14, 0xee, 0x5c, 0x12, 0xee, 0x65, 0xd8, 0xf5, 0xd6, 0x04, 0x9a, 0x58, 0x90, 0x55, 0x59, 0x30, - 0x15, 0x4c, 0xdc, 0x0b, 0x6e, 0xd9, 0x60, 0x8c, 0xc6, 0x8d, 0x99, 0xfe, 0x64, 0x98, 0x20, 0x9d, - 0xa6, 0x67, 0x40, 0x7c, 0x0b, 0x5f, 0x43, 0xd6, 0xc6, 0x67, 0x60, 0x49, 0x5c, 0xb9, 0x52, 0x03, - 0x2f, 0x62, 0xda, 0x4e, 0x81, 0x85, 0x86, 0xad, 0xab, 0x9e, 0x99, 0xef, 0x27, 0xdf, 0x7c, 0x3d, - 0xf8, 0x70, 0x44, 0xa7, 0xd4, 0x01, 0x3a, 0xe5, 0x21, 0x03, 0x67, 0xda, 0x76, 0x03, 0x49, 0xdb, - 0x8e, 0x9c, 0x91, 0x28, 0x16, 0x52, 0xe8, 0x46, 0x02, 0x13, 0x05, 0x13, 0x05, 0x9b, 0x96, 0x27, - 0x60, 0x2c, 0xc0, 0x71, 0x29, 0x04, 0x1b, 0x8d, 0x27, 0x78, 0x98, 0xa9, 0xcc, 0x6a, 0x86, 0xdf, - 0xa6, 0x27, 0x27, 0x3b, 0x28, 0xc8, 0x60, 0x82, 0x89, 0xec, 0x3e, 0x99, 0xb2, 0xdb, 0xc6, 0x13, - 0xc2, 0xb8, 0x0f, 0xec, 0x3c, 0x88, 0x04, 0x70, 0xa9, 0x9f, 0xe2, 0x92, 0x9f, 0x8d, 0x22, 0xae, - 0xa0, 0x3a, 0xb2, 0x4b, 0xdd, 0xca, 0xeb, 0x73, 0xcb, 0x50, 0x4e, 0x67, 0xbe, 0x1f, 0x07, 0x00, - 0x17, 0x32, 0xe6, 0x21, 0x1b, 0x6c, 0xa9, 0xba, 0x87, 0x8b, 0x74, 0x2c, 0x26, 0xa1, 0xac, 0xfc, - 0xa9, 0x17, 0xec, 0x72, 0xa7, 0x4a, 0x94, 0x22, 0x09, 0x9a, 0xa7, 0x27, 0x3d, 0xc1, 0xc3, 0xee, - 0xf1, 0xe2, 0xbd, 0xa6, 0xcd, 0x3f, 0x6a, 0x36, 0xe3, 0x72, 0x38, 0x71, 0x89, 0x27, 0xc6, 0x2a, - 0xa8, 0xfa, 0xb4, 0xc0, 0x1f, 0x39, 0xf2, 0x21, 0x0a, 0x20, 0x15, 0xc0, 0x40, 0x59, 0x37, 0x0c, - 0xac, 0x6f, 0xa3, 0x0e, 0x02, 0x88, 0x44, 0x08, 0x41, 0x63, 0x8e, 0x70, 0xb9, 0x0f, 0xec, 0x8a, - 0xcb, 0xa1, 0x1f, 0xd3, 0xfb, 0xdf, 0xfd, 0x84, 0x03, 0xfc, 0x7f, 0x27, 0x6b, 0xfe, 0x86, 0xce, - 0x0b, 0xc2, 0x85, 0x3e, 0x30, 0xfd, 0x12, 0xff, 0xcd, 0xff, 0x44, 0x9d, 0x7c, 0xb7, 0x00, 0x64, - 0x5b, 0x80, 0x69, 0xef, 0x63, 0xe4, 0xf6, 0xfa, 0x35, 0xfe, 0xb7, 0xa9, 0xe7, 0xe8, 0x47, 0x55, - 0x4e, 0x31, 0x9b, 0x7b, 0x29, 0xb9, 0x73, 0xb7, 0xb7, 0x58, 0x59, 0x68, 0xb9, 0xb2, 0xd0, 0xe7, - 0xca, 0x42, 0x8f, 0x6b, 0x4b, 0x5b, 0xae, 0x2d, 0xed, 0x6d, 0x6d, 0x69, 0x37, 0xcd, 0x9d, 0x6e, - 0x12, 0xbb, 0xd6, 0x1d, 0x75, 0x21, 0x9d, 0x9c, 0xd9, 0x66, 0xeb, 0xd3, 0x8a, 0xdc, 0x62, 0xba, - 0x8a, 0x27, 0x5f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x4e, 0x17, 0x24, 0x24, 0x12, 0x03, 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 { - // Deposit defines a method for depositing funds to the savings module account - Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) - // Withdraw defines a method for withdrawing funds to the savings module account - Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) { - out := new(MsgDepositResponse) - err := c.cc.Invoke(ctx, "/kava.savings.v1beta1.Msg/Deposit", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) { - out := new(MsgWithdrawResponse) - err := c.cc.Invoke(ctx, "/kava.savings.v1beta1.Msg/Withdraw", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // Deposit defines a method for depositing funds to the savings module account - Deposit(context.Context, *MsgDeposit) (*MsgDepositResponse, error) - // Withdraw defines a method for withdrawing funds to the savings module account - Withdraw(context.Context, *MsgWithdraw) (*MsgWithdrawResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Deposit(ctx context.Context, req *MsgDeposit) (*MsgDepositResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposit not implemented") -} -func (*UnimplementedMsgServer) Withdraw(ctx context.Context, req *MsgWithdraw) (*MsgWithdrawResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Withdraw not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Deposit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgDeposit) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Deposit(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.savings.v1beta1.Msg/Deposit", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Deposit(ctx, req.(*MsgDeposit)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Withdraw_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdraw) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Withdraw(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.savings.v1beta1.Msg/Withdraw", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Withdraw(ctx, req.(*MsgWithdraw)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.savings.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Deposit", - Handler: _Msg_Deposit_Handler, - }, - { - MethodName: "Withdraw", - Handler: _Msg_Withdraw_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/savings/v1beta1/tx.proto", -} - -func (m *MsgDeposit) 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 *MsgDeposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDeposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgDepositResponse) 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 *MsgDepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgWithdraw) 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 *MsgWithdraw) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdraw) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawResponse) 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 *MsgWithdrawResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgDeposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgDepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgWithdraw) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgWithdrawResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgDeposit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDeposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDeposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDepositResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdraw) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdraw: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdraw: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/swap/client/cli/query.go b/x/swap/client/cli/query.go deleted file mode 100644 index a2fb1eec..00000000 --- a/x/swap/client/cli/query.go +++ /dev/null @@ -1,154 +0,0 @@ -package cli - -import ( - "context" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - - "github.com/kava-labs/kava/x/swap/types" -) - -// flags for cli queries -const ( - flagOwner = "owner" - flagPool = "pool" -) - -// GetQueryCmd returns the cli query commands for the module -func GetQueryCmd(queryRoute string) *cobra.Command { - swapQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the swap module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - queryParamsCmd(queryRoute), - queryDepositsCmd(queryRoute), - queryPoolsCmd(queryRoute), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - swapQueryCmd.AddCommand(cmds...) - - return swapQueryCmd -} - -func queryParamsCmd(queryRoute string) *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: "get the swap module parameters", - Long: "Get the current global swap module parameters.", - 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(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } -} - -func queryDepositsCmd(queryRoute string) *cobra.Command { - cmd := &cobra.Command{ - Use: "deposits", - Short: "get liquidity provider deposits", - Long: strings.TrimSpace(`get liquidity provider deposits: - Example: - $ kvcli q swap deposits --pool bnb:usdx - $ kvcli q swap deposits --owner kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny - $ kvcli q swap deposits --pool bnb:usdx --owner kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny - $ kvcli q swap deposits --page=2 --limit=100 - `, - ), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - bechOwnerAddr, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - pool, err := cmd.Flags().GetString(flagPool) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - params := types.QueryDepositsRequest{ - Owner: bechOwnerAddr, - PoolId: pool, - Pagination: pageReq, - } - res, err := queryClient.Deposits(context.Background(), ¶ms) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, "deposits") - - cmd.Flags().String(flagPool, "", "pool name") - cmd.Flags().String(flagOwner, "", "owner, also known as a liquidity provider") - - return cmd -} - -func queryPoolsCmd(queryRoute string) *cobra.Command { - cmd := &cobra.Command{ - Use: "pools", - Short: "get statistics for all pools", - Long: strings.TrimSpace(`get statistics for all liquidity pools: - Example: - $ kvcli q swap pools`, - ), - 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) - - params := types.QueryPoolsRequest{} - res, err := queryClient.Pools(context.Background(), ¶ms) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - return cmd -} diff --git a/x/swap/client/cli/tx.go b/x/swap/client/cli/tx.go deleted file mode 100644 index f6f93365..00000000 --- a/x/swap/client/cli/tx.go +++ /dev/null @@ -1,228 +0,0 @@ -package cli - -import ( - "fmt" - "strconv" - - "github.com/spf13/cobra" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/kava-labs/kava/x/swap/types" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - swapTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName), - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - getCmdDeposit(), - getCmdWithdraw(), - getCmdSwapExactForTokens(), - getCmdSwapForExactTokens(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - swapTxCmd.AddCommand(cmds...) - - return swapTxCmd -} - -func getCmdDeposit() *cobra.Command { - return &cobra.Command{ - Use: "deposit [tokenA] [tokenB] [slippage] [deadline]", - Short: "deposit coins to a swap liquidity pool", - Example: fmt.Sprintf( - `%s tx %s deposit 10000000ukava 10000000usdx 0.01 1624224736 --from `, - version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - tokenA, err := sdk.ParseCoinNormalized(args[0]) - if err != nil { - return err - } - - tokenB, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - slippage, err := sdk.NewDecFromStr(args[2]) - if err != nil { - return err - } - - deadline, err := strconv.ParseInt(args[3], 10, 64) - if err != nil { - return err - } - - signer := clientCtx.GetFromAddress() - msg := types.NewMsgDeposit(signer.String(), tokenA, tokenB, slippage, deadline) - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} - -func getCmdWithdraw() *cobra.Command { - return &cobra.Command{ - Use: "withdraw [shares] [minCoinA] [minCoinB] [deadline]", - Short: "withdraw coins from a swap liquidity pool", - Example: fmt.Sprintf( - `%s tx %s withdraw 153000 10000000ukava 20000000usdx 176293740 --from `, - version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - numShares, err := strconv.ParseInt(args[0], 10, 64) - if err != nil { - return err - } - shares := sdkmath.NewInt(numShares) - - minTokenA, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - minTokenB, err := sdk.ParseCoinNormalized(args[2]) - if err != nil { - return err - } - - deadline, err := strconv.ParseInt(args[3], 10, 64) - if err != nil { - return err - } - - fromAddr := clientCtx.GetFromAddress() - msg := types.NewMsgWithdraw(fromAddr.String(), shares, minTokenA, minTokenB, deadline) - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} - -func getCmdSwapExactForTokens() *cobra.Command { - return &cobra.Command{ - Use: "swap-exact-for-tokens [exactCoinA] [coinB] [slippage] [deadline]", - Short: "swap an exact amount of token a for token b", - Example: fmt.Sprintf( - `%s tx %s swap-exact-for-tokens 1000000ukava 5000000usdx 0.01 1624224736 --from `, - version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - exactTokenA, err := sdk.ParseCoinNormalized(args[0]) - if err != nil { - return err - } - - tokenB, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - slippage, err := sdk.NewDecFromStr(args[2]) - if err != nil { - return err - } - - deadline, err := strconv.ParseInt(args[3], 10, 64) - if err != nil { - return err - } - - fromAddr := clientCtx.GetFromAddress() - msg := types.NewMsgSwapExactForTokens(fromAddr.String(), exactTokenA, tokenB, slippage, deadline) - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} - -func getCmdSwapForExactTokens() *cobra.Command { - return &cobra.Command{ - Use: "swap-for-exact-tokens [coinA] [exactCoinB] [slippage] [deadline]", - Short: "swap token a for exact amount of token b", - Example: fmt.Sprintf( - `%s tx %s swap-for-exact-tokens 1000000ukava 5000000usdx 0.01 1624224736 --from `, - version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - tokenA, err := sdk.ParseCoinNormalized(args[0]) - if err != nil { - return err - } - - exactTokenB, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - slippage, err := sdk.NewDecFromStr(args[2]) - if err != nil { - return err - } - - deadline, err := strconv.ParseInt(args[3], 10, 64) - if err != nil { - return err - } - - fromAddr := clientCtx.GetFromAddress() - msg := types.NewMsgSwapForExactTokens(fromAddr.String(), tokenA, exactTokenB, slippage, deadline) - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} diff --git a/x/swap/genesis.go b/x/swap/genesis.go deleted file mode 100644 index 07ce5771..00000000 --- a/x/swap/genesis.go +++ /dev/null @@ -1,34 +0,0 @@ -package swap - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/swap/keeper" - "github.com/kava-labs/kava/x/swap/types" -) - -// InitGenesis initializes story state from genesis file -func InitGenesis(ctx sdk.Context, k keeper.Keeper, gs types.GenesisState) { - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - k.SetParams(ctx, gs.Params) - for _, pr := range gs.PoolRecords { - k.SetPool(ctx, pr) - } - for _, sh := range gs.ShareRecords { - k.SetDepositorShares(ctx, sh) - } -} - -// ExportGenesis exports the genesis state -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { - params := k.GetParams(ctx) - pools := k.GetAllPools(ctx) - shares := k.GetAllDepositorShares(ctx) - - return types.NewGenesisState(params, pools, shares) -} diff --git a/x/swap/genesis_test.go b/x/swap/genesis_test.go deleted file mode 100644 index ea7b72b2..00000000 --- a/x/swap/genesis_test.go +++ /dev/null @@ -1,151 +0,0 @@ -package swap_test - -import ( - "testing" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/swap" - "github.com/kava-labs/kava/x/swap/testutil" - "github.com/kava-labs/kava/x/swap/types" - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type genesisTestSuite struct { - testutil.Suite -} - -func (suite *genesisTestSuite) Test_InitGenesis_ValidationPanic() { - invalidState := types.NewGenesisState( - types.Params{ - SwapFee: sdk.NewDec(-1), - }, - types.PoolRecords{}, - types.ShareRecords{}, - ) - - suite.Panics(func() { - swap.InitGenesis(suite.Ctx, suite.Keeper, invalidState) - }, "expected init genesis to panic with invalid state") -} - -func (suite *genesisTestSuite) Test_InitAndExportGenesis() { - depositor_1, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - suite.Require().NoError(err) - depositor_2, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") - suite.Require().NoError(err) - - // slices are sorted by key as stored in the data store, so init and export can be compared with equal - state := types.NewGenesisState( - types.Params{ - AllowedPools: types.AllowedPools{types.NewAllowedPool("ukava", "usdx")}, - SwapFee: sdk.MustNewDecFromStr("0.00255"), - }, - types.PoolRecords{ - types.NewPoolRecord(sdk.NewCoins(sdk.NewCoin("hard", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(2e6))), sdkmath.NewInt(1e6)), - types.NewPoolRecord(sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6))), sdkmath.NewInt(3e6)), - }, - types.ShareRecords{ - types.NewShareRecord(depositor_2, types.PoolID("hard", "usdx"), sdkmath.NewInt(1e6)), - types.NewShareRecord(depositor_1, types.PoolID("ukava", "usdx"), sdkmath.NewInt(3e6)), - }, - ) - - swap.InitGenesis(suite.Ctx, suite.Keeper, state) - suite.Equal(state.Params, suite.Keeper.GetParams(suite.Ctx)) - - poolRecord1, _ := suite.Keeper.GetPool(suite.Ctx, types.PoolID("hard", "usdx")) - suite.Equal(state.PoolRecords[0], poolRecord1) - poolRecord2, _ := suite.Keeper.GetPool(suite.Ctx, types.PoolID("ukava", "usdx")) - suite.Equal(state.PoolRecords[1], poolRecord2) - - shareRecord1, _ := suite.Keeper.GetDepositorShares(suite.Ctx, depositor_2, types.PoolID("hard", "usdx")) - suite.Equal(state.ShareRecords[0], shareRecord1) - shareRecord2, _ := suite.Keeper.GetDepositorShares(suite.Ctx, depositor_1, types.PoolID("ukava", "usdx")) - suite.Equal(state.ShareRecords[1], shareRecord2) - - exportedState := swap.ExportGenesis(suite.Ctx, suite.Keeper) - suite.Equal(state, exportedState) -} - -func (suite *genesisTestSuite) Test_Marshall() { - depositor_1, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - suite.Require().NoError(err) - depositor_2, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") - suite.Require().NoError(err) - - // slices are sorted by key as stored in the data store, so init and export can be compared with equal - state := types.NewGenesisState( - types.Params{ - AllowedPools: types.AllowedPools{types.NewAllowedPool("ukava", "usdx")}, - SwapFee: sdk.MustNewDecFromStr("0.00255"), - }, - types.PoolRecords{ - types.NewPoolRecord(sdk.NewCoins(sdk.NewCoin("hard", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(2e6))), sdkmath.NewInt(1e6)), - types.NewPoolRecord(sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6))), sdkmath.NewInt(3e6)), - }, - types.ShareRecords{ - types.NewShareRecord(depositor_2, types.PoolID("hard", "usdx"), sdkmath.NewInt(1e6)), - types.NewShareRecord(depositor_1, types.PoolID("ukava", "usdx"), sdkmath.NewInt(3e6)), - }, - ) - - encodingCfg := app.MakeEncodingConfig() - cdc := encodingCfg.Marshaler - - bz, err := cdc.Marshal(&state) - suite.Require().NoError(err, "expected genesis state to marshal without error") - - var decodedState types.GenesisState - err = cdc.Unmarshal(bz, &decodedState) - suite.Require().NoError(err, "expected genesis state to unmarshal without error") - - suite.Equal(state, decodedState) -} - -func (suite *genesisTestSuite) Test_LegacyJSONConversion() { - depositor_1, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - suite.Require().NoError(err) - depositor_2, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") - suite.Require().NoError(err) - - // slices are sorted by key as stored in the data store, so init and export can be compared with equal - state := types.NewGenesisState( - types.Params{ - AllowedPools: types.AllowedPools{types.NewAllowedPool("ukava", "usdx")}, - SwapFee: sdk.MustNewDecFromStr("0.00255"), - }, - types.PoolRecords{ - types.NewPoolRecord(sdk.NewCoins(sdk.NewCoin("hard", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(2e6))), sdkmath.NewInt(1e6)), - types.NewPoolRecord(sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6))), sdkmath.NewInt(3e6)), - }, - types.ShareRecords{ - types.NewShareRecord(depositor_2, types.PoolID("hard", "usdx"), sdkmath.NewInt(1e6)), - types.NewShareRecord(depositor_1, types.PoolID("ukava", "usdx"), sdkmath.NewInt(3e6)), - }, - ) - - encodingCfg := app.MakeEncodingConfig() - cdc := encodingCfg.Marshaler - legacyCdc := encodingCfg.Amino - - protoJson, err := cdc.MarshalJSON(&state) - suite.Require().NoError(err, "expected genesis state to marshal amino json without error") - - aminoJson, err := legacyCdc.MarshalJSON(&state) - suite.Require().NoError(err, "expected genesis state to marshal amino json without error") - - suite.JSONEq(string(protoJson), string(aminoJson), "expected json outputs to be equal") - - var importedState types.GenesisState - err = cdc.UnmarshalJSON(aminoJson, &importedState) - suite.Require().NoError(err, "expected amino json to unmarshall to proto without error") - - suite.Equal(state, importedState, "expected genesis state to be equal") -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(genesisTestSuite)) -} diff --git a/x/swap/keeper/deposit.go b/x/swap/keeper/deposit.go deleted file mode 100644 index f88ba775..00000000 --- a/x/swap/keeper/deposit.go +++ /dev/null @@ -1,139 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/swap/types" -) - -// Deposit creates a new pool or adds liquidity to an existing pool. For a pool to be created, a pool -// for the coin denominations must not exist yet, and it must be allowed by the swap module parameters. -// -// When adding liquidity to an existing pool, the provided coins are considered to be the desired deposit -// amount, and the actual deposited coins may be less than or equal to the provided coins. A deposit -// will never be exceed the coinA and coinB amounts. -// -// The slippage is calculated using both the price and inverse price of the provided coinA and coinB. -// Since adding liquidity is not directional, like a swap would be, using both the price (coinB/coinA), -// and the inverse price (coinA/coinB), protects the depositor from a large deviation in their deposit. -// -// The amount deposited may only change by B' < B or A' < A -- either B depreciates, or A depreciates. -// Therefore, slippage can be written as a function of this depreciation d. Where the new price is -// B*(1-d)/A or A*(1-d)/B, and the inverse of each, and is A/(B*(1-d)) and B/(A*(1-d)) -// respectively. -// -// Since 1/(1-d) >= (1-d) for d <= 1, the maximum slippage is always in the appreciating price -// A/(B*(1-d)) and B/(A*(1-d)). In other words, when the price of an asset depreciates, the -// inverse price -- or the price of the other pool asset, appreciates by a larger amount. -// It's this percent change we calculate and compare to the slippage limit provided. -// -// For example, if we have a pool with 100e6 ukava and 400e6 usdx. The ukava price is 4 usdx and the -// usdx price is 0.25 ukava. If a depositor adds liquidity of 4e6 ukava and 14e6 usdx, a kava price of -// 3.50 usdx and a usdx price of 0.29 ukava. This is a -12.5% slippage is the ukava price, and a 14.3% -// slippage in the usdx price. -// -// These slippages can be calculated by S_B = ((A/B')/(A/B) - 1) and S_A ((B/A')/(B/A) - 1), simplifying to -// S_B = (A/A' - 1), and S_B = (B/B' - 1). An error is returned when max(S_A, S_B) > slippageLimit. -func (k Keeper) Deposit(ctx sdk.Context, depositor sdk.AccAddress, coinA sdk.Coin, coinB sdk.Coin, slippageLimit sdk.Dec) error { - desiredAmount := sdk.NewCoins(coinA, coinB) - - poolID := types.PoolIDFromCoins(desiredAmount) - poolRecord, found := k.GetPool(ctx, poolID) - - var ( - pool *types.DenominatedPool - depositAmount sdk.Coins - shares sdkmath.Int - err error - ) - if found { - pool, depositAmount, shares, err = k.addLiquidityToPool(ctx, poolRecord, depositor, desiredAmount) - } else { - pool, depositAmount, shares, err = k.initializePool(ctx, poolID, depositor, desiredAmount) - } - if err != nil { - return err - } - - if depositAmount.AmountOf(coinA.Denom).IsZero() || depositAmount.AmountOf(coinB.Denom).IsZero() { - return errorsmod.Wrap(types.ErrInsufficientLiquidity, "deposit must be increased") - } - - if shares.IsZero() { - return errorsmod.Wrap(types.ErrInsufficientLiquidity, "deposit must be increased") - } - - maxPercentPriceChange := sdk.MaxDec( - sdk.NewDecFromInt(desiredAmount.AmountOf(coinA.Denom)).Quo(sdk.NewDecFromInt(depositAmount.AmountOf(coinA.Denom))), - sdk.NewDecFromInt(desiredAmount.AmountOf(coinB.Denom)).Quo(sdk.NewDecFromInt(depositAmount.AmountOf(coinB.Denom))), - ) - slippage := maxPercentPriceChange.Sub(sdk.OneDec()) - - if slippage.GT(slippageLimit) { - return errorsmod.Wrapf(types.ErrSlippageExceeded, "slippage %s > limit %s", slippage, slippageLimit) - } - - k.updatePool(ctx, poolID, pool) - if shareRecord, hasExistingShares := k.GetDepositorShares(ctx, depositor, poolID); hasExistingShares { - k.BeforePoolDepositModified(ctx, poolID, depositor, shareRecord.SharesOwned) - k.updateDepositorShares(ctx, depositor, poolID, shareRecord.SharesOwned.Add(shares)) - } else { - k.updateDepositorShares(ctx, depositor, poolID, shares) - k.AfterPoolDepositCreated(ctx, poolID, depositor, shares) - } - - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, depositor, types.ModuleAccountName, depositAmount) - if err != nil { - return err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeSwapDeposit, - sdk.NewAttribute(types.AttributeKeyPoolID, poolID), - sdk.NewAttribute(types.AttributeKeyDepositor, depositor.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, depositAmount.String()), - sdk.NewAttribute(types.AttributeKeyShares, shares.String()), - ), - ) - - return nil -} - -func (k Keeper) depositAllowed(ctx sdk.Context, poolID string) bool { - params := k.GetParams(ctx) - for _, p := range params.AllowedPools { - if poolID == types.PoolID(p.TokenA, p.TokenB) { - return true - } - } - return false -} - -func (k Keeper) initializePool(ctx sdk.Context, poolID string, depositor sdk.AccAddress, reserves sdk.Coins) (*types.DenominatedPool, sdk.Coins, sdkmath.Int, error) { - if allowed := k.depositAllowed(ctx, poolID); !allowed { - return nil, sdk.Coins{}, sdk.ZeroInt(), errorsmod.Wrap(types.ErrNotAllowed, fmt.Sprintf("can not create pool '%s'", poolID)) - } - - pool, err := types.NewDenominatedPool(reserves) - if err != nil { - return nil, sdk.Coins{}, sdk.ZeroInt(), err - } - - return pool, pool.Reserves(), pool.TotalShares(), nil -} - -func (k Keeper) addLiquidityToPool(ctx sdk.Context, record types.PoolRecord, depositor sdk.AccAddress, desiredAmount sdk.Coins) (*types.DenominatedPool, sdk.Coins, sdkmath.Int, error) { - pool, err := types.NewDenominatedPoolWithExistingShares(record.Reserves(), record.TotalShares) - if err != nil { - return nil, sdk.Coins{}, sdk.ZeroInt(), err - } - - depositAmount, shares := pool.AddLiquidity(desiredAmount) - - return pool, depositAmount, shares, nil -} diff --git a/x/swap/keeper/deposit_test.go b/x/swap/keeper/deposit_test.go deleted file mode 100644 index f0bf042a..00000000 --- a/x/swap/keeper/deposit_test.go +++ /dev/null @@ -1,341 +0,0 @@ -package keeper_test - -import ( - "errors" - "fmt" - - "github.com/kava-labs/kava/x/swap/types" - - sdkmath "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -func (suite *keeperTestSuite) TestDeposit_CreatePool_PoolNotAllowed() { - depositor := suite.CreateAccount(sdk.Coins{}) - amountA := sdk.NewCoin("ukava", sdkmath.NewInt(10e6)) - amountB := sdk.NewCoin("usdx", sdkmath.NewInt(50e6)) - - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), amountA, amountB, sdk.MustNewDecFromStr("0.01")) - suite.Require().EqualError(err, "can not create pool 'ukava:usdx': not allowed") -} - -func (suite *keeperTestSuite) TestDeposit_InsufficientFunds() { - testCases := []struct { - name string - balanceA sdk.Coin - balanceB sdk.Coin - depositA sdk.Coin - depositB sdk.Coin - }{ - { - name: "no balance", - balanceA: sdk.NewCoin("unuseddenom", sdk.ZeroInt()), - balanceB: sdk.NewCoin("unuseddenom", sdk.ZeroInt()), - depositA: sdk.NewCoin("ukava", sdkmath.NewInt(100)), - depositB: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - }, - { - name: "low balance", - balanceA: sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), - balanceB: sdk.NewCoin("usdx", sdkmath.NewInt(1000000)), - depositA: sdk.NewCoin("ukava", sdkmath.NewInt(1000001)), - depositB: sdk.NewCoin("usdx", sdkmath.NewInt(10000001)), - }, - { - name: "large balance difference", - balanceA: sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - balanceB: sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), - depositA: sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - depositB: sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - pool := types.NewAllowedPool(tc.depositA.Denom, tc.depositB.Denom) - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.NewAllowedPools(pool), types.DefaultSwapFee)) - - balance := sdk.NewCoins(tc.balanceA, tc.balanceB) - depositor := suite.CreateAccount(balance) - - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), tc.depositA, tc.depositB, sdk.MustNewDecFromStr("0")) - // TODO: wrap in module specific error? - suite.Require().True(errors.Is(err, sdkerrors.ErrInsufficientFunds), fmt.Sprintf("got err %s", err)) - - suite.SetupTest() - // test deposit to existing pool insuffient funds - err = suite.CreatePool(sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.NewCoin("usdx", sdkmath.NewInt(50e6)))) - suite.Require().NoError(err) - err = suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), tc.depositA, tc.depositB, sdk.MustNewDecFromStr("10")) - suite.Require().True(errors.Is(err, sdkerrors.ErrInsufficientFunds)) - }) - } -} - -func (suite *keeperTestSuite) TestDeposit_InsufficientFunds_Vesting() { - testCases := []struct { - name string - balanceA sdk.Coin - balanceB sdk.Coin - vestingA sdk.Coin - vestingB sdk.Coin - depositA sdk.Coin - depositB sdk.Coin - }{ - { - name: "no balance, vesting only", - balanceA: sdk.NewCoin("ukava", sdk.ZeroInt()), - balanceB: sdk.NewCoin("usdx", sdk.ZeroInt()), - vestingA: sdk.NewCoin("ukava", sdkmath.NewInt(100)), - vestingB: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - depositA: sdk.NewCoin("ukava", sdkmath.NewInt(100)), - depositB: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - }, - { - name: "vesting matches balance exactly", - balanceA: sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), - balanceB: sdk.NewCoin("usdx", sdkmath.NewInt(1000000)), - vestingA: sdk.NewCoin("ukava", sdkmath.NewInt(1)), - vestingB: sdk.NewCoin("usdx", sdkmath.NewInt(1)), - depositA: sdk.NewCoin("ukava", sdkmath.NewInt(1000001)), - depositB: sdk.NewCoin("usdx", sdkmath.NewInt(10000001)), - }, - { - name: "large balance difference, vesting covers difference", - balanceA: sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - balanceB: sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), - vestingA: sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - vestingB: sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - depositA: sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - depositB: sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - pool := types.NewAllowedPool(tc.depositA.Denom, tc.depositB.Denom) - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.NewAllowedPools(pool), types.DefaultSwapFee)) - - balance := sdk.NewCoins(tc.balanceA, tc.balanceB) - vesting := sdk.NewCoins(tc.vestingA, tc.vestingB) - depositor := suite.CreateVestingAccount(balance, vesting) - - // test create pool insuffient funds - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), tc.depositA, tc.depositB, sdk.MustNewDecFromStr("0")) - // TODO: wrap in module specific error? - suite.Require().True(errors.Is(err, sdkerrors.ErrInsufficientFunds)) - - suite.SetupTest() - // test deposit to existing pool insuffient funds - err = suite.CreatePool(sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.NewCoin("usdx", sdkmath.NewInt(50e6)))) - suite.Require().NoError(err) - err = suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), tc.depositA, tc.depositB, sdk.MustNewDecFromStr("4")) - suite.Require().True(errors.Is(err, sdkerrors.ErrInsufficientFunds)) - }) - } -} - -func (suite *keeperTestSuite) TestDeposit_CreatePool() { - pool := types.NewAllowedPool("ukava", "usdx") - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.NewAllowedPools(pool), types.DefaultSwapFee)) - - amountA := sdk.NewCoin(pool.TokenA, sdkmath.NewInt(11e6)) - amountB := sdk.NewCoin(pool.TokenB, sdkmath.NewInt(51e6)) - balance := sdk.NewCoins(amountA, amountB) - depositor := suite.CreateAccount(balance) - - depositA := sdk.NewCoin(pool.TokenA, sdkmath.NewInt(10e6)) - depositB := sdk.NewCoin(pool.TokenB, sdkmath.NewInt(50e6)) - deposit := sdk.NewCoins(depositA, depositB) - - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), depositA, depositB, sdk.MustNewDecFromStr("0")) - suite.Require().NoError(err) - suite.AccountBalanceEqual(depositor.GetAddress(), sdk.NewCoins(amountA.Sub(depositA), amountB.Sub(depositB))) - suite.ModuleAccountBalanceEqual(sdk.NewCoins(depositA, depositB)) - suite.PoolLiquidityEqual(deposit) - suite.PoolShareValueEqual(depositor, pool, deposit) - - suite.EventsContains(suite.Ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeSwapDeposit, - sdk.NewAttribute(types.AttributeKeyPoolID, pool.Name()), - sdk.NewAttribute(types.AttributeKeyDepositor, depositor.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, deposit.String()), - sdk.NewAttribute(types.AttributeKeyShares, "22360679"), - )) -} - -func (suite *keeperTestSuite) TestDeposit_PoolExists() { - pool := types.NewAllowedPool("ukava", "usdx") - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - err := suite.CreatePool(reserves) - suite.Require().NoError(err) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ) - depositor := suite.NewAccountFromAddr(sdk.AccAddress("new depositor-------"), balance) // TODO this is padded to the correct length, find a nicer way of creating test addresses - - depositA := sdk.NewCoin("usdx", balance.AmountOf("usdx")) - depositB := sdk.NewCoin("ukava", balance.AmountOf("ukava")) - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - err = suite.Keeper.Deposit(ctx, depositor.GetAddress(), depositA, depositB, sdk.MustNewDecFromStr("4")) - suite.Require().NoError(err) - - expectedDeposit := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ) - - expectedShareValue := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(999999)), - sdk.NewCoin("usdx", sdkmath.NewInt(4999998)), - ) - - suite.AccountBalanceEqual(depositor.GetAddress(), balance.Sub(expectedDeposit...)) - suite.ModuleAccountBalanceEqual(reserves.Add(expectedDeposit...)) - suite.PoolLiquidityEqual(reserves.Add(expectedDeposit...)) - suite.PoolShareValueEqual(depositor, pool, expectedShareValue) - - suite.EventsContains(ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeSwapDeposit, - sdk.NewAttribute(types.AttributeKeyPoolID, types.PoolID(pool.TokenA, pool.TokenB)), - sdk.NewAttribute(types.AttributeKeyDepositor, depositor.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, expectedDeposit.String()), - sdk.NewAttribute(types.AttributeKeyShares, "2236067"), - )) -} - -func (suite *keeperTestSuite) TestDeposit_MultipleDeposit() { - fundsToDeposit := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(25e6)), - ) - owner := suite.CreateAccount(fundsToDeposit) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - initialShares := sdkmath.NewInt(30e6) - poolID := suite.setupPool(reserves, initialShares, owner.GetAddress()) - - depositA := sdk.NewCoin("usdx", fundsToDeposit.AmountOf("usdx")) - depositB := sdk.NewCoin("ukava", fundsToDeposit.AmountOf("ukava")) - - err := suite.Keeper.Deposit(suite.Ctx, owner.GetAddress(), depositA, depositB, sdk.MustNewDecFromStr("4")) - suite.Require().NoError(err) - - totalDeposit := reserves.Add(fundsToDeposit...) - totalShares := initialShares.Add(sdkmath.NewInt(15e6)) - - suite.AccountBalanceEqual(owner.GetAddress(), sdk.Coins{}) - suite.ModuleAccountBalanceEqual(totalDeposit) - suite.PoolLiquidityEqual(totalDeposit) - suite.PoolDepositorSharesEqual(owner.GetAddress(), poolID, totalShares) - - suite.EventsContains(suite.Ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeSwapDeposit, - sdk.NewAttribute(types.AttributeKeyPoolID, poolID), - sdk.NewAttribute(types.AttributeKeyDepositor, owner.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, fundsToDeposit.String()), - sdk.NewAttribute(types.AttributeKeyShares, "15000000"), - )) -} - -func (suite *keeperTestSuite) TestDeposit_Slippage() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - - testCases := []struct { - depositA sdk.Coin - depositB sdk.Coin - slippage sdk.Dec - shouldFail bool - }{ - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.7"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.8"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("3"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("4"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4e6)), sdk.MustNewDecFromStr("0.25"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4e6)), sdk.MustNewDecFromStr("0.2"), true}, - } - - for _, tc := range testCases { - suite.Run(fmt.Sprintf("depositA=%s depositB=%s slippage=%s", tc.depositA, tc.depositB, tc.slippage), func() { - suite.SetupTest() - - err := suite.CreatePool(reserves) - suite.Require().NoError(err) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(100e6)), - ) - depositor := suite.CreateAccount(balance) - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - err = suite.Keeper.Deposit(ctx, depositor.GetAddress(), tc.depositA, tc.depositB, tc.slippage) - if tc.shouldFail { - suite.Require().Error(err) - suite.Contains(err.Error(), "slippage exceeded") - } else { - suite.NoError(err) - } - }) - } -} - -func (suite *keeperTestSuite) TestDeposit_InsufficientLiquidity() { - testCases := []struct { - poolA sdk.Coin - poolB sdk.Coin - poolShares sdkmath.Int - depositA sdk.Coin - depositB sdk.Coin - }{ - // test deposit amount truncating to zero - {sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), sdkmath.NewInt(40e6), sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1))}, - // test share value rounding to zero - {sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), sdkmath.NewInt(100), sdk.NewCoin("ukava", sdkmath.NewInt(1000)), sdk.NewCoin("usdx", sdkmath.NewInt(1000))}, - } - - for _, tc := range testCases { - suite.Run(fmt.Sprintf("depositA=%s depositB=%s", tc.depositA, tc.depositB), func() { - suite.SetupTest() - - record := types.PoolRecord{ - PoolID: types.PoolID("ukava", "usdx"), - ReservesA: tc.poolA, - ReservesB: tc.poolB, - TotalShares: tc.poolShares, - } - - suite.Keeper.SetPool(suite.Ctx, record) - - balance := sdk.NewCoins(tc.depositA, tc.depositB) - depositor := suite.CreateAccount(balance) - - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), tc.depositA, tc.depositB, sdk.MustNewDecFromStr("10")) - suite.EqualError(err, "deposit must be increased: insufficient liquidity") - }) - } -} diff --git a/x/swap/keeper/grpc_query.go b/x/swap/keeper/grpc_query.go deleted file mode 100644 index ba697c54..00000000 --- a/x/swap/keeper/grpc_query.go +++ /dev/null @@ -1,150 +0,0 @@ -package keeper - -import ( - "context" - "strings" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - - "github.com/kava-labs/kava/x/swap/types" -) - -type queryServer struct { - keeper Keeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -var _ types.QueryServer = queryServer{} - -// Params implements the gRPC service handler for querying x/swap parameters. -func (s queryServer) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - params := s.keeper.GetParams(sdkCtx) - - return &types.QueryParamsResponse{Params: params}, nil -} - -// Pools implements the Query/Pools gRPC method -func (s queryServer) Pools(c context.Context, req *types.QueryPoolsRequest) (*types.QueryPoolsResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(c) - store := prefix.NewStore(ctx.KVStore(s.keeper.key), types.PoolKeyPrefix) - - var queryResults []types.PoolResponse - pageRes, err := query.FilteredPaginate(store, req.Pagination, func(_, value []byte, shouldAccumulate bool) (bool, error) { - var poolRecord types.PoolRecord - err := s.keeper.cdc.Unmarshal(value, &poolRecord) - if err != nil { - return false, err - } - - if (len(req.PoolId) > 0) && strings.Compare(poolRecord.PoolID, req.PoolId) != 0 { - return false, nil - } - - if shouldAccumulate { - denominatedPool, err := types.NewDenominatedPoolWithExistingShares(poolRecord.Reserves(), poolRecord.TotalShares) - if err != nil { - return true, types.ErrInvalidPool - } - totalCoins := denominatedPool.ShareValue(denominatedPool.TotalShares()) - queryResult := types.PoolResponse{ - Name: poolRecord.PoolID, - Coins: totalCoins, - TotalShares: denominatedPool.TotalShares(), - } - queryResults = append(queryResults, queryResult) - } - return true, nil - }) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "paginate: %v", err) - } - - return &types.QueryPoolsResponse{ - Pools: queryResults, - Pagination: pageRes, - }, nil -} - -// Deposits implements the Query/Deposits gRPC method -func (s queryServer) Deposits(c context.Context, req *types.QueryDepositsRequest) (*types.QueryDepositsResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(c) - store := prefix.NewStore(ctx.KVStore(s.keeper.key), types.DepositorPoolSharesPrefix) - - records := types.ShareRecords{} - pageRes, err := query.FilteredPaginate( - store, - req.Pagination, - func(key []byte, value []byte, accumulate bool) (bool, error) { - var record types.ShareRecord - err := s.keeper.cdc.Unmarshal(value, &record) - if err != nil { - return false, err - } - - // Filter for results match the request's pool ID/owner params if given - matchOwner, matchPool := true, true - if len(req.Owner) > 0 { - matchOwner = record.Depositor.String() == req.Owner - } - if len(req.PoolId) > 0 { - matchPool = strings.Compare(record.PoolID, req.PoolId) == 0 - } - if !(matchOwner && matchPool) { - // inform paginate that there was no match on this key - return false, nil - } - if accumulate { - // only add to results if paginate tells us to - records = append(records, record) - } - // inform paginate that were was a match on this key - return true, nil - }, - ) - if err != nil { - return nil, status.Error(codes.Internal, err.Error()) - } - - var queryResults []types.DepositResponse - for _, record := range records { - pool, err := s.keeper.loadDenominatedPool(ctx, record.PoolID) - if err != nil { - return nil, err - } - shareValue := pool.ShareValue(record.SharesOwned) - queryResult := types.DepositResponse{ - Depositor: record.Depositor.String(), - PoolId: record.PoolID, - SharesOwned: record.SharesOwned, - SharesValue: shareValue, - } - queryResults = append(queryResults, queryResult) - } - - return &types.QueryDepositsResponse{ - Deposits: queryResults, - Pagination: pageRes, - }, nil -} diff --git a/x/swap/keeper/hooks.go b/x/swap/keeper/hooks.go deleted file mode 100644 index 11e0f510..00000000 --- a/x/swap/keeper/hooks.go +++ /dev/null @@ -1,25 +0,0 @@ -package keeper - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/swap/types" -) - -// Implements SwapHooks interface -var _ types.SwapHooks = Keeper{} - -// AfterPoolDepositCreated - call hook if registered -func (k Keeper) AfterPoolDepositCreated(ctx sdk.Context, poolID string, depositor sdk.AccAddress, sharesOwned sdkmath.Int) { - if k.hooks != nil { - k.hooks.AfterPoolDepositCreated(ctx, poolID, depositor, sharesOwned) - } -} - -// BeforePoolDepositModified - call hook if registered -func (k Keeper) BeforePoolDepositModified(ctx sdk.Context, poolID string, depositor sdk.AccAddress, sharesOwned sdkmath.Int) { - if k.hooks != nil { - k.hooks.BeforePoolDepositModified(ctx, poolID, depositor, sharesOwned) - } -} diff --git a/x/swap/keeper/hooks_test.go b/x/swap/keeper/hooks_test.go deleted file mode 100644 index 893aa658..00000000 --- a/x/swap/keeper/hooks_test.go +++ /dev/null @@ -1,198 +0,0 @@ -package keeper_test - -import ( - "github.com/kava-labs/kava/x/swap/types" - "github.com/kava-labs/kava/x/swap/types/mocks" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/mock" -) - -func (suite *keeperTestSuite) TestHooks_DepositAndWithdraw() { - suite.Keeper.ClearHooks() - swapHooks := &mocks.SwapHooks{} - suite.Keeper.SetHooks(swapHooks) - - pool := types.NewAllowedPool("ukava", "usdx") - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.NewAllowedPools(pool), types.DefaultSwapFee)) - - balance := sdk.NewCoins( - sdk.NewCoin(pool.TokenA, sdkmath.NewInt(1000e6)), - sdk.NewCoin(pool.TokenB, sdkmath.NewInt(1000e6)), - ) - depositor_1 := suite.CreateAccount(balance) - - depositA := sdk.NewCoin(pool.TokenA, sdkmath.NewInt(10e6)) - depositB := sdk.NewCoin(pool.TokenB, sdkmath.NewInt(50e6)) - deposit := sdk.NewCoins(depositA, depositB) - - // expected initial shares - geometric mean - expectedShares := sdkmath.NewInt(22360679) - - // first deposit creates pool - calls AfterPoolDepositCreated with initial shares - swapHooks.On("AfterPoolDepositCreated", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_1.GetAddress(), expectedShares).Once() - err := suite.Keeper.Deposit(suite.Ctx, depositor_1.GetAddress(), depositA, depositB, sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - // second deposit adds to pool - calls BeforePoolDepositModified - // shares given are the initial shares, not the shares added to the pool - swapHooks.On("BeforePoolDepositModified", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_1.GetAddress(), expectedShares).Once() - err = suite.Keeper.Deposit(suite.Ctx, depositor_1.GetAddress(), sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.NewCoin("usdx", sdkmath.NewInt(25e6)), sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - // get the shares from the store from the last deposit - shareRecord, found := suite.Keeper.GetDepositorShares(suite.Ctx, depositor_1.GetAddress(), types.PoolIDFromCoins(deposit)) - suite.Require().True(found) - - // third deposit adds to pool - calls BeforePoolDepositModified - // shares given are the shares added in previous deposit, not the shares added to the pool now - swapHooks.On("BeforePoolDepositModified", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_1.GetAddress(), shareRecord.SharesOwned).Once() - err = suite.Keeper.Deposit(suite.Ctx, depositor_1.GetAddress(), sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - depositor_2 := suite.NewAccountFromAddr( - sdk.AccAddress("depositor 2---------"), - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(100e6)), - ), - ) - - // first deposit deposit into pool creates the deposit and calls AfterPoolDepositCreated - expectedShares = sdkmath.NewInt(2236067) - swapHooks.On("AfterPoolDepositCreated", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_2.GetAddress(), expectedShares).Once() - err = suite.Keeper.Deposit(suite.Ctx, depositor_2.GetAddress(), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - // second deposit into pool calls BeforePoolDepositModified with initial shares given - swapHooks.On("BeforePoolDepositModified", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_2.GetAddress(), expectedShares).Once() - err = suite.Keeper.Deposit(suite.Ctx, depositor_2.GetAddress(), sdk.NewCoin("ukava", sdkmath.NewInt(2e6)), sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - // get the shares from the store from the last deposit - shareRecord, found = suite.Keeper.GetDepositorShares(suite.Ctx, depositor_2.GetAddress(), types.PoolIDFromCoins(deposit)) - suite.Require().True(found) - - // third deposit into pool calls BeforePoolDepositModified with shares from last deposit - swapHooks.On("BeforePoolDepositModified", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_2.GetAddress(), shareRecord.SharesOwned).Once() - err = suite.Keeper.Deposit(suite.Ctx, depositor_2.GetAddress(), sdk.NewCoin("ukava", sdkmath.NewInt(3e6)), sdk.NewCoin("usdx", sdkmath.NewInt(15e6)), sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - // test hooks with a full withdraw of all shares - shareRecord, found = suite.Keeper.GetDepositorShares(suite.Ctx, depositor_1.GetAddress(), types.PoolIDFromCoins(deposit)) - suite.Require().True(found) - // all shares given to BeforePoolDepositModified - swapHooks.On("BeforePoolDepositModified", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_1.GetAddress(), shareRecord.SharesOwned).Once() - err = suite.Keeper.Withdraw(suite.Ctx, depositor_1.GetAddress(), shareRecord.SharesOwned, sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1))) - suite.Require().NoError(err) - - // test hooks on partial withdraw - shareRecord, found = suite.Keeper.GetDepositorShares(suite.Ctx, depositor_2.GetAddress(), types.PoolIDFromCoins(deposit)) - suite.Require().True(found) - partialShares := shareRecord.SharesOwned.Quo(sdkmath.NewInt(3)) - // all shares given to before deposit modified even with partial withdraw - swapHooks.On("BeforePoolDepositModified", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_2.GetAddress(), shareRecord.SharesOwned).Once() - err = suite.Keeper.Withdraw(suite.Ctx, depositor_2.GetAddress(), partialShares, sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1))) - suite.Require().NoError(err) - - // test hooks on second partial withdraw - shareRecord, found = suite.Keeper.GetDepositorShares(suite.Ctx, depositor_2.GetAddress(), types.PoolIDFromCoins(deposit)) - suite.Require().True(found) - partialShares = shareRecord.SharesOwned.Quo(sdkmath.NewInt(2)) - // all shares given to before deposit modified even with partial withdraw - swapHooks.On("BeforePoolDepositModified", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_2.GetAddress(), shareRecord.SharesOwned).Once() - err = suite.Keeper.Withdraw(suite.Ctx, depositor_2.GetAddress(), partialShares, sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1))) - suite.Require().NoError(err) - - // test hooks withdraw all shares with second depositor - shareRecord, found = suite.Keeper.GetDepositorShares(suite.Ctx, depositor_2.GetAddress(), types.PoolIDFromCoins(deposit)) - suite.Require().True(found) - // all shares given to before deposit modified even with partial withdraw - swapHooks.On("BeforePoolDepositModified", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_2.GetAddress(), shareRecord.SharesOwned).Once() - err = suite.Keeper.Withdraw(suite.Ctx, depositor_2.GetAddress(), shareRecord.SharesOwned, sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1))) - suite.Require().NoError(err) - - swapHooks.AssertExpectations(suite.T()) -} - -func (suite *keeperTestSuite) TestHooks_NoPanicsOnNilHooks() { - suite.Keeper.ClearHooks() - - pool := types.NewAllowedPool("ukava", "usdx") - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.NewAllowedPools(pool), types.DefaultSwapFee)) - - balance := sdk.NewCoins( - sdk.NewCoin(pool.TokenA, sdkmath.NewInt(1000e6)), - sdk.NewCoin(pool.TokenB, sdkmath.NewInt(1000e6)), - ) - depositor := suite.CreateAccount(balance) - - depositA := sdk.NewCoin(pool.TokenA, sdkmath.NewInt(10e6)) - depositB := sdk.NewCoin(pool.TokenB, sdkmath.NewInt(50e6)) - deposit := sdk.NewCoins(depositA, depositB) - - // deposit create pool should not panic when hooks are not set - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), depositA, depositB, sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - // existing deposit should not panic with hooks are not set - err = suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.NewCoin("usdx", sdkmath.NewInt(25e6)), sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - // withdraw of shares should not panic when hooks are not set - shareRecord, found := suite.Keeper.GetDepositorShares(suite.Ctx, depositor.GetAddress(), types.PoolIDFromCoins(deposit)) - suite.Require().True(found) - err = suite.Keeper.Withdraw(suite.Ctx, depositor.GetAddress(), shareRecord.SharesOwned, sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1))) - suite.Require().NoError(err) -} - -func (suite *keeperTestSuite) TestHooks_HookOrdering() { - suite.Keeper.ClearHooks() - swapHooks := &mocks.SwapHooks{} - suite.Keeper.SetHooks(swapHooks) - - pool := types.NewAllowedPool("ukava", "usdx") - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.NewAllowedPools(pool), types.DefaultSwapFee)) - - balance := sdk.NewCoins( - sdk.NewCoin(pool.TokenA, sdkmath.NewInt(1000e6)), - sdk.NewCoin(pool.TokenB, sdkmath.NewInt(1000e6)), - ) - depositor := suite.CreateAccount(balance) - - depositA := sdk.NewCoin(pool.TokenA, sdkmath.NewInt(10e6)) - depositB := sdk.NewCoin(pool.TokenB, sdkmath.NewInt(50e6)) - deposit := sdk.NewCoins(depositA, depositB) - - poolID := types.PoolIDFromCoins(deposit) - expectedShares := sdkmath.NewInt(22360679) - - swapHooks.On("AfterPoolDepositCreated", suite.Ctx, poolID, depositor.GetAddress(), expectedShares).Run(func(args mock.Arguments) { - _, found := suite.Keeper.GetDepositorShares(suite.Ctx, depositor.GetAddress(), poolID) - suite.Require().True(found, "expected after hook to be called after shares are updated") - }) - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), depositA, depositB, sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - swapHooks.On("BeforePoolDepositModified", suite.Ctx, poolID, depositor.GetAddress(), expectedShares).Run(func(args mock.Arguments) { - shareRecord, found := suite.Keeper.GetDepositorShares(suite.Ctx, depositor.GetAddress(), poolID) - suite.Require().True(found, "expected share record to exist") - suite.Equal(expectedShares, shareRecord.SharesOwned, "expected hook to be called before shares are updated") - }) - err = suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), depositA, depositB, sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - existingShareRecord, found := suite.Keeper.GetDepositorShares(suite.Ctx, depositor.GetAddress(), types.PoolIDFromCoins(deposit)) - suite.Require().True(found) - swapHooks.On("BeforePoolDepositModified", suite.Ctx, poolID, depositor.GetAddress(), existingShareRecord.SharesOwned).Run(func(args mock.Arguments) { - shareRecord, found := suite.Keeper.GetDepositorShares(suite.Ctx, depositor.GetAddress(), poolID) - suite.Require().True(found, "expected share record to exist") - suite.Equal(existingShareRecord.SharesOwned, shareRecord.SharesOwned, "expected hook to be called before shares are updated") - }) - err = suite.Keeper.Withdraw(suite.Ctx, depositor.GetAddress(), existingShareRecord.SharesOwned.Quo(sdkmath.NewInt(2)), sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1))) - suite.Require().NoError(err) -} diff --git a/x/swap/keeper/integration_test.go b/x/swap/keeper/integration_test.go deleted file mode 100644 index 9e6f8de6..00000000 --- a/x/swap/keeper/integration_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package keeper_test - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// nolint -func i(in int64) sdkmath.Int { return sdkmath.NewInt(in) } - -// nolint -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } - -// nolint -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } - -// func NewAuthGenStateFromAccs(accounts ...authexported.GenesisAccount) app.GenesisState { -// authGenesis := auth.NewGenesisState(auth.DefaultParams(), accounts) -// return app.GenesisState{auth.ModuleName: auth.ModuleCdc.MustMarshalJSON(authGenesis)} -// } - -// func NewSwapGenStateMulti() app.GenesisState { -// swapGenesis := types.GenesisState{ -// Params: types.Params{ -// AllowedPools: types.AllowedPools{ -// types.NewAllowedPool("ukava", "usdx"), -// }, -// SwapFee: sdk.MustNewDecFromStr("0.03"), -// }, -// } - -// return app.GenesisState{types.ModuleName: types.ModuleCdc.MustMarshalJSON(swapGenesis)} -// } diff --git a/x/swap/keeper/invariants.go b/x/swap/keeper/invariants.go deleted file mode 100644 index c4bce02b..00000000 --- a/x/swap/keeper/invariants.go +++ /dev/null @@ -1,139 +0,0 @@ -package keeper - -import ( - "github.com/kava-labs/kava/x/swap/types" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// RegisterInvariants registers the swap module invariants -func RegisterInvariants(ir sdk.InvariantRegistry, k Keeper) { - ir.RegisterRoute(types.ModuleName, "pool-records", PoolRecordsInvariant(k)) - ir.RegisterRoute(types.ModuleName, "share-records", ShareRecordsInvariant(k)) - ir.RegisterRoute(types.ModuleName, "pool-reserves", PoolReservesInvariant(k)) - ir.RegisterRoute(types.ModuleName, "pool-shares", PoolSharesInvariant(k)) -} - -// AllInvariants runs all invariants of the swap module -func AllInvariants(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - if res, stop := PoolRecordsInvariant(k)(ctx); stop { - return res, stop - } - - if res, stop := ShareRecordsInvariant(k)(ctx); stop { - return res, stop - } - - if res, stop := PoolReservesInvariant(k)(ctx); stop { - return res, stop - } - - res, stop := PoolSharesInvariant(k)(ctx) - return res, stop - } -} - -// PoolRecordsInvariant iterates all pool records and asserts that they are valid -func PoolRecordsInvariant(k Keeper) sdk.Invariant { - broken := false - message := sdk.FormatInvariant(types.ModuleName, "validate pool records broken", "pool record invalid") - - return func(ctx sdk.Context) (string, bool) { - k.IteratePools(ctx, func(record types.PoolRecord) bool { - if err := record.Validate(); err != nil { - broken = true - return true - } - return false - }) - - return message, broken - } -} - -// ShareRecordsInvariant iterates all share records and asserts that they are valid -func ShareRecordsInvariant(k Keeper) sdk.Invariant { - broken := false - message := sdk.FormatInvariant(types.ModuleName, "validate share records broken", "share record invalid") - - return func(ctx sdk.Context) (string, bool) { - k.IterateDepositorShares(ctx, func(record types.ShareRecord) bool { - if err := record.Validate(); err != nil { - broken = true - return true - } - return false - }) - - return message, broken - } -} - -// PoolReservesInvariant iterates all pools and ensures the total reserves matches the module account coins -func PoolReservesInvariant(k Keeper) sdk.Invariant { - message := sdk.FormatInvariant(types.ModuleName, "pool reserves broken", "pool reserves do not match module account") - - return func(ctx sdk.Context) (string, bool) { - balance := k.bankKeeper.GetAllBalances(ctx, k.GetSwapModuleAccount(ctx).GetAddress()) - - reserves := sdk.Coins{} - k.IteratePools(ctx, func(record types.PoolRecord) bool { - for _, coin := range record.Reserves() { - reserves = reserves.Add(coin) - } - return false - }) - - broken := !reserves.IsEqual(balance) - return message, broken - } -} - -type poolShares struct { - totalShares sdkmath.Int - totalSharesOwned sdkmath.Int -} - -// PoolSharesInvariant iterates all pools and shares and ensures the total pool shares match the sum of depositor shares -func PoolSharesInvariant(k Keeper) sdk.Invariant { - broken := false - message := sdk.FormatInvariant(types.ModuleName, "pool shares broken", "pool shares do not match depositor shares") - - return func(ctx sdk.Context) (string, bool) { - totalShares := make(map[string]poolShares) - - k.IteratePools(ctx, func(pr types.PoolRecord) bool { - totalShares[pr.PoolID] = poolShares{ - totalShares: pr.TotalShares, - totalSharesOwned: sdk.ZeroInt(), - } - - return false - }) - - k.IterateDepositorShares(ctx, func(sr types.ShareRecord) bool { - if shares, found := totalShares[sr.PoolID]; found { - shares.totalSharesOwned = shares.totalSharesOwned.Add(sr.SharesOwned) - totalShares[sr.PoolID] = shares - } else { - totalShares[sr.PoolID] = poolShares{ - totalShares: sdk.ZeroInt(), - totalSharesOwned: sr.SharesOwned, - } - } - - return false - }) - - for _, ps := range totalShares { - if !ps.totalShares.Equal(ps.totalSharesOwned) { - broken = true - break - } - } - - return message, broken - } -} diff --git a/x/swap/keeper/invariants_test.go b/x/swap/keeper/invariants_test.go deleted file mode 100644 index a388ee74..00000000 --- a/x/swap/keeper/invariants_test.go +++ /dev/null @@ -1,235 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/kava-labs/kava/x/swap/keeper" - "github.com/kava-labs/kava/x/swap/testutil" - "github.com/kava-labs/kava/x/swap/types" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" -) - -type invariantTestSuite struct { - testutil.Suite - invariants map[string]map[string]sdk.Invariant -} - -func (suite *invariantTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.invariants = make(map[string]map[string]sdk.Invariant) - keeper.RegisterInvariants(suite, suite.Keeper) -} - -func (suite *invariantTestSuite) SetupValidState() { - suite.Keeper.SetPool(suite.Ctx, types.NewPoolRecord( - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ), - sdkmath.NewInt(3e6), - )) - suite.AddCoinsToModule( - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ), - ) - suite.Keeper.SetDepositorShares(suite.Ctx, types.NewShareRecord( - sdk.AccAddress("depositor 1---------"), // TODO these addresses are padded to get to the required length of 20 bytes. What is a nicer setup? - types.PoolID("ukava", "usdx"), - sdkmath.NewInt(2e6), - )) - suite.Keeper.SetDepositorShares(suite.Ctx, types.NewShareRecord( - sdk.AccAddress("depositor 2---------"), - types.PoolID("ukava", "usdx"), - sdkmath.NewInt(1e6), - )) - - suite.Keeper.SetPool(suite.Ctx, types.NewPoolRecord( - sdk.NewCoins( - sdk.NewCoin("hard", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(2e6)), - ), - sdkmath.NewInt(1e6), - )) - suite.AddCoinsToModule( - sdk.NewCoins( - sdk.NewCoin("hard", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(2e6)), - ), - ) - suite.Keeper.SetDepositorShares(suite.Ctx, types.NewShareRecord( - sdk.AccAddress("depositor 1---------"), - types.PoolID("hard", "usdx"), - sdkmath.NewInt(1e6), - )) -} - -func (suite *invariantTestSuite) RegisterRoute(moduleName string, route string, invariant sdk.Invariant) { - _, exists := suite.invariants[moduleName] - - if !exists { - suite.invariants[moduleName] = make(map[string]sdk.Invariant) - } - - suite.invariants[moduleName][route] = invariant -} - -func (suite *invariantTestSuite) runInvariant(route string, invariant func(k keeper.Keeper) sdk.Invariant) (string, bool) { - ctx := suite.Ctx - registeredInvariant := suite.invariants[types.ModuleName][route] - suite.Require().NotNil(registeredInvariant) - - // direct call - dMessage, dBroken := invariant(suite.Keeper)(ctx) - // registered call - rMessage, rBroken := registeredInvariant(ctx) - // all call - aMessage, aBroken := keeper.AllInvariants(suite.Keeper)(ctx) - - // require matching values for direct call and registered call - suite.Require().Equal(dMessage, rMessage, "expected registered invariant message to match") - suite.Require().Equal(dBroken, rBroken, "expected registered invariant broken to match") - // require matching values for direct call and all invariants call if broken - suite.Require().Equal(dBroken, aBroken, "expected all invariant broken to match") - if dBroken { - suite.Require().Equal(dMessage, aMessage, "expected all invariant message to match") - } - - // return message, broken - return dMessage, dBroken -} - -func (suite *invariantTestSuite) TestPoolRecordsInvariant() { - // default state is valid - message, broken := suite.runInvariant("pool-records", keeper.PoolRecordsInvariant) - suite.Equal("swap: validate pool records broken invariant\npool record invalid\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("pool-records", keeper.PoolRecordsInvariant) - suite.Equal("swap: validate pool records broken invariant\npool record invalid\n", message) - suite.Equal(false, broken) - - // broken with invalid pool record - suite.Keeper.SetPool_Raw(suite.Ctx, types.NewPoolRecord( - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ), - sdkmath.NewInt(-1e6), - )) - message, broken = suite.runInvariant("pool-records", keeper.PoolRecordsInvariant) - suite.Equal("swap: validate pool records broken invariant\npool record invalid\n", message) - suite.Equal(true, broken) -} - -func (suite *invariantTestSuite) TestShareRecordsInvariant() { - message, broken := suite.runInvariant("share-records", keeper.ShareRecordsInvariant) - suite.Equal("swap: validate share records broken invariant\nshare record invalid\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("share-records", keeper.ShareRecordsInvariant) - suite.Equal("swap: validate share records broken invariant\nshare record invalid\n", message) - suite.Equal(false, broken) - - // broken with invalid share record - suite.Keeper.SetDepositorShares_Raw(suite.Ctx, types.NewShareRecord( - sdk.AccAddress("depositor 1---------"), - types.PoolID("ukava", "usdx"), - sdkmath.NewInt(-1e6), - )) - message, broken = suite.runInvariant("share-records", keeper.ShareRecordsInvariant) - suite.Equal("swap: validate share records broken invariant\nshare record invalid\n", message) - suite.Equal(true, broken) -} - -func (suite *invariantTestSuite) TestPoolReservesInvariant() { - message, broken := suite.runInvariant("pool-reserves", keeper.PoolReservesInvariant) - suite.Equal("swap: pool reserves broken invariant\npool reserves do not match module account\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("pool-reserves", keeper.PoolReservesInvariant) - suite.Equal("swap: pool reserves broken invariant\npool reserves do not match module account\n", message) - suite.Equal(false, broken) - - // broken when reserves are greater than module balance - suite.Keeper.SetPool(suite.Ctx, types.NewPoolRecord( - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(2e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), - ), - sdkmath.NewInt(5e6), - )) - message, broken = suite.runInvariant("pool-reserves", keeper.PoolReservesInvariant) - suite.Equal("swap: pool reserves broken invariant\npool reserves do not match module account\n", message) - suite.Equal(true, broken) - - // broken when reserves are less than the module balance - suite.Keeper.SetPool(suite.Ctx, types.NewPoolRecord( - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e5)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e5)), - ), - sdkmath.NewInt(3e5), - )) - message, broken = suite.runInvariant("pool-reserves", keeper.PoolReservesInvariant) - suite.Equal("swap: pool reserves broken invariant\npool reserves do not match module account\n", message) - suite.Equal(true, broken) -} - -func (suite *invariantTestSuite) TestPoolSharesInvariant() { - message, broken := suite.runInvariant("pool-shares", keeper.PoolSharesInvariant) - suite.Equal("swap: pool shares broken invariant\npool shares do not match depositor shares\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("pool-shares", keeper.PoolSharesInvariant) - suite.Equal("swap: pool shares broken invariant\npool shares do not match depositor shares\n", message) - suite.Equal(false, broken) - - // broken when total shares are greater than depositor shares - suite.Keeper.SetPool(suite.Ctx, types.NewPoolRecord( - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ), - sdkmath.NewInt(5e6), - )) - message, broken = suite.runInvariant("pool-shares", keeper.PoolSharesInvariant) - suite.Equal("swap: pool shares broken invariant\npool shares do not match depositor shares\n", message) - suite.Equal(true, broken) - - // broken when total shares are less than the depositor shares - suite.Keeper.SetPool(suite.Ctx, types.NewPoolRecord( - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ), - sdkmath.NewInt(1e5), - )) - message, broken = suite.runInvariant("pool-shares", keeper.PoolSharesInvariant) - suite.Equal("swap: pool shares broken invariant\npool shares do not match depositor shares\n", message) - suite.Equal(true, broken) - - // broken when pool record is missing - suite.Keeper.DeletePool(suite.Ctx, types.PoolID("ukava", "usdx")) - suite.RemoveCoinsFromModule( - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ), - ) - message, broken = suite.runInvariant("pool-shares", keeper.PoolSharesInvariant) - suite.Equal("swap: pool shares broken invariant\npool shares do not match depositor shares\n", message) - suite.Equal(true, broken) -} - -func TestInvariantTestSuite(t *testing.T) { - suite.Run(t, new(invariantTestSuite)) -} diff --git a/x/swap/keeper/keeper.go b/x/swap/keeper/keeper.go deleted file mode 100644 index 86bb3269..00000000 --- a/x/swap/keeper/keeper.go +++ /dev/null @@ -1,271 +0,0 @@ -package keeper - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store/prefix" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - - "github.com/kava-labs/kava/x/swap/types" -) - -// Keeper keeper for the swap module -type Keeper struct { - key storetypes.StoreKey - cdc codec.Codec - paramSubspace paramtypes.Subspace - hooks types.SwapHooks - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper -} - -// NewKeeper creates a new keeper -func NewKeeper( - cdc codec.Codec, - key storetypes.StoreKey, - paramstore paramtypes.Subspace, - accountKeeper types.AccountKeeper, - bankKeeper types.BankKeeper, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - key: key, - cdc: cdc, - paramSubspace: paramstore, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - } -} - -// SetHooks adds hooks to the keeper. -func (k *Keeper) SetHooks(sh types.SwapHooks) *Keeper { - if k.hooks != nil { - panic("cannot set swap hooks twice") - } - k.hooks = sh - return k -} - -// ClearHooks clears the hooks on the keeper -func (k *Keeper) ClearHooks() { - k.hooks = nil -} - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - var p types.Params - k.paramSubspace.GetParamSet(ctx, &p) - return p -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} - -// GetSwapFee returns the swap fee set in the module parameters -func (k Keeper) GetSwapFee(ctx sdk.Context) sdk.Dec { - return k.GetParams(ctx).SwapFee -} - -// GetSwapModuleAccount returns the swap ModuleAccount -func (k Keeper) GetSwapModuleAccount(ctx sdk.Context) authtypes.ModuleAccountI { - return k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) -} - -// GetPool retrieves a pool record from the store -func (k Keeper) GetPool(ctx sdk.Context, poolID string) (types.PoolRecord, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PoolKeyPrefix) - - bz := store.Get(types.PoolKey(poolID)) - if bz == nil { - return types.PoolRecord{}, false - } - - var record types.PoolRecord - k.cdc.MustUnmarshal(bz, &record) - - return record, true -} - -// SetPool_Raw saves a pool record to the store without any validation -func (k Keeper) SetPool_Raw(ctx sdk.Context, record types.PoolRecord) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PoolKeyPrefix) - bz := k.cdc.MustMarshal(&record) - store.Set(types.PoolKey(record.PoolID), bz) -} - -// SetPool saves a pool to the store and panics if the record is invalid -func (k Keeper) SetPool(ctx sdk.Context, record types.PoolRecord) { - if err := record.Validate(); err != nil { - panic(fmt.Sprintf("invalid pool record: %s", err)) - } - - k.SetPool_Raw(ctx, record) -} - -// DeletePool deletes a pool record from the store -func (k Keeper) DeletePool(ctx sdk.Context, poolID string) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PoolKeyPrefix) - store.Delete(types.PoolKey(poolID)) -} - -// IteratePools iterates over all pool objects in the store and performs a callback function -func (k Keeper) IteratePools(ctx sdk.Context, cb func(record types.PoolRecord) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PoolKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var record types.PoolRecord - k.cdc.MustUnmarshal(iterator.Value(), &record) - if cb(record) { - break - } - } -} - -// GetAllPools returns all pool records from the store -func (k Keeper) GetAllPools(ctx sdk.Context) (records types.PoolRecords) { - k.IteratePools(ctx, func(record types.PoolRecord) bool { - records = append(records, record) - return false - }) - return -} - -// GetPoolShares gets the total shares in a pool from the store -func (k Keeper) GetPoolShares(ctx sdk.Context, poolID string) (sdkmath.Int, bool) { - pool, found := k.GetPool(ctx, poolID) - if !found { - return sdkmath.Int{}, false - } - return pool.TotalShares, true -} - -// GetDepositorShares gets a share record from the store -func (k Keeper) GetDepositorShares(ctx sdk.Context, depositor sdk.AccAddress, poolID string) (types.ShareRecord, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositorPoolSharesPrefix) - bz := store.Get(types.DepositorPoolSharesKey(depositor, poolID)) - if bz == nil { - return types.ShareRecord{}, false - } - var record types.ShareRecord - k.cdc.MustUnmarshal(bz, &record) - return record, true -} - -// SetDepositorShares_Raw saves a share record to the store without validation -func (k Keeper) SetDepositorShares_Raw(ctx sdk.Context, record types.ShareRecord) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositorPoolSharesPrefix) - bz := k.cdc.MustMarshal(&record) - store.Set(types.DepositorPoolSharesKey(record.Depositor, record.PoolID), bz) -} - -// SetDepositorShares saves a share record to the store and panics if the record is invalid -func (k Keeper) SetDepositorShares(ctx sdk.Context, record types.ShareRecord) { - if err := record.Validate(); err != nil { - panic(fmt.Sprintf("invalid share record: %s", err)) - } - - k.SetDepositorShares_Raw(ctx, record) -} - -// DeleteDepositorShares deletes a share record from the store -func (k Keeper) DeleteDepositorShares(ctx sdk.Context, depositor sdk.AccAddress, poolID string) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositorPoolSharesPrefix) - store.Delete(types.DepositorPoolSharesKey(depositor, poolID)) -} - -// IterateDepositorShares iterates over all pool objects in the store and performs a callback function -func (k Keeper) IterateDepositorShares(ctx sdk.Context, cb func(record types.ShareRecord) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositorPoolSharesPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var record types.ShareRecord - k.cdc.MustUnmarshal(iterator.Value(), &record) - if cb(record) { - break - } - } -} - -// GetAllDepositorShares returns all depositor share records from the store -func (k Keeper) GetAllDepositorShares(ctx sdk.Context) (records types.ShareRecords) { - k.IterateDepositorShares(ctx, func(record types.ShareRecord) bool { - records = append(records, record) - return false - }) - return -} - -// IterateDepositorSharesByOwner iterates over share records for a specific address and performs a callback function -func (k Keeper) IterateDepositorSharesByOwner(ctx sdk.Context, owner sdk.AccAddress, cb func(record types.ShareRecord) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositorPoolSharesPrefix) - iterator := sdk.KVStorePrefixIterator(store, owner.Bytes()) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var record types.ShareRecord - k.cdc.MustUnmarshal(iterator.Value(), &record) - if cb(record) { - break - } - } -} - -// GetAllDepositorSharesByOwner returns all depositor share records from the store for a specific address -func (k Keeper) GetAllDepositorSharesByOwner(ctx sdk.Context, owner sdk.AccAddress) (records types.ShareRecords) { - k.IterateDepositorSharesByOwner(ctx, owner, func(record types.ShareRecord) bool { - records = append(records, record) - return false - }) - return -} - -// GetDepositorSharesAmount gets a depositor's shares in a pool from the store -func (k Keeper) GetDepositorSharesAmount(ctx sdk.Context, depositor sdk.AccAddress, poolID string) (sdkmath.Int, bool) { - record, found := k.GetDepositorShares(ctx, depositor, poolID) - if !found { - return sdkmath.Int{}, false - } - return record.SharesOwned, true -} - -// updatePool updates a pool, deleting the pool record if the shares are zero -func (k Keeper) updatePool(ctx sdk.Context, poolID string, pool *types.DenominatedPool) { - if pool.TotalShares().IsZero() { - k.DeletePool(ctx, poolID) - } else { - k.SetPool(ctx, types.NewPoolRecordFromPool(pool)) - } -} - -// updateDepositorShares updates a depositor share records for a pool, deleting the record if the new shares are zero -func (k Keeper) updateDepositorShares(ctx sdk.Context, owner sdk.AccAddress, poolID string, shares sdkmath.Int) { - if shares.IsZero() { - k.DeleteDepositorShares(ctx, owner, poolID) - } else { - shareRecord := types.NewShareRecord(owner, poolID, shares) - k.SetDepositorShares(ctx, shareRecord) - } -} - -func (k Keeper) loadDenominatedPool(ctx sdk.Context, poolID string) (*types.DenominatedPool, error) { - poolRecord, found := k.GetPool(ctx, poolID) - if !found { - return &types.DenominatedPool{}, types.ErrInvalidPool - } - denominatedPool, err := types.NewDenominatedPoolWithExistingShares(poolRecord.Reserves(), poolRecord.TotalShares) - if err != nil { - return &types.DenominatedPool{}, types.ErrInvalidPool - } - return denominatedPool, nil -} diff --git a/x/swap/keeper/keeper_test.go b/x/swap/keeper/keeper_test.go deleted file mode 100644 index 07c0f6ca..00000000 --- a/x/swap/keeper/keeper_test.go +++ /dev/null @@ -1,196 +0,0 @@ -package keeper_test - -import ( - "os" - "testing" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/swap/testutil" - "github.com/kava-labs/kava/x/swap/types" - "github.com/kava-labs/kava/x/swap/types/mocks" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" -) - -func TestMain(m *testing.M) { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - os.Exit(m.Run()) -} - -type keeperTestSuite struct { - testutil.Suite -} - -func (suite *keeperTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(keeperTestSuite)) -} - -func (suite *keeperTestSuite) setupPool(reserves sdk.Coins, totalShares sdkmath.Int, depositor sdk.AccAddress) string { - poolID := types.PoolIDFromCoins(reserves) - suite.AddCoinsToModule(reserves) - - poolRecord := types.PoolRecord{ - PoolID: poolID, - ReservesA: reserves[0], - ReservesB: reserves[1], - TotalShares: totalShares, - } - suite.Keeper.SetPool(suite.Ctx, poolRecord) - - shareRecord := types.ShareRecord{ - Depositor: depositor, - PoolID: poolID, - SharesOwned: totalShares, - } - suite.Keeper.SetDepositorShares(suite.Ctx, shareRecord) - - return poolID -} - -func (suite keeperTestSuite) TestParams_Persistance() { - keeper := suite.Keeper - - params := types.Params{ - AllowedPools: types.AllowedPools{ - types.NewAllowedPool("ukava", "usdx"), - }, - SwapFee: sdk.MustNewDecFromStr("0.03"), - } - keeper.SetParams(suite.Ctx, params) - suite.Equal(keeper.GetParams(suite.Ctx), params) - - oldParams := params - params = types.Params{ - AllowedPools: types.AllowedPools{ - types.NewAllowedPool("hard", "ukava"), - }, - SwapFee: sdk.MustNewDecFromStr("0.01"), - } - keeper.SetParams(suite.Ctx, params) - suite.NotEqual(keeper.GetParams(suite.Ctx), oldParams) - suite.Equal(keeper.GetParams(suite.Ctx), params) -} - -func (suite keeperTestSuite) TestParams_GetSwapFee() { - keeper := suite.Keeper - - params := types.Params{ - SwapFee: sdk.MustNewDecFromStr("0.00333"), - } - keeper.SetParams(suite.Ctx, params) - - suite.Equal(keeper.GetSwapFee(suite.Ctx), params.SwapFee) -} - -func (suite *keeperTestSuite) TestPool_Persistance() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - - pool, err := types.NewDenominatedPool(reserves) - suite.Nil(err) - record := types.NewPoolRecordFromPool(pool) - - suite.Keeper.SetPool(suite.Ctx, record) - - savedRecord, ok := suite.Keeper.GetPool(suite.Ctx, record.PoolID) - suite.True(ok) - suite.Equal(record, savedRecord) - - savedShares, ok := suite.Keeper.GetPoolShares(suite.Ctx, record.PoolID) - suite.True(ok) - suite.Equal(record.TotalShares, savedShares) - - suite.Keeper.DeletePool(suite.Ctx, record.PoolID) - deletedPool, ok := suite.Keeper.GetPool(suite.Ctx, record.PoolID) - suite.False(ok) - suite.Equal(deletedPool, types.PoolRecord{}) -} - -func (suite *keeperTestSuite) TestPool_PanicsWhenInvalid() { - invalidRecord := types.NewPoolRecord( - sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), sdk.NewCoin("usdx", sdkmath.NewInt(100e6))), - i(-1), - ) - - suite.Panics(func() { - suite.Keeper.SetPool(suite.Ctx, invalidRecord) - }, "expected set pool to panic with invalid record") -} - -func (suite *keeperTestSuite) TestShare_Persistance() { - poolID := types.PoolID("ukava", "usdx") - depositor, err := sdk.AccAddressFromBech32("kava1skpsgk5cnrarn69ql2tfun47fyjssataz0g07l") - suite.NoError(err) - shares := sdkmath.NewInt(3126432331) - - record := types.NewShareRecord(depositor, poolID, shares) - suite.Keeper.SetDepositorShares(suite.Ctx, record) - - savedRecord, ok := suite.Keeper.GetDepositorShares(suite.Ctx, depositor, poolID) - suite.True(ok) - suite.Equal(record, savedRecord) - - savedShares, ok := suite.Keeper.GetDepositorSharesAmount(suite.Ctx, depositor, poolID) - suite.True(ok) - suite.Equal(record.SharesOwned, savedShares) - - suite.Keeper.DeleteDepositorShares(suite.Ctx, depositor, poolID) - deletedShares, ok := suite.Keeper.GetDepositorShares(suite.Ctx, depositor, poolID) - suite.False(ok) - suite.Equal(deletedShares, types.ShareRecord{}) -} - -func (suite *keeperTestSuite) TestShare_PanicsWhenInvalid() { - depositor, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - suite.Require().NoError(err) - - invalidRecord := types.NewShareRecord( - depositor, - "hard/usdx", - i(-1), - ) - - suite.Panics(func() { - suite.Keeper.SetDepositorShares(suite.Ctx, invalidRecord) - }, "expected set depositor shares to panic with invalid record") -} - -func (suite *keeperTestSuite) TestHooks() { - // ensure no hooks are set - suite.Keeper.ClearHooks() - - // data - depositor, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - suite.Require().NoError(err) - - // hooks can be called when not set - suite.Keeper.AfterPoolDepositCreated(suite.Ctx, "ukava/usdx", depositor, sdkmath.NewInt(1e6)) - suite.Keeper.BeforePoolDepositModified(suite.Ctx, "ukava/usdx", depositor, sdkmath.NewInt(1e6)) - - // set hooks - swapHooks := &mocks.SwapHooks{} - suite.Keeper.SetHooks(swapHooks) - - // test hook calls are correct - swapHooks.On("AfterPoolDepositCreated", suite.Ctx, "ukava/usdx", depositor, sdkmath.NewInt(1e6)).Once() - suite.Keeper.AfterPoolDepositCreated(suite.Ctx, "ukava/usdx", depositor, sdkmath.NewInt(1e6)) - swapHooks.On("BeforePoolDepositModified", suite.Ctx, "ukava/usdx", depositor, sdkmath.NewInt(1e6)).Once() - suite.Keeper.BeforePoolDepositModified(suite.Ctx, "ukava/usdx", depositor, sdkmath.NewInt(1e6)) - swapHooks.AssertExpectations(suite.T()) - - // test second set panics - suite.PanicsWithValue("cannot set swap hooks twice", func() { - suite.Keeper.SetHooks(swapHooks) - }, "expected hooks to panic on second set") -} diff --git a/x/swap/keeper/msg_server.go b/x/swap/keeper/msg_server.go deleted file mode 100644 index 6a02b591..00000000 --- a/x/swap/keeper/msg_server.go +++ /dev/null @@ -1,153 +0,0 @@ -package keeper - -import ( - "context" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/swap/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the swap MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -// Deposit handles MsgDeposit messages -func (m msgServer) Deposit(goCtx context.Context, msg *types.MsgDeposit) (*types.MsgDepositResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := checkDeadline(ctx, msg); err != nil { - return nil, err - } - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - - if err := m.keeper.Deposit(ctx, depositor, msg.TokenA, msg.TokenB, msg.Slippage); err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.String()), - ), - ) - - return &types.MsgDepositResponse{}, nil -} - -// Withdraw handles MsgWithdraw messages -func (m msgServer) Withdraw(goCtx context.Context, msg *types.MsgWithdraw) (*types.MsgWithdrawResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := checkDeadline(ctx, msg); err != nil { - return nil, err - } - - from, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - return nil, err - } - - if err := m.keeper.Withdraw(ctx, from, msg.Shares, msg.MinTokenA, msg.MinTokenB); err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, from.String()), - ), - ) - - return &types.MsgWithdrawResponse{}, nil -} - -// SwapExactForTokens handles MsgSwapExactForTokens messages -func (m msgServer) SwapExactForTokens(goCtx context.Context, msg *types.MsgSwapExactForTokens) (*types.MsgSwapExactForTokensResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := checkDeadline(ctx, msg); err != nil { - return nil, err - } - - requester, err := sdk.AccAddressFromBech32(msg.Requester) - if err != nil { - return nil, err - } - - if err := m.keeper.SwapExactForTokens(ctx, requester, msg.ExactTokenA, msg.TokenB, msg.Slippage); err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, requester.String()), - ), - ) - - return &types.MsgSwapExactForTokensResponse{}, nil -} - -// SwapForExactTokens handles MsgSwapForExactTokens messages -func (m msgServer) SwapForExactTokens(goCtx context.Context, msg *types.MsgSwapForExactTokens) (*types.MsgSwapForExactTokensResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := checkDeadline(ctx, msg); err != nil { - return nil, err - } - - requester, err := sdk.AccAddressFromBech32(msg.Requester) - if err != nil { - return nil, err - } - - if err := m.keeper.SwapForExactTokens(ctx, requester, msg.TokenA, msg.ExactTokenB, msg.Slippage); err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, requester.String()), - ), - ) - - return &types.MsgSwapForExactTokensResponse{}, nil -} - -// checkDeadline returns an error if block time exceeds an included deadline -func checkDeadline(ctx sdk.Context, msg sdk.Msg) error { - deadlineMsg, ok := msg.(types.MsgWithDeadline) - if !ok { - return nil - } - - if deadlineMsg.DeadlineExceeded(ctx.BlockTime()) { - return errorsmod.Wrapf( - types.ErrDeadlineExceeded, - "block time %d >= deadline %d", - ctx.BlockTime().Unix(), - deadlineMsg.GetDeadline().Unix(), - ) - } - - return nil -} diff --git a/x/swap/keeper/msg_server_test.go b/x/swap/keeper/msg_server_test.go deleted file mode 100644 index 483cc656..00000000 --- a/x/swap/keeper/msg_server_test.go +++ /dev/null @@ -1,591 +0,0 @@ -package keeper_test - -import ( - "fmt" - "testing" - "time" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - "github.com/kava-labs/kava/x/swap/keeper" - "github.com/kava-labs/kava/x/swap/testutil" - "github.com/kava-labs/kava/x/swap/types" - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" - bank "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -var swapModuleAccountAddress = sdk.AccAddress(crypto.AddressHash([]byte(types.ModuleAccountName))) - -type msgServerTestSuite struct { - testutil.Suite - msgServer types.MsgServer -} - -func (suite *msgServerTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.msgServer = keeper.NewMsgServerImpl(suite.Keeper) -} - -func (suite *msgServerTestSuite) TestDeposit_CreatePool() { - pool := types.NewAllowedPool("ukava", "usdx") - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.AllowedPools{pool}, types.DefaultSwapFee)) - - balance := sdk.NewCoins( - sdk.NewCoin(pool.TokenA, sdkmath.NewInt(10e6)), - sdk.NewCoin(pool.TokenB, sdkmath.NewInt(50e6)), - ) - depositor := suite.NewAccountFromAddr(sdk.AccAddress("new depositor-------"), balance) - - deposit := types.NewMsgDeposit( - depositor.GetAddress().String(), - suite.BankKeeper.GetBalance(suite.Ctx, depositor.GetAddress(), pool.TokenA), - suite.BankKeeper.GetBalance(suite.Ctx, depositor.GetAddress(), pool.TokenB), - sdk.MustNewDecFromStr("0.01"), - time.Now().Add(10*time.Minute).Unix(), - ) - - res, err := suite.msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), deposit) - suite.Require().Equal(&types.MsgDepositResponse{}, res) - suite.Require().NoError(err) - - suite.AccountBalanceEqual(depositor.GetAddress(), sdk.Coins{}) - suite.ModuleAccountBalanceEqual(balance) - suite.PoolLiquidityEqual(balance) - suite.PoolShareValueEqual(depositor, pool, balance) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.GetAddress().String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - bank.EventTypeTransfer, - sdk.NewAttribute(bank.AttributeKeyRecipient, swapModuleAccountAddress.String()), - sdk.NewAttribute(bank.AttributeKeySender, depositor.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, balance.String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - types.EventTypeSwapDeposit, - sdk.NewAttribute(types.AttributeKeyPoolID, types.PoolID(pool.TokenA, pool.TokenB)), - sdk.NewAttribute(types.AttributeKeyDepositor, depositor.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, balance.String()), - sdk.NewAttribute(types.AttributeKeyShares, "22360679"), - )) -} - -func (suite *msgServerTestSuite) TestDeposit_DeadlineExceeded() { - pool := types.NewAllowedPool("ukava", "usdx") - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.AllowedPools{pool}, types.DefaultSwapFee)) - - balance := sdk.NewCoins( - sdk.NewCoin(pool.TokenA, sdkmath.NewInt(10e6)), - sdk.NewCoin(pool.TokenB, sdkmath.NewInt(50e6)), - ) - depositor := suite.NewAccountFromAddr(sdk.AccAddress("new depositor-------"), balance) - - deposit := types.NewMsgDeposit( - depositor.GetAddress().String(), - suite.BankKeeper.GetBalance(suite.Ctx, depositor.GetAddress(), pool.TokenA), - suite.BankKeeper.GetBalance(suite.Ctx, depositor.GetAddress(), pool.TokenB), - sdk.MustNewDecFromStr("0.01"), - suite.Ctx.BlockTime().Add(-1*time.Second).Unix(), - ) - - res, err := suite.msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), deposit) - suite.Require().Nil(res) - suite.EqualError(err, fmt.Sprintf("block time %d >= deadline %d: deadline exceeded", suite.Ctx.BlockTime().Unix(), deposit.GetDeadline().Unix())) - suite.Nil(res) -} - -func (suite *msgServerTestSuite) TestDeposit_ExistingPool() { - pool := types.NewAllowedPool("ukava", "usdx") - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - err := suite.CreatePool(reserves) - suite.Require().NoError(err) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ) - depositor := suite.NewAccountFromAddr(sdk.AccAddress("new depositor-------"), balance) - - deposit := types.NewMsgDeposit( - depositor.GetAddress().String(), - suite.BankKeeper.GetBalance(suite.Ctx, depositor.GetAddress(), "usdx"), - suite.BankKeeper.GetBalance(suite.Ctx, depositor.GetAddress(), "ukava"), - sdk.MustNewDecFromStr("0.01"), - time.Now().Add(10*time.Minute).Unix(), - ) - - res, err := suite.msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), deposit) - suite.Require().Equal(&types.MsgDepositResponse{}, res) - suite.Require().NoError(err) - - expectedDeposit := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ) - - expectedShareValue := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(999999)), - sdk.NewCoin("usdx", sdkmath.NewInt(4999998)), - ) - - // Use sdk.NewCoins to remove zero coins, otherwise it will compare sdk.Coins(nil) with sdk.Coins{} - suite.AccountBalanceEqual(depositor.GetAddress(), sdk.NewCoins(balance.Sub(expectedDeposit...)...)) - suite.ModuleAccountBalanceEqual(reserves.Add(expectedDeposit...)) - suite.PoolLiquidityEqual(reserves.Add(expectedDeposit...)) - suite.PoolShareValueEqual(depositor, pool, expectedShareValue) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.GetAddress().String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - bank.EventTypeTransfer, - sdk.NewAttribute(bank.AttributeKeyRecipient, swapModuleAccountAddress.String()), - sdk.NewAttribute(bank.AttributeKeySender, depositor.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, expectedDeposit.String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - types.EventTypeSwapDeposit, - sdk.NewAttribute(types.AttributeKeyPoolID, types.PoolID(pool.TokenA, pool.TokenB)), - sdk.NewAttribute(types.AttributeKeyDepositor, depositor.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, expectedDeposit.String()), - sdk.NewAttribute(types.AttributeKeyShares, "2236067"), - )) -} - -func (suite *msgServerTestSuite) TestDeposit_ExistingPool_SlippageFailure() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - err := suite.CreatePool(reserves) - suite.Require().NoError(err) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ) - depositor := suite.NewAccountFromAddr(sdk.AccAddress("new depositor-------"), balance) - - deposit := types.NewMsgDeposit( - depositor.GetAddress().String(), - suite.BankKeeper.GetBalance(suite.Ctx, depositor.GetAddress(), "usdx"), - suite.BankKeeper.GetBalance(suite.Ctx, depositor.GetAddress(), "ukava"), - sdk.MustNewDecFromStr("0.01"), - time.Now().Add(10*time.Minute).Unix(), - ) - - res, err := suite.msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), deposit) - suite.Require().Nil(res) - suite.EqualError(err, "slippage 4.000000000000000000 > limit 0.010000000000000000: slippage exceeded") - suite.Nil(res) -} - -func (suite *msgServerTestSuite) TestWithdraw_AllShares() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - depositor := suite.NewAccountFromAddr(sdk.AccAddress("new depositor-------"), reserves) - pool := types.NewAllowedPool(reserves[0].Denom, reserves[1].Denom) - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.AllowedPools{pool}, types.DefaultSwapFee)) - - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), reserves[0], reserves[1], sdk.MustNewDecFromStr("1")) - suite.Require().NoError(err) - - withdraw := types.NewMsgWithdraw( - depositor.GetAddress().String(), - sdkmath.NewInt(22360679), - reserves[0], - reserves[1], - time.Now().Add(10*time.Minute).Unix(), - ) - - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - res, err := suite.msgServer.Withdraw(sdk.WrapSDKContext(suite.Ctx), withdraw) - suite.Require().Equal(&types.MsgWithdrawResponse{}, res) - suite.Require().NoError(err) - - suite.AccountBalanceEqual(depositor.GetAddress(), reserves) - suite.ModuleAccountBalanceEqual(sdk.Coins{}) - suite.PoolDeleted("ukava", "usdx") - suite.PoolSharesDeleted(depositor.GetAddress(), "ukava", "usdx") - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.GetAddress().String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - bank.EventTypeTransfer, - sdk.NewAttribute(bank.AttributeKeyRecipient, depositor.GetAddress().String()), - sdk.NewAttribute(bank.AttributeKeySender, swapModuleAccountAddress.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, reserves.String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - types.EventTypeSwapWithdraw, - sdk.NewAttribute(types.AttributeKeyPoolID, types.PoolID(pool.TokenA, pool.TokenB)), - sdk.NewAttribute(types.AttributeKeyOwner, depositor.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, reserves.String()), - sdk.NewAttribute(types.AttributeKeyShares, "22360679"), - )) -} - -func (suite *msgServerTestSuite) TestWithdraw_PartialShares() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - depositor := suite.NewAccountFromAddr(sdk.AccAddress("new depositor-------"), reserves) - pool := types.NewAllowedPool(reserves[0].Denom, reserves[1].Denom) - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.AllowedPools{pool}, types.DefaultSwapFee)) - - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), reserves[0], reserves[1], sdk.MustNewDecFromStr("1")) - suite.Require().NoError(err) - - minTokenA := sdk.NewCoin("ukava", sdkmath.NewInt(4999999)) - minTokenB := sdk.NewCoin("usdx", sdkmath.NewInt(24999998)) - - withdraw := types.NewMsgWithdraw( - depositor.GetAddress().String(), - sdkmath.NewInt(11180339), - minTokenA, - minTokenB, - time.Now().Add(10*time.Minute).Unix(), - ) - - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - res, err := suite.msgServer.Withdraw(sdk.WrapSDKContext(suite.Ctx), withdraw) - suite.Require().Equal(&types.MsgWithdrawResponse{}, res) - suite.Require().NoError(err) - - expectedCoinsReceived := sdk.NewCoins(minTokenA, minTokenB) - - suite.AccountBalanceEqual(depositor.GetAddress(), expectedCoinsReceived) - suite.ModuleAccountBalanceEqual(reserves.Sub(expectedCoinsReceived...)) - suite.PoolLiquidityEqual(reserves.Sub(expectedCoinsReceived...)) - suite.PoolShareValueEqual(depositor, types.NewAllowedPool("ukava", "usdx"), reserves.Sub(expectedCoinsReceived...)) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.GetAddress().String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - bank.EventTypeTransfer, - sdk.NewAttribute(bank.AttributeKeyRecipient, depositor.GetAddress().String()), - sdk.NewAttribute(bank.AttributeKeySender, swapModuleAccountAddress.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, expectedCoinsReceived.String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - types.EventTypeSwapWithdraw, - sdk.NewAttribute(types.AttributeKeyPoolID, types.PoolID(pool.TokenA, pool.TokenB)), - sdk.NewAttribute(types.AttributeKeyOwner, depositor.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, expectedCoinsReceived.String()), - sdk.NewAttribute(types.AttributeKeyShares, "11180339"), - )) -} - -func (suite *msgServerTestSuite) TestWithdraw_SlippageFailure() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - depositor := suite.NewAccountFromAddr(sdk.AccAddress("new depositor-------"), reserves) - pool := types.NewAllowedPool(reserves[0].Denom, reserves[1].Denom) - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.AllowedPools{pool}, types.DefaultSwapFee)) - - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), reserves[0], reserves[1], sdk.MustNewDecFromStr("1")) - suite.Require().NoError(err) - - minTokenA := sdk.NewCoin("ukava", sdkmath.NewInt(5e6)) - minTokenB := sdk.NewCoin("usdx", sdkmath.NewInt(25e6)) - - withdraw := types.NewMsgWithdraw( - depositor.GetAddress().String(), - sdkmath.NewInt(11180339), - minTokenA, - minTokenB, - time.Now().Add(10*time.Minute).Unix(), - ) - - res, err := suite.msgServer.Withdraw(sdk.WrapSDKContext(suite.Ctx), withdraw) - suite.Require().Nil(res) - suite.EqualError(err, "minimum withdraw not met: slippage exceeded") - suite.Nil(res) -} - -func (suite *msgServerTestSuite) TestWithdraw_DeadlineExceeded() { - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - from := suite.NewAccountFromAddr(sdk.AccAddress("from----------------"), balance) - - withdraw := types.NewMsgWithdraw( - from.GetAddress().String(), - sdkmath.NewInt(2e6), - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - suite.Ctx.BlockTime().Add(-1*time.Second).Unix(), - ) - - res, err := suite.msgServer.Withdraw(sdk.WrapSDKContext(suite.Ctx), withdraw) - suite.Require().Nil(res) - suite.EqualError(err, fmt.Sprintf("block time %d >= deadline %d: deadline exceeded", suite.Ctx.BlockTime().Unix(), withdraw.GetDeadline().Unix())) - suite.Nil(res) -} - -func (suite *msgServerTestSuite) TestSwapExactForTokens() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - err := suite.CreatePool(reserves) - suite.Require().NoError(err) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - swapInput := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - swapMsg := types.NewMsgSwapExactForTokens( - requester.GetAddress().String(), - swapInput, - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - sdk.MustNewDecFromStr("0.01"), - time.Now().Add(10*time.Minute).Unix(), - ) - - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - res, err := suite.msgServer.SwapExactForTokens(sdk.WrapSDKContext(suite.Ctx), swapMsg) - suite.Require().Equal(&types.MsgSwapExactForTokensResponse{}, res) - suite.Require().NoError(err) - - expectedSwapOutput := sdk.NewCoin("usdx", sdkmath.NewInt(4980034)) - - suite.AccountBalanceEqual(requester.GetAddress(), balance.Sub(swapInput).Add(expectedSwapOutput)) - suite.ModuleAccountBalanceEqual(reserves.Add(swapInput).Sub(expectedSwapOutput)) - suite.PoolLiquidityEqual(reserves.Add(swapInput).Sub(expectedSwapOutput)) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, requester.GetAddress().String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - bank.EventTypeTransfer, - sdk.NewAttribute(bank.AttributeKeyRecipient, swapModuleAccountAddress.String()), - sdk.NewAttribute(bank.AttributeKeySender, requester.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, swapInput.String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - bank.EventTypeTransfer, - sdk.NewAttribute(bank.AttributeKeyRecipient, requester.GetAddress().String()), - sdk.NewAttribute(bank.AttributeKeySender, swapModuleAccountAddress.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, expectedSwapOutput.String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - types.EventTypeSwapTrade, - sdk.NewAttribute(types.AttributeKeyPoolID, types.PoolID("ukava", "usdx")), - sdk.NewAttribute(types.AttributeKeyRequester, requester.GetAddress().String()), - sdk.NewAttribute(types.AttributeKeySwapInput, swapInput.String()), - sdk.NewAttribute(types.AttributeKeySwapOutput, expectedSwapOutput.String()), - sdk.NewAttribute(types.AttributeKeyFeePaid, "3000ukava"), - sdk.NewAttribute(types.AttributeKeyExactDirection, "input"), - )) -} - -func (suite *msgServerTestSuite) TestSwapExactForTokens_SlippageFailure() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - err := suite.CreatePool(reserves) - suite.Require().NoError(err) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - swapInput := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - swapMsg := types.NewMsgSwapExactForTokens( - requester.GetAddress().String(), - swapInput, - sdk.NewCoin("usdx", sdkmath.NewInt(5030338)), - sdk.MustNewDecFromStr("0.01"), - time.Now().Add(10*time.Minute).Unix(), - ) - - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - res, err := suite.msgServer.SwapExactForTokens(sdk.WrapSDKContext(suite.Ctx), swapMsg) - suite.Require().Nil(res) - suite.EqualError(err, "slippage 0.010000123252155223 > limit 0.010000000000000000: slippage exceeded") - suite.Nil(res) -} - -func (suite *msgServerTestSuite) TestSwapExactForTokens_DeadlineExceeded() { - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - swapMsg := types.NewMsgSwapExactForTokens( - requester.GetAddress().String(), - sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(25e5)), - sdk.MustNewDecFromStr("0.01"), - suite.Ctx.BlockTime().Add(-1*time.Second).Unix(), - ) - - res, err := suite.msgServer.SwapExactForTokens(sdk.WrapSDKContext(suite.Ctx), swapMsg) - suite.Require().Nil(res) - suite.EqualError(err, fmt.Sprintf("block time %d >= deadline %d: deadline exceeded", suite.Ctx.BlockTime().Unix(), swapMsg.GetDeadline().Unix())) - suite.Nil(res) -} - -func (suite *msgServerTestSuite) TestSwapForExactTokens() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - err := suite.CreatePool(reserves) - suite.Require().NoError(err) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - swapOutput := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - swapMsg := types.NewMsgSwapForExactTokens( - requester.GetAddress().String(), - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - swapOutput, - sdk.MustNewDecFromStr("0.01"), - time.Now().Add(10*time.Minute).Unix(), - ) - - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - res, err := suite.msgServer.SwapForExactTokens(sdk.WrapSDKContext(suite.Ctx), swapMsg) - suite.Require().Equal(&types.MsgSwapForExactTokensResponse{}, res) - suite.Require().NoError(err) - - expectedSwapInput := sdk.NewCoin("ukava", sdkmath.NewInt(1004015)) - - suite.AccountBalanceEqual(requester.GetAddress(), balance.Sub(expectedSwapInput).Add(swapOutput)) - suite.ModuleAccountBalanceEqual(reserves.Add(expectedSwapInput).Sub(swapOutput)) - suite.PoolLiquidityEqual(reserves.Add(expectedSwapInput).Sub(swapOutput)) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, requester.GetAddress().String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - bank.EventTypeTransfer, - sdk.NewAttribute(bank.AttributeKeyRecipient, swapModuleAccountAddress.String()), - sdk.NewAttribute(bank.AttributeKeySender, requester.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, expectedSwapInput.String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - bank.EventTypeTransfer, - sdk.NewAttribute(bank.AttributeKeyRecipient, requester.GetAddress().String()), - sdk.NewAttribute(bank.AttributeKeySender, swapModuleAccountAddress.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, swapOutput.String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - types.EventTypeSwapTrade, - sdk.NewAttribute(types.AttributeKeyPoolID, types.PoolID("ukava", "usdx")), - sdk.NewAttribute(types.AttributeKeyRequester, requester.GetAddress().String()), - sdk.NewAttribute(types.AttributeKeySwapInput, expectedSwapInput.String()), - sdk.NewAttribute(types.AttributeKeySwapOutput, swapOutput.String()), - sdk.NewAttribute(types.AttributeKeyFeePaid, "3013ukava"), - sdk.NewAttribute(types.AttributeKeyExactDirection, "output"), - )) -} - -func (suite *msgServerTestSuite) TestSwapForExactTokens_SlippageFailure() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - err := suite.CreatePool(reserves) - suite.Require().NoError(err) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - swapOutput := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - swapMsg := types.NewMsgSwapForExactTokens( - requester.GetAddress().String(), - sdk.NewCoin("ukava", sdkmath.NewInt(990991)), - swapOutput, - sdk.MustNewDecFromStr("0.01"), - time.Now().Add(10*time.Minute).Unix(), - ) - - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - res, err := suite.msgServer.SwapForExactTokens(sdk.WrapSDKContext(suite.Ctx), swapMsg) - suite.Require().Nil(res) - suite.EqualError(err, "slippage 0.010000979019022939 > limit 0.010000000000000000: slippage exceeded") - suite.Nil(res) -} - -func (suite *msgServerTestSuite) TestSwapForExactTokens_DeadlineExceeded() { - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - swapMsg := types.NewMsgSwapForExactTokens( - requester.GetAddress().String(), - sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(25e5)), - sdk.MustNewDecFromStr("0.01"), - suite.Ctx.BlockTime().Add(-1*time.Second).Unix(), - ) - - res, err := suite.msgServer.SwapForExactTokens(sdk.WrapSDKContext(suite.Ctx), swapMsg) - suite.Require().Nil(res) - suite.EqualError(err, fmt.Sprintf("block time %d >= deadline %d: deadline exceeded", suite.Ctx.BlockTime().Unix(), swapMsg.GetDeadline().Unix())) - suite.Nil(res) -} - -func TestMsgServerTestSuite(t *testing.T) { - suite.Run(t, new(msgServerTestSuite)) -} diff --git a/x/swap/keeper/swap.go b/x/swap/keeper/swap.go deleted file mode 100644 index b77aeee2..00000000 --- a/x/swap/keeper/swap.go +++ /dev/null @@ -1,122 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/kava-labs/kava/x/swap/types" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// SwapExactForTokens swaps an exact coin a input for a coin b output -func (k *Keeper) SwapExactForTokens(ctx sdk.Context, requester sdk.AccAddress, exactCoinA, coinB sdk.Coin, slippageLimit sdk.Dec) error { - poolID, pool, err := k.loadPool(ctx, exactCoinA.Denom, coinB.Denom) - if err != nil { - return err - } - - swapOutput, feePaid := pool.SwapWithExactInput(exactCoinA, k.GetSwapFee(ctx)) - if swapOutput.IsZero() { - return errorsmod.Wrapf(types.ErrInsufficientLiquidity, "swap output rounds to zero, increase input amount") - } - - priceChange := sdk.NewDecFromInt(swapOutput.Amount).Quo(sdk.NewDecFromInt(coinB.Amount)) - if err := k.assertSlippageWithinLimit(priceChange, slippageLimit); err != nil { - return err - } - - if err := k.commitSwap(ctx, poolID, pool, requester, exactCoinA, swapOutput, feePaid, "input"); err != nil { - return err - } - - return nil -} - -// SwapForExactTokens swaps a coin a input for an exact coin b output -func (k *Keeper) SwapForExactTokens(ctx sdk.Context, requester sdk.AccAddress, coinA, exactCoinB sdk.Coin, slippageLimit sdk.Dec) error { - poolID, pool, err := k.loadPool(ctx, coinA.Denom, exactCoinB.Denom) - if err != nil { - return err - } - - if exactCoinB.Amount.GTE(pool.Reserves().AmountOf(exactCoinB.Denom)) { - return errorsmod.Wrapf( - types.ErrInsufficientLiquidity, - "output %s >= pool reserves %s", exactCoinB.Amount.String(), pool.Reserves().AmountOf(exactCoinB.Denom).String(), - ) - } - - swapInput, feePaid := pool.SwapWithExactOutput(exactCoinB, k.GetSwapFee(ctx)) - - priceChange := sdk.NewDecFromInt(coinA.Amount).Quo(sdk.NewDecFromInt(swapInput.Sub(feePaid).Amount)) - if err := k.assertSlippageWithinLimit(priceChange, slippageLimit); err != nil { - return err - } - - if err := k.commitSwap(ctx, poolID, pool, requester, swapInput, exactCoinB, feePaid, "output"); err != nil { - return err - } - - return nil -} - -func (k Keeper) loadPool(ctx sdk.Context, denomA string, denomB string) (string, *types.DenominatedPool, error) { - poolID := types.PoolID(denomA, denomB) - - poolRecord, found := k.GetPool(ctx, poolID) - if !found { - return poolID, nil, errorsmod.Wrapf(types.ErrInvalidPool, "pool %s not found", poolID) - } - - pool, err := types.NewDenominatedPoolWithExistingShares(poolRecord.Reserves(), poolRecord.TotalShares) - if err != nil { - panic(fmt.Sprintf("invalid pool %s: %s", poolID, err)) - } - - return poolID, pool, nil -} - -func (k Keeper) assertSlippageWithinLimit(priceChange sdk.Dec, slippageLimit sdk.Dec) error { - slippage := sdk.OneDec().Sub(priceChange) - if slippage.GT(slippageLimit) { - return errorsmod.Wrapf(types.ErrSlippageExceeded, "slippage %s > limit %s", slippage, slippageLimit) - } - - return nil -} - -func (k Keeper) commitSwap( - ctx sdk.Context, - poolID string, - pool *types.DenominatedPool, - requester sdk.AccAddress, - swapInput sdk.Coin, - swapOutput sdk.Coin, - feePaid sdk.Coin, - exactDirection string, -) error { - k.SetPool(ctx, types.NewPoolRecordFromPool(pool)) - - if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, requester, types.ModuleAccountName, sdk.NewCoins(swapInput)); err != nil { - return err - } - - if err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, requester, sdk.NewCoins(swapOutput)); err != nil { - panic(err) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeSwapTrade, - sdk.NewAttribute(types.AttributeKeyPoolID, poolID), - sdk.NewAttribute(types.AttributeKeyRequester, requester.String()), - sdk.NewAttribute(types.AttributeKeySwapInput, swapInput.String()), - sdk.NewAttribute(types.AttributeKeySwapOutput, swapOutput.String()), - sdk.NewAttribute(types.AttributeKeyFeePaid, feePaid.String()), - sdk.NewAttribute(types.AttributeKeyExactDirection, exactDirection), - ), - ) - - return nil -} diff --git a/x/swap/keeper/swap_test.go b/x/swap/keeper/swap_test.go deleted file mode 100644 index 12d13af6..00000000 --- a/x/swap/keeper/swap_test.go +++ /dev/null @@ -1,631 +0,0 @@ -package keeper_test - -import ( - "errors" - "fmt" - - sdkmath "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/kava-labs/kava/x/swap/types" -) - -func (suite *keeperTestSuite) TestSwapExactForTokens() { - suite.Keeper.SetParams(suite.Ctx, types.Params{ - SwapFee: sdk.MustNewDecFromStr("0.0025"), - }) - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - totalShares := sdkmath.NewInt(30e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - - err := suite.Keeper.SwapExactForTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - suite.Require().NoError(err) - - expectedOutput := sdk.NewCoin("usdx", sdkmath.NewInt(4982529)) - - suite.AccountBalanceEqual(requester.GetAddress(), balance.Sub(coinA).Add(expectedOutput)) - suite.ModuleAccountBalanceEqual(reserves.Add(coinA).Sub(expectedOutput)) - suite.PoolLiquidityEqual(reserves.Add(coinA).Sub(expectedOutput)) - - suite.EventsContains(suite.Ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeSwapTrade, - sdk.NewAttribute(types.AttributeKeyPoolID, poolID), - sdk.NewAttribute(types.AttributeKeyRequester, requester.GetAddress().String()), - sdk.NewAttribute(types.AttributeKeySwapInput, coinA.String()), - sdk.NewAttribute(types.AttributeKeySwapOutput, expectedOutput.String()), - sdk.NewAttribute(types.AttributeKeyFeePaid, "2500ukava"), - sdk.NewAttribute(types.AttributeKeyExactDirection, "input"), - )) -} - -func (suite *keeperTestSuite) TestSwapExactForTokens_OutputGreaterThanZero() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - balance := sdk.NewCoins( - sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("usdx", sdkmath.NewInt(5)) - coinB := sdk.NewCoin("ukava", sdkmath.NewInt(1)) - - err := suite.Keeper.SwapExactForTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("1")) - suite.EqualError(err, "swap output rounds to zero, increase input amount: insufficient liquidity") -} - -func (suite *keeperTestSuite) TestSwapExactForTokens_Slippage() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), - ) - totalShares := sdkmath.NewInt(30e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - testCases := []struct { - coinA sdk.Coin - coinB sdk.Coin - slippage sdk.Dec - fee sdk.Dec - shouldFail bool - }{ - // positive slippage OK - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(2e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.0025"), false}, - // positive slippage with zero slippage OK - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(2e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.0025"), false}, - // exact zero slippage OK - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4950495)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4935790)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.003"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4705299)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.05"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(990099)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(987158)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.003"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(941059)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.05"), false}, - // slippage failure, zero slippage tolerance - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4950496)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4935793)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.003"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4705300)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.05"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(990100)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(987159)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.003"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(941060)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.05"), true}, - // slippage failure, 1 percent slippage - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000501)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4985647)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.003"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4752828)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.05"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000101)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(997130)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.003"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(950565)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.05"), true}, - // slippage OK, 1 percent slippage - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000500)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4985646)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.003"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4752827)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.05"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000100)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(997129)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.003"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(950564)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.05"), false}, - } - - for _, tc := range testCases { - suite.Run(fmt.Sprintf("coinA=%s coinB=%s slippage=%s fee=%s", tc.coinA, tc.coinB, tc.slippage, tc.fee), func() { - suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.Params{ - SwapFee: tc.fee, - }) - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), - ) - totalShares := sdkmath.NewInt(30e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(100e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - err := suite.Keeper.SwapExactForTokens(ctx, requester.GetAddress(), tc.coinA, tc.coinB, tc.slippage) - - if tc.shouldFail { - suite.Require().Error(err) - suite.Contains(err.Error(), "slippage exceeded") - } else { - suite.NoError(err) - } - }) - } -} - -func (suite *keeperTestSuite) TestSwapExactForTokens_InsufficientFunds() { - testCases := []struct { - name string - balanceA sdk.Coin - coinA sdk.Coin - coinB sdk.Coin - }{ - {"no ukava balance", sdk.NewCoin("ukava", sdk.ZeroInt()), sdk.NewCoin("ukava", sdkmath.NewInt(100)), sdk.NewCoin("usdx", sdkmath.NewInt(500))}, - {"no usdx balance", sdk.NewCoin("usdx", sdk.ZeroInt()), sdk.NewCoin("usdx", sdkmath.NewInt(500)), sdk.NewCoin("ukava", sdkmath.NewInt(100))}, - {"low ukava balance", sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("ukava", sdkmath.NewInt(1000001)), sdk.NewCoin("usdx", sdkmath.NewInt(5000000))}, - {"low ukava balance", sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("usdx", sdkmath.NewInt(5000001)), sdk.NewCoin("ukava", sdkmath.NewInt(1000000))}, - {"large ukava balance difference", sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6))}, - {"large usdx balance difference", sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6))}, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500000e6)), - ) - totalShares := sdkmath.NewInt(30000e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - balance := sdk.NewCoins(tc.balanceA) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - err := suite.Keeper.SwapExactForTokens(ctx, requester.GetAddress(), tc.coinA, tc.coinB, sdk.MustNewDecFromStr("0.1")) - suite.Require().True(errors.Is(err, sdkerrors.ErrInsufficientFunds), fmt.Sprintf("got err %s", err)) - }) - } -} - -func (suite *keeperTestSuite) TestSwapExactForTokens_InsufficientFunds_Vesting() { - testCases := []struct { - name string - balanceA sdk.Coin - vestingA sdk.Coin - coinA sdk.Coin - coinB sdk.Coin - }{ - {"no ukava balance, vesting only", sdk.NewCoin("ukava", sdk.ZeroInt()), sdk.NewCoin("ukava", sdkmath.NewInt(100)), sdk.NewCoin("ukava", sdkmath.NewInt(100)), sdk.NewCoin("usdx", sdkmath.NewInt(500))}, - {"no usdx balance, vesting only", sdk.NewCoin("usdx", sdk.ZeroInt()), sdk.NewCoin("usdx", sdkmath.NewInt(500)), sdk.NewCoin("usdx", sdkmath.NewInt(500)), sdk.NewCoin("ukava", sdkmath.NewInt(100))}, - {"low ukava balance, vesting matches exact", sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("ukava", sdkmath.NewInt(1000001)), sdk.NewCoin("usdx", sdkmath.NewInt(5000000))}, - {"low ukava balance, vesting matches exact", sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("usdx", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(5000001)), sdk.NewCoin("ukava", sdkmath.NewInt(1000000))}, - {"large ukava balance difference, vesting covers difference", sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6))}, - {"large usdx balance difference, vesting covers difference", sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6))}, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500000e6)), - ) - totalShares := sdkmath.NewInt(30000e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - balance := sdk.NewCoins(tc.balanceA) - vesting := sdk.NewCoins(tc.vestingA) - requester := suite.CreateVestingAccount(balance, vesting) - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - err := suite.Keeper.SwapExactForTokens(ctx, requester.GetAddress(), tc.coinA, tc.coinB, sdk.MustNewDecFromStr("0.1")) - suite.Require().True(errors.Is(err, sdkerrors.ErrInsufficientFunds), fmt.Sprintf("got err %s", err)) - }) - } -} - -func (suite *keeperTestSuite) TestSwapExactForTokens_PoolNotFound() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - totalShares := sdkmath.NewInt(3000e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - suite.Keeper.DeletePool(suite.Ctx, poolID) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - - err := suite.Keeper.SwapExactForTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - suite.EqualError(err, "pool ukava:usdx not found: invalid pool") - - err = suite.Keeper.SwapExactForTokens(suite.Ctx, requester.GetAddress(), coinB, coinA, sdk.MustNewDecFromStr("0.01")) - suite.EqualError(err, "pool ukava:usdx not found: invalid pool") -} - -func (suite *keeperTestSuite) TestSwapExactForTokens_PanicOnInvalidPool() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - totalShares := sdkmath.NewInt(3000e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - poolRecord, found := suite.Keeper.GetPool(suite.Ctx, poolID) - suite.Require().True(found, "expected pool record to exist") - - poolRecord.TotalShares = sdk.ZeroInt() - suite.Keeper.SetPool_Raw(suite.Ctx, poolRecord) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - - suite.PanicsWithValue("invalid pool ukava:usdx: total shares must be greater than zero: invalid pool", func() { - _ = suite.Keeper.SwapExactForTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - }, "expected invalid pool record to panic") - - suite.PanicsWithValue("invalid pool ukava:usdx: total shares must be greater than zero: invalid pool", func() { - _ = suite.Keeper.SwapExactForTokens(suite.Ctx, requester.GetAddress(), coinB, coinA, sdk.MustNewDecFromStr("0.01")) - }, "expected invalid pool record to panic") -} - -func (suite *keeperTestSuite) TestSwapExactForTokens_PanicOnInsufficientModuleAccFunds() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - totalShares := sdkmath.NewInt(3000e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - suite.RemoveCoinsFromModule(sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - )) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - - suite.Panics(func() { - _ = suite.Keeper.SwapExactForTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - }, "expected panic when module account does not have enough funds") - - suite.Panics(func() { - _ = suite.Keeper.SwapExactForTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - }, "expected panic when module account does not have enough funds") -} - -func (suite *keeperTestSuite) TestSwapForExactTokens() { - suite.Keeper.SetParams(suite.Ctx, types.Params{ - SwapFee: sdk.MustNewDecFromStr("0.0025"), - }) - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - totalShares := sdkmath.NewInt(30e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - - err := suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - suite.Require().NoError(err) - - expectedInput := sdk.NewCoin("ukava", sdkmath.NewInt(1003511)) - - suite.AccountBalanceEqual(requester.GetAddress(), balance.Sub(expectedInput).Add(coinB)) - suite.ModuleAccountBalanceEqual(reserves.Add(expectedInput).Sub(coinB)) - suite.PoolLiquidityEqual(reserves.Add(expectedInput).Sub(coinB)) - - suite.EventsContains(suite.Ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeSwapTrade, - sdk.NewAttribute(types.AttributeKeyPoolID, poolID), - sdk.NewAttribute(types.AttributeKeyRequester, requester.GetAddress().String()), - sdk.NewAttribute(types.AttributeKeySwapInput, expectedInput.String()), - sdk.NewAttribute(types.AttributeKeySwapOutput, coinB.String()), - sdk.NewAttribute(types.AttributeKeyFeePaid, "2509ukava"), - sdk.NewAttribute(types.AttributeKeyExactDirection, "output"), - )) -} - -func (suite *keeperTestSuite) TestSwapForExactTokens_OutputLessThanPoolReserves() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), - ) - totalShares := sdkmath.NewInt(300e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(500e6).Add(sdk.OneInt())) - err := suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - suite.EqualError(err, "output 500000001 >= pool reserves 500000000: insufficient liquidity") - - coinB = sdk.NewCoin("usdx", sdkmath.NewInt(500e6)) - err = suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - suite.EqualError(err, "output 500000000 >= pool reserves 500000000: insufficient liquidity") -} - -func (suite *keeperTestSuite) TestSwapForExactTokens_Slippage() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), - ) - totalShares := sdkmath.NewInt(30e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - testCases := []struct { - coinA sdk.Coin - coinB sdk.Coin - slippage sdk.Dec - fee sdk.Dec - shouldFail bool - }{ - // positive slippage OK - {sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(100e6)), sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(100e6)), sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.0025"), false}, - // positive slippage with zero slippage OK - {sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(100e6)), sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(100e6)), sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.0025"), false}, - // exact zero slippage OK - {sdk.NewCoin("ukava", sdkmath.NewInt(1010102)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1010102)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.003"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1010102)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.05"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5050506)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5050506)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.003"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5050506)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.05"), false}, - // slippage failure, zero slippage tolerance - {sdk.NewCoin("ukava", sdkmath.NewInt(1010101)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1010101)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.003"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1010101)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.05"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5050505)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5050505)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.003"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5050505)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.05"), true}, - // slippage failure, 1 percent slippage - {sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.003"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.05"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.003"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.05"), true}, - // slippage OK, 1 percent slippage - {sdk.NewCoin("ukava", sdkmath.NewInt(1000001)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1000001)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.003"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1000001)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.05"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5000001)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5000001)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.003"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5000001)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.05"), false}, - } - - for _, tc := range testCases { - suite.Run(fmt.Sprintf("coinA=%s coinB=%s slippage=%s fee=%s", tc.coinA, tc.coinB, tc.slippage, tc.fee), func() { - suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.Params{ - SwapFee: tc.fee, - }) - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), - ) - totalShares := sdkmath.NewInt(30e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(100e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - err := suite.Keeper.SwapForExactTokens(ctx, requester.GetAddress(), tc.coinA, tc.coinB, tc.slippage) - - if tc.shouldFail { - suite.Require().Error(err) - suite.Contains(err.Error(), "slippage exceeded") - } else { - suite.NoError(err) - } - }) - } -} - -func (suite *keeperTestSuite) TestSwapForExactTokens_InsufficientFunds() { - testCases := []struct { - name string - balanceA sdk.Coin - coinA sdk.Coin - coinB sdk.Coin - }{ - {"no ukava balance", sdk.NewCoin("ukava", sdk.ZeroInt()), sdk.NewCoin("ukava", sdkmath.NewInt(100)), sdk.NewCoin("usdx", sdkmath.NewInt(500))}, - {"no usdx balance", sdk.NewCoin("usdx", sdk.ZeroInt()), sdk.NewCoin("usdx", sdkmath.NewInt(500)), sdk.NewCoin("ukava", sdkmath.NewInt(100))}, - {"low ukava balance", sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("usdx", sdkmath.NewInt(5000000))}, - {"low ukava balance", sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("ukava", sdkmath.NewInt(1000000))}, - {"large ukava balance difference", sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6))}, - {"large usdx balance difference", sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6))}, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500000e6)), - ) - totalShares := sdkmath.NewInt(30000e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - balance := sdk.NewCoins(tc.balanceA) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - err := suite.Keeper.SwapForExactTokens(ctx, requester.GetAddress(), tc.coinA, tc.coinB, sdk.MustNewDecFromStr("0.1")) - suite.Require().True(errors.Is(err, sdkerrors.ErrInsufficientFunds), fmt.Sprintf("got err %s", err)) - }) - } -} - -func (suite *keeperTestSuite) TestSwapForExactTokens_InsufficientFunds_Vesting() { - testCases := []struct { - name string - balanceA sdk.Coin - vestingA sdk.Coin - coinA sdk.Coin - coinB sdk.Coin - }{ - {"no ukava balance, vesting only", sdk.NewCoin("ukava", sdk.ZeroInt()), sdk.NewCoin("ukava", sdkmath.NewInt(100)), sdk.NewCoin("ukava", sdkmath.NewInt(1000)), sdk.NewCoin("usdx", sdkmath.NewInt(500))}, - {"no usdx balance, vesting only", sdk.NewCoin("usdx", sdk.ZeroInt()), sdk.NewCoin("usdx", sdkmath.NewInt(500)), sdk.NewCoin("usdx", sdkmath.NewInt(5000)), sdk.NewCoin("ukava", sdkmath.NewInt(100))}, - {"low ukava balance, vesting matches exact", sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("ukava", sdkmath.NewInt(100000)), sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("usdx", sdkmath.NewInt(5000000))}, - {"low ukava balance, vesting matches exact", sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("usdx", sdkmath.NewInt(500000)), sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("ukava", sdkmath.NewInt(1000000))}, - {"large ukava balance difference, vesting covers difference", sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), sdk.NewCoin("ukava", sdkmath.NewInt(10000e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6))}, - {"large usdx balance difference, vesting covers difference", sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), sdk.NewCoin("usdx", sdkmath.NewInt(500000e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6))}, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500000e6)), - ) - totalShares := sdkmath.NewInt(30000e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - balance := sdk.NewCoins(tc.balanceA) - vesting := sdk.NewCoins(tc.vestingA) - requester := suite.CreateVestingAccount(balance, vesting) - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - err := suite.Keeper.SwapForExactTokens(ctx, requester.GetAddress(), tc.coinA, tc.coinB, sdk.MustNewDecFromStr("0.1")) - suite.Require().True(errors.Is(err, sdkerrors.ErrInsufficientFunds), fmt.Sprintf("got err %s", err)) - }) - } -} - -func (suite *keeperTestSuite) TestSwapForExactTokens_PoolNotFound() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - totalShares := sdkmath.NewInt(3000e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - suite.Keeper.DeletePool(suite.Ctx, poolID) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - - err := suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - suite.EqualError(err, "pool ukava:usdx not found: invalid pool") - - err = suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinB, coinA, sdk.MustNewDecFromStr("0.01")) - suite.EqualError(err, "pool ukava:usdx not found: invalid pool") -} - -func (suite *keeperTestSuite) TestSwapForExactTokens_PanicOnInvalidPool() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - totalShares := sdkmath.NewInt(3000e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - poolRecord, found := suite.Keeper.GetPool(suite.Ctx, poolID) - suite.Require().True(found, "expected pool record to exist") - - poolRecord.TotalShares = sdk.ZeroInt() - suite.Keeper.SetPool_Raw(suite.Ctx, poolRecord) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - - suite.PanicsWithValue("invalid pool ukava:usdx: total shares must be greater than zero: invalid pool", func() { - _ = suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - }, "expected invalid pool record to panic") - - suite.PanicsWithValue("invalid pool ukava:usdx: total shares must be greater than zero: invalid pool", func() { - _ = suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinB, coinA, sdk.MustNewDecFromStr("0.01")) - }, "expected invalid pool record to panic") -} - -func (suite *keeperTestSuite) TestSwapForExactTokens_PanicOnInsufficientModuleAccFunds() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - totalShares := sdkmath.NewInt(3000e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - suite.RemoveCoinsFromModule(sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - )) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - - suite.Panics(func() { - _ = suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - }, "expected panic when module account does not have enough funds") - - suite.Panics(func() { - _ = suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - }, "expected panic when module account does not have enough funds") -} diff --git a/x/swap/keeper/withdraw.go b/x/swap/keeper/withdraw.go deleted file mode 100644 index a0970824..00000000 --- a/x/swap/keeper/withdraw.go +++ /dev/null @@ -1,75 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/kava-labs/kava/x/swap/types" -) - -// Withdraw removes liquidity from an existing pool from an owners deposit, converting the provided shares for -// the returned pool liquidity. -// -// If 100% of the owners shares are removed, then the deposit is deleted. In addition, if all the pool shares -// are removed then the pool is deleted. -// -// The number of shares must be large enough to result in at least 1 unit of the smallest reserve in the pool. -// If the share input is below the minimum required for positive liquidity to be remove from both reserves, a -// insufficient error is returned. -// -// In addition, if the withdrawn liquidity for each reserve is below the provided minimum, a slippage exceeded -// error is returned. -func (k Keeper) Withdraw(ctx sdk.Context, owner sdk.AccAddress, shares sdkmath.Int, minCoinA, minCoinB sdk.Coin) error { - poolID := types.PoolID(minCoinA.Denom, minCoinB.Denom) - - shareRecord, found := k.GetDepositorShares(ctx, owner, poolID) - if !found { - return errorsmod.Wrapf(types.ErrDepositNotFound, "no deposit for account %s and pool %s", owner, poolID) - } - - if shares.GT(shareRecord.SharesOwned) { - return errorsmod.Wrapf(types.ErrInvalidShares, "withdraw of %s shares greater than %s shares owned", shares, shareRecord.SharesOwned) - } - - poolRecord, found := k.GetPool(ctx, poolID) - if !found { - panic(fmt.Sprintf("pool %s not found", poolID)) - } - - pool, err := types.NewDenominatedPoolWithExistingShares(poolRecord.Reserves(), poolRecord.TotalShares) - if err != nil { - panic(fmt.Sprintf("invalid pool %s: %s", poolID, err)) - } - - withdrawnAmount := pool.RemoveLiquidity(shares) - if withdrawnAmount.AmountOf(minCoinA.Denom).IsZero() || withdrawnAmount.AmountOf(minCoinB.Denom).IsZero() { - return errorsmod.Wrap(types.ErrInsufficientLiquidity, "shares must be increased") - } - if withdrawnAmount.AmountOf(minCoinA.Denom).LT(minCoinA.Amount) || withdrawnAmount.AmountOf(minCoinB.Denom).LT(minCoinB.Amount) { - return errorsmod.Wrap(types.ErrSlippageExceeded, "minimum withdraw not met") - } - - k.updatePool(ctx, poolID, pool) - k.BeforePoolDepositModified(ctx, poolID, owner, shareRecord.SharesOwned) - k.updateDepositorShares(ctx, owner, poolID, shareRecord.SharesOwned.Sub(shares)) - - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, owner, withdrawnAmount) - if err != nil { - panic(err) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeSwapWithdraw, - sdk.NewAttribute(types.AttributeKeyPoolID, poolID), - sdk.NewAttribute(types.AttributeKeyOwner, owner.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, withdrawnAmount.String()), - sdk.NewAttribute(types.AttributeKeyShares, shares.String()), - ), - ) - - return nil -} diff --git a/x/swap/keeper/withdraw_test.go b/x/swap/keeper/withdraw_test.go deleted file mode 100644 index f89e7658..00000000 --- a/x/swap/keeper/withdraw_test.go +++ /dev/null @@ -1,224 +0,0 @@ -package keeper_test - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/swap/types" -) - -func (suite *keeperTestSuite) TestWithdraw_AllShares() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - err := suite.Keeper.Withdraw(suite.Ctx, owner.GetAddress(), totalShares, reserves[0], reserves[1]) - suite.Require().NoError(err) - - suite.PoolDeleted(reserves[0].Denom, reserves[1].Denom) - suite.PoolSharesDeleted(owner.GetAddress(), reserves[0].Denom, reserves[1].Denom) - suite.AccountBalanceEqual(owner.GetAddress(), reserves) - suite.ModuleAccountBalanceEqual(sdk.Coins{}) - - suite.EventsContains(suite.Ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeSwapWithdraw, - sdk.NewAttribute(types.AttributeKeyPoolID, poolID), - sdk.NewAttribute(types.AttributeKeyOwner, owner.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, reserves.String()), - sdk.NewAttribute(types.AttributeKeyShares, totalShares.String()), - )) -} - -func (suite *keeperTestSuite) TestWithdraw_PartialShares() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - sharesToWithdraw := sdkmath.NewInt(15e6) - minCoinA := sdk.NewCoin("usdx", sdkmath.NewInt(25e6)) - minCoinB := sdk.NewCoin("ukava", sdkmath.NewInt(5e6)) - - err := suite.Keeper.Withdraw(suite.Ctx, owner.GetAddress(), sharesToWithdraw, minCoinA, minCoinB) - suite.Require().NoError(err) - - sharesLeft := totalShares.Sub(sharesToWithdraw) - reservesLeft := sdk.NewCoins(reserves[0].Sub(minCoinB), reserves[1].Sub(minCoinA)) - - suite.PoolShareTotalEqual(poolID, sharesLeft) - suite.PoolDepositorSharesEqual(owner.GetAddress(), poolID, sharesLeft) - suite.PoolReservesEqual(poolID, reservesLeft) - suite.AccountBalanceEqual(owner.GetAddress(), sdk.NewCoins(minCoinA, minCoinB)) - suite.ModuleAccountBalanceEqual(reservesLeft) - - suite.EventsContains(suite.Ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeSwapWithdraw, - sdk.NewAttribute(types.AttributeKeyPoolID, poolID), - sdk.NewAttribute(types.AttributeKeyOwner, owner.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, sdk.NewCoins(minCoinA, minCoinB).String()), - sdk.NewAttribute(types.AttributeKeyShares, sharesToWithdraw.String()), - )) -} - -func (suite *keeperTestSuite) TestWithdraw_NoSharesOwned() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - accWithNoDeposit := sdk.AccAddress("some account") - - err := suite.Keeper.Withdraw(suite.Ctx, accWithNoDeposit, totalShares, reserves[0], reserves[1]) - suite.EqualError(err, fmt.Sprintf("no deposit for account %s and pool %s: deposit not found", accWithNoDeposit.String(), poolID)) -} - -func (suite *keeperTestSuite) TestWithdraw_GreaterThanSharesOwned() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - sharesToWithdraw := totalShares.Add(sdk.OneInt()) - err := suite.Keeper.Withdraw(suite.Ctx, owner.GetAddress(), sharesToWithdraw, reserves[0], reserves[1]) - suite.EqualError(err, fmt.Sprintf("withdraw of %s shares greater than %s shares owned: invalid shares", sharesToWithdraw, totalShares)) -} - -func (suite *keeperTestSuite) TestWithdraw_MinWithdraw() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - - testCases := []struct { - shares sdkmath.Int - minCoinA sdk.Coin - minCoinB sdk.Coin - shouldFail bool - }{ - {sdkmath.NewInt(1), sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1)), true}, - {sdkmath.NewInt(1), sdk.NewCoin("usdx", sdkmath.NewInt(5)), sdk.NewCoin("ukava", sdkmath.NewInt(1)), true}, - - {sdkmath.NewInt(2), sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1)), true}, - {sdkmath.NewInt(2), sdk.NewCoin("usdx", sdkmath.NewInt(5)), sdk.NewCoin("ukava", sdkmath.NewInt(1)), true}, - - {sdkmath.NewInt(3), sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(5)), false}, - {sdkmath.NewInt(3), sdk.NewCoin("usdx", sdkmath.NewInt(5)), sdk.NewCoin("ukava", sdkmath.NewInt(1)), false}, - } - - for _, tc := range testCases { - suite.Run(fmt.Sprintf("shares=%s minCoinA=%s minCoinB=%s", tc.shares, tc.minCoinA, tc.minCoinB), func() { - suite.SetupTest() - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - err := suite.Keeper.Withdraw(suite.Ctx, owner.GetAddress(), tc.shares, tc.minCoinA, tc.minCoinB) - if tc.shouldFail { - suite.EqualError(err, "shares must be increased: insufficient liquidity") - } else { - suite.NoError(err, "expected no liquidity error") - } - }) - } -} - -func (suite *keeperTestSuite) TestWithdraw_BelowMinimum() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - - testCases := []struct { - shares sdkmath.Int - minCoinA sdk.Coin - minCoinB sdk.Coin - shouldFail bool - }{ - {sdkmath.NewInt(15e6), sdk.NewCoin("ukava", sdkmath.NewInt(5000001)), sdk.NewCoin("usdx", sdkmath.NewInt(25e6)), true}, - } - - for _, tc := range testCases { - suite.Run(fmt.Sprintf("shares=%s minCoinA=%s minCoinB=%s", tc.shares, tc.minCoinA, tc.minCoinB), func() { - suite.SetupTest() - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - err := suite.Keeper.Withdraw(suite.Ctx, owner.GetAddress(), tc.shares, tc.minCoinA, tc.minCoinB) - if tc.shouldFail { - suite.EqualError(err, "minimum withdraw not met: slippage exceeded") - } else { - suite.NoError(err, "expected no slippage error") - } - }) - } -} - -func (suite *keeperTestSuite) TestWithdraw_PanicOnMissingPool() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - suite.Keeper.DeletePool(suite.Ctx, poolID) - - suite.PanicsWithValue("pool ukava:usdx not found", func() { - _ = suite.Keeper.Withdraw(suite.Ctx, owner.GetAddress(), totalShares, reserves[0], reserves[1]) - }, "expected missing pool record to panic") -} - -func (suite *keeperTestSuite) TestWithdraw_PanicOnInvalidPool() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - poolRecord, found := suite.Keeper.GetPool(suite.Ctx, poolID) - suite.Require().True(found, "expected pool record to exist") - - poolRecord.TotalShares = sdk.ZeroInt() - suite.Keeper.SetPool_Raw(suite.Ctx, poolRecord) - - suite.PanicsWithValue("invalid pool ukava:usdx: total shares must be greater than zero: invalid pool", func() { - _ = suite.Keeper.Withdraw(suite.Ctx, owner.GetAddress(), totalShares, reserves[0], reserves[1]) - }, "expected invalid pool record to panic") -} - -func (suite *keeperTestSuite) TestWithdraw_PanicOnModuleInsufficientFunds() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - suite.RemoveCoinsFromModule(sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - )) - - suite.Panics(func() { - _ = suite.Keeper.Withdraw(suite.Ctx, owner.GetAddress(), totalShares, reserves[0], reserves[1]) - }, "expected panic when module account does not have enough funds") -} diff --git a/x/swap/legacy/v0_15/types.go b/x/swap/legacy/v0_15/types.go deleted file mode 100644 index 95d4d8e6..00000000 --- a/x/swap/legacy/v0_15/types.go +++ /dev/null @@ -1,58 +0,0 @@ -package v0_15 - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName name that will be used throughout the module - ModuleName = "swap" -) - -// GenesisState is the state that must be provided at genesis. -type GenesisState struct { - Params Params `json:"params" yaml:"params"` - PoolRecords `json:"pool_records" yaml:"pool_records"` - ShareRecords `json:"share_records" yaml:"share_records"` -} - -// Params are governance parameters for the swap module -type Params struct { - AllowedPools AllowedPools `json:"allowed_pools" yaml:"allowed_pools"` - SwapFee sdk.Dec `json:"swap_fee" yaml:"swap_fee"` -} - -// PoolRecords is a slice of PoolRecord -type PoolRecords []PoolRecord - -// PoolRecord represents the state of a liquidity pool -// and is used to store the state of a denominated pool -type PoolRecord struct { - // primary key - PoolID string `json:"pool_id" yaml:"pool_id"` - ReservesA sdk.Coin `json:"reserves_a" yaml:"reserves_a"` - ReservesB sdk.Coin `json:"reserves_b" yaml:"reserves_b"` - TotalShares sdkmath.Int `json:"total_shares" yaml:"total_shares"` -} - -// ShareRecords is a slice of ShareRecord -type ShareRecords []ShareRecord - -// ShareRecord stores the shares owned for a depositor and pool -type ShareRecord struct { - // primary key - Depositor sdk.AccAddress `json:"depositor" yaml:"depositor"` - // secondary / sort key - PoolID string `json:"pool_id" yaml:"pool_id"` - SharesOwned sdkmath.Int `json:"shares_owned" yaml:"shares_owned"` -} - -// AllowedPools is a slice of AllowedPool -type AllowedPools []AllowedPool - -// AllowedPool defines a tradable pool -type AllowedPool struct { - TokenA string `json:"token_a" yaml:"token_a"` - TokenB string `json:"token_b" yaml:"token_b"` -} diff --git a/x/swap/legacy/v0_16/migrate.go b/x/swap/legacy/v0_16/migrate.go deleted file mode 100644 index 7ccfa136..00000000 --- a/x/swap/legacy/v0_16/migrate.go +++ /dev/null @@ -1,54 +0,0 @@ -package v0_16 - -import ( - v015swap "github.com/kava-labs/kava/x/swap/legacy/v0_15" - v016swap "github.com/kava-labs/kava/x/swap/types" -) - -func migrateParams(params v015swap.Params) v016swap.Params { - allowedPools := make(v016swap.AllowedPools, len(params.AllowedPools)) - for i, pool := range params.AllowedPools { - allowedPools[i] = v016swap.AllowedPool{ - TokenA: pool.TokenA, - TokenB: pool.TokenB, - } - } - return v016swap.Params{ - AllowedPools: allowedPools, - SwapFee: params.SwapFee, - } -} - -func migratePoolRecords(oldRecords v015swap.PoolRecords) v016swap.PoolRecords { - newRecords := make(v016swap.PoolRecords, len(oldRecords)) - for i, oldRecord := range oldRecords { - newRecords[i] = v016swap.PoolRecord{ - PoolID: oldRecord.PoolID, - ReservesA: oldRecord.ReservesA, - ReservesB: oldRecord.ReservesB, - TotalShares: oldRecord.TotalShares, - } - } - return newRecords -} - -func migrateShareRecords(oldRecords v015swap.ShareRecords) v016swap.ShareRecords { - newRecords := make(v016swap.ShareRecords, len(oldRecords)) - for i, oldRecord := range oldRecords { - newRecords[i] = v016swap.ShareRecord{ - Depositor: oldRecord.Depositor, - PoolID: oldRecord.PoolID, - SharesOwned: oldRecord.SharesOwned, - } - } - return newRecords -} - -// Migrate converts v0.15 swap state and returns it in v0.16 format -func Migrate(oldState v015swap.GenesisState) *v016swap.GenesisState { - return &v016swap.GenesisState{ - Params: migrateParams(oldState.Params), - PoolRecords: migratePoolRecords(oldState.PoolRecords), - ShareRecords: migrateShareRecords(oldState.ShareRecords), - } -} diff --git a/x/swap/legacy/v0_16/migrate_test.go b/x/swap/legacy/v0_16/migrate_test.go deleted file mode 100644 index 6b757e26..00000000 --- a/x/swap/legacy/v0_16/migrate_test.go +++ /dev/null @@ -1,147 +0,0 @@ -package v0_16 - -import ( - "io/ioutil" - "path/filepath" - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - app "github.com/kava-labs/kava/app" - v015swap "github.com/kava-labs/kava/x/swap/legacy/v0_15" - v016swap "github.com/kava-labs/kava/x/swap/types" -) - -type migrateTestSuite struct { - suite.Suite - - addresses []sdk.AccAddress - v15genstate v015swap.GenesisState - cdc codec.Codec - legacyCdc *codec.LegacyAmino -} - -func (s *migrateTestSuite) SetupTest() { - app.SetSDKConfig() - - s.v15genstate = v015swap.GenesisState{ - Params: v015swap.Params{}, - PoolRecords: v015swap.PoolRecords{}, - ShareRecords: v015swap.ShareRecords{}, - } - - config := app.MakeEncodingConfig() - s.cdc = config.Marshaler - - legacyCodec := codec.NewLegacyAmino() - s.legacyCdc = legacyCodec - - _, accAddresses := app.GeneratePrivKeyAddressPairs(10) - s.addresses = accAddresses -} - -func (s *migrateTestSuite) TestMigrate_JSON() { - // Migrate v15 swap to v16 - file := filepath.Join("testdata", "v15-swap.json") - data, err := ioutil.ReadFile(file) - s.Require().NoError(err) - err = s.legacyCdc.UnmarshalJSON(data, &s.v15genstate) - s.Require().NoError(err) - genstate := Migrate(s.v15genstate) - - // Compare expect v16 swap json with migrated json - actual := s.cdc.MustMarshalJSON(genstate) - file = filepath.Join("testdata", "v16-swap.json") - expected, err := ioutil.ReadFile(file) - s.Require().NoError(err) - s.Require().JSONEq(string(expected), string(actual)) -} - -func (s *migrateTestSuite) TestMigrate_Params() { - params := v015swap.Params{ - SwapFee: sdk.MustNewDecFromStr("0.33"), - AllowedPools: v015swap.AllowedPools{ - {TokenA: "A", TokenB: "B"}, - {TokenA: "C", TokenB: "D"}, - }, - } - expectedParams := v016swap.Params{ - SwapFee: sdk.MustNewDecFromStr("0.33"), - AllowedPools: v016swap.AllowedPools{ - {TokenA: "A", TokenB: "B"}, - {TokenA: "C", TokenB: "D"}, - }, - } - s.v15genstate.Params = params - genState := Migrate(s.v15genstate) - s.Require().Equal(expectedParams, genState.Params) -} - -func (s *migrateTestSuite) TestMigrate_PoolRecords() { - s.v15genstate.PoolRecords = v015swap.PoolRecords{ - { - PoolID: "pool-1", - ReservesA: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - ReservesB: sdk.NewCoin("xrpb", sdkmath.NewInt(200)), - TotalShares: sdkmath.NewInt(300), - }, - { - PoolID: "pool-2", - ReservesA: sdk.NewCoin("usdx", sdkmath.NewInt(500)), - ReservesB: sdk.NewCoin("ukava", sdkmath.NewInt(500)), - TotalShares: sdkmath.NewInt(1000), - }, - } - expected := v016swap.PoolRecords{ - { - PoolID: "pool-1", - ReservesA: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - ReservesB: sdk.NewCoin("xrpb", sdkmath.NewInt(200)), - TotalShares: sdkmath.NewInt(300), - }, - { - PoolID: "pool-2", - ReservesA: sdk.NewCoin("usdx", sdkmath.NewInt(500)), - ReservesB: sdk.NewCoin("ukava", sdkmath.NewInt(500)), - TotalShares: sdkmath.NewInt(1000), - }, - } - genState := Migrate(s.v15genstate) - s.Require().Equal(expected, genState.PoolRecords) -} - -func (s *migrateTestSuite) TestMigrate_ShareRecords() { - s.v15genstate.ShareRecords = v015swap.ShareRecords{ - { - PoolID: "pool-1", - Depositor: s.addresses[0], - SharesOwned: sdkmath.NewInt(100), - }, - { - PoolID: "pool-2", - Depositor: s.addresses[1], - SharesOwned: sdkmath.NewInt(410), - }, - } - expected := v016swap.ShareRecords{ - { - PoolID: "pool-1", - Depositor: s.addresses[0], - SharesOwned: sdkmath.NewInt(100), - }, - { - PoolID: "pool-2", - Depositor: s.addresses[1], - SharesOwned: sdkmath.NewInt(410), - }, - } - genState := Migrate(s.v15genstate) - s.Require().Equal(expected, genState.ShareRecords) -} - -func TestMigrateTestSuite(t *testing.T) { - suite.Run(t, new(migrateTestSuite)) -} diff --git a/x/swap/legacy/v0_16/testdata/v15-swap.json b/x/swap/legacy/v0_16/testdata/v15-swap.json deleted file mode 100644 index 50f09d8a..00000000 --- a/x/swap/legacy/v0_16/testdata/v15-swap.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "params": { - "allowed_pools": [ - { - "token_a": "bnb", - "token_b": "usdx" - }, - { - "token_a": "btcb", - "token_b": "usdx" - }, - { - "token_a": "busd", - "token_b": "usdx" - }, - { - "token_a": "hard", - "token_b": "usdx" - }, - { - "token_a": "swp", - "token_b": "usdx" - }, - { - "token_a": "ukava", - "token_b": "usdx" - }, - { - "token_a": "usdx", - "token_b": "xrpb" - } - ], - "swap_fee": "0.001500000000000000" - }, - "pool_records": [ - { - "pool_id": "ukava:usdx", - "reserves_a": { - "amount": "583616549439", - "denom": "ukava" - }, - "reserves_b": { - "amount": "3431399443511", - "denom": "usdx" - }, - "total_shares": "1398497336200" - }, - { - "pool_id": "usdx:xrpb", - "reserves_a": { - "amount": "843639517257", - "denom": "usdx" - }, - "reserves_b": { - "amount": "72251274276145", - "denom": "xrpb" - }, - "total_shares": "7739661881008" - } - ], - "share_records": [ - { - "depositor": "kava1l77xymdt2ya0rl2mludkny5aqmr67u88ymgdje", - "pool_id": "usdx:xrpb", - "shares_owned": "29034728969" - }, - { - "depositor": "kava1llqkrdr69wc76cuxpx6j06x9pt63f52f7mlcye", - "pool_id": "busd:usdx", - "shares_owned": "24905307583" - }, - { - "depositor": "kava1ll3ndyv333aet6mzqltu5wdepqhyme8umv34es", - "pool_id": "hard:usdx", - "shares_owned": "708138421" - }, - { - "depositor": "kava1ll3ndyv333aet6mzqltu5wdepqhyme8umv34es", - "pool_id": "ukava:usdx", - "shares_owned": "3427014047" - } - ] -} diff --git a/x/swap/legacy/v0_16/testdata/v16-swap.json b/x/swap/legacy/v0_16/testdata/v16-swap.json deleted file mode 100644 index 6911ab40..00000000 --- a/x/swap/legacy/v0_16/testdata/v16-swap.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "params": { - "allowed_pools": [ - { "token_a": "bnb", "token_b": "usdx" }, - { "token_a": "btcb", "token_b": "usdx" }, - { "token_a": "busd", "token_b": "usdx" }, - { "token_a": "hard", "token_b": "usdx" }, - { "token_a": "swp", "token_b": "usdx" }, - { "token_a": "ukava", "token_b": "usdx" }, - { "token_a": "usdx", "token_b": "xrpb" } - ], - "swap_fee": "0.001500000000000000" - }, - "pool_records": [ - { - "pool_id": "ukava:usdx", - "reserves_a": { "denom": "ukava", "amount": "583616549439" }, - "reserves_b": { "denom": "usdx", "amount": "3431399443511" }, - "total_shares": "1398497336200" - }, - { - "pool_id": "usdx:xrpb", - "reserves_a": { "denom": "usdx", "amount": "843639517257" }, - "reserves_b": { "denom": "xrpb", "amount": "72251274276145" }, - "total_shares": "7739661881008" - } - ], - "share_records": [ - { - "depositor": "kava1l77xymdt2ya0rl2mludkny5aqmr67u88ymgdje", - "pool_id": "usdx:xrpb", - "shares_owned": "29034728969" - }, - { - "depositor": "kava1llqkrdr69wc76cuxpx6j06x9pt63f52f7mlcye", - "pool_id": "busd:usdx", - "shares_owned": "24905307583" - }, - { - "depositor": "kava1ll3ndyv333aet6mzqltu5wdepqhyme8umv34es", - "pool_id": "hard:usdx", - "shares_owned": "708138421" - }, - { - "depositor": "kava1ll3ndyv333aet6mzqltu5wdepqhyme8umv34es", - "pool_id": "ukava:usdx", - "shares_owned": "3427014047" - } - ] -} diff --git a/x/swap/module.go b/x/swap/module.go deleted file mode 100644 index 8a9ac1fe..00000000 --- a/x/swap/module.go +++ /dev/null @@ -1,141 +0,0 @@ -package swap - -import ( - "context" - "encoding/json" - - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/kava-labs/kava/x/swap/client/cli" - "github.com/kava-labs/kava/x/swap/keeper" - "github.com/kava-labs/kava/x/swap/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - gs := types.DefaultGenesisState() - return cdc.MustMarshalJSON(&gs) -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) - if err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the gov module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// GetTxCmd returns the root tx command for the swap module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the swap module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd(types.StoreKey) -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper types.AccountKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: accountKeeper, - } -} - -// Name module name -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// RegisterInvariants register module invariants -func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { - keeper.RegisterInvariants(ir, am.keeper) -} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) -} - -// InitGenesis module init-genesis -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 module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(&gs) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) { -} - -// EndBlock module end-block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/swap/module_test.go b/x/swap/module_test.go deleted file mode 100644 index 868d618c..00000000 --- a/x/swap/module_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package swap_test - -import ( - "testing" - - "github.com/kava-labs/kava/x/swap/testutil" - "github.com/kava-labs/kava/x/swap/types" - - crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper" - "github.com/stretchr/testify/suite" -) - -type moduleTestSuite struct { - testutil.Suite - crisisKeeper crisiskeeper.Keeper -} - -func (suite *moduleTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.crisisKeeper = suite.App.GetCrisisKeeper() -} - -func (suite *moduleTestSuite) TestRegisterInvariants() { - swapRoutes := []string{} - - for _, route := range suite.crisisKeeper.Routes() { - if route.ModuleName == types.ModuleName { - swapRoutes = append(swapRoutes, route.Route) - } - } - - suite.Contains(swapRoutes, "pool-records") - suite.Contains(swapRoutes, "share-records") - suite.Contains(swapRoutes, "pool-reserves") - suite.Contains(swapRoutes, "pool-shares") -} - -func TestModuleTestSuite(t *testing.T) { - suite.Run(t, new(moduleTestSuite)) -} diff --git a/x/swap/spec/01_concepts.md b/x/swap/spec/01_concepts.md deleted file mode 100644 index b7a0a305..00000000 --- a/x/swap/spec/01_concepts.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# Concepts - -## Automated Market Maker - -The swap module provides for functionality and governance of an Automated Market Maker protocol. The main state transitions in the swap module include deposits/withdrawals to liquidity pools by liquidity providers and token swaps executed against liquidity pools by users. Each liquidity pool consists of a unique pair of two tokens. A global swap fee set by governance is paid by users to execute trades, with the proceeds going to the relevant pool's liquidity providers. - -## SWP Token distribution - -[See Incentive Module](../../incentive/spec/01_concepts.md) diff --git a/x/swap/spec/02_state.md b/x/swap/spec/02_state.md deleted file mode 100644 index 15b68165..00000000 --- a/x/swap/spec/02_state.md +++ /dev/null @@ -1,62 +0,0 @@ - - -# State - -## Parameters and Genesis State - -`Parameters` define the governance parameters and default behavior of the swap module. - -```go -// Params are governance parameters for the swap module -type Params struct { - AllowedPools AllowedPools `json:"allowed_pools" yaml:"allowed_pools"` - SwapFee sdk.Dec `json:"swap_fee" yaml:"swap_fee"` -} - -// AllowedPool defines a tradable pool -type AllowedPool struct { - TokenA string `json:"token_a" yaml:"token_a"` - TokenB string `json:"token_b" yaml:"token_b"` -} - -// AllowedPools is a slice of AllowedPool -type AllowedPools []AllowedPool -``` - -`GenesisState` defines the state that must be persisted when the blockchain stops/restarts in order for the normal function of the swap module to resume. - -```go -// GenesisState is the state that must be provided at genesis. -type GenesisState struct { - Params Params `json:"params" yaml:"params"` - PoolRecords `json:"pool_records" yaml:"pool_records"` - ShareRecords `json:"share_records" yaml:"share_records"` -} - -// PoolRecord represents the state of a liquidity pool -// and is used to store the state of a denominated pool -type PoolRecord struct { - // primary key - PoolID string `json:"pool_id" yaml:"pool_id"` - ReservesA sdk.Coin `json:"reserves_a" yaml:"reserves_a"` - ReservesB sdk.Coin `json:"reserves_b" yaml:"reserves_b"` - TotalShares sdkmath.Int `json:"total_shares" yaml:"total_shares"` -} - -// PoolRecords is a slice of PoolRecord -type PoolRecords []PoolRecord - -// ShareRecord stores the shares owned for a depositor and pool -type ShareRecord struct { - // primary key - Depositor sdk.AccAddress `json:"depositor" yaml:"depositor"` - // secondary / sort key - PoolID string `json:"pool_id" yaml:"pool_id"` - SharesOwned sdkmath.Int `json:"shares_owned" yaml:"shares_owned"` -} - -// ShareRecords is a slice of ShareRecord -type ShareRecords []ShareRecord -``` diff --git a/x/swap/spec/03_messages.md b/x/swap/spec/03_messages.md deleted file mode 100644 index 1b331f95..00000000 --- a/x/swap/spec/03_messages.md +++ /dev/null @@ -1,65 +0,0 @@ - - -# Messages - - -MsgDeposit adds liquidity to a pool: - -```go -// MsgDeposit deposits liquidity into a pool -type MsgDeposit struct { - Depositor sdk.AccAddress `json:"depositor" yaml:"depositor"` - TokenA sdk.Coin `json:"token_a" yaml:"token_a"` - TokenB sdk.Coin `json:"token_b" yaml:"token_b"` - Slippage sdk.Dec `json:"slippage" yaml:"slippage"` - Deadline int64 `json:"deadline" yaml:"deadline"` -} -``` - -The first deposit to a pool results in a `PoolRecord` being created. For each deposit, a `ShareRecord` is created or updated, depending on if the depositor has an existing deposit. The deposited tokens are converted to shares. For the first deposit to a pool, shares are equal to the geometric mean of the deposited amount. For example, depositing 200 TokenA and 100 TokenB will create `sqrt(100 * 200) = 141` shares. For subsequent deposits, shares are issued equal to the current conversion between tokens and shares in that pool. - -MsgWithdraw removes liquidity from a pool: - -```go -// MsgWithdraw deposits liquidity into a pool -type MsgWithdraw struct { - From sdk.AccAddress `json:"from" yaml:"from"` - Shares sdkmath.Int `json:"shares" yaml:"shares"` - MinTokenA sdk.Coin `json:"min_token_a" yaml:"min_token_a"` - MinTokenB sdk.Coin `json:"min_token_b" yaml:"min_token_b"` - Deadline int64 `json:"deadline" yaml:"deadline"` -} -``` -When withdrawing from a pool, the user specifies the amount of shares they want to withdraw, as well as the minimum amount of tokenA and tokenB that they must receive for the transaction to succeed. When withdrawing, the `ShareRecord` of the user will be decremented by the corresponding amount of shares, or deleted in the case that all liquidity has been withdrawn. If all shares of a pool have been withdrawn from a pool, the `PoolRecord` will be deleted. - -MsgSwapExactForTokens trades an exact amount of input tokens for a variable amount of output tokens, with a specified maximum slippage tolerance. - -```go -// MsgSwapExactForTokens trades an exact coinA for coinB -type MsgSwapExactForTokens struct { - Requester sdk.AccAddress `json:"requester" yaml:"requester"` - ExactTokenA sdk.Coin `json:"exact_token_a" yaml:"exact_token_a"` - TokenB sdk.Coin `json:"token_b" yaml:"token_b"` - Slippage sdk.Dec `json:"slippage" yaml:"slippage"` - Deadline int64 `json:"deadline" yaml:"deadline"` -} -``` - -When trading exact inputs for variable outputs, the swap fee is removed from TokenA and added to the pool, then slippage is calculated based on the actual amount of TokenB received compared to the desired amount of TokenB. If the realized slippage of the trade is greater than the specified slippage tolerance, the transaction fails. - -MsgSwapForExactTokens trades a variable amount of input tokens for an exact amount of output tokens, with a specified maximum slippage tolerance. - -```go -// MsgSwapForExactTokens trades coinA for an exact coinB -type MsgSwapForExactTokens struct { - Requester sdk.AccAddress `json:"requester" yaml:"requester"` - TokenA sdk.Coin `json:"token_a" yaml:"token_a"` - ExactTokenB sdk.Coin `json:"exact_token_b" yaml:"exact_token_b"` - Slippage sdk.Dec `json:"slippage" yaml:"slippage"` - Deadline int64 `json:"deadline" yaml:"deadline"` -} -``` - -When trading variable inputs for exact outputs, the fee swap fee is removed from TokenA and added to the pool, then slippage is calculated based on the actual amount of TokenA required to acquire the exact TokenB amount versus the desired TokenA required. If the realized slippage of the trade is greater than the specified slippage tolerance, the transaction fails. diff --git a/x/swap/spec/04_events.md b/x/swap/spec/04_events.md deleted file mode 100644 index 75aa8ea2..00000000 --- a/x/swap/spec/04_events.md +++ /dev/null @@ -1,59 +0,0 @@ - - -# Events - -The swap module emits the following events: - -## Handlers - -### MsgDeposit - -| Type | Attribute Key | Attribute Value | -| ------------ | ------------- | --------------------- | -| message | module | swap | -| message | sender | `{sender address}` | -| swap_deposit | pool_id | `{poolID}` | -| swap_deposit | depositor | `{depositor address}` | -| swap_deposit | amount | `{amount}` | -| swap_deposit | shares | `{shares}` | - -### MsgWithdraw - -| Type | Attribute Key | Attribute Value | -| ------------- | ------------- | --------------------- | -| message | module | swap | -| message | sender | `{sender address}` | -| swap_withdraw | pool_id | `{poolID}` | -| swap_withdraw | owner | `{owner address}` | -| swap_withdraw | amount | `{amount}` | -| swap_withdraw | shares | `{shares}` | - - -### MsgSwapExactForTokens - -| Type | Attribute Key | Attribute Value | -| ------------- | ------------- | ------------------------ | -| message | module | swap | -| message | sender | `{sender address}` | -| swap_trade | pool_id | `{poolID}` | -| swap_trade | requester | `{requester address}` | -| swap_trade | swap_input | `{input amount}` | -| swap_trade | swap_output | `{output amount}` | -| swap_trade | fee_paid | `{fee amount}` | -| swap_trade | exact | `{exact trade direction}`| - - -### MsgSwapForExactTokens - -| Type | Attribute Key | Attribute Value | -| ------------- | ------------- | ------------------------ | -| message | module | swap | -| message | sender | `{sender address}` | -| swap_trade | pool_id | `{poolID}` | -| swap_trade | requester | `{requester address}` | -| swap_trade | swap_input | `{input amount}` | -| swap_trade | swap_output | `{output amount}` | -| swap_trade | fee_paid | `{fee amount}` | -| swap_trade | exact | `{exact trade direction}`| diff --git a/x/swap/spec/05_params.md b/x/swap/spec/05_params.md deleted file mode 100644 index 321187da..00000000 --- a/x/swap/spec/05_params.md +++ /dev/null @@ -1,19 +0,0 @@ - - -# Parameters - -Example parameters for the swap module: - -| Key | Type | Example | Description | -| ------------ | ------------------- | ------------- | --------------------------------------- | -| AllowedPools | array (AllowedPool) | [{see below}] | Array of tradable pools supported | -| SwapFee | sdk.Dec | 0.03 | Global trading fee in percentage format | - -Example parameters for `AllowedPool`: - -| Key | Type | Example | Description | -| ------ | ------ | ------- | ------------------- | -| TokenA | string | "ukava" | First coin's denom | -| TokenB | string | "usdx" | Second coin's denom | diff --git a/x/swap/spec/README.md b/x/swap/spec/README.md deleted file mode 100644 index 3a8da861..00000000 --- a/x/swap/spec/README.md +++ /dev/null @@ -1,20 +0,0 @@ - - -# `swap` - - - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** -5. **[Params](05_params.md)** - -## Abstract - -`x/swap` is a Cosmos SDK module that implements an Automated Market Maker (AMM) that enables users to swap coins by trading against liquidity pools. diff --git a/x/swap/testutil/suite.go b/x/swap/testutil/suite.go deleted file mode 100644 index 35e5429b..00000000 --- a/x/swap/testutil/suite.go +++ /dev/null @@ -1,214 +0,0 @@ -package testutil - -import ( - "fmt" - "reflect" - "time" - - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/swap/keeper" - "github.com/kava-labs/kava/x/swap/types" - - sdkmath "cosmossdk.io/math" - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - BankKeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/stretchr/testify/suite" -) - -var defaultSwapFee = sdk.MustNewDecFromStr("0.003") - -// Suite implements a test suite for the swap module integration tests -type Suite struct { - suite.Suite - Keeper keeper.Keeper - App app.TestApp - Ctx sdk.Context - BankKeeper BankKeeper.Keeper - AccountKeeper authkeeper.AccountKeeper -} - -// SetupTest instantiates a new app, keepers, and sets suite state -func (suite *Suite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - suite.Ctx = ctx - suite.App = tApp - suite.Keeper = tApp.GetSwapKeeper() - suite.BankKeeper = tApp.GetBankKeeper() - suite.AccountKeeper = tApp.GetAccountKeeper() -} - -// GetEvents returns emitted events on the sdk context -func (suite *Suite) GetEvents() sdk.Events { - return suite.Ctx.EventManager().Events() -} - -// AddCoinsToModule adds coins to the swap module account -func (suite *Suite) AddCoinsToModule(amount sdk.Coins) { - // Does not use suite.BankKeeper.MintCoins as module account would not have permission to mint - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, amount) - suite.Require().NoError(err) -} - -// RemoveCoinsFromModule removes coins to the swap module account -func (suite *Suite) RemoveCoinsFromModule(amount sdk.Coins) { - // Swap module does not have BurnCoins permission so we need to transfer to gov first to burn - err := suite.BankKeeper.SendCoinsFromModuleToModule(suite.Ctx, types.ModuleAccountName, govtypes.ModuleName, amount) - suite.Require().NoError(err) - err = suite.BankKeeper.BurnCoins(suite.Ctx, govtypes.ModuleName, amount) - suite.Require().NoError(err) -} - -// CreateAccount creates a new account from the provided balance -func (suite *Suite) CreateAccount(initialBalance sdk.Coins) authtypes.AccountI { - _, addrs := app.GeneratePrivKeyAddressPairs(1) - ak := suite.App.GetAccountKeeper() - - acc := ak.NewAccountWithAddress(suite.Ctx, addrs[0]) - ak.SetAccount(suite.Ctx, acc) - - err := suite.App.FundAccount(suite.Ctx, acc.GetAddress(), initialBalance) - suite.Require().NoError(err) - - return acc -} - -// NewAccountFromAddr creates a new account from the provided address with the provided balance -func (suite *Suite) NewAccountFromAddr(addr sdk.AccAddress, balance sdk.Coins) authtypes.AccountI { - ak := suite.App.GetAccountKeeper() - - acc := ak.NewAccountWithAddress(suite.Ctx, addr) - ak.SetAccount(suite.Ctx, acc) - - err := suite.App.FundAccount(suite.Ctx, acc.GetAddress(), balance) - suite.Require().NoError(err) - - return acc -} - -// CreateVestingAccount creates a new vesting account from the provided balance and vesting balance -func (suite *Suite) CreateVestingAccount(initialBalance sdk.Coins, vestingBalance sdk.Coins) authtypes.AccountI { - acc := suite.CreateAccount(initialBalance) - bacc := acc.(*authtypes.BaseAccount) - - periods := vestingtypes.Periods{ - vestingtypes.Period{ - Length: 31556952, - Amount: vestingBalance, - }, - } - vacc := vestingtypes.NewPeriodicVestingAccount(bacc, initialBalance, time.Now().Unix(), periods) // TODO is initialBalance correct for originalVesting? - - return vacc -} - -// CreatePool creates a pool and stores it in state with the provided reserves -func (suite *Suite) CreatePool(reserves sdk.Coins) error { - depositor := suite.CreateAccount(reserves) - pool := types.NewAllowedPool(reserves[0].Denom, reserves[1].Denom) - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.AllowedPools{pool}, defaultSwapFee)) - - return suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), reserves[0], reserves[1], sdk.MustNewDecFromStr("1")) -} - -// AccountBalanceEqual asserts that the coins match the account balance -func (suite *Suite) AccountBalanceEqual(addr sdk.AccAddress, coins sdk.Coins) { - balance := suite.BankKeeper.GetAllBalances(suite.Ctx, addr) - suite.Equal(coins, balance, fmt.Sprintf("expected account balance to equal coins %s, but got %s", coins, balance)) -} - -// ModuleAccountBalanceEqual asserts that the swap module account balance matches the provided coins -func (suite *Suite) ModuleAccountBalanceEqual(coins sdk.Coins) { - balance := suite.BankKeeper.GetAllBalances( - suite.Ctx, - suite.AccountKeeper.GetModuleAddress(types.ModuleAccountName), - ) - suite.Equal(coins, balance, fmt.Sprintf("expected module account balance to equal coins %s, but got %s", coins, balance)) -} - -// PoolLiquidityEqual asserts that the pool matching the provided coins has those reserves -func (suite *Suite) PoolLiquidityEqual(coins sdk.Coins) { - poolRecord, ok := suite.Keeper.GetPool(suite.Ctx, types.PoolIDFromCoins(coins)) - suite.Require().True(ok, "expected pool to exist") - reserves := sdk.NewCoins(poolRecord.ReservesA, poolRecord.ReservesB) - suite.Equal(coins, reserves, fmt.Sprintf("expected pool reserves of %s, got %s", coins, reserves)) -} - -// PoolDeleted asserts that the pool does not exist -func (suite *Suite) PoolDeleted(denomA, denomB string) { - _, ok := suite.Keeper.GetPool(suite.Ctx, types.PoolID(denomA, denomB)) - suite.Require().False(ok, "expected pool to not exist") -} - -// PoolShareTotalEqual asserts the total shares match the stored pool -func (suite *Suite) PoolShareTotalEqual(poolID string, totalShares sdkmath.Int) { - poolRecord, found := suite.Keeper.GetPool(suite.Ctx, poolID) - suite.Require().True(found, fmt.Sprintf("expected pool %s to exist", poolID)) - suite.Equal(totalShares, poolRecord.TotalShares, "expected pool total shares to be equal") -} - -// PoolDepositorSharesEqual asserts the depositor owns the shares for the provided pool -func (suite *Suite) PoolDepositorSharesEqual(depositor sdk.AccAddress, poolID string, shares sdkmath.Int) { - shareRecord, found := suite.Keeper.GetDepositorShares(suite.Ctx, depositor, poolID) - suite.Require().True(found, fmt.Sprintf("expected share record to exist for depositor %s and pool %s", depositor.String(), poolID)) - suite.Equal(shares, shareRecord.SharesOwned) -} - -// PoolReservesEqual assets the stored pool reserves are equal to the provided reserves -func (suite *Suite) PoolReservesEqual(poolID string, reserves sdk.Coins) { - poolRecord, found := suite.Keeper.GetPool(suite.Ctx, poolID) - suite.Require().True(found, fmt.Sprintf("expected pool %s to exist", poolID)) - suite.Equal(reserves, poolRecord.Reserves(), "expected pool reserves to be equal") -} - -// PoolShareValueEqual asserts that the depositor shares are in state and the value matches the expected coins -func (suite *Suite) PoolShareValueEqual(depositor authtypes.AccountI, pool types.AllowedPool, coins sdk.Coins) { - poolRecord, ok := suite.Keeper.GetPool(suite.Ctx, pool.Name()) - suite.Require().True(ok, fmt.Sprintf("expected pool %s to exist", pool.Name())) - shares, ok := suite.Keeper.GetDepositorShares(suite.Ctx, depositor.GetAddress(), poolRecord.PoolID) - suite.Require().True(ok, fmt.Sprintf("expected shares to exist for depositor %s", depositor.GetAddress())) - - storedPool, err := types.NewDenominatedPoolWithExistingShares(sdk.NewCoins(poolRecord.ReservesA, poolRecord.ReservesB), poolRecord.TotalShares) - suite.Nil(err) - value := storedPool.ShareValue(shares.SharesOwned) - suite.Equal(coins, value, fmt.Sprintf("expected shares to equal %s, but got %s", coins, value)) -} - -// PoolSharesDeleted asserts that the pool shares have been removed -func (suite *Suite) PoolSharesDeleted(depositor sdk.AccAddress, denomA, denomB string) { - _, ok := suite.Keeper.GetDepositorShares(suite.Ctx, depositor, types.PoolID(denomA, denomB)) - suite.Require().False(ok, "expected pool shares to not exist") -} - -// EventsContains asserts that the expected event is in the provided events -func (suite *Suite) EventsContains(events sdk.Events, expectedEvent sdk.Event) { - foundMatch := false - for _, event := range events { - if event.Type == expectedEvent.Type { - if reflect.DeepEqual(attrsToMap(expectedEvent.Attributes), attrsToMap(event.Attributes)) { - foundMatch = true - } - } - } - - suite.True(foundMatch, fmt.Sprintf("event of type %s not found or did not match", expectedEvent.Type)) -} - -func attrsToMap(attrs []abci.EventAttribute) []sdk.Attribute { // new cosmos changed the event attribute type - out := []sdk.Attribute{} - - for _, attr := range attrs { - out = append(out, sdk.NewAttribute(string(attr.Key), string(attr.Value))) - } - - return out -} diff --git a/x/swap/types/base_pool.go b/x/swap/types/base_pool.go deleted file mode 100644 index fcc2e6b6..00000000 --- a/x/swap/types/base_pool.go +++ /dev/null @@ -1,436 +0,0 @@ -package types - -import ( - "fmt" - "math/big" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var zero = sdk.ZeroInt() - -// calculateInitialShares calculates initial shares as sqrt(A*B), the geometric mean of A and B -func calculateInitialShares(reservesA, reservesB sdkmath.Int) sdkmath.Int { - // Big.Int allows multiplication without overflow at 255 bits. - // In addition, Sqrt converges to a correct solution for inputs - // where sdkmath.Int.ApproxSqrt does not converge due to exceeding - // 100 iterations. - var result big.Int - result.Mul(reservesA.BigInt(), reservesB.BigInt()).Sqrt(&result) - return sdkmath.NewIntFromBigInt(&result) -} - -// BasePool implements a unitless constant-product liquidity pool. -// -// The pool is symmetric. For all A,B,s, any operation F on a pool (A,B,s) and pool (B,A,s) -// will result in equal state values of A', B', s': F(A,B,s) => (A',B',s'), F(B,A,s) => (B',A',s') -// -// In addition, the pool is protected from overflow in intermediate calculations, and will -// only overflow when A, B, or s become larger than the max sdkmath.Int. -// -// Pool operations with non-positive values are invalid, and all functions on a pool will panic -// when given zero or negative values. -type BasePool struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - totalShares sdkmath.Int -} - -// NewBasePool returns a pointer to a base pool with reserves and total shares initialized -func NewBasePool(reservesA, reservesB sdkmath.Int) (*BasePool, error) { - if reservesA.LTE(zero) || reservesB.LTE(zero) { - return nil, errorsmod.Wrap(ErrInvalidPool, "reserves must be greater than zero") - } - - totalShares := calculateInitialShares(reservesA, reservesB) - - return &BasePool{ - reservesA: reservesA, - reservesB: reservesB, - totalShares: totalShares, - }, nil -} - -// NewBasePoolWithExistingShares returns a pointer to a base pool with existing shares -func NewBasePoolWithExistingShares(reservesA, reservesB, totalShares sdkmath.Int) (*BasePool, error) { - if reservesA.LTE(zero) || reservesB.LTE(zero) { - return nil, errorsmod.Wrap(ErrInvalidPool, "reserves must be greater than zero") - } - - if totalShares.LTE(zero) { - return nil, errorsmod.Wrap(ErrInvalidPool, "total shares must be greater than zero") - } - - return &BasePool{ - reservesA: reservesA, - reservesB: reservesB, - totalShares: totalShares, - }, nil -} - -// ReservesA returns the A reserves of the pool -func (p *BasePool) ReservesA() sdkmath.Int { - return p.reservesA -} - -// ReservesB returns the B reserves of the pool -func (p *BasePool) ReservesB() sdkmath.Int { - return p.reservesB -} - -// IsEmpty returns true if all reserves are zero and -// returns false if reserveA or reserveB is not empty -func (p *BasePool) IsEmpty() bool { - return p.reservesA.IsZero() && p.reservesB.IsZero() -} - -// TotalShares returns the total number of shares in the pool -func (p *BasePool) TotalShares() sdkmath.Int { - return p.totalShares -} - -// AddLiquidity adds liquidity to the pool returns the actual reservesA, reservesB deposits in addition -// to the number of shares created. The deposits are always less than or equal to the provided and desired -// values. -func (p *BasePool) AddLiquidity(desiredA sdkmath.Int, desiredB sdkmath.Int) (sdkmath.Int, sdkmath.Int, sdkmath.Int) { - // Panics if provided values are zero - p.assertDepositsArePositive(desiredA, desiredB) - - // Reinitialize the pool if reserves are empty and return the initialized state. - if p.IsEmpty() { - p.reservesA = desiredA - p.reservesB = desiredB - p.totalShares = calculateInitialShares(desiredA, desiredB) - return p.ReservesA(), p.ReservesB(), p.TotalShares() - } - - // Panics if reserveA or reserveB is zero. - p.assertReservesArePositive() - - // In order to preserve the reserve ratio of the pool, we must deposit - // A and B in the same ratio of the existing reserves. In addition, - // we should not deposit more funds than requested. - // - // To meet these requirements, we first calculate the optimalB to deposit - // if we keep desiredA fixed. If this is less than or equal to the desiredB, - // then we use (desiredA, optimalB) as the deposit. - // - // If the optimalB is greater than the desiredB, we calculate the optimalA - // from the desiredB and use (optimalA, desiredB) as the deposit. - // - // These optimal values are calculated as: - // - // optimalB = reservesB * desiredA / reservesA - // optimalA = reservesA * desiredB / reservesB - // - // Which shows us: - // - // if optimalB < desiredB then optimalA > desiredA - // if optimalB = desiredB then optimalA = desiredA - // if optimalB > desiredB then optimalA < desiredA - // - // so we first check if optimalB <= desiredB, then deposit - // (desiredA, optimalB) else deposit (optimalA, desiredA). - // - // In order avoid precision loss, we rearrange the inequality - // of optimalB <= desiredB - // from: - // reservesB * desiredA / reservesA <= desiredB - // to: - // reservesB * desiredA <= desiredB * reservesA - // - // which also shares the same intermediate products - // as the calculations for optimalB and optimalA. - actualA := desiredA.BigInt() - actualB := desiredB.BigInt() - - // productA = reservesB * desiredA - var productA big.Int - productA.Mul(p.reservesB.BigInt(), actualA) - - // productB = reservesA * desiredB - var productB big.Int - productB.Mul(p.reservesA.BigInt(), actualB) - - // optimalB <= desiredB - if productA.Cmp(&productB) <= 0 { - actualB.Quo(&productA, p.reservesA.BigInt()) - } else { // optimalA < desiredA - actualA.Quo(&productB, p.reservesB.BigInt()) - } - - var sharesA big.Int - sharesA.Mul(actualA, p.totalShares.BigInt()).Quo(&sharesA, p.reservesA.BigInt()) - - var sharesB big.Int - sharesB.Mul(actualB, p.totalShares.BigInt()).Quo(&sharesB, p.reservesB.BigInt()) - - // a/A and b/B may not be equal due to discrete math and truncation errors, - // so use the smallest deposit ratio to calculate the number of shares - // - // If we do not use the min or max ratio, then the result becomes - // dependent on the order of reserves in the pool - // - // Min is used to always ensure the share ratio is never larger - // than the deposit ratio for either A or B, ensuring there are no - // cases where a withdraw will allow funds to be removed at a higher ratio - // than it was deposited. - var shares sdkmath.Int - if sharesA.Cmp(&sharesB) <= 0 { - shares = sdkmath.NewIntFromBigInt(&sharesA) - } else { - shares = sdkmath.NewIntFromBigInt(&sharesB) - } - - depositA := sdkmath.NewIntFromBigInt(actualA) - depositB := sdkmath.NewIntFromBigInt(actualB) - - // update internal pool state - p.reservesA = p.reservesA.Add(depositA) - p.reservesB = p.reservesB.Add(depositB) - p.totalShares = p.totalShares.Add(shares) - - return depositA, depositB, shares -} - -// RemoveLiquidity removes liquidity from the pool and panics if the -// shares provided are greater than the total shares of the pool -// or the shares are not positive. -// In addition, also panics if reserves go negative, which should not happen. -// If panic occurs, it is a bug. -func (p *BasePool) RemoveLiquidity(shares sdkmath.Int) (sdkmath.Int, sdkmath.Int) { - // calculate amount to withdraw from the pool based - // on the number of shares provided. s/S * reserves - withdrawA, withdrawB := p.ShareValue(shares) - - // update internal pool state - p.reservesA = p.reservesA.Sub(withdrawA) - p.reservesB = p.reservesB.Sub(withdrawB) - p.totalShares = p.totalShares.Sub(shares) - - // Panics if reserveA or reserveB are negative - // A zero value (100% withdraw) is OK and should not panic. - p.assertReservesAreNotNegative() - - return withdrawA, withdrawB -} - -// SwapExactAForB trades an exact value of a for b. Returns the positive amount b -// that is removed from the pool and the portion of a that is used for paying the fee. -func (p *BasePool) SwapExactAForB(a sdkmath.Int, fee sdk.Dec) (sdkmath.Int, sdkmath.Int) { - b, feeValue := p.calculateOutputForExactInput(a, p.reservesA, p.reservesB, fee) - - p.assertInvariantAndUpdateReserves( - p.reservesA.Add(a), feeValue, p.reservesB.Sub(b), sdk.ZeroInt(), - ) - - return b, feeValue -} - -// SwapExactBForA trades an exact value of b for a. Returns the positive amount a -// that is removed from the pool and the portion of b that is used for paying the fee. -func (p *BasePool) SwapExactBForA(b sdkmath.Int, fee sdk.Dec) (sdkmath.Int, sdkmath.Int) { - a, feeValue := p.calculateOutputForExactInput(b, p.reservesB, p.reservesA, fee) - - p.assertInvariantAndUpdateReserves( - p.reservesA.Sub(a), sdk.ZeroInt(), p.reservesB.Add(b), feeValue, - ) - - return a, feeValue -} - -// calculateOutputForExactInput calculates the output amount of a swap using a fixed input, returning this amount in -// addition to the amount of input that is used to pay the fee. -// -// The fee is ceiled, ensuring a minimum fee of 1 and ensuring fees of a trade can not be reduced -// by splitting a trade into multiple trades. -// -// The swap output is truncated to ensure the pool invariant is always greater than or equal to the previous invariant. -func (p *BasePool) calculateOutputForExactInput(in, inReserves, outReserves sdkmath.Int, fee sdk.Dec) (sdkmath.Int, sdkmath.Int) { - p.assertSwapInputIsValid(in) - p.assertFeeIsValid(fee) - - inAfterFee := sdk.NewDecFromInt(in).Mul(sdk.OneDec().Sub(fee)).TruncateInt() - - var result big.Int - result.Mul(outReserves.BigInt(), inAfterFee.BigInt()) - result.Quo(&result, inReserves.Add(inAfterFee).BigInt()) - - out := sdkmath.NewIntFromBigInt(&result) - feeValue := in.Sub(inAfterFee) - - return out, feeValue -} - -// SwapAForExactB trades a for an exact b. Returns the positive amount a -// that is added to the pool, and the portion of a that is used to pay the fee. -func (p *BasePool) SwapAForExactB(b sdkmath.Int, fee sdk.Dec) (sdkmath.Int, sdkmath.Int) { - a, feeValue := p.calculateInputForExactOutput(b, p.reservesB, p.reservesA, fee) - - p.assertInvariantAndUpdateReserves( - p.reservesA.Add(a), feeValue, p.reservesB.Sub(b), sdk.ZeroInt(), - ) - - return a, feeValue -} - -// SwapBForExactA trades b for an exact a. Returns the positive amount b -// that is added to the pool, and the portion of b that is used to pay the fee. -func (p *BasePool) SwapBForExactA(a sdkmath.Int, fee sdk.Dec) (sdkmath.Int, sdkmath.Int) { - b, feeValue := p.calculateInputForExactOutput(a, p.reservesA, p.reservesB, fee) - - p.assertInvariantAndUpdateReserves( - p.reservesA.Sub(a), sdk.ZeroInt(), p.reservesB.Add(b), feeValue, - ) - - return b, feeValue -} - -// calculateInputForExactOutput calculates the input amount of a swap using a fixed output, returning this amount in -// addition to the amount of input that is used to pay the fee. -// -// The fee is ceiled, ensuring a minimum fee of 1 and ensuring fees of a trade can not be reduced -// by splitting a trade into multiple trades. -// -// The swap input is ceiled to ensure the pool invariant is always greater than or equal to the previous invariant. -func (p *BasePool) calculateInputForExactOutput(out, outReserves, inReserves sdkmath.Int, fee sdk.Dec) (sdkmath.Int, sdkmath.Int) { - p.assertSwapOutputIsValid(out, outReserves) - p.assertFeeIsValid(fee) - - var result big.Int - result.Mul(inReserves.BigInt(), out.BigInt()) - - newOutReserves := outReserves.Sub(out) - var remainder big.Int - result.QuoRem(&result, newOutReserves.BigInt(), &remainder) - - inWithoutFee := sdkmath.NewIntFromBigInt(&result) - if remainder.Sign() != 0 { - inWithoutFee = inWithoutFee.Add(sdk.OneInt()) - } - - in := sdk.NewDecFromInt(inWithoutFee).Quo(sdk.OneDec().Sub(fee)).Ceil().TruncateInt() - feeValue := in.Sub(inWithoutFee) - - return in, feeValue -} - -// ShareValue returns the value of the provided shares and panics -// if the shares are greater than the total shares of the pool or -// if the shares are not positive. -func (p *BasePool) ShareValue(shares sdkmath.Int) (sdkmath.Int, sdkmath.Int) { - p.assertSharesArePositive(shares) - p.assertSharesAreLessThanTotal(shares) - - var resultA big.Int - resultA.Mul(p.reservesA.BigInt(), shares.BigInt()) - resultA.Quo(&resultA, p.totalShares.BigInt()) - - var resultB big.Int - resultB.Mul(p.reservesB.BigInt(), shares.BigInt()) - resultB.Quo(&resultB, p.totalShares.BigInt()) - - return sdkmath.NewIntFromBigInt(&resultA), sdkmath.NewIntFromBigInt(&resultB) -} - -// assertInvariantAndUpdateRerserves asserts the constant product invariant is not violated, subtracting -// any fees first, then updates the pool reserves. Panics if invariant is violated. -func (p *BasePool) assertInvariantAndUpdateReserves(newReservesA, feeA, newReservesB, feeB sdkmath.Int) { - var invariant big.Int - invariant.Mul(p.reservesA.BigInt(), p.reservesB.BigInt()) - - var newInvariant big.Int - newInvariant.Mul(newReservesA.Sub(feeA).BigInt(), newReservesB.Sub(feeB).BigInt()) - - p.assertInvariant(&invariant, &newInvariant) - - p.reservesA = newReservesA - p.reservesB = newReservesB -} - -// assertSwapInputIsValid checks if the provided swap input is positive -// and panics if it is 0 or negative -func (p *BasePool) assertSwapInputIsValid(input sdkmath.Int) { - if !input.IsPositive() { - panic("invalid value: swap input must be positive") - } -} - -// assertSwapOutputIsValid checks if the provided swap input is positive and -// less than the provided reserves. -func (p *BasePool) assertSwapOutputIsValid(output sdkmath.Int, reserves sdkmath.Int) { - if !output.IsPositive() { - panic("invalid value: swap output must be positive") - } - - if output.GTE(reserves) { - panic("invalid value: swap output must be less than reserves") - } -} - -// assertFeeIsValid checks if the provided fee is less -func (p *BasePool) assertFeeIsValid(fee sdk.Dec) { - if fee.IsNegative() || fee.GTE(sdk.OneDec()) { - panic("invalid value: fee must be between 0 and 1") - } -} - -// assertSharesPositive panics if shares is zero or negative -func (p *BasePool) assertSharesArePositive(shares sdkmath.Int) { - if !shares.IsPositive() { - panic("invalid value: shares must be positive") - } -} - -// assertSharesLessThanTotal panics if the number of shares is greater than the total shares -func (p *BasePool) assertSharesAreLessThanTotal(shares sdkmath.Int) { - if shares.GT(p.totalShares) { - panic(fmt.Sprintf("out of bounds: shares %s > total shares %s", shares, p.totalShares)) - } -} - -// assertDepositsPositive panics if a deposit is zero or negative -func (p *BasePool) assertDepositsArePositive(depositA, depositB sdkmath.Int) { - if !depositA.IsPositive() { - panic("invalid value: deposit A must be positive") - } - - if !depositB.IsPositive() { - panic("invalid state: deposit B must be positive") - } -} - -// assertReservesArePositive panics if any reserves are zero. This is an invalid -// state that should never happen. If this panic is seen, it is a bug. -func (p *BasePool) assertReservesArePositive() { - if !p.reservesA.IsPositive() { - panic("invalid state: reserves A must be positive") - } - - if !p.reservesB.IsPositive() { - panic("invalid state: reserves B must be positive") - } -} - -// assertReservesAreNotNegative panics if any reserves are negative. This is an invalid -// state that should never happen. If this panic is seen, it is a bug. -func (p *BasePool) assertReservesAreNotNegative() { - if p.reservesA.IsNegative() { - panic("invalid state: reserves A can not be negative") - } - - if p.reservesB.IsNegative() { - panic("invalid state: reserves B can not be negative") - } -} - -// assertInvariant panics if the new invariant is less than the previous invariant. This -// is an invalid state that should never happen. If this panic is seen, it is a bug. -func (p *BasePool) assertInvariant(prevInvariant, newInvariant *big.Int) { - // invariant > newInvariant - if prevInvariant.Cmp(newInvariant) == 1 { - panic(fmt.Sprintf("invalid state: invariant %s decreased to %s", prevInvariant.String(), newInvariant.String())) - } -} diff --git a/x/swap/types/base_pool_test.go b/x/swap/types/base_pool_test.go deleted file mode 100644 index 2d0b02e1..00000000 --- a/x/swap/types/base_pool_test.go +++ /dev/null @@ -1,591 +0,0 @@ -package types_test - -import ( - "fmt" - "math/big" - "testing" - - types "github.com/kava-labs/kava/x/swap/types" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// i creates a new sdkmath.Int from int64 -func i(n int64) sdkmath.Int { - return sdkmath.NewInt(n) -} - -// s returns a new sdkmath.Int from a string -func s(str string) sdkmath.Int { - num, ok := sdkmath.NewIntFromString(str) - if !ok { - panic(fmt.Sprintf("overflow creating Int from %s", str)) - } - return num -} - -// d creates a new sdk.Dec from a string -func d(str string) sdk.Dec { - return sdk.MustNewDecFromStr(str) -} - -// exp takes a sdkmath.Int and computes the power -// helper to generate large numbers -func exp(n sdkmath.Int, power int64) sdkmath.Int { - b := n.BigInt() - b.Exp(b, big.NewInt(power), nil) - return sdkmath.NewIntFromBigInt(b) -} - -func TestBasePool_NewPool_Validation(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - expectedErr string - }{ - {i(0), i(1e6), "reserves must be greater than zero: invalid pool"}, - {i(0), i(0), "reserves must be greater than zero: invalid pool"}, - {i(-1), i(1e6), "reserves must be greater than zero: invalid pool"}, - {i(1e6), i(-1), "reserves must be greater than zero: invalid pool"}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s", tc.reservesA, tc.reservesB), func(t *testing.T) { - pool, err := types.NewBasePool(tc.reservesA, tc.reservesB) - require.EqualError(t, err, tc.expectedErr) - assert.Nil(t, pool) - }) - } -} - -func TestBasePool_NewPoolWithExistingShares_Validation(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - totalShares sdkmath.Int - expectedErr string - }{ - {i(0), i(1e6), i(1), "reserves must be greater than zero: invalid pool"}, - {i(0), i(0), i(1), "reserves must be greater than zero: invalid pool"}, - {i(-1), i(1e6), i(3), "reserves must be greater than zero: invalid pool"}, - {i(1e6), i(-1), i(100), "reserves must be greater than zero: invalid pool"}, - {i(1e6), i(-1), i(3), "reserves must be greater than zero: invalid pool"}, - {i(1e6), i(1e6), i(0), "total shares must be greater than zero: invalid pool"}, - {i(1e6), i(1e6), i(-1), "total shares must be greater than zero: invalid pool"}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s shares=%s", tc.reservesA, tc.reservesB, tc.totalShares), func(t *testing.T) { - pool, err := types.NewBasePoolWithExistingShares(tc.reservesA, tc.reservesB, tc.totalShares) - require.EqualError(t, err, tc.expectedErr) - assert.Nil(t, pool) - }) - } -} - -func TestBasePool_InitialState(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - expectedShares sdkmath.Int - }{ - {i(1), i(1), i(1)}, - {i(100), i(100), i(100)}, - {i(100), i(10000000), i(31622)}, - {i(1e5), i(5e6), i(707106)}, - {i(1e6), i(5e6), i(2236067)}, - {i(1e15), i(7e15), i(2645751311064590)}, - {i(1), i(6e18), i(2449489742)}, - {i(1.345678e18), i(4.313456e18), i(2409257736973775913)}, - // handle sqrt of large numbers, sdkmath.Int.ApproxSqrt() doesn't converge in 100 iterations - {i(145345664).Mul(exp(i(10), 26)), i(6432294561).Mul(exp(i(10), 20)), s("96690543695447979624812468142651")}, - {i(465432423).Mul(exp(i(10), 50)), i(4565432).Mul(exp(i(10), 50)), s("4609663846531258725944608083913166083991595286362304230475")}, - {exp(i(2), 253), exp(i(2), 253), s("14474011154664524427946373126085988481658748083205070504932198000989141204992")}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s", tc.reservesA, tc.reservesB), func(t *testing.T) { - pool, err := types.NewBasePool(tc.reservesA, tc.reservesB) - require.Nil(t, err) - assert.Equal(t, tc.reservesA, pool.ReservesA()) - assert.Equal(t, tc.reservesB, pool.ReservesB()) - assert.Equal(t, tc.expectedShares, pool.TotalShares()) - }) - } -} - -func TestBasePool_ExistingState(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - totalShares sdkmath.Int - }{ - {i(1), i(1), i(1)}, - {i(100), i(100), i(100)}, - {i(1e5), i(5e6), i(707106)}, - {i(1e15), i(7e15), i(2645751311064590)}, - {i(465432423).Mul(exp(i(10), 50)), i(4565432).Mul(exp(i(10), 50)), s("4609663846531258725944608083913166083991595286362304230475")}, - {exp(i(2), 253), exp(i(2), 253), s("14474011154664524427946373126085988481658748083205070504932198000989141204992")}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s shares=%s", tc.reservesA, tc.reservesB, tc.totalShares), func(t *testing.T) { - pool, err := types.NewBasePoolWithExistingShares(tc.reservesA, tc.reservesB, tc.totalShares) - require.Nil(t, err) - assert.Equal(t, tc.reservesA, pool.ReservesA()) - assert.Equal(t, tc.reservesB, pool.ReservesB()) - assert.Equal(t, tc.totalShares, pool.TotalShares()) - }) - } -} - -func TestBasePool_ShareValue_PoolCreator(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - }{ - {i(1), i(1)}, - {i(100), i(100)}, - {i(100), i(10000000)}, - {i(1e5), i(5e6)}, - {i(1e15), i(7e15)}, - {i(1), i(6e18)}, - {i(1.345678e18), i(4.313456e18)}, - // ensure no overflows in intermediate values - {exp(i(2), 253), exp(i(2), 253)}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s", tc.reservesA, tc.reservesB), func(t *testing.T) { - pool, err := types.NewBasePool(tc.reservesA, tc.reservesB) - assert.NoError(t, err) - - a, b := pool.ShareValue(pool.TotalShares()) - // pool creators experience zero truncation error and always - // and always receive their original balance on a 100% withdraw - // when there are no other deposits that result in a fractional share ownership - assert.Equal(t, tc.reservesA, a, "share value of reserves A not equal") - assert.Equal(t, tc.reservesB, b, "share value of reserves B not equal") - }) - } -} - -func TestBasePool_AddLiquidity(t *testing.T) { - testCases := []struct { - initialA sdkmath.Int - initialB sdkmath.Int - desiredA sdkmath.Int - desiredB sdkmath.Int - expectedA sdkmath.Int - expectedB sdkmath.Int - expectedShares sdkmath.Int - }{ - {i(1), i(1), i(1), i(1), i(1), i(1), i(1)}, // small pool, i(100)% deposit - {i(10), i(10), i(5), i(5), i(5), i(5), i(5)}, // i(50)% deposit - {i(10), i(10), i(3), i(3), i(3), i(3), i(3)}, // i(30)% deposit - {i(10), i(10), i(1), i(1), i(1), i(1), i(1)}, // i(10)% deposit - - // small pools, unequal deposit ratios - {i(11), i(10), i(5), i(6), i(5), i(4), i(4)}, - {i(11), i(10), i(5), i(5), i(5), i(4), i(4)}, - // this test case fails if we don't use min share ratio - {i(11), i(10), i(5), i(4), i(4), i(4), i(3)}, - - // small pools, unequal deposit ratios, reversed - {i(10), i(11), i(6), i(5), i(4), i(5), i(4)}, - {i(10), i(11), i(5), i(5), i(4), i(5), i(4)}, - // this test case fails if we don't use min share ratio - {i(10), i(11), i(4), i(5), i(4), i(4), i(3)}, - - {i(10e6), i(11e6), i(5e6), i(5e6), i(4545454), i(5e6), i(4767312)}, - {i(11e6), i(10e6), i(5e6), i(5e6), i(5e6), i(4545454), i(4767312)}, - - // pool size near max of sdkmath.Int, ensure intermidiate calculations do not overflow - {exp(i(10), 70), exp(i(10), 70), i(1e18), i(1e18), i(1e18), i(1e18), i(1e18)}, - } - - for _, tc := range testCases { - name := fmt.Sprintf("initialA=%s initialB=%s desiredA=%s desiredB=%s", tc.initialA, tc.initialB, tc.desiredA, tc.desiredB) - t.Run(name, func(t *testing.T) { - pool, err := types.NewBasePool(tc.initialA, tc.initialB) - require.NoError(t, err) - initialShares := pool.TotalShares() - - actualA, actualB, actualShares := pool.AddLiquidity(tc.desiredA, tc.desiredB) - - // assert correct values are retruned - assert.Equal(t, tc.expectedA, actualA, "deposited A liquidity not equal") - assert.Equal(t, tc.expectedB, actualB, "deposited B liquidity not equal") - assert.Equal(t, tc.expectedShares, actualShares, "calculated shares not equal") - - // assert pool liquidity and shares are updated - assert.Equal(t, tc.initialA.Add(actualA), pool.ReservesA(), "total reserves A not equal") - assert.Equal(t, tc.initialB.Add(actualB), pool.ReservesB(), "total reserves B not equal") - assert.Equal(t, initialShares.Add(actualShares), pool.TotalShares(), "total shares not equal") - - leftA := actualShares.BigInt() - leftA.Mul(leftA, tc.initialA.BigInt()) - rightA := initialShares.BigInt() - rightA.Mul(rightA, actualA.BigInt()) - - leftB := actualShares.BigInt() - leftB.Mul(leftB, tc.initialB.BigInt()) - rightB := initialShares.BigInt() - rightB.Mul(rightB, actualB.BigInt()) - - // assert that the share ratio is less than or equal to the deposit ratio - // actualShares / initialShares <= actualA / initialA - assert.True(t, leftA.Cmp(rightA) <= 0, "share ratio is greater than deposit A ratio") - // actualShares / initialShares <= actualB / initialB - assert.True(t, leftB.Cmp(rightB) <= 0, "share ratio is greater than deposit B ratio") - - // assert that share value of returned shares is not greater than the deposited amount - shareValueA, shareValueB := pool.ShareValue(actualShares) - assert.True(t, shareValueA.LTE(actualA), "share value A greater than deposited A") - assert.True(t, shareValueB.LTE(actualB), "share value B greater than deposited B") - }) - } -} - -func TestBasePool_RemoveLiquidity(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - shares sdkmath.Int - expectedA sdkmath.Int - expectedB sdkmath.Int - }{ - {i(1), i(1), i(1), i(1), i(1)}, - {i(100), i(100), i(50), i(50), i(50)}, - {i(100), i(10000000), i(10435), i(32), i(3299917)}, - {i(10000000), i(100), i(10435), i(3299917), i(32)}, - {i(1.345678e18), i(4.313456e18), i(3.134541e17), i(175078108044025869), i(561197935621412888)}, - // ensure no overflows in intermediate values - {exp(i(10), 70), exp(i(10), 70), i(1e18), i(1e18), i(1e18)}, - {exp(i(2), 253), exp(i(2), 253), exp(i(2), 253), exp(i(2), 253), exp(i(2), 253)}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s shares=%s", tc.reservesA, tc.reservesB, tc.shares), func(t *testing.T) { - pool, err := types.NewBasePool(tc.reservesA, tc.reservesB) - assert.NoError(t, err) - initialShares := pool.TotalShares() - - a, b := pool.RemoveLiquidity(tc.shares) - - // pool creators experience zero truncation error and always - // and always receive their original balance on a 100% withdraw - // when there are no other deposits that result in a fractional share ownership - assert.Equal(t, tc.expectedA, a, "withdrawn A not equal") - assert.Equal(t, tc.expectedB, b, "withdrawn B not equal") - - // asset that pool state is updated - assert.Equal(t, tc.reservesA.Sub(a), pool.ReservesA(), "reserves A after withdraw not equal") - assert.Equal(t, tc.reservesB.Sub(b), pool.ReservesB(), "reserves B after withdraw not equal") - assert.Equal(t, initialShares.Sub(tc.shares), pool.TotalShares(), "total shares after withdraw not equal") - }) - } -} - -func TestBasePool_Panic_OutOfBounds(t *testing.T) { - pool, err := types.NewBasePool(sdkmath.NewInt(100), sdkmath.NewInt(100)) - require.NoError(t, err) - - assert.Panics(t, func() { pool.ShareValue(pool.TotalShares().Add(sdkmath.NewInt(1))) }, "ShareValue did not panic when shares > totalShares") - assert.Panics(t, func() { pool.RemoveLiquidity(pool.TotalShares().Add(sdkmath.NewInt(1))) }, "RemoveLiquidity did not panic when shares > totalShares") -} - -func TestBasePool_EmptyAndRefill(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - }{ - {i(1), i(1)}, - {i(100), i(100)}, - {i(100), i(10000000)}, - {i(1e5), i(5e6)}, - {i(1e6), i(5e6)}, - {i(1e15), i(7e15)}, - {i(1), i(6e18)}, - {i(1.345678e18), i(4.313456e18)}, - {i(145345664).Mul(exp(i(10), 26)), i(6432294561).Mul(exp(i(10), 20))}, - {i(465432423).Mul(exp(i(10), 50)), i(4565432).Mul(exp(i(10), 50))}, - {exp(i(2), 253), exp(i(2), 253)}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s", tc.reservesA, tc.reservesB), func(t *testing.T) { - pool, err := types.NewBasePool(tc.reservesA, tc.reservesB) - require.NoError(t, err) - - initialShares := pool.TotalShares() - pool.RemoveLiquidity(initialShares) - - assert.True(t, pool.IsEmpty()) - assert.True(t, pool.TotalShares().IsZero(), "total shares are not depleted") - - pool.AddLiquidity(tc.reservesA, tc.reservesB) - assert.Equal(t, initialShares, pool.TotalShares(), "total shares not equal") - }) - } -} - -func TestBasePool_Panics_AddLiquidity(t *testing.T) { - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.AddLiquidity(i(0), i(1e6)) - }, "did not panic when reserve A is zero") - - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.AddLiquidity(i(-1), i(1e6)) - }, "did not panic when reserve A is negative") - - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.AddLiquidity(i(1e6), i(0)) - }, "did not panic when reserve B is zero") - - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.AddLiquidity(i(1e6), i(0)) - }, "did not panic when reserve B is zero") -} - -func TestBasePool_Panics_RemoveLiquidity(t *testing.T) { - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.RemoveLiquidity(i(0)) - }, "did not panic when shares are zero") - - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.RemoveLiquidity(i(-1)) - }, "did not panic when shares are negative") -} - -func TestBasePool_ReservesOnlyDepletedWithLastShare(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - }{ - {i(5), i(5)}, - {i(100), i(100)}, - {i(100), i(10000000)}, - {i(1e5), i(5e6)}, - {i(1e6), i(5e6)}, - {i(1e15), i(7e15)}, - {i(1), i(6e18)}, - {i(1.345678e18), i(4.313456e18)}, - {i(145345664).Mul(exp(i(10), 26)), i(6432294561).Mul(exp(i(10), 20))}, - {i(465432423).Mul(exp(i(10), 50)), i(4565432).Mul(exp(i(10), 50))}, - {exp(i(2), 253), exp(i(2), 253)}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s", tc.reservesA, tc.reservesB), func(t *testing.T) { - pool, err := types.NewBasePool(tc.reservesA, tc.reservesB) - require.NoError(t, err) - - initialShares := pool.TotalShares() - pool.RemoveLiquidity(initialShares.Sub(i(1))) - - assert.False(t, pool.ReservesA().IsZero(), "reserves A equal to zero") - assert.False(t, pool.ReservesB().IsZero(), "reserves B equal to zero") - - pool.RemoveLiquidity(i(1)) - assert.True(t, pool.IsEmpty()) - }) - } -} - -func TestBasePool_Swap_ExactInput(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - exactInput sdkmath.Int - fee sdk.Dec - expectedOutput sdkmath.Int - expectedFee sdkmath.Int - }{ - // test small pools - {i(10), i(10), i(1), d("0.003"), i(0), i(1)}, - {i(10), i(10), i(3), d("0.003"), i(1), i(1)}, - {i(10), i(10), i(10), d("0.003"), i(4), i(1)}, - {i(10), i(10), i(91), d("0.003"), i(9), i(1)}, - // test fee values and ceil - {i(1e6), i(1e6), i(1000), d("0.003"), i(996), i(3)}, - {i(1e6), i(1e6), i(1000), d("0.0031"), i(995), i(4)}, - {i(1e6), i(1e6), i(1000), d("0.0039"), i(995), i(4)}, - {i(1e6), i(1e6), i(1000), d("0.001"), i(998), i(1)}, - {i(1e6), i(1e6), i(1000), d("0.025"), i(974), i(25)}, - {i(1e6), i(1e6), i(1000), d("0.1"), i(899), i(100)}, - {i(1e6), i(1e6), i(1000), d("0.5"), i(499), i(500)}, - // test various random pools and swaps - {i(10e6), i(500e6), i(1e6), d("0.0025"), i(45351216), i(2500)}, - {i(10e6), i(500e6), i(8e6), d("0.003456"), i(221794899), i(27648)}, - // test very large pools and swaps - {exp(i(2), 250), exp(i(2), 250), exp(i(2), 249), d("0.003"), s("601876423139828614225164081027182620796370196819963934493551943901658899790"), s("2713877091499598330239944961141122840311015265600950719674787125185463976")}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s exactInput=%s fee=%s", tc.reservesA, tc.reservesB, tc.exactInput, tc.fee), func(t *testing.T) { - poolA, err := types.NewBasePool(tc.reservesA, tc.reservesB) - require.NoError(t, err) - swapA, feeA := poolA.SwapExactAForB(tc.exactInput, tc.fee) - - poolB, err := types.NewBasePool(tc.reservesB, tc.reservesA) - require.NoError(t, err) - swapB, feeB := poolB.SwapExactBForA(tc.exactInput, tc.fee) - - // pool must be symmetric - if we swap reserves, then swap opposite direction - // then the results should be equal - require.Equal(t, swapA, swapB, "expected swap methods to have equal swap results") - require.Equal(t, feeA, feeB, "expected swap methods to have equal fee results") - require.Equal(t, poolA.ReservesA(), poolB.ReservesB(), "expected reserves A to be equal") - require.Equal(t, poolA.ReservesB(), poolB.ReservesA(), "expected reserves B to be equal") - - assert.Equal(t, tc.expectedOutput, swapA, "returned swap not equal") - assert.Equal(t, tc.expectedFee, feeA, "returned fee not equal") - - expectedReservesA := tc.reservesA.Add(tc.exactInput) - expectedReservesB := tc.reservesB.Sub(tc.expectedOutput) - - assert.Equal(t, expectedReservesA, poolA.ReservesA(), "expected new reserves A not equal") - assert.Equal(t, expectedReservesB, poolA.ReservesB(), "expected new reserves B not equal") - }) - } -} - -func TestBasePool_Swap_ExactOutput(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - exactOutput sdkmath.Int - fee sdk.Dec - expectedInput sdkmath.Int - expectedFee sdkmath.Int - }{ - // test small pools - {i(10), i(10), i(1), d("0.003"), i(3), i(1)}, - {i(10), i(10), i(9), d("0.003"), i(91), i(1)}, - // test fee values and ceil - {i(1e6), i(1e6), i(996), d("0.003"), i(1000), i(3)}, - {i(1e6), i(1e6), i(995), d("0.0031"), i(1000), i(4)}, - {i(1e6), i(1e6), i(995), d("0.0039"), i(1000), i(4)}, - {i(1e6), i(1e6), i(998), d("0.001"), i(1000), i(1)}, - {i(1e6), i(1e6), i(974), d("0.025"), i(1000), i(25)}, - {i(1e6), i(1e6), i(899), d("0.1"), i(1000), i(100)}, - {i(1e6), i(1e6), i(499), d("0.5"), i(1000), i(500)}, - // test various random pools and swaps - {i(10e6), i(500e6), i(45351216), d("0.0025"), i(1e6), i(2500)}, - {i(10e6), i(500e6), i(221794899), d("0.003456"), i(8e6), i(27648)}, - // test very large pools and swaps - {exp(i(2), 250), exp(i(2), 250), s("601876423139828614225164081027182620796370196819963934493551943901658899790"), d("0.003"), s("904625697166532776746648320380374280103671755200316906558262375061821325311"), s("2713877091499598330239944961141122840311015265600950719674787125185463976")}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s exactOutput=%s fee=%s", tc.reservesA, tc.reservesB, tc.exactOutput, tc.fee), func(t *testing.T) { - poolA, err := types.NewBasePool(tc.reservesA, tc.reservesB) - require.NoError(t, err) - swapA, feeA := poolA.SwapAForExactB(tc.exactOutput, tc.fee) - - poolB, err := types.NewBasePool(tc.reservesB, tc.reservesA) - require.NoError(t, err) - swapB, feeB := poolB.SwapBForExactA(tc.exactOutput, tc.fee) - - // pool must be symmetric - if we swap reserves, then swap opposite direction - // then the results should be equal - require.Equal(t, swapA, swapB, "expected swap methods to have equal swap results") - require.Equal(t, feeA, feeB, "expected swap methods to have equal fee results") - require.Equal(t, poolA.ReservesA(), poolB.ReservesB(), "expected reserves A to be equal") - require.Equal(t, poolA.ReservesB(), poolB.ReservesA(), "expected reserves B to be equal") - - assert.Equal(t, tc.expectedInput.String(), swapA.String(), "returned swap not equal") - assert.Equal(t, tc.expectedFee, feeA, "returned fee not equal") - - expectedReservesA := tc.reservesA.Add(tc.expectedInput) - expectedReservesB := tc.reservesB.Sub(tc.exactOutput) - - assert.Equal(t, expectedReservesA, poolA.ReservesA(), "expected new reserves A not equal") - assert.Equal(t, expectedReservesB, poolA.ReservesB(), "expected new reserves B not equal") - }) - } -} - -func TestBasePool_Panics_Swap_ExactInput(t *testing.T) { - testCases := []struct { - swap sdkmath.Int - fee sdk.Dec - }{ - {i(0), d("0.003")}, - {i(-1), d("0.003")}, - {i(1), d("1")}, - {i(1), d("-0.003")}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("swap=%s fee=%s", tc.swap, tc.fee), func(t *testing.T) { - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.SwapExactAForB(tc.swap, tc.fee) - }, "SwapExactAForB did not panic") - - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.SwapExactBForA(tc.swap, tc.fee) - }, "SwapExactBForA did not panic") - }) - } -} - -func TestBasePool_Panics_Swap_ExactOutput(t *testing.T) { - testCases := []struct { - swap sdkmath.Int - fee sdk.Dec - }{ - {i(0), d("0.003")}, - {i(-1), d("0.003")}, - {i(1), d("1")}, - {i(1), d("-0.003")}, - {i(1000000), d("0.003")}, - {i(1000001), d("0.003")}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("swap=%s fee=%s", tc.swap, tc.fee), func(t *testing.T) { - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.SwapAForExactB(tc.swap, tc.fee) - }, "SwapAForExactB did not panic") - - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.SwapBForExactA(tc.swap, tc.fee) - }, "SwapBForExactA did not panic") - }) - } -} diff --git a/x/swap/types/codec.go b/x/swap/types/codec.go deleted file mode 100644 index 2d1d5c12..00000000 --- a/x/swap/types/codec.go +++ /dev/null @@ -1,47 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the -// governance module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgDeposit{}, "swap/MsgDeposit", nil) - cdc.RegisterConcrete(&MsgWithdraw{}, "swap/MsgWithdraw", nil) - cdc.RegisterConcrete(&MsgSwapExactForTokens{}, "swap/MsgSwapExactForTokens", nil) - cdc.RegisterConcrete(&MsgSwapForExactTokens{}, "swap/MsgSwapForExactTokens", nil) -} - -// RegisterInterfaces registers proto messages under their interfaces for unmarshalling, -// in addition to registerting the msg service for handling tx msgs -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgDeposit{}, - &MsgWithdraw{}, - &MsgSwapExactForTokens{}, - &MsgSwapForExactTokens{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - // ModuleCdc represents the legacy amino codec for the module - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/swap/types/common_test.go b/x/swap/types/common_test.go deleted file mode 100644 index fa6189ce..00000000 --- a/x/swap/types/common_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package types_test - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/app" -) - -func init() { - kavaConfig := sdk.GetConfig() - app.SetBech32AddressPrefixes(kavaConfig) - app.SetBip44CoinType(kavaConfig) - kavaConfig.Seal() -} diff --git a/x/swap/types/denominated_pool.go b/x/swap/types/denominated_pool.go deleted file mode 100644 index c816ce13..00000000 --- a/x/swap/types/denominated_pool.go +++ /dev/null @@ -1,160 +0,0 @@ -package types - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// DenominatedPool implements a denominated constant-product liquidity pool -type DenominatedPool struct { - // all pool operations are implemented in a unitless base pool - pool *BasePool - // track units of the reserveA and reserveB in base pool - denomA string - denomB string -} - -// NewDenominatedPool creates a new denominated pool from reserve coins -func NewDenominatedPool(reserves sdk.Coins) (*DenominatedPool, error) { - if len(reserves) != 2 { - return nil, errorsmod.Wrap(ErrInvalidPool, "reserves must have two denominations") - } - - // Coins should always sorted, so this is deterministic, though it does not need to be. - // The base pool calculation results do not depend on reserve order. - reservesA := reserves[0] - reservesB := reserves[1] - - pool, err := NewBasePool(reservesA.Amount, reservesB.Amount) - if err != nil { - return nil, err - } - - return &DenominatedPool{ - pool: pool, - denomA: reservesA.Denom, - denomB: reservesB.Denom, - }, nil -} - -// NewDenominatedPoolWithExistingShares creates a new denominated pool from reserve coins -func NewDenominatedPoolWithExistingShares(reserves sdk.Coins, totalShares sdkmath.Int) (*DenominatedPool, error) { - if len(reserves) != 2 { - return nil, errorsmod.Wrap(ErrInvalidPool, "reserves must have two denominations") - } - - // Coins should always sorted, so this is deterministic, though it does not need to be. - // The base pool calculation results do not depend on reserve order. - reservesA := reserves[0] - reservesB := reserves[1] - - pool, err := NewBasePoolWithExistingShares(reservesA.Amount, reservesB.Amount, totalShares) - if err != nil { - return nil, err - } - - return &DenominatedPool{ - pool: pool, - denomA: reservesA.Denom, - denomB: reservesB.Denom, - }, nil -} - -// Reserves returns the reserves held in the pool -func (p *DenominatedPool) Reserves() sdk.Coins { - return p.coins(p.pool.ReservesA(), p.pool.ReservesB()) -} - -// TotalShares returns the total shares for the pool -func (p *DenominatedPool) TotalShares() sdkmath.Int { - return p.pool.TotalShares() -} - -// IsEmpty returns true if the pool is empty -func (p *DenominatedPool) IsEmpty() bool { - return p.pool.IsEmpty() -} - -// AddLiquidity adds liquidity to the reserves and returns the added amount and shares created -func (p *DenominatedPool) AddLiquidity(deposit sdk.Coins) (sdk.Coins, sdkmath.Int) { - desiredA := deposit.AmountOf(p.denomA) - desiredB := deposit.AmountOf(p.denomB) - - actualA, actualB, shares := p.pool.AddLiquidity(desiredA, desiredB) - - return p.coins(actualA, actualB), shares -} - -// RemoveLiquidity removes liquidity from the pool -func (p *DenominatedPool) RemoveLiquidity(shares sdkmath.Int) sdk.Coins { - withdrawnA, withdrawnB := p.pool.RemoveLiquidity(shares) - - return p.coins(withdrawnA, withdrawnB) -} - -// ShareValue returns the value of the provided shares -func (p *DenominatedPool) ShareValue(shares sdkmath.Int) sdk.Coins { - valueA, valueB := p.pool.ShareValue(shares) - - return p.coins(valueA, valueB) -} - -// SwapWithExactInput trades an exact input coin for the other. Returns the positive other coin amount -// that is removed from the pool and the portion of the input coin that is used for the fee. -// It panics if the input denom does not match the pool reserves. -func (p *DenominatedPool) SwapWithExactInput(swapInput sdk.Coin, fee sdk.Dec) (sdk.Coin, sdk.Coin) { - var ( - swapOutput sdkmath.Int - feePaid sdkmath.Int - ) - - switch swapInput.Denom { - case p.denomA: - swapOutput, feePaid = p.pool.SwapExactAForB(swapInput.Amount, fee) - return p.coinB(swapOutput), p.coinA(feePaid) - case p.denomB: - swapOutput, feePaid = p.pool.SwapExactBForA(swapInput.Amount, fee) - return p.coinA(swapOutput), p.coinB(feePaid) - default: - panic(fmt.Sprintf("invalid denomination: denom '%s' does not match pool reserves", swapInput.Denom)) - } -} - -// SwapWithExactOutput trades a coin for an exact output coin b. Returns the positive input coin -// that is added to the pool, and the portion of that input that is used to pay the fee. -// Panics if the output denom does not match the pool reserves. -func (p *DenominatedPool) SwapWithExactOutput(swapOutput sdk.Coin, fee sdk.Dec) (sdk.Coin, sdk.Coin) { - var ( - swapInput sdkmath.Int - feePaid sdkmath.Int - ) - - switch swapOutput.Denom { - case p.denomA: - swapInput, feePaid = p.pool.SwapBForExactA(swapOutput.Amount, fee) - return p.coinB(swapInput), p.coinB(feePaid) - case p.denomB: - swapInput, feePaid = p.pool.SwapAForExactB(swapOutput.Amount, fee) - return p.coinA(swapInput), p.coinA(feePaid) - default: - panic(fmt.Sprintf("invalid denomination: denom '%s' does not match pool reserves", swapOutput.Denom)) - } -} - -// coins returns a new coins slice with correct reserve denoms from ordered sdk.Ints -func (p *DenominatedPool) coins(amountA, amountB sdkmath.Int) sdk.Coins { - return sdk.NewCoins(p.coinA(amountA), p.coinB(amountB)) -} - -// coinA returns a new coin denominated in denomA -func (p *DenominatedPool) coinA(amount sdkmath.Int) sdk.Coin { - return sdk.NewCoin(p.denomA, amount) -} - -// coinA returns a new coin denominated in denomB -func (p *DenominatedPool) coinB(amount sdkmath.Int) sdk.Coin { - return sdk.NewCoin(p.denomB, amount) -} diff --git a/x/swap/types/denominated_pool_test.go b/x/swap/types/denominated_pool_test.go deleted file mode 100644 index fb0c3d57..00000000 --- a/x/swap/types/denominated_pool_test.go +++ /dev/null @@ -1,183 +0,0 @@ -package types_test - -import ( - "fmt" - "testing" - - types "github.com/kava-labs/kava/x/swap/types" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// create a new ukava coin from int64 -func ukava(amount int64) sdk.Coin { - return sdk.NewCoin("ukava", sdkmath.NewInt(amount)) -} - -// create a new usdx coin from int64 -func usdx(amount int64) sdk.Coin { - return sdk.NewCoin("usdx", sdkmath.NewInt(amount)) -} - -// create a new hard coin from int64 -func hard(amount int64) sdk.Coin { - return sdk.NewCoin("hard", sdkmath.NewInt(amount)) -} - -func TestDenominatedPool_NewDenominatedPool_Validation(t *testing.T) { - testCases := []struct { - reservesA sdk.Coin - reservesB sdk.Coin - expectedErr string - }{ - {ukava(0), usdx(1e6), "reserves must have two denominations: invalid pool"}, - {ukava(1e6), usdx(0), "reserves must have two denominations: invalid pool"}, - {usdx(0), ukava(1e6), "reserves must have two denominations: invalid pool"}, - {usdx(0), ukava(1e6), "reserves must have two denominations: invalid pool"}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s", tc.reservesA, tc.reservesB), func(t *testing.T) { - pool, err := types.NewDenominatedPool(sdk.NewCoins(tc.reservesA, tc.reservesB)) - require.EqualError(t, err, tc.expectedErr) - assert.Nil(t, pool) - }) - } -} - -func TestDenominatedPool_NewDenominatedPoolWithExistingShares_Validation(t *testing.T) { - testCases := []struct { - reservesA sdk.Coin - reservesB sdk.Coin - totalShares sdkmath.Int - expectedErr string - }{ - {ukava(0), usdx(1e6), i(1), "reserves must have two denominations: invalid pool"}, - {usdx(0), ukava(1e6), i(1), "reserves must have two denominations: invalid pool"}, - {ukava(1e6), usdx(1e6), i(0), "total shares must be greater than zero: invalid pool"}, - {usdx(1e6), ukava(1e6), i(-1), "total shares must be greater than zero: invalid pool"}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s", tc.reservesA, tc.reservesB), func(t *testing.T) { - pool, err := types.NewDenominatedPoolWithExistingShares(sdk.NewCoins(tc.reservesA, tc.reservesB), tc.totalShares) - require.EqualError(t, err, tc.expectedErr) - assert.Nil(t, pool) - }) - } -} - -func TestDenominatedPool_InitialState(t *testing.T) { - reserves := sdk.NewCoins(ukava(1e6), usdx(5e6)) - totalShares := i(2236067) - - pool, err := types.NewDenominatedPool(reserves) - require.NoError(t, err) - - assert.Equal(t, pool.Reserves(), reserves) - assert.Equal(t, pool.TotalShares(), totalShares) -} - -func TestDenominatedPool_InitialState_ExistingShares(t *testing.T) { - reserves := sdk.NewCoins(ukava(1e6), usdx(5e6)) - totalShares := i(2e6) - - pool, err := types.NewDenominatedPoolWithExistingShares(reserves, totalShares) - require.NoError(t, err) - - assert.Equal(t, pool.Reserves(), reserves) - assert.Equal(t, pool.TotalShares(), totalShares) -} - -func TestDenominatedPool_ShareValue(t *testing.T) { - reserves := sdk.NewCoins(ukava(10e6), usdx(50e6)) - - pool, err := types.NewDenominatedPool(reserves) - require.NoError(t, err) - - assert.Equal(t, reserves, pool.ShareValue(pool.TotalShares())) - - halfReserves := sdk.NewCoins(ukava(4999999), usdx(24999998)) - assert.Equal(t, halfReserves, pool.ShareValue(pool.TotalShares().Quo(i(2)))) -} - -func TestDenominatedPool_AddLiquidity(t *testing.T) { - reserves := sdk.NewCoins(ukava(10e6), usdx(50e6)) - desired := sdk.NewCoins(ukava(1e6), usdx(1e6)) - - pool, err := types.NewDenominatedPool(reserves) - require.NoError(t, err) - initialShares := pool.TotalShares() - - deposit, shares := pool.AddLiquidity(desired) - require.True(t, shares.IsPositive()) - require.True(t, deposit.IsAllPositive()) - - assert.Equal(t, reserves.Add(deposit...), pool.Reserves()) - assert.Equal(t, initialShares.Add(shares), pool.TotalShares()) -} - -func TestDenominatedPool_RemoveLiquidity(t *testing.T) { - reserves := sdk.NewCoins(ukava(10e6), usdx(50e6)) - - pool, err := types.NewDenominatedPool(reserves) - require.NoError(t, err) - - withdraw := pool.RemoveLiquidity(pool.TotalShares()) - - assert.True(t, pool.Reserves().IsZero()) - assert.True(t, pool.TotalShares().IsZero()) - assert.True(t, pool.IsEmpty()) - assert.Equal(t, reserves, withdraw) -} - -func TestDenominatedPool_SwapWithExactInput(t *testing.T) { - reserves := sdk.NewCoins(ukava(10e6), usdx(50e6)) - - pool, err := types.NewDenominatedPool(reserves) - require.NoError(t, err) - - output, fee := pool.SwapWithExactInput(ukava(1e6), d("0.003")) - - assert.Equal(t, usdx(4533054), output) - assert.Equal(t, ukava(3000), fee) - assert.Equal(t, sdk.NewCoins(ukava(11e6), usdx(45466946)), pool.Reserves()) - - pool, err = types.NewDenominatedPool(reserves) - require.NoError(t, err) - - output, fee = pool.SwapWithExactInput(usdx(5e6), d("0.003")) - - assert.Equal(t, ukava(906610), output) - assert.Equal(t, usdx(15000), fee) - assert.Equal(t, sdk.NewCoins(ukava(9093390), usdx(55e6)), pool.Reserves()) - - assert.Panics(t, func() { pool.SwapWithExactInput(hard(1e6), d("0.003")) }, "SwapWithExactInput did not panic on invalid denomination") -} - -func TestDenominatedPool_SwapWithExactOuput(t *testing.T) { - reserves := sdk.NewCoins(ukava(10e6), usdx(50e6)) - - pool, err := types.NewDenominatedPool(reserves) - require.NoError(t, err) - - input, fee := pool.SwapWithExactOutput(ukava(1e6), d("0.003")) - - assert.Equal(t, usdx(5572273), input) - assert.Equal(t, usdx(16717), fee) - assert.Equal(t, sdk.NewCoins(ukava(9e6), usdx(55572273)), pool.Reserves()) - - pool, err = types.NewDenominatedPool(reserves) - require.NoError(t, err) - - input, fee = pool.SwapWithExactOutput(usdx(5e6), d("0.003")) - - assert.Equal(t, ukava(1114456), input) - assert.Equal(t, ukava(3344), fee) - assert.Equal(t, sdk.NewCoins(ukava(11114456), usdx(45e6)), pool.Reserves()) - - assert.Panics(t, func() { pool.SwapWithExactOutput(hard(1e6), d("0.003")) }, "SwapWithExactOutput did not panic on invalid denomination") -} diff --git a/x/swap/types/errors.go b/x/swap/types/errors.go deleted file mode 100644 index 5c116d71..00000000 --- a/x/swap/types/errors.go +++ /dev/null @@ -1,18 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// swap module errors -var ( - ErrNotAllowed = errorsmod.Register(ModuleName, 2, "not allowed") - ErrInvalidDeadline = errorsmod.Register(ModuleName, 3, "invalid deadline") - ErrDeadlineExceeded = errorsmod.Register(ModuleName, 4, "deadline exceeded") - ErrSlippageExceeded = errorsmod.Register(ModuleName, 5, "slippage exceeded") - ErrInvalidPool = errorsmod.Register(ModuleName, 6, "invalid pool") - ErrInvalidSlippage = errorsmod.Register(ModuleName, 7, "invalid slippage") - ErrInsufficientLiquidity = errorsmod.Register(ModuleName, 8, "insufficient liquidity") - ErrInvalidShares = errorsmod.Register(ModuleName, 9, "invalid shares") - ErrDepositNotFound = errorsmod.Register(ModuleName, 10, "deposit not found") - ErrInvalidCoin = errorsmod.Register(ModuleName, 11, "invalid coin") - ErrNotImplemented = errorsmod.Register(ModuleName, 12, "not implemented") -) diff --git a/x/swap/types/events.go b/x/swap/types/events.go deleted file mode 100644 index 8bb9519d..00000000 --- a/x/swap/types/events.go +++ /dev/null @@ -1,18 +0,0 @@ -package types - -// Event types for swap module -const ( - AttributeValueCategory = ModuleName - EventTypeSwapDeposit = "swap_deposit" - EventTypeSwapWithdraw = "swap_withdraw" - EventTypeSwapTrade = "swap_trade" - AttributeKeyPoolID = "pool_id" - AttributeKeyDepositor = "depositor" - AttributeKeyShares = "shares" - AttributeKeyOwner = "owner" - AttributeKeyRequester = "requester" - AttributeKeySwapInput = "input" - AttributeKeySwapOutput = "output" - AttributeKeyFeePaid = "fee" - AttributeKeyExactDirection = "exact" -) diff --git a/x/swap/types/expected_keepers.go b/x/swap/types/expected_keepers.go deleted file mode 100644 index 258b9aea..00000000 --- a/x/swap/types/expected_keepers.go +++ /dev/null @@ -1,32 +0,0 @@ -package types - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// AccountKeeper defines the expected account keeper (noalias) -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI - SetModuleAccount(sdk.Context, types.ModuleAccountI) - - // moved in from supply - GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, name string) types.ModuleAccountI -} - -// BankKeeper defines the expected interface needed to retrieve account balances. -type BankKeeper interface { - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, 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 -} - -// SwapHooks are event hooks called when a user's deposit to a swap pool changes. -type SwapHooks interface { - AfterPoolDepositCreated(ctx sdk.Context, poolID string, depositor sdk.AccAddress, sharedOwned sdkmath.Int) - BeforePoolDepositModified(ctx sdk.Context, poolID string, depositor sdk.AccAddress, sharedOwned sdkmath.Int) -} diff --git a/x/swap/types/genesis.go b/x/swap/types/genesis.go deleted file mode 100644 index 6738e950..00000000 --- a/x/swap/types/genesis.go +++ /dev/null @@ -1,78 +0,0 @@ -package types - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type poolShares struct { - totalShares sdkmath.Int - totalSharesOwned sdkmath.Int -} - -var ( - // DefaultPoolRecords is used to set default records in default genesis state - DefaultPoolRecords = PoolRecords{} - // DefaultShareRecords is used to set default records in default genesis state - DefaultShareRecords = ShareRecords{} -) - -// NewGenesisState creates a new genesis state. -func NewGenesisState(params Params, poolRecords PoolRecords, shareRecords ShareRecords) GenesisState { - return GenesisState{ - Params: params, - PoolRecords: poolRecords, - ShareRecords: shareRecords, - } -} - -// Validate validates the module's genesis state -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - if err := gs.PoolRecords.Validate(); err != nil { - return err - } - if err := gs.ShareRecords.Validate(); err != nil { - return err - } - - totalShares := make(map[string]poolShares) - for _, pr := range gs.PoolRecords { - totalShares[pr.PoolID] = poolShares{ - totalShares: pr.TotalShares, - totalSharesOwned: sdk.ZeroInt(), - } - } - for _, sr := range gs.ShareRecords { - if shares, found := totalShares[sr.PoolID]; found { - shares.totalSharesOwned = shares.totalSharesOwned.Add(sr.SharesOwned) - totalShares[sr.PoolID] = shares - } else { - totalShares[sr.PoolID] = poolShares{ - totalShares: sdk.ZeroInt(), - totalSharesOwned: sr.SharesOwned, - } - } - } - - for poolID, ps := range totalShares { - if !ps.totalShares.Equal(ps.totalSharesOwned) { - return fmt.Errorf("total depositor shares %s not equal to pool '%s' total shares %s", ps.totalSharesOwned.String(), poolID, ps.totalShares.String()) - } - } - - return nil -} - -// DefaultGenesisState returns a default genesis state -func DefaultGenesisState() GenesisState { - return NewGenesisState( - DefaultParams(), - DefaultPoolRecords, - DefaultShareRecords, - ) -} diff --git a/x/swap/types/genesis.pb.go b/x/swap/types/genesis.pb.go deleted file mode 100644 index a58cc8c4..00000000 --- a/x/swap/types/genesis.pb.go +++ /dev/null @@ -1,453 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/swap/v1beta1/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 swap module's genesis state. -type GenesisState struct { - // params defines all the parameters related to swap - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - // pool_records defines the available pools - PoolRecords PoolRecords `protobuf:"bytes,2,rep,name=pool_records,json=poolRecords,proto3,castrepeated=PoolRecords" json:"pool_records"` - // share_records defines the owned shares of each pool - ShareRecords ShareRecords `protobuf:"bytes,3,rep,name=share_records,json=shareRecords,proto3,castrepeated=ShareRecords" json:"share_records"` -} - -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_b1a1a1687f484a21, []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) GetPoolRecords() PoolRecords { - if m != nil { - return m.PoolRecords - } - return nil -} - -func (m *GenesisState) GetShareRecords() ShareRecords { - if m != nil { - return m.ShareRecords - } - return nil -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.swap.v1beta1.GenesisState") -} - -func init() { proto.RegisterFile("kava/swap/v1beta1/genesis.proto", fileDescriptor_b1a1a1687f484a21) } - -var fileDescriptor_b1a1a1687f484a21 = []byte{ - // 283 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcf, 0x4e, 0x2c, 0x4b, - 0xd4, 0x2f, 0x2e, 0x4f, 0x2c, 0xd0, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x4f, - 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x04, 0x29, 0xd0, - 0x03, 0x29, 0xd0, 0x83, 0x2a, 0x90, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0xcb, 0xea, 0x83, 0x58, - 0x10, 0x85, 0x52, 0x32, 0x98, 0x26, 0x81, 0x75, 0x81, 0x65, 0x95, 0x7e, 0x32, 0x72, 0xf1, 0xb8, - 0x43, 0x0c, 0x0e, 0x2e, 0x49, 0x2c, 0x49, 0x15, 0x32, 0xe7, 0x62, 0x2b, 0x48, 0x2c, 0x4a, 0xcc, - 0x2d, 0x96, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x36, 0x92, 0xd4, 0xc3, 0xb0, 0x48, 0x2f, 0x00, 0xac, - 0xc0, 0x89, 0xe5, 0xc4, 0x3d, 0x79, 0x86, 0x20, 0xa8, 0x72, 0xa1, 0x50, 0x2e, 0x9e, 0x82, 0xfc, - 0xfc, 0x9c, 0xf8, 0xa2, 0xd4, 0xe4, 0xfc, 0xa2, 0x94, 0x62, 0x09, 0x26, 0x05, 0x66, 0x0d, 0x6e, - 0x23, 0x59, 0x6c, 0xda, 0xf3, 0xf3, 0x73, 0x82, 0xc0, 0xaa, 0x9c, 0x84, 0x41, 0x46, 0xac, 0xba, - 0x2f, 0xcf, 0x8d, 0x10, 0x2b, 0x0e, 0xe2, 0x2e, 0x40, 0x70, 0x84, 0x22, 0xb9, 0x78, 0x8b, 0x33, - 0x12, 0x8b, 0x52, 0xe1, 0xe6, 0x32, 0x83, 0xcd, 0x95, 0xc3, 0x62, 0x6e, 0x30, 0x48, 0x1d, 0xd4, - 0x60, 0x11, 0xa8, 0xc1, 0x3c, 0x48, 0x82, 0xc5, 0x41, 0x3c, 0xc5, 0x48, 0x3c, 0x27, 0x87, 0x13, - 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, - 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, 0x88, 0x52, 0x4b, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, - 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x07, 0xd9, 0xa3, 0x9b, 0x93, 0x98, 0x54, 0x0c, 0x66, 0xe9, 0x57, - 0x40, 0x82, 0xb2, 0xa4, 0xb2, 0x20, 0xb5, 0x38, 0x89, 0x0d, 0x1c, 0x88, 0xc6, 0x80, 0x00, 0x00, - 0x00, 0xff, 0xff, 0xca, 0xb8, 0xb9, 0x95, 0xae, 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.ShareRecords) > 0 { - for iNdEx := len(m.ShareRecords) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ShareRecords[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.PoolRecords) > 0 { - for iNdEx := len(m.PoolRecords) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.PoolRecords[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.PoolRecords) > 0 { - for _, e := range m.PoolRecords { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.ShareRecords) > 0 { - for _, e := range m.ShareRecords { - 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 PoolRecords", 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.PoolRecords = append(m.PoolRecords, PoolRecord{}) - if err := m.PoolRecords[len(m.PoolRecords)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ShareRecords", 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.ShareRecords = append(m.ShareRecords, ShareRecord{}) - if err := m.ShareRecords[len(m.ShareRecords)-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/swap/types/genesis_test.go b/x/swap/types/genesis_test.go deleted file mode 100644 index 770d228f..00000000 --- a/x/swap/types/genesis_test.go +++ /dev/null @@ -1,336 +0,0 @@ -package types_test - -import ( - "encoding/json" - "testing" - - "github.com/kava-labs/kava/x/swap/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "sigs.k8s.io/yaml" -) - -func TestGenesis_Default(t *testing.T) { - defaultGenesis := types.DefaultGenesisState() - - require.NoError(t, defaultGenesis.Validate()) - - defaultParams := types.DefaultParams() - assert.Equal(t, defaultParams, defaultGenesis.Params) -} - -func TestGenesis_Validate_SwapFee(t *testing.T) { - type args struct { - name string - swapFee sdk.Dec - expectErr bool - } - // More comprehensive swap fee tests are in prams_test.go - testCases := []args{ - { - "normal", - sdk.MustNewDecFromStr("0.25"), - false, - }, - { - "negative", - sdk.MustNewDecFromStr("-0.5"), - true, - }, - { - "greater than 1.0", - sdk.MustNewDecFromStr("1.001"), - true, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - genesisState := types.GenesisState{ - Params: types.Params{ - AllowedPools: types.DefaultAllowedPools, - SwapFee: tc.swapFee, - }, - } - - err := genesisState.Validate() - if tc.expectErr { - assert.NotNil(t, err) - } else { - assert.Nil(t, err) - } - }) - } -} - -func TestGenesis_Validate_AllowedPools(t *testing.T) { - type args struct { - name string - pairs types.AllowedPools - expectErr bool - } - // More comprehensive pair validation tests are in pair_test.go, params_test.go - testCases := []args{ - { - "normal", - types.DefaultAllowedPools, - false, - }, - { - "invalid", - types.AllowedPools{ - { - TokenA: "same", - TokenB: "same", - }, - }, - true, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - genesisState := types.GenesisState{ - Params: types.Params{ - AllowedPools: tc.pairs, - SwapFee: types.DefaultSwapFee, - }, - } - - err := genesisState.Validate() - if tc.expectErr { - assert.NotNil(t, err) - } else { - assert.Nil(t, err) - } - }) - } -} - -func TestGenesis_JSONEncoding(t *testing.T) { - raw := `{ - "params": { - "allowed_pools": [ - { - "token_a": "ukava", - "token_b": "usdx" - }, - { - "token_a": "hard", - "token_b": "busd" - } - ], - "swap_fee": "0.003000000000000000" - }, - "pool_records": [ - { - "pool_id": "ukava:usdx", - "reserves_a": { "denom": "ukava", "amount": "1000000" }, - "reserves_b": { "denom": "usdx", "amount": "5000000" }, - "total_shares": "3000000" - }, - { - "pool_id": "hard:usdx", - "reserves_a": { "denom": "ukava", "amount": "1000000" }, - "reserves_b": { "denom": "usdx", "amount": "2000000" }, - "total_shares": "2000000" - } - ], - "share_records": [ - { - "depositor": "kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w", - "pool_id": "ukava:usdx", - "shares_owned": "100000" - }, - { - "depositor": "kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea", - "pool_id": "hard:usdx", - "shares_owned": "200000" - } - ] - }` - - var state types.GenesisState - err := json.Unmarshal([]byte(raw), &state) - require.NoError(t, err) - - assert.Equal(t, 2, len(state.Params.AllowedPools)) - assert.Equal(t, sdk.MustNewDecFromStr("0.003"), state.Params.SwapFee) - assert.Equal(t, 2, len(state.PoolRecords)) - assert.Equal(t, 2, len(state.ShareRecords)) -} - -func TestGenesis_YAMLEncoding(t *testing.T) { - expected := `params: - allowed_pools: - - token_a: ukava - token_b: usdx - - token_a: hard - token_b: busd - swap_fee: "0.003000000000000000" -pool_records: -- pool_id: ukava:usdx - reserves_a: - amount: "1000000" - denom: ukava - reserves_b: - amount: "5000000" - denom: usdx - total_shares: "3000000" -- pool_id: hard:usdx - reserves_a: - amount: "1000000" - denom: hard - reserves_b: - amount: "2000000" - denom: usdx - total_shares: "1500000" -share_records: -- depositor: kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w - pool_id: ukava:usdx - shares_owned: "100000" -- depositor: kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea - pool_id: hard:usdx - shares_owned: "200000" -` - - depositor_1, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - require.NoError(t, err) - depositor_2, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") - require.NoError(t, err) - - state := types.NewGenesisState( - types.NewParams( - types.NewAllowedPools( - types.NewAllowedPool("ukava", "usdx"), - types.NewAllowedPool("hard", "busd"), - ), - sdk.MustNewDecFromStr("0.003"), - ), - types.PoolRecords{ - types.NewPoolRecord(sdk.NewCoins(ukava(1e6), usdx(5e6)), i(3e6)), - types.NewPoolRecord(sdk.NewCoins(hard(1e6), usdx(2e6)), i(15e5)), - }, - types.ShareRecords{ - types.NewShareRecord(depositor_1, types.PoolID("ukava", "usdx"), i(1e5)), - types.NewShareRecord(depositor_2, types.PoolID("hard", "usdx"), i(2e5)), - }, - ) - - data, err := yaml.Marshal(state) - require.NoError(t, err) - - assert.Equal(t, expected, string(data)) -} - -func TestGenesis_ValidatePoolRecords(t *testing.T) { - invalidPoolRecord := types.NewPoolRecord(sdk.NewCoins(ukava(1e6), usdx(5e6)), i(-1)) - - state := types.NewGenesisState( - types.DefaultParams(), - types.PoolRecords{invalidPoolRecord}, - types.ShareRecords{}, - ) - - assert.Error(t, state.Validate()) -} - -func TestGenesis_ValidateShareRecords(t *testing.T) { - depositor, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - require.NoError(t, err) - - invalidShareRecord := types.NewShareRecord(depositor, "", i(-1)) - - state := types.NewGenesisState( - types.DefaultParams(), - types.PoolRecords{}, - types.ShareRecords{invalidShareRecord}, - ) - - assert.Error(t, state.Validate()) -} - -func TestGenesis_Validate_PoolShareIntegration(t *testing.T) { - depositor_1, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - require.NoError(t, err) - depositor_2, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") - require.NoError(t, err) - - testCases := []struct { - name string - poolRecords types.PoolRecords - shareRecords types.ShareRecords - expectedErr string - }{ - { - name: "single pool record, zero share records", - poolRecords: types.PoolRecords{ - types.NewPoolRecord(sdk.NewCoins(ukava(1e6), usdx(5e6)), i(3e6)), - }, - shareRecords: types.ShareRecords{}, - expectedErr: "total depositor shares 0 not equal to pool 'ukava:usdx' total shares 3000000", - }, - { - name: "zero pool records, one share record", - poolRecords: types.PoolRecords{}, - shareRecords: types.ShareRecords{ - types.NewShareRecord(depositor_1, types.PoolID("ukava", "usdx"), i(5e6)), - }, - expectedErr: "total depositor shares 5000000 not equal to pool 'ukava:usdx' total shares 0", - }, - { - name: "one pool record, one share record", - poolRecords: types.PoolRecords{ - types.NewPoolRecord(sdk.NewCoins(ukava(1e6), usdx(5e6)), i(3e6)), - }, - shareRecords: types.ShareRecords{ - types.NewShareRecord(depositor_1, "ukava:usdx", i(15e5)), - }, - expectedErr: "total depositor shares 1500000 not equal to pool 'ukava:usdx' total shares 3000000", - }, - { - name: "more than one pool records, more than one share record", - poolRecords: types.PoolRecords{ - types.NewPoolRecord(sdk.NewCoins(ukava(1e6), usdx(5e6)), i(3e6)), - types.NewPoolRecord(sdk.NewCoins(hard(1e6), usdx(2e6)), i(2e6)), - }, - shareRecords: types.ShareRecords{ - types.NewShareRecord(depositor_1, types.PoolID("ukava", "usdx"), i(15e5)), - types.NewShareRecord(depositor_2, types.PoolID("ukava", "usdx"), i(15e5)), - types.NewShareRecord(depositor_1, types.PoolID("hard", "usdx"), i(1e6)), - }, - expectedErr: "total depositor shares 1000000 not equal to pool 'hard:usdx' total shares 2000000", - }, - { - name: "valid case with many pool records and share records", - poolRecords: types.PoolRecords{ - types.NewPoolRecord(sdk.NewCoins(ukava(1e6), usdx(5e6)), i(3e6)), - types.NewPoolRecord(sdk.NewCoins(hard(1e6), usdx(2e6)), i(2e6)), - types.NewPoolRecord(sdk.NewCoins(hard(7e6), ukava(10e6)), i(8e6)), - }, - shareRecords: types.ShareRecords{ - types.NewShareRecord(depositor_1, types.PoolID("ukava", "usdx"), i(15e5)), - types.NewShareRecord(depositor_2, types.PoolID("ukava", "usdx"), i(15e5)), - types.NewShareRecord(depositor_1, types.PoolID("hard", "usdx"), i(2e6)), - types.NewShareRecord(depositor_1, types.PoolID("hard", "ukava"), i(3e6)), - types.NewShareRecord(depositor_2, types.PoolID("hard", "ukava"), i(5e6)), - }, - expectedErr: "", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - state := types.NewGenesisState(types.DefaultParams(), tc.poolRecords, tc.shareRecords) - err := state.Validate() - - if tc.expectedErr == "" { - assert.NoError(t, err) - } else { - assert.EqualError(t, err, tc.expectedErr) - } - }) - } -} diff --git a/x/swap/types/keys.go b/x/swap/types/keys.go deleted file mode 100644 index a3e52a58..00000000 --- a/x/swap/types/keys.go +++ /dev/null @@ -1,47 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName name that will be used throughout the module - ModuleName = "swap" - - // ModuleAccountName name of module account used to hold liquidity - ModuleAccountName = "swap" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default name for parameter store - DefaultParamspace = ModuleName -) - -// key prefixes for store -var ( - PoolKeyPrefix = []byte{0x01} - DepositorPoolSharesPrefix = []byte{0x02} - - sep = []byte("|") -) - -// PoolKey returns a key generated from a poolID -func PoolKey(poolID string) []byte { - return []byte(poolID) -} - -// DepositorPoolSharesKey returns a key from a depositor and poolID -func DepositorPoolSharesKey(depositor sdk.AccAddress, poolID string) []byte { - return createKey(depositor, sep, []byte(poolID)) -} - -func createKey(bytes ...[]byte) (r []byte) { - for _, b := range bytes { - r = append(r, b...) - } - return -} diff --git a/x/swap/types/keys_test.go b/x/swap/types/keys_test.go deleted file mode 100644 index cb5496c2..00000000 --- a/x/swap/types/keys_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/kava-labs/kava/x/swap/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" -) - -func TestKeys(t *testing.T) { - key := types.PoolKey(types.PoolID("ukava", "usdx")) - assert.Equal(t, types.PoolID("ukava", "usdx"), string(key)) - - key = types.DepositorPoolSharesKey(sdk.AccAddress("testaddress1"), types.PoolID("ukava", "usdx")) - assert.Equal(t, string(sdk.AccAddress("testaddress1"))+"|"+types.PoolID("ukava", "usdx"), string(key)) -} diff --git a/x/swap/types/mocks/swap_hooks.go b/x/swap/types/mocks/swap_hooks.go deleted file mode 100644 index 674f17cb..00000000 --- a/x/swap/types/mocks/swap_hooks.go +++ /dev/null @@ -1,25 +0,0 @@ -// Code generated by mockery 2.7.4. DO NOT EDIT. - -package mocks - -import ( - math "cosmossdk.io/math" - mock "github.com/stretchr/testify/mock" - - types "github.com/cosmos/cosmos-sdk/types" -) - -// SwapHooks is an autogenerated mock type for the SwapHooks type -type SwapHooks struct { - mock.Mock -} - -// AfterPoolDepositCreated provides a mock function with given fields: ctx, poolID, depositor, sharedOwned -func (_m *SwapHooks) AfterPoolDepositCreated(ctx types.Context, poolID string, depositor types.AccAddress, sharedOwned math.Int) { - _m.Called(ctx, poolID, depositor, sharedOwned) -} - -// BeforePoolDepositModified provides a mock function with given fields: ctx, poolID, depositor, sharedOwned -func (_m *SwapHooks) BeforePoolDepositModified(ctx types.Context, poolID string, depositor types.AccAddress, sharedOwned math.Int) { - _m.Called(ctx, poolID, depositor, sharedOwned) -} diff --git a/x/swap/types/msg.go b/x/swap/types/msg.go deleted file mode 100644 index b415a01c..00000000 --- a/x/swap/types/msg.go +++ /dev/null @@ -1,342 +0,0 @@ -package types - -import ( - "time" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -const ( - // TypeMsgDeposit represents the type string for MsgDeposit - TypeMsgDeposit = "swap_deposit" - // TypeMsgWithdraw represents the type string for MsgWithdraw - TypeMsgWithdraw = "swap_withdraw" - // TypeSwapExactForTokens represents the type string for MsgSwapExactForTokens - TypeSwapExactForTokens = "swap_exact_for_tokens" - // TypeSwapForExactTokens represents the type string for MsgSwapForExactTokens - TypeSwapForExactTokens = "swap_for_exact_tokens" -) - -var ( - _ sdk.Msg = &MsgDeposit{} - _ MsgWithDeadline = &MsgDeposit{} - _ sdk.Msg = &MsgWithdraw{} - _ MsgWithDeadline = &MsgWithdraw{} - _ sdk.Msg = &MsgSwapExactForTokens{} - _ MsgWithDeadline = &MsgSwapExactForTokens{} - _ sdk.Msg = &MsgSwapForExactTokens{} - _ MsgWithDeadline = &MsgSwapForExactTokens{} -) - -// MsgWithDeadline allows messages to define a deadline of when they are considered invalid -type MsgWithDeadline interface { - GetDeadline() time.Time - DeadlineExceeded(blockTime time.Time) bool -} - -// NewMsgDeposit returns a new MsgDeposit -func NewMsgDeposit(depositor string, tokenA sdk.Coin, tokenB sdk.Coin, slippage sdk.Dec, deadline int64) *MsgDeposit { - return &MsgDeposit{ - Depositor: depositor, - TokenA: tokenA, - TokenB: tokenB, - Slippage: slippage, - Deadline: deadline, - } -} - -// Route return the message type used for routing the message. -func (msg MsgDeposit) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgDeposit) Type() string { return TypeMsgDeposit } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgDeposit) ValidateBasic() error { - if msg.Depositor == "" { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "depositor address cannot be empty") - } - - if _, err := sdk.AccAddressFromBech32(msg.Depositor); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid depositor address: %s", err) - } - - if !msg.TokenA.IsValid() || msg.TokenA.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "token a deposit amount %s", msg.TokenA) - } - - if !msg.TokenB.IsValid() || msg.TokenB.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "token b deposit amount %s", msg.TokenB) - } - - if msg.TokenA.Denom == msg.TokenB.Denom { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, "denominations can not be equal") - } - - if msg.Slippage.IsNil() { - return errorsmod.Wrapf(ErrInvalidSlippage, "slippage must be set") - } - - if msg.Slippage.IsNegative() { - return errorsmod.Wrapf(ErrInvalidSlippage, "slippage can not be negative") - } - - if msg.Deadline <= 0 { - return errorsmod.Wrapf(ErrInvalidDeadline, "deadline %d", msg.Deadline) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgDeposit) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgDeposit) GetSigners() []sdk.AccAddress { - depositor, _ := sdk.AccAddressFromBech32(msg.Depositor) - return []sdk.AccAddress{depositor} -} - -// GetDeadline returns the time at which the msg is considered invalid -func (msg MsgDeposit) GetDeadline() time.Time { - return time.Unix(msg.Deadline, 0) -} - -// DeadlineExceeded returns if the msg has exceeded it's deadline -func (msg MsgDeposit) DeadlineExceeded(blockTime time.Time) bool { - return blockTime.Unix() >= msg.Deadline -} - -// NewMsgWithdraw returns a new MsgWithdraw -func NewMsgWithdraw(from string, shares sdkmath.Int, minTokenA, minTokenB sdk.Coin, deadline int64) *MsgWithdraw { - return &MsgWithdraw{ - From: from, - Shares: shares, - MinTokenA: minTokenA, - MinTokenB: minTokenB, - Deadline: deadline, - } -} - -// Route return the message type used for routing the message. -func (msg MsgWithdraw) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgWithdraw) Type() string { return TypeMsgWithdraw } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgWithdraw) ValidateBasic() error { - if msg.From == "" { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "from address cannot be empty") - } - - if _, err := sdk.AccAddressFromBech32(msg.From); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid from address: %s", err) - } - - if msg.Shares.IsNil() { - return errorsmod.Wrapf(ErrInvalidShares, "shares must be set") - } - - if msg.Shares.IsZero() || msg.Shares.IsNegative() { - return errorsmod.Wrapf(ErrInvalidShares, msg.Shares.String()) - } - - if !msg.MinTokenA.IsValid() || msg.MinTokenA.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "min token a amount %s", msg.MinTokenA) - } - - if !msg.MinTokenB.IsValid() || msg.MinTokenB.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "min token b amount %s", msg.MinTokenB) - } - - if msg.MinTokenA.Denom == msg.MinTokenB.Denom { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, "denominations can not be equal") - } - - if msg.Deadline <= 0 { - return errorsmod.Wrapf(ErrInvalidDeadline, "deadline %d", msg.Deadline) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgWithdraw) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgWithdraw) GetSigners() []sdk.AccAddress { - from, _ := sdk.AccAddressFromBech32(msg.From) - return []sdk.AccAddress{from} -} - -// GetDeadline returns the time at which the msg is considered invalid -func (msg MsgWithdraw) GetDeadline() time.Time { - return time.Unix(msg.Deadline, 0) -} - -// DeadlineExceeded returns if the msg has exceeded it's deadline -func (msg MsgWithdraw) DeadlineExceeded(blockTime time.Time) bool { - return blockTime.Unix() >= msg.Deadline -} - -// NewMsgSwapExactForTokens returns a new MsgSwapExactForTokens -func NewMsgSwapExactForTokens(requester string, exactTokenA sdk.Coin, tokenB sdk.Coin, slippage sdk.Dec, deadline int64) *MsgSwapExactForTokens { - return &MsgSwapExactForTokens{ - Requester: requester, - ExactTokenA: exactTokenA, - TokenB: tokenB, - Slippage: slippage, - Deadline: deadline, - } -} - -// Route return the message type used for routing the message. -func (msg MsgSwapExactForTokens) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgSwapExactForTokens) Type() string { return TypeSwapExactForTokens } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgSwapExactForTokens) ValidateBasic() error { - if msg.Requester == "" { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "requester address cannot be empty") - } - - if _, err := sdk.AccAddressFromBech32(msg.Requester); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid requester address: %s", err) - } - - if !msg.ExactTokenA.IsValid() || msg.ExactTokenA.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "exact token a deposit amount %s", msg.ExactTokenA) - } - - if !msg.TokenB.IsValid() || msg.TokenB.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "token b deposit amount %s", msg.TokenB) - } - - if msg.ExactTokenA.Denom == msg.TokenB.Denom { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, "denominations can not be equal") - } - - if msg.Slippage.IsNil() { - return errorsmod.Wrapf(ErrInvalidSlippage, "slippage must be set") - } - - if msg.Slippage.IsNegative() { - return errorsmod.Wrapf(ErrInvalidSlippage, "slippage can not be negative") - } - - if msg.Deadline <= 0 { - return errorsmod.Wrapf(ErrInvalidDeadline, "deadline %d", msg.Deadline) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgSwapExactForTokens) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgSwapExactForTokens) GetSigners() []sdk.AccAddress { - requester, _ := sdk.AccAddressFromBech32(msg.Requester) - return []sdk.AccAddress{requester} -} - -// GetDeadline returns the time at which the msg is considered invalid -func (msg MsgSwapExactForTokens) GetDeadline() time.Time { - return time.Unix(msg.Deadline, 0) -} - -// DeadlineExceeded returns if the msg has exceeded it's deadline -func (msg MsgSwapExactForTokens) DeadlineExceeded(blockTime time.Time) bool { - return blockTime.Unix() >= msg.Deadline -} - -// NewMsgSwapForExactTokens returns a new MsgSwapForExactTokens -func NewMsgSwapForExactTokens(requester string, tokenA sdk.Coin, exactTokenB sdk.Coin, slippage sdk.Dec, deadline int64) *MsgSwapForExactTokens { - return &MsgSwapForExactTokens{ - Requester: requester, - TokenA: tokenA, - ExactTokenB: exactTokenB, - Slippage: slippage, - Deadline: deadline, - } -} - -// Route return the message type used for routing the message. -func (msg MsgSwapForExactTokens) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgSwapForExactTokens) Type() string { return TypeSwapForExactTokens } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgSwapForExactTokens) ValidateBasic() error { - if msg.Requester == "" { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "requester address cannot be empty") - } - - if _, err := sdk.AccAddressFromBech32(msg.Requester); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid requester address: %s", err) - } - - if !msg.TokenA.IsValid() || msg.TokenA.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "token a deposit amount %s", msg.TokenA) - } - - if !msg.ExactTokenB.IsValid() || msg.ExactTokenB.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "exact token b deposit amount %s", msg.ExactTokenB) - } - - if msg.TokenA.Denom == msg.ExactTokenB.Denom { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, "denominations can not be equal") - } - - if msg.Slippage.IsNil() { - return errorsmod.Wrapf(ErrInvalidSlippage, "slippage must be set") - } - - if msg.Slippage.IsNegative() { - return errorsmod.Wrapf(ErrInvalidSlippage, "slippage can not be negative") - } - - if msg.Deadline <= 0 { - return errorsmod.Wrapf(ErrInvalidDeadline, "deadline %d", msg.Deadline) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgSwapForExactTokens) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgSwapForExactTokens) GetSigners() []sdk.AccAddress { - requester, _ := sdk.AccAddressFromBech32(msg.Requester) - return []sdk.AccAddress{requester} -} - -// GetDeadline returns the time at which the msg is considered invalid -func (msg MsgSwapForExactTokens) GetDeadline() time.Time { - return time.Unix(msg.Deadline, 0) -} - -// DeadlineExceeded returns if the msg has exceeded it's deadline -func (msg MsgSwapForExactTokens) DeadlineExceeded(blockTime time.Time) bool { - return blockTime.Unix() >= msg.Deadline -} diff --git a/x/swap/types/msg_test.go b/x/swap/types/msg_test.go deleted file mode 100644 index ca155ee4..00000000 --- a/x/swap/types/msg_test.go +++ /dev/null @@ -1,766 +0,0 @@ -package types_test - -import ( - "testing" - "time" - - "github.com/kava-labs/kava/x/swap/types" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestMsgDeposit_Attributes(t *testing.T) { - msg := types.MsgDeposit{} - assert.Equal(t, "swap", msg.Route()) - assert.Equal(t, "swap_deposit", msg.Type()) -} - -func TestMsgDeposit_Signing(t *testing.T) { - signData := `{"type":"swap/MsgDeposit","value":{"deadline":"1623606299","depositor":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","slippage":"0.010000000000000000","token_a":{"amount":"1000000","denom":"ukava"},"token_b":{"amount":"5000000","denom":"usdx"}}}` - signBytes := []byte(signData) - - addr, err := sdk.AccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - require.NoError(t, err) - - msg := types.NewMsgDeposit(addr.String(), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), 1623606299) - assert.Equal(t, []sdk.AccAddress{addr}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsgDeposit_Validation(t *testing.T) { - addr, err := sdk.AccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - require.NoError(t, err) - - validMsg := types.NewMsgDeposit( - addr.String(), - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - sdk.MustNewDecFromStr("0.01"), - 1623606299, - ) - require.NoError(t, validMsg.ValidateBasic()) - - testCases := []struct { - name string - depositor string - tokenA sdk.Coin - tokenB sdk.Coin - slippage sdk.Dec - deadline int64 - expectedErr string - }{ - { - name: "empty address", - depositor: "", - tokenA: validMsg.TokenA, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "depositor address cannot be empty: invalid address", - }, - { - name: "invalid address", - depositor: "kava1abcde", - tokenA: validMsg.TokenA, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "invalid depositor address: decoding bech32 failed: invalid separator index 4: invalid address", - }, - { - name: "negative token a", - depositor: validMsg.Depositor, - tokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "token a deposit amount -1ukava: invalid coins", - }, - { - name: "zero token a", - depositor: validMsg.Depositor, - tokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(0)}, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "token a deposit amount 0ukava: invalid coins", - }, - { - name: "negative token b", - depositor: validMsg.Depositor, - tokenA: validMsg.TokenA, - tokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "token b deposit amount -1ukava: invalid coins", - }, - { - name: "zero token b", - depositor: validMsg.Depositor, - tokenA: validMsg.TokenA, - tokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(0)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "token b deposit amount 0ukava: invalid coins", - }, - { - name: "denoms can not be the same", - depositor: validMsg.Depositor, - tokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(1e6)}, - tokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(1e6)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "denominations can not be equal: invalid coins", - }, - { - name: "zero deadline", - depositor: validMsg.Depositor, - tokenA: validMsg.TokenA, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: 0, - expectedErr: "deadline 0: invalid deadline", - }, - { - name: "negative deadline", - depositor: validMsg.Depositor, - tokenA: validMsg.TokenA, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: -1, - expectedErr: "deadline -1: invalid deadline", - }, - { - name: "negative slippage", - depositor: validMsg.Depositor, - tokenA: validMsg.TokenA, - tokenB: validMsg.TokenB, - slippage: sdk.MustNewDecFromStr("-0.01"), - deadline: validMsg.Deadline, - expectedErr: "slippage can not be negative: invalid slippage", - }, - { - name: "nil slippage", - depositor: validMsg.Depositor, - tokenA: validMsg.TokenA, - tokenB: validMsg.TokenB, - slippage: sdk.Dec{}, - deadline: validMsg.Deadline, - expectedErr: "slippage must be set: invalid slippage", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := types.NewMsgDeposit(tc.depositor, tc.tokenA, tc.tokenB, tc.slippage, tc.deadline) - err := msg.ValidateBasic() - assert.EqualError(t, err, tc.expectedErr) - }) - } -} - -func TestMsgDeposit_Deadline(t *testing.T) { - blockTime := time.Now() - - testCases := []struct { - name string - deadline int64 - isExceeded bool - }{ - { - name: "deadline in future", - deadline: blockTime.Add(1 * time.Second).Unix(), - isExceeded: false, - }, - { - name: "deadline in past", - deadline: blockTime.Add(-1 * time.Second).Unix(), - isExceeded: true, - }, - { - name: "deadline is equal", - deadline: blockTime.Unix(), - isExceeded: true, - }, - } - - for _, tc := range testCases { - msg := types.NewMsgDeposit( - sdk.AccAddress("test1").String(), - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - sdk.MustNewDecFromStr("0.01"), - tc.deadline, - ) - require.NoError(t, msg.ValidateBasic()) - assert.Equal(t, tc.isExceeded, msg.DeadlineExceeded(blockTime)) - assert.Equal(t, time.Unix(tc.deadline, 0), msg.GetDeadline()) - } -} - -func TestMsgWithdraw_Attributes(t *testing.T) { - msg := types.MsgWithdraw{} - assert.Equal(t, "swap", msg.Route()) - assert.Equal(t, "swap_withdraw", msg.Type()) -} - -func TestMsgWithdraw_Signing(t *testing.T) { - signData := `{"type":"swap/MsgWithdraw","value":{"deadline":"1623606299","from":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","min_token_a":{"amount":"1000000","denom":"ukava"},"min_token_b":{"amount":"2000000","denom":"usdx"},"shares":"1500000"}}` - signBytes := []byte(signData) - - addr, err := sdk.AccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - require.NoError(t, err) - - msg := types.NewMsgWithdraw( - addr.String(), - sdkmath.NewInt(1500000), - sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), - sdk.NewCoin("usdx", sdkmath.NewInt(2000000)), - 1623606299, - ) - assert.Equal(t, []sdk.AccAddress{addr}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsgWithdraw_Validation(t *testing.T) { - validMsg := types.NewMsgWithdraw( - sdk.AccAddress("test1").String(), - sdkmath.NewInt(1500000), - sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), - sdk.NewCoin("usdx", sdkmath.NewInt(2000000)), - 1623606299, - ) - require.NoError(t, validMsg.ValidateBasic()) - - testCases := []struct { - name string - from string - shares sdkmath.Int - minTokenA sdk.Coin - minTokenB sdk.Coin - deadline int64 - expectedErr string - }{ - { - name: "empty address", - from: "", - shares: validMsg.Shares, - minTokenA: validMsg.MinTokenA, - minTokenB: validMsg.MinTokenB, - deadline: validMsg.Deadline, - expectedErr: "from address cannot be empty: invalid address", - }, - { - name: "invalid address", - from: "kava1abcde", - shares: validMsg.Shares, - minTokenA: validMsg.MinTokenA, - minTokenB: validMsg.MinTokenB, - deadline: validMsg.Deadline, - expectedErr: "invalid from address: decoding bech32 failed: invalid separator index 4: invalid address", - }, - { - name: "zero token a", - from: validMsg.From, - shares: validMsg.Shares, - minTokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(0)}, - minTokenB: validMsg.MinTokenB, - deadline: validMsg.Deadline, - expectedErr: "min token a amount 0ukava: invalid coins", - }, - { - name: "negative token b", - from: validMsg.From, - shares: validMsg.Shares, - minTokenA: validMsg.MinTokenA, - minTokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - deadline: validMsg.Deadline, - expectedErr: "min token b amount -1ukava: invalid coins", - }, - { - name: "zero token b", - from: validMsg.From, - shares: validMsg.Shares, - minTokenA: validMsg.MinTokenA, - minTokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(0)}, - deadline: validMsg.Deadline, - expectedErr: "min token b amount 0ukava: invalid coins", - }, - { - name: "denoms can not be the same", - from: validMsg.From, - shares: validMsg.Shares, - minTokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(1e6)}, - minTokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(1e6)}, - deadline: validMsg.Deadline, - expectedErr: "denominations can not be equal: invalid coins", - }, - { - name: "zero shares", - from: validMsg.From, - shares: sdk.ZeroInt(), - minTokenA: validMsg.MinTokenA, - minTokenB: validMsg.MinTokenB, - deadline: validMsg.Deadline, - expectedErr: "0: invalid shares", - }, - { - name: "negative shares", - from: validMsg.From, - shares: sdkmath.NewInt(-1), - minTokenA: validMsg.MinTokenA, - minTokenB: validMsg.MinTokenB, - deadline: validMsg.Deadline, - expectedErr: "-1: invalid shares", - }, - { - name: "nil shares", - from: validMsg.From, - shares: sdkmath.Int{}, - minTokenA: validMsg.MinTokenA, - minTokenB: validMsg.MinTokenB, - deadline: validMsg.Deadline, - expectedErr: "shares must be set: invalid shares", - }, - { - name: "zero deadline", - from: validMsg.From, - shares: validMsg.Shares, - minTokenA: validMsg.MinTokenA, - minTokenB: validMsg.MinTokenB, - deadline: 0, - expectedErr: "deadline 0: invalid deadline", - }, - { - name: "negative deadline", - from: validMsg.From, - shares: validMsg.Shares, - minTokenA: validMsg.MinTokenA, - minTokenB: validMsg.MinTokenB, - deadline: -1, - expectedErr: "deadline -1: invalid deadline", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := types.NewMsgWithdraw(tc.from, tc.shares, tc.minTokenA, tc.minTokenB, tc.deadline) - err := msg.ValidateBasic() - assert.EqualError(t, err, tc.expectedErr) - }) - } -} - -func TestMsgWithdraw_Deadline(t *testing.T) { - blockTime := time.Now() - - testCases := []struct { - name string - deadline int64 - isExceeded bool - }{ - { - name: "deadline in future", - deadline: blockTime.Add(1 * time.Second).Unix(), - isExceeded: false, - }, - { - name: "deadline in past", - deadline: blockTime.Add(-1 * time.Second).Unix(), - isExceeded: true, - }, - { - name: "deadline is equal", - deadline: blockTime.Unix(), - isExceeded: true, - }, - } - - for _, tc := range testCases { - msg := types.NewMsgWithdraw( - sdk.AccAddress("test1").String(), - sdkmath.NewInt(1500000), - sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), - sdk.NewCoin("usdx", sdkmath.NewInt(2000000)), - tc.deadline, - ) - require.NoError(t, msg.ValidateBasic()) - assert.Equal(t, tc.isExceeded, msg.DeadlineExceeded(blockTime)) - assert.Equal(t, time.Unix(tc.deadline, 0), msg.GetDeadline()) - } -} - -func TestMsgSwapExactForTokens_Attributes(t *testing.T) { - msg := types.MsgSwapExactForTokens{} - assert.Equal(t, "swap", msg.Route()) - assert.Equal(t, "swap_exact_for_tokens", msg.Type()) -} - -func TestMsgSwapExactForTokens_Signing(t *testing.T) { - signData := `{"type":"swap/MsgSwapExactForTokens","value":{"deadline":"1623606299","exact_token_a":{"amount":"1000000","denom":"ukava"},"requester":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","slippage":"0.010000000000000000","token_b":{"amount":"5000000","denom":"usdx"}}}` - signBytes := []byte(signData) - - addr, err := sdk.AccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - require.NoError(t, err) - - msg := types.NewMsgSwapExactForTokens(addr.String(), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), 1623606299) - assert.Equal(t, []sdk.AccAddress{addr}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsgSwapExactForTokens_Validation(t *testing.T) { - validMsg := types.NewMsgSwapExactForTokens( - sdk.AccAddress("test1").String(), - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - sdk.MustNewDecFromStr("0.01"), - 1623606299, - ) - require.NoError(t, validMsg.ValidateBasic()) - - testCases := []struct { - name string - requester string - exactTokenA sdk.Coin - tokenB sdk.Coin - slippage sdk.Dec - deadline int64 - expectedErr string - }{ - { - name: "empty address", - requester: sdk.AccAddress("").String(), - exactTokenA: validMsg.ExactTokenA, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "requester address cannot be empty: invalid address", - }, - { - name: "invalid address", - requester: "kava1abcde", - exactTokenA: validMsg.ExactTokenA, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "invalid requester address: decoding bech32 failed: invalid separator index 4: invalid address", - }, - { - name: "negative token a", - requester: validMsg.Requester, - exactTokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "exact token a deposit amount -1ukava: invalid coins", - }, - { - name: "zero token a", - requester: validMsg.Requester, - exactTokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(0)}, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "exact token a deposit amount 0ukava: invalid coins", - }, - { - name: "negative token b", - requester: validMsg.Requester, - exactTokenA: validMsg.ExactTokenA, - tokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "token b deposit amount -1ukava: invalid coins", - }, - { - name: "zero token b", - requester: validMsg.Requester, - exactTokenA: validMsg.ExactTokenA, - tokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(0)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "token b deposit amount 0ukava: invalid coins", - }, - { - name: "denoms can not be the same", - requester: validMsg.Requester, - exactTokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(1e6)}, - tokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(1e6)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "denominations can not be equal: invalid coins", - }, - { - name: "zero deadline", - requester: validMsg.Requester, - exactTokenA: validMsg.ExactTokenA, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: 0, - expectedErr: "deadline 0: invalid deadline", - }, - { - name: "negative deadline", - requester: validMsg.Requester, - exactTokenA: validMsg.ExactTokenA, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: -1, - expectedErr: "deadline -1: invalid deadline", - }, - { - name: "negative slippage", - requester: validMsg.Requester, - exactTokenA: validMsg.ExactTokenA, - tokenB: validMsg.TokenB, - slippage: sdk.MustNewDecFromStr("-0.01"), - deadline: validMsg.Deadline, - expectedErr: "slippage can not be negative: invalid slippage", - }, - { - name: "nil slippage", - requester: validMsg.Requester, - exactTokenA: validMsg.ExactTokenA, - tokenB: validMsg.TokenB, - slippage: sdk.Dec{}, - deadline: validMsg.Deadline, - expectedErr: "slippage must be set: invalid slippage", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := types.NewMsgSwapExactForTokens(tc.requester, tc.exactTokenA, tc.tokenB, tc.slippage, tc.deadline) - err := msg.ValidateBasic() - assert.EqualError(t, err, tc.expectedErr) - }) - } -} - -func TestMsgSwapExactForTokens_Deadline(t *testing.T) { - blockTime := time.Now() - - testCases := []struct { - name string - deadline int64 - isExceeded bool - }{ - { - name: "deadline in future", - deadline: blockTime.Add(1 * time.Second).Unix(), - isExceeded: false, - }, - { - name: "deadline in past", - deadline: blockTime.Add(-1 * time.Second).Unix(), - isExceeded: true, - }, - { - name: "deadline is equal", - deadline: blockTime.Unix(), - isExceeded: true, - }, - } - - for _, tc := range testCases { - msg := types.NewMsgSwapExactForTokens( - sdk.AccAddress("test1").String(), - sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), - sdk.NewCoin("usdx", sdkmath.NewInt(2000000)), - sdk.MustNewDecFromStr("0.01"), - tc.deadline, - ) - require.NoError(t, msg.ValidateBasic()) - assert.Equal(t, tc.isExceeded, msg.DeadlineExceeded(blockTime)) - assert.Equal(t, time.Unix(tc.deadline, 0), msg.GetDeadline()) - } -} - -func TestMsgSwapForExactTokens_Attributes(t *testing.T) { - msg := types.MsgSwapForExactTokens{} - assert.Equal(t, "swap", msg.Route()) - assert.Equal(t, "swap_for_exact_tokens", msg.Type()) -} - -func TestMsgSwapForExactTokens_Signing(t *testing.T) { - signData := `{"type":"swap/MsgSwapForExactTokens","value":{"deadline":"1623606299","exact_token_b":{"amount":"5000000","denom":"usdx"},"requester":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","slippage":"0.010000000000000000","token_a":{"amount":"1000000","denom":"ukava"}}}` - signBytes := []byte(signData) - - addr, err := sdk.AccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - require.NoError(t, err) - - msg := types.NewMsgSwapForExactTokens(addr.String(), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), 1623606299) - assert.Equal(t, []sdk.AccAddress{addr}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsgSwapForExactTokens_Validation(t *testing.T) { - validMsg := types.NewMsgSwapForExactTokens( - sdk.AccAddress("test1").String(), - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - sdk.MustNewDecFromStr("0.01"), - 1623606299, - ) - require.NoError(t, validMsg.ValidateBasic()) - - testCases := []struct { - name string - requester string - tokenA sdk.Coin - exactTokenB sdk.Coin - slippage sdk.Dec - deadline int64 - expectedErr string - }{ - { - name: "empty address", - requester: sdk.AccAddress("").String(), - tokenA: validMsg.TokenA, - exactTokenB: validMsg.ExactTokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "requester address cannot be empty: invalid address", - }, - { - name: "invalid address", - requester: "kava1abcde", - tokenA: validMsg.TokenA, - exactTokenB: validMsg.ExactTokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "invalid requester address: decoding bech32 failed: invalid separator index 4: invalid address", - }, - { - name: "negative token a", - requester: validMsg.Requester, - tokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - exactTokenB: validMsg.ExactTokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "token a deposit amount -1ukava: invalid coins", - }, - { - name: "zero token a", - requester: validMsg.Requester, - tokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(0)}, - exactTokenB: validMsg.ExactTokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "token a deposit amount 0ukava: invalid coins", - }, - { - name: "negative token b", - requester: validMsg.Requester, - tokenA: validMsg.TokenA, - exactTokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "exact token b deposit amount -1ukava: invalid coins", - }, - { - name: "zero token b", - requester: validMsg.Requester, - tokenA: validMsg.TokenA, - exactTokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(0)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "exact token b deposit amount 0ukava: invalid coins", - }, - { - name: "denoms can not be the same", - requester: validMsg.Requester, - tokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(1e6)}, - exactTokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(1e6)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "denominations can not be equal: invalid coins", - }, - { - name: "zero deadline", - requester: validMsg.Requester, - tokenA: validMsg.TokenA, - exactTokenB: validMsg.ExactTokenB, - slippage: validMsg.Slippage, - deadline: 0, - expectedErr: "deadline 0: invalid deadline", - }, - { - name: "negative deadline", - requester: validMsg.Requester, - tokenA: validMsg.TokenA, - exactTokenB: validMsg.ExactTokenB, - slippage: validMsg.Slippage, - deadline: -1, - expectedErr: "deadline -1: invalid deadline", - }, - { - name: "negative slippage", - requester: validMsg.Requester, - tokenA: validMsg.TokenA, - exactTokenB: validMsg.ExactTokenB, - slippage: sdk.MustNewDecFromStr("-0.01"), - deadline: validMsg.Deadline, - expectedErr: "slippage can not be negative: invalid slippage", - }, - { - name: "nil slippage", - requester: validMsg.Requester, - tokenA: validMsg.TokenA, - exactTokenB: validMsg.ExactTokenB, - slippage: sdk.Dec{}, - deadline: validMsg.Deadline, - expectedErr: "slippage must be set: invalid slippage", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := types.NewMsgSwapForExactTokens(tc.requester, tc.tokenA, tc.exactTokenB, tc.slippage, tc.deadline) - err := msg.ValidateBasic() - assert.EqualError(t, err, tc.expectedErr) - }) - } -} - -func TestMsgSwapForExactTokens_Deadline(t *testing.T) { - blockTime := time.Now() - - testCases := []struct { - name string - deadline int64 - isExceeded bool - }{ - { - name: "deadline in future", - deadline: blockTime.Add(1 * time.Second).Unix(), - isExceeded: false, - }, - { - name: "deadline in past", - deadline: blockTime.Add(-1 * time.Second).Unix(), - isExceeded: true, - }, - { - name: "deadline is equal", - deadline: blockTime.Unix(), - isExceeded: true, - }, - } - - for _, tc := range testCases { - msg := types.NewMsgSwapForExactTokens( - sdk.AccAddress("test1").String(), - sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), - sdk.NewCoin("usdx", sdkmath.NewInt(2000000)), - sdk.MustNewDecFromStr("0.01"), - tc.deadline, - ) - require.NoError(t, msg.ValidateBasic()) - assert.Equal(t, tc.isExceeded, msg.DeadlineExceeded(blockTime)) - assert.Equal(t, time.Unix(tc.deadline, 0), msg.GetDeadline()) - } -} diff --git a/x/swap/types/params.go b/x/swap/types/params.go deleted file mode 100644 index 6cd67964..00000000 --- a/x/swap/types/params.go +++ /dev/null @@ -1,173 +0,0 @@ -package types - -import ( - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// Parameter keys and default values -var ( - KeyAllowedPools = []byte("AllowedPools") - KeySwapFee = []byte("SwapFee") - DefaultAllowedPools = AllowedPools{} - DefaultSwapFee = sdk.ZeroDec() - MaxSwapFee = sdk.OneDec() -) - -// NewParams returns a new params object -func NewParams(pairs AllowedPools, swapFee sdk.Dec) Params { - return Params{ - AllowedPools: pairs, - SwapFee: swapFee, - } -} - -// DefaultParams returns default params for swap module -func DefaultParams() Params { - return NewParams( - DefaultAllowedPools, - DefaultSwapFee, - ) -} - -// String implements fmt.Stringer -func (p Params) String() string { - return fmt.Sprintf(`Params: - AllowedPools: %s - SwapFee: %s`, - p.AllowedPools, p.SwapFee) -} - -// ParamKeyTable for swap module. -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements params.ParamSet -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyAllowedPools, &p.AllowedPools, validateAllowedPoolsParams), - paramtypes.NewParamSetPair(KeySwapFee, &p.SwapFee, validateSwapFee), - } -} - -// Validate checks that the parameters have valid values. -func (p Params) Validate() error { - if err := validateAllowedPoolsParams(p.AllowedPools); err != nil { - return err - } - - return validateSwapFee(p.SwapFee) -} - -func validateAllowedPoolsParams(i interface{}) error { - p, ok := i.(AllowedPools) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return p.Validate() -} - -func validateSwapFee(i interface{}) error { - swapFee, ok := i.(sdk.Dec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if swapFee.IsNil() || swapFee.IsNegative() || swapFee.GTE(MaxSwapFee) { - return fmt.Errorf(fmt.Sprintf("invalid swap fee: %s", swapFee)) - } - - return nil -} - -// NewAllowedPool returns a new AllowedPool object -func NewAllowedPool(tokenA, tokenB string) AllowedPool { - return AllowedPool{ - TokenA: tokenA, - TokenB: tokenB, - } -} - -// Validate validates allowedPool attributes and returns an error if invalid -func (p AllowedPool) Validate() error { - err := sdk.ValidateDenom(p.TokenA) - if err != nil { - return err - } - - err = sdk.ValidateDenom(p.TokenB) - if err != nil { - return err - } - - // Ensure there is no colon in the token denoms as they are used as separators - // and is now valid in Cosmos denoms. - if strings.Contains(p.TokenA, ":") { - return fmt.Errorf("tokenA cannot have colons in the denom: %s", p.TokenA) - } - - if strings.Contains(p.TokenB, ":") { - return fmt.Errorf("tokenB cannot have colons in the denom: %s", p.TokenB) - } - - if p.TokenA == p.TokenB { - return fmt.Errorf( - "pool cannot have two tokens of the same type, received '%s' and '%s'", - p.TokenA, p.TokenB, - ) - } - - if p.TokenA > p.TokenB { - return fmt.Errorf( - "invalid token order: '%s' must come before '%s'", - p.TokenB, p.TokenA, - ) - } - - return nil -} - -// Name returns the name for the allowed pool -func (p AllowedPool) Name() string { - return PoolID(p.TokenA, p.TokenB) -} - -// String pretty prints the allowedPool -func (p AllowedPool) String() string { - return fmt.Sprintf(`AllowedPool: - Name: %s - Token A: %s - Token B: %s -`, p.Name(), p.TokenA, p.TokenB) -} - -// AllowedPools is a slice of AllowedPool -type AllowedPools []AllowedPool - -// NewAllowedPools returns AllowedPools from the provided values -func NewAllowedPools(allowedPools ...AllowedPool) AllowedPools { - return AllowedPools(allowedPools) -} - -// Validate validates each allowedPool and returns an error if there are any duplicates -func (p AllowedPools) Validate() error { - seenAllowedPools := make(map[string]bool) - for _, allowedPool := range p { - err := allowedPool.Validate() - if err != nil { - return err - } - - if seen := seenAllowedPools[allowedPool.Name()]; seen { - return fmt.Errorf("duplicate pool: %s", allowedPool.Name()) - } - seenAllowedPools[allowedPool.Name()] = true - } - - return nil -} diff --git a/x/swap/types/params_test.go b/x/swap/types/params_test.go deleted file mode 100644 index 50598166..00000000 --- a/x/swap/types/params_test.go +++ /dev/null @@ -1,396 +0,0 @@ -package types_test - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "strings" - "testing" - - "github.com/kava-labs/kava/x/swap/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "sigs.k8s.io/yaml" -) - -func TestParams_UnmarshalJSON(t *testing.T) { - pools := types.NewAllowedPools( - types.NewAllowedPool("hard", "ukava"), - types.NewAllowedPool("hard", "usdx"), - ) - poolData, err := json.Marshal(pools) - require.NoError(t, err) - - fee, err := sdk.NewDecFromStr("0.5") - require.NoError(t, err) - feeData, err := json.Marshal(fee) - require.NoError(t, err) - - data := fmt.Sprintf(`{ - "allowed_pools": %s, - "swap_fee": %s -}`, string(poolData), string(feeData)) - - var params types.Params - err = json.Unmarshal([]byte(data), ¶ms) - require.NoError(t, err) - - assert.Equal(t, pools, params.AllowedPools) - assert.Equal(t, fee, params.SwapFee) -} - -func TestParams_MarshalYAML(t *testing.T) { - pools := types.NewAllowedPools( - types.NewAllowedPool("hard", "ukava"), - types.NewAllowedPool("hard", "usdx"), - ) - fee, err := sdk.NewDecFromStr("0.5") - require.NoError(t, err) - - p := types.Params{ - AllowedPools: pools, - SwapFee: fee, - } - - data, err := yaml.Marshal(p) - require.NoError(t, err) - - var params map[string]interface{} - err = yaml.Unmarshal(data, ¶ms) - require.NoError(t, err) - - _, ok := params["allowed_pools"] - require.True(t, ok) - _, ok = params["swap_fee"] - require.True(t, ok) -} - -func TestParams_Default(t *testing.T) { - defaultParams := types.DefaultParams() - - require.NoError(t, defaultParams.Validate()) - - assert.Equal(t, types.DefaultAllowedPools, defaultParams.AllowedPools) - assert.Equal(t, types.DefaultSwapFee, defaultParams.SwapFee) - - assert.Equal(t, 0, len(defaultParams.AllowedPools)) - assert.Equal(t, sdk.ZeroDec(), defaultParams.SwapFee) -} - -func TestParams_ParamSetPairs_AllowedPools(t *testing.T) { - assert.Equal(t, []byte("AllowedPools"), types.KeyAllowedPools) - defaultParams := types.DefaultParams() - - var paramSetPair *paramstypes.ParamSetPair - for _, pair := range defaultParams.ParamSetPairs() { - if bytes.Equal(pair.Key, types.KeyAllowedPools) { - paramSetPair = &pair - break - } - } - require.NotNil(t, paramSetPair) - - pairs, ok := paramSetPair.Value.(*types.AllowedPools) - require.True(t, ok) - assert.Equal(t, pairs, &defaultParams.AllowedPools) - - assert.Nil(t, paramSetPair.ValidatorFn(*pairs)) - assert.EqualError(t, paramSetPair.ValidatorFn(struct{}{}), "invalid parameter type: struct {}") -} - -func TestParams_ParamSetPairs_SwapFee(t *testing.T) { - assert.Equal(t, []byte("SwapFee"), types.KeySwapFee) - defaultParams := types.DefaultParams() - - var paramSetPair *paramstypes.ParamSetPair - for _, pair := range defaultParams.ParamSetPairs() { - if bytes.Equal(pair.Key, types.KeySwapFee) { - paramSetPair = &pair - break - } - } - require.NotNil(t, paramSetPair) - - swapFee, ok := paramSetPair.Value.(*sdk.Dec) - require.True(t, ok) - assert.Equal(t, swapFee, &defaultParams.SwapFee) - - assert.Nil(t, paramSetPair.ValidatorFn(*swapFee)) - assert.EqualError(t, paramSetPair.ValidatorFn(struct{}{}), "invalid parameter type: struct {}") -} - -func TestParams_Validation(t *testing.T) { - testCases := []struct { - name string - key []byte - testFn func(params *types.Params) - expectedErr string - }{ - { - name: "duplicate pools", - key: types.KeyAllowedPools, - testFn: func(params *types.Params) { - params.AllowedPools = types.NewAllowedPools(types.NewAllowedPool("ukava", "ukava")) - }, - expectedErr: "pool cannot have two tokens of the same type, received 'ukava' and 'ukava'", - }, - { - name: "nil swap fee", - key: types.KeySwapFee, - testFn: func(params *types.Params) { - params.SwapFee = sdk.Dec{} - }, - expectedErr: "invalid swap fee: ", - }, - { - name: "negative swap fee", - key: types.KeySwapFee, - testFn: func(params *types.Params) { - params.SwapFee = sdk.NewDec(-1) - }, - expectedErr: "invalid swap fee: -1.000000000000000000", - }, - { - name: "swap fee greater than 1", - key: types.KeySwapFee, - testFn: func(params *types.Params) { - params.SwapFee = sdk.MustNewDecFromStr("1.000000000000000001") - }, - expectedErr: "invalid swap fee: 1.000000000000000001", - }, - { - name: "0 swap fee", - key: types.KeySwapFee, - testFn: func(params *types.Params) { - params.SwapFee = sdk.ZeroDec() - }, - expectedErr: "", - }, - { - name: "1 swap fee", - key: types.KeySwapFee, - testFn: func(params *types.Params) { - params.SwapFee = sdk.OneDec() - }, - expectedErr: "invalid swap fee: 1.000000000000000000", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - params := types.DefaultParams() - tc.testFn(¶ms) - - err := params.Validate() - - if tc.expectedErr == "" { - assert.Nil(t, err) - } else { - assert.EqualError(t, err, tc.expectedErr) - } - - var paramSetPair *paramstypes.ParamSetPair - for _, pair := range params.ParamSetPairs() { - if bytes.Equal(pair.Key, tc.key) { - paramSetPair = &pair - break - } - } - require.NotNil(t, paramSetPair) - value := reflect.ValueOf(paramSetPair.Value).Elem().Interface() - - // assert validation error is same as param set validation - assert.Equal(t, err, paramSetPair.ValidatorFn(value)) - }) - } -} - -func TestParams_String(t *testing.T) { - params := types.NewParams( - types.NewAllowedPools( - types.NewAllowedPool("hard", "ukava"), - types.NewAllowedPool("ukava", "usdx"), - ), - sdk.MustNewDecFromStr("0.5"), - ) - - require.NoError(t, params.Validate()) - - output := params.String() - assert.Contains(t, output, types.PoolID("hard", "ukava")) - assert.Contains(t, output, types.PoolID("ukava", "usdx")) - assert.Contains(t, output, "0.5") -} - -func TestAllowedPool_Validation(t *testing.T) { - testCases := []struct { - name string - allowedPool types.AllowedPool - expectedErr string - }{ - { - name: "blank token a", - allowedPool: types.NewAllowedPool("", "ukava"), - expectedErr: "invalid denom: ", - }, - { - name: "blank token b", - allowedPool: types.NewAllowedPool("ukava", ""), - expectedErr: "invalid denom: ", - }, - { - name: "invalid token a", - allowedPool: types.NewAllowedPool("1ukava", "ukava"), - expectedErr: "invalid denom: 1ukava", - }, - { - name: "invalid token b", - allowedPool: types.NewAllowedPool("ukava", "1ukava"), - expectedErr: "invalid denom: 1ukava", - }, - { - name: "matching tokens", - allowedPool: types.NewAllowedPool("ukava", "ukava"), - expectedErr: "pool cannot have two tokens of the same type, received 'ukava' and 'ukava'", - }, - { - name: "invalid token order", - allowedPool: types.NewAllowedPool("usdx", "ukava"), - expectedErr: "invalid token order: 'ukava' must come before 'usdx'", - }, - { - name: "invalid token order due to capitalization", - allowedPool: types.NewAllowedPool("ukava", "UKAVA"), - expectedErr: "invalid token order: 'UKAVA' must come before 'ukava'", - }, - { - name: "invalid token a with colon", - allowedPool: types.NewAllowedPool("test:denom", "ukava"), - expectedErr: "tokenA cannot have colons in the denom: test:denom", - }, - { - name: "invalid token b with colon", - allowedPool: types.NewAllowedPool("ukava", "u:kava"), - expectedErr: "tokenB cannot have colons in the denom: u:kava", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.allowedPool.Validate() - assert.EqualError(t, err, tc.expectedErr) - }) - } -} - -func TestAllowedPool_TokenMatch_CaseSensitive(t *testing.T) { - allowedPool := types.NewAllowedPool("UKAVA", "ukava") - err := allowedPool.Validate() - assert.NoError(t, err) - - allowedPool = types.NewAllowedPool("haRd", "hard") - err = allowedPool.Validate() - assert.NoError(t, err) - - allowedPool = types.NewAllowedPool("Usdx", "uSdX") - err = allowedPool.Validate() - assert.NoError(t, err) -} - -func TestAllowedPool_String(t *testing.T) { - allowedPool := types.NewAllowedPool("hard", "ukava") - require.NoError(t, allowedPool.Validate()) - - output := `AllowedPool: - Name: hard:ukava - Token A: hard - Token B: ukava -` - assert.Equal(t, output, allowedPool.String()) -} - -func TestAllowedPool_Name(t *testing.T) { - testCases := []struct { - tokens string - name string - }{ - { - tokens: "atoken btoken", - name: "atoken:btoken", - }, - { - tokens: "aaa aaaa", - name: "aaa:aaaa", - }, - { - tokens: "aaaa aaab", - name: "aaaa:aaab", - }, - { - tokens: "a001 a002", - name: "a001:a002", - }, - { - tokens: "hard ukava", - name: "hard:ukava", - }, - { - tokens: "bnb hard", - name: "bnb:hard", - }, - { - tokens: "bnb xrpb", - name: "bnb:xrpb", - }, - } - - for _, tc := range testCases { - t.Run(tc.tokens, func(t *testing.T) { - tokens := strings.Split(tc.tokens, " ") - require.Equal(t, 2, len(tokens)) - - allowedPool := types.NewAllowedPool(tokens[0], tokens[1]) - require.NoError(t, allowedPool.Validate()) - - assert.Equal(t, tc.name, allowedPool.Name()) - }) - } -} - -func TestAllowedPools_Validate(t *testing.T) { - testCases := []struct { - name string - allowedPools types.AllowedPools - expectedErr string - }{ - { - name: "duplicate pool", - allowedPools: types.NewAllowedPools( - types.NewAllowedPool("hard", "ukava"), - types.NewAllowedPool("hard", "ukava"), - ), - expectedErr: "duplicate pool: hard:ukava", - }, - { - name: "duplicate pools", - allowedPools: types.NewAllowedPools( - types.NewAllowedPool("hard", "ukava"), - types.NewAllowedPool("bnb", "usdx"), - types.NewAllowedPool("btcb", "xrpb"), - types.NewAllowedPool("bnb", "usdx"), - ), - expectedErr: "duplicate pool: bnb:usdx", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.allowedPools.Validate() - assert.EqualError(t, err, tc.expectedErr) - }) - } -} diff --git a/x/swap/types/query.pb.go b/x/swap/types/query.pb.go deleted file mode 100644 index fc239a03..00000000 --- a/x/swap/types/query.pb.go +++ /dev/null @@ -1,2191 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/swap/v1beta1/query.proto - -package types - -import ( - context "context" - 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" - 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 defines the request type for querying x/swap parameters. -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_652c07bb38685396, []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 defines the response type for querying x/swap parameters. -type QueryParamsResponse struct { - // params represents the swap module parameters - 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_652c07bb38685396, []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 - -// QueryPoolsRequest is the request type for the Query/Pools RPC method. -type QueryPoolsRequest struct { - // pool_id filters pools by id - PoolId string `protobuf:"bytes,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryPoolsRequest) Reset() { *m = QueryPoolsRequest{} } -func (m *QueryPoolsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryPoolsRequest) ProtoMessage() {} -func (*QueryPoolsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_652c07bb38685396, []int{2} -} -func (m *QueryPoolsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPoolsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPoolsRequest.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 *QueryPoolsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPoolsRequest.Merge(m, src) -} -func (m *QueryPoolsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryPoolsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPoolsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPoolsRequest proto.InternalMessageInfo - -func (m *QueryPoolsRequest) GetPoolId() string { - if m != nil { - return m.PoolId - } - return "" -} - -func (m *QueryPoolsRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryPoolsResponse is the response type for the Query/Pools RPC method. -type QueryPoolsResponse struct { - // pools represents returned pools - Pools []PoolResponse `protobuf:"bytes,1,rep,name=pools,proto3" json:"pools"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryPoolsResponse) Reset() { *m = QueryPoolsResponse{} } -func (m *QueryPoolsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryPoolsResponse) ProtoMessage() {} -func (*QueryPoolsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_652c07bb38685396, []int{3} -} -func (m *QueryPoolsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPoolsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPoolsResponse.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 *QueryPoolsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPoolsResponse.Merge(m, src) -} -func (m *QueryPoolsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryPoolsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPoolsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPoolsResponse proto.InternalMessageInfo - -func (m *QueryPoolsResponse) GetPools() []PoolResponse { - if m != nil { - return m.Pools - } - return nil -} - -func (m *QueryPoolsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// Pool represents the state of a single pool -type PoolResponse struct { - // name represents the name of the pool - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // coins represents the total reserves of the pool - Coins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=coins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"coins"` - // total_shares represents the total shares of the pool - TotalShares github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=total_shares,json=totalShares,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"total_shares"` -} - -func (m *PoolResponse) Reset() { *m = PoolResponse{} } -func (m *PoolResponse) String() string { return proto.CompactTextString(m) } -func (*PoolResponse) ProtoMessage() {} -func (*PoolResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_652c07bb38685396, []int{4} -} -func (m *PoolResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *PoolResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PoolResponse.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 *PoolResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_PoolResponse.Merge(m, src) -} -func (m *PoolResponse) XXX_Size() int { - return m.Size() -} -func (m *PoolResponse) XXX_DiscardUnknown() { - xxx_messageInfo_PoolResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_PoolResponse proto.InternalMessageInfo - -// QueryDepositsRequest is the request type for the Query/Deposits RPC method. -type QueryDepositsRequest struct { - // owner optionally filters deposits by owner - Owner string `protobuf:"bytes,1,opt,name=owner,proto3" json:"owner,omitempty"` - // pool_id optionally fitlers deposits by pool id - PoolId string `protobuf:"bytes,2,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDepositsRequest) Reset() { *m = QueryDepositsRequest{} } -func (m *QueryDepositsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsRequest) ProtoMessage() {} -func (*QueryDepositsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_652c07bb38685396, []int{5} -} -func (m *QueryDepositsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsRequest.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 *QueryDepositsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsRequest.Merge(m, src) -} -func (m *QueryDepositsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsRequest proto.InternalMessageInfo - -// QueryDepositsResponse is the response type for the Query/Deposits RPC method. -type QueryDepositsResponse struct { - // deposits returns the deposits matching the requested parameters - Deposits []DepositResponse `protobuf:"bytes,1,rep,name=deposits,proto3" json:"deposits"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDepositsResponse) Reset() { *m = QueryDepositsResponse{} } -func (m *QueryDepositsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsResponse) ProtoMessage() {} -func (*QueryDepositsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_652c07bb38685396, []int{6} -} -func (m *QueryDepositsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsResponse.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 *QueryDepositsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsResponse.Merge(m, src) -} -func (m *QueryDepositsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsResponse proto.InternalMessageInfo - -// DepositResponse defines a single deposit query response type. -type DepositResponse struct { - // depositor represents the owner of the deposit - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - // pool_id represents the pool the deposit is for - PoolId string `protobuf:"bytes,2,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` - // shares_owned presents the shares owned by the depositor for the pool - SharesOwned github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=shares_owned,json=sharesOwned,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"shares_owned"` - // shares_value represents the coin value of the shares_owned - SharesValue github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,4,rep,name=shares_value,json=sharesValue,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"shares_value"` -} - -func (m *DepositResponse) Reset() { *m = DepositResponse{} } -func (m *DepositResponse) String() string { return proto.CompactTextString(m) } -func (*DepositResponse) ProtoMessage() {} -func (*DepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_652c07bb38685396, []int{7} -} -func (m *DepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DepositResponse.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 *DepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_DepositResponse.Merge(m, src) -} -func (m *DepositResponse) XXX_Size() int { - return m.Size() -} -func (m *DepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_DepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_DepositResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.swap.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.swap.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryPoolsRequest)(nil), "kava.swap.v1beta1.QueryPoolsRequest") - proto.RegisterType((*QueryPoolsResponse)(nil), "kava.swap.v1beta1.QueryPoolsResponse") - proto.RegisterType((*PoolResponse)(nil), "kava.swap.v1beta1.PoolResponse") - proto.RegisterType((*QueryDepositsRequest)(nil), "kava.swap.v1beta1.QueryDepositsRequest") - proto.RegisterType((*QueryDepositsResponse)(nil), "kava.swap.v1beta1.QueryDepositsResponse") - proto.RegisterType((*DepositResponse)(nil), "kava.swap.v1beta1.DepositResponse") -} - -func init() { proto.RegisterFile("kava/swap/v1beta1/query.proto", fileDescriptor_652c07bb38685396) } - -var fileDescriptor_652c07bb38685396 = []byte{ - // 747 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x55, 0xcf, 0x4f, 0x13, 0x4d, - 0x18, 0xee, 0xf6, 0xd7, 0x07, 0x53, 0x92, 0x2f, 0xcc, 0xc7, 0x17, 0xdb, 0x05, 0xb6, 0x58, 0x05, - 0x1a, 0x93, 0xee, 0x0a, 0x26, 0x9a, 0xa8, 0x07, 0xad, 0x04, 0xc3, 0x49, 0x5d, 0x8c, 0x07, 0x2f, - 0xcd, 0x94, 0x9d, 0x2c, 0x1b, 0xb6, 0x3b, 0xcb, 0xce, 0xb4, 0x88, 0x27, 0xc3, 0xc9, 0xa3, 0x89, - 0x37, 0x4f, 0x9e, 0x8d, 0xde, 0xf8, 0x0f, 0xbc, 0x70, 0x24, 0x78, 0x31, 0x1e, 0xd0, 0x80, 0x47, - 0xff, 0x08, 0x33, 0x3f, 0xb6, 0x94, 0x76, 0xb1, 0x6a, 0x38, 0x75, 0x77, 0xde, 0xf7, 0x7d, 0x9e, - 0xe7, 0x7d, 0xdf, 0x67, 0xa7, 0x60, 0x7a, 0x03, 0x75, 0x90, 0x45, 0xb7, 0x50, 0x68, 0x75, 0x16, - 0x9a, 0x98, 0xa1, 0x05, 0x6b, 0xb3, 0x8d, 0xa3, 0x6d, 0x33, 0x8c, 0x08, 0x23, 0x70, 0x9c, 0x87, - 0x4d, 0x1e, 0x36, 0x55, 0x58, 0xbf, 0xb2, 0x46, 0x68, 0x8b, 0x50, 0xab, 0x89, 0x28, 0x96, 0xb9, - 0xdd, 0xca, 0x10, 0xb9, 0x5e, 0x80, 0x98, 0x47, 0x02, 0x59, 0xae, 0x1b, 0xbd, 0xb9, 0x71, 0xd6, - 0x1a, 0xf1, 0xe2, 0x78, 0x49, 0xc6, 0x1b, 0xe2, 0xcd, 0x92, 0x2f, 0x2a, 0x34, 0xe1, 0x12, 0x97, - 0xc8, 0x73, 0xfe, 0xa4, 0x4e, 0xa7, 0x5c, 0x42, 0x5c, 0x1f, 0x5b, 0x28, 0xf4, 0x2c, 0x14, 0x04, - 0x84, 0x09, 0xb6, 0xb8, 0x66, 0x6a, 0xb0, 0x19, 0x21, 0x5d, 0x44, 0x2b, 0x3a, 0x80, 0x8f, 0xb8, - 0xdc, 0x87, 0x28, 0x42, 0x2d, 0x6a, 0xe3, 0xcd, 0x36, 0xa6, 0xec, 0x66, 0xf6, 0xe5, 0xdb, 0x72, - 0xaa, 0xf2, 0x18, 0xfc, 0x77, 0x2a, 0x46, 0x43, 0x12, 0x50, 0x0c, 0x6f, 0x80, 0x7c, 0x28, 0x4e, - 0x8a, 0xda, 0x8c, 0x56, 0x2d, 0x2c, 0x96, 0xcc, 0x81, 0x79, 0x98, 0xb2, 0xa4, 0x9e, 0xdd, 0x3b, - 0x2c, 0xa7, 0x6c, 0x95, 0xae, 0x50, 0x19, 0x18, 0x97, 0xa8, 0x84, 0xf8, 0x31, 0x21, 0xbc, 0x00, - 0xfe, 0x09, 0x09, 0xf1, 0x1b, 0x9e, 0x23, 0x40, 0x47, 0xed, 0x3c, 0x7f, 0x5d, 0x71, 0xe0, 0x32, - 0x00, 0x27, 0x03, 0x2c, 0xa6, 0x05, 0xe1, 0x9c, 0xa9, 0x86, 0xc2, 0x27, 0x68, 0xca, 0xcd, 0x9c, - 0x10, 0xbb, 0x58, 0x81, 0xda, 0x3d, 0x95, 0x95, 0x37, 0x5a, 0xdc, 0xa8, 0xa4, 0x55, 0xbd, 0xdc, - 0x02, 0x39, 0x4e, 0xc4, 0x5b, 0xc9, 0x54, 0x0b, 0x8b, 0xe5, 0xa4, 0x56, 0x08, 0xf1, 0xe3, 0x7c, - 0xd5, 0x90, 0xac, 0x81, 0xf7, 0x13, 0xb4, 0xcd, 0x0f, 0xd5, 0x26, 0x91, 0x4e, 0x89, 0xfb, 0xa1, - 0x81, 0xb1, 0x5e, 0x1a, 0x08, 0x41, 0x36, 0x40, 0x2d, 0xac, 0x66, 0x21, 0x9e, 0x21, 0x02, 0x39, - 0x6e, 0x12, 0x5a, 0x4c, 0x0b, 0xa9, 0xa5, 0x53, 0x44, 0x31, 0xc5, 0x3d, 0xe2, 0x05, 0xf5, 0xab, - 0x5c, 0xe4, 0xbb, 0xaf, 0xe5, 0xaa, 0xeb, 0xb1, 0xf5, 0x76, 0xd3, 0x5c, 0x23, 0x2d, 0x65, 0x23, - 0xf5, 0x53, 0xa3, 0xce, 0x86, 0xc5, 0xb6, 0x43, 0x4c, 0x45, 0x01, 0xb5, 0x25, 0x32, 0x6c, 0x80, - 0x31, 0x46, 0x18, 0xf2, 0x1b, 0x74, 0x1d, 0x45, 0x98, 0x16, 0x33, 0x9c, 0xbe, 0x7e, 0x9b, 0xc3, - 0x7d, 0x39, 0x2c, 0xcf, 0xfd, 0x06, 0xdc, 0x4a, 0xc0, 0x0e, 0x76, 0x6b, 0x40, 0x49, 0x5b, 0x09, - 0x98, 0x5d, 0x10, 0x88, 0xab, 0x02, 0x50, 0x39, 0xe0, 0x83, 0x06, 0x26, 0xc4, 0x2e, 0x96, 0x70, - 0x48, 0xa8, 0xc7, 0xba, 0x2e, 0x30, 0x41, 0x8e, 0x6c, 0x05, 0x38, 0x92, 0x7d, 0xd7, 0x8b, 0x07, - 0xbb, 0xb5, 0x09, 0x05, 0x75, 0xd7, 0x71, 0x22, 0x4c, 0xe9, 0x2a, 0x8b, 0xbc, 0xc0, 0xb5, 0x65, - 0x5a, 0xaf, 0x6b, 0xd2, 0xbf, 0x70, 0x4d, 0xe6, 0x6f, 0x5d, 0xa3, 0xf4, 0xbe, 0xd7, 0xc0, 0xff, - 0x7d, 0x7a, 0xd5, 0x9e, 0x96, 0xc0, 0x88, 0xa3, 0xce, 0x94, 0x83, 0x2a, 0x09, 0x0e, 0x52, 0x65, - 0x7d, 0x26, 0xea, 0x56, 0x9e, 0x9b, 0x8f, 0x94, 0xdc, 0x8f, 0x69, 0xf0, 0x6f, 0x1f, 0x25, 0xbc, - 0x0e, 0x46, 0x15, 0x1d, 0x19, 0x3e, 0xdd, 0x93, 0xd4, 0xb3, 0x27, 0xec, 0x81, 0x31, 0x69, 0x92, - 0x06, 0x5f, 0x85, 0xa3, 0xac, 0xb2, 0xfc, 0xc7, 0x56, 0x49, 0x56, 0x50, 0x90, 0xd8, 0x0f, 0x38, - 0x34, 0x0c, 0xba, 0x54, 0x1d, 0xe4, 0xb7, 0x71, 0x31, 0x7b, 0xfe, 0xfe, 0x57, 0x7c, 0x4f, 0x38, - 0xbe, 0x9c, 0xe2, 0xe2, 0x8b, 0x0c, 0xc8, 0x89, 0xa5, 0xc3, 0xe7, 0x20, 0x2f, 0xaf, 0x33, 0x38, - 0x9b, 0xb0, 0xdc, 0xc1, 0xdb, 0x53, 0x9f, 0x1b, 0x96, 0x26, 0x97, 0x52, 0xb9, 0xb8, 0xf3, 0xe9, - 0xfb, 0xeb, 0xf4, 0x24, 0x2c, 0x59, 0x83, 0x57, 0xb4, 0xbc, 0x32, 0x61, 0x07, 0xe4, 0xc4, 0x85, - 0x05, 0x2f, 0x9f, 0x89, 0xd9, 0x73, 0x8d, 0xea, 0xb3, 0x43, 0xb2, 0x14, 0xf1, 0x8c, 0x20, 0xd6, - 0x61, 0x31, 0x89, 0x58, 0xd0, 0xed, 0x68, 0x60, 0x24, 0x76, 0x3b, 0x9c, 0x3f, 0x0b, 0xb5, 0xef, - 0xfb, 0xd5, 0xab, 0xc3, 0x13, 0x95, 0x82, 0x4b, 0x42, 0xc1, 0x34, 0x9c, 0x4c, 0x50, 0x10, 0x7f, - 0x17, 0xf5, 0x3b, 0x7b, 0x47, 0x86, 0xb6, 0x7f, 0x64, 0x68, 0xdf, 0x8e, 0x0c, 0xed, 0xd5, 0xb1, - 0x91, 0xda, 0x3f, 0x36, 0x52, 0x9f, 0x8f, 0x8d, 0xd4, 0xd3, 0x5e, 0x7f, 0x71, 0x80, 0x9a, 0x8f, - 0x9a, 0x54, 0x42, 0x3d, 0x93, 0x60, 0x62, 0xbb, 0xcd, 0xbc, 0xf8, 0x93, 0xbb, 0xf6, 0x33, 0x00, - 0x00, 0xff, 0xff, 0x7b, 0x1b, 0x3a, 0x0f, 0xd1, 0x07, 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 { - // Params queries all parameters of the swap module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Pools queries pools based on pool ID - Pools(ctx context.Context, in *QueryPoolsRequest, opts ...grpc.CallOption) (*QueryPoolsResponse, error) - // Deposits queries deposit details based on owner address and pool - Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, 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, "/kava.swap.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Pools(ctx context.Context, in *QueryPoolsRequest, opts ...grpc.CallOption) (*QueryPoolsResponse, error) { - out := new(QueryPoolsResponse) - err := c.cc.Invoke(ctx, "/kava.swap.v1beta1.Query/Pools", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) { - out := new(QueryDepositsResponse) - err := c.cc.Invoke(ctx, "/kava.swap.v1beta1.Query/Deposits", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries all parameters of the swap module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Pools queries pools based on pool ID - Pools(context.Context, *QueryPoolsRequest) (*QueryPoolsResponse, error) - // Deposits queries deposit details based on owner address and pool - Deposits(context.Context, *QueryDepositsRequest) (*QueryDepositsResponse, 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) Pools(ctx context.Context, req *QueryPoolsRequest) (*QueryPoolsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Pools not implemented") -} -func (*UnimplementedQueryServer) Deposits(ctx context.Context, req *QueryDepositsRequest) (*QueryDepositsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposits 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: "/kava.swap.v1beta1.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_Pools_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryPoolsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Pools(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.swap.v1beta1.Query/Pools", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Pools(ctx, req.(*QueryPoolsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Deposits_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDepositsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Deposits(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.swap.v1beta1.Query/Deposits", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Deposits(ctx, req.(*QueryDepositsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.swap.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Pools", - Handler: _Query_Pools_Handler, - }, - { - MethodName: "Deposits", - Handler: _Query_Deposits_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/swap/v1beta1/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 *QueryPoolsRequest) 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 *QueryPoolsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPoolsRequest) 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.PoolId) > 0 { - i -= len(m.PoolId) - copy(dAtA[i:], m.PoolId) - i = encodeVarintQuery(dAtA, i, uint64(len(m.PoolId))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryPoolsResponse) 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 *QueryPoolsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPoolsResponse) 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.Pools) > 0 { - for iNdEx := len(m.Pools) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Pools[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 (m *PoolResponse) 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 *PoolResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PoolResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.TotalShares.Size() - i -= size - if _, err := m.TotalShares.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Coins) > 0 { - for iNdEx := len(m.Coins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Coins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Name) > 0 { - i -= len(m.Name) - copy(dAtA[i:], m.Name) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Name))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDepositsRequest) 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 *QueryDepositsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsRequest) 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] = 0x1a - } - if len(m.PoolId) > 0 { - i -= len(m.PoolId) - copy(dAtA[i:], m.PoolId) - i = encodeVarintQuery(dAtA, i, uint64(len(m.PoolId))) - i-- - dAtA[i] = 0x12 - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDepositsResponse) 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 *QueryDepositsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsResponse) 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.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[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 (m *DepositResponse) 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 *DepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.SharesValue) > 0 { - for iNdEx := len(m.SharesValue) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SharesValue[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - { - size := m.SharesOwned.Size() - i -= size - if _, err := m.SharesOwned.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.PoolId) > 0 { - i -= len(m.PoolId) - copy(dAtA[i:], m.PoolId) - i = encodeVarintQuery(dAtA, i, uint64(len(m.PoolId))) - i-- - dAtA[i] = 0x12 - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Depositor))) - 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 *QueryPoolsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.PoolId) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryPoolsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Pools) > 0 { - for _, e := range m.Pools { - 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 (m *PoolResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Name) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.Coins) > 0 { - for _, e := range m.Coins { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - l = m.TotalShares.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryDepositsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.PoolId) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDepositsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Deposits) > 0 { - for _, e := range m.Deposits { - 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 (m *DepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.PoolId) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = m.SharesOwned.Size() - n += 1 + l + sovQuery(uint64(l)) - if len(m.SharesValue) > 0 { - for _, e := range m.SharesValue { - l = e.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 *QueryPoolsRequest) 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: QueryPoolsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPoolsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PoolId = string(dAtA[iNdEx:postIndex]) - 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.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 *QueryPoolsResponse) 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: QueryPoolsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPoolsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pools", 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.Pools = append(m.Pools, PoolResponse{}) - if err := m.Pools[len(m.Pools)-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 (m *PoolResponse) 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: PoolResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PoolResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Name = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Coins", 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.Coins = append(m.Coins, types.Coin{}) - if err := m.Coins[len(m.Coins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalShares", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TotalShares.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 *QueryDepositsRequest) 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: QueryDepositsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PoolId = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - 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 *QueryDepositsResponse) 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: QueryDepositsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposits", 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.Deposits = append(m.Deposits, DepositResponse{}) - if err := m.Deposits[len(m.Deposits)-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 (m *DepositResponse) 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: DepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PoolId = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SharesOwned", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - 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 ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SharesOwned.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SharesValue", 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.SharesValue = append(m.SharesValue, types.Coin{}) - if err := m.SharesValue[len(m.SharesValue)-1].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/swap/types/query.pb.gw.go b/x/swap/types/query.pb.gw.go deleted file mode 100644 index d0c87d04..00000000 --- a/x/swap/types/query.pb.gw.go +++ /dev/null @@ -1,319 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/swap/v1beta1/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 - -} - -var ( - filter_Query_Pools_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Pools_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPoolsRequest - 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_Pools_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Pools(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Pools_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPoolsRequest - 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_Pools_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Pools(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Deposits_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - 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_Deposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Deposits(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - 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_Deposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Deposits(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_Pools_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_Pools_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_Pools_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_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_Deposits_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_Deposits_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_Pools_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_Pools_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_Pools_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_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_Deposits_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_Deposits_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{"kava", "swap", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Pools_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "swap", "v1beta1", "pools"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Deposits_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "swap", "v1beta1", "deposits"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Pools_0 = runtime.ForwardResponseMessage - - forward_Query_Deposits_0 = runtime.ForwardResponseMessage -) diff --git a/x/swap/types/state.go b/x/swap/types/state.go deleted file mode 100644 index 7c729fc8..00000000 --- a/x/swap/types/state.go +++ /dev/null @@ -1,180 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "strings" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// PoolIDSep represents the separator used in pool ids to separate two denominations -const PoolIDSep = ":" - -// PoolIDFromCoins returns a poolID from a coins object -func PoolIDFromCoins(coins sdk.Coins) string { - return PoolID(coins[0].Denom, coins[1].Denom) -} - -// PoolID returns an alphabetically sorted pool name from two denoms. -// The name is commutative for any all pairs A,B: f(A,B) == f(B,A). -func PoolID(denomA string, denomB string) string { - if denomB < denomA { - return fmt.Sprintf("%s%s%s", denomB, PoolIDSep, denomA) - } - - return fmt.Sprintf("%s%s%s", denomA, PoolIDSep, denomB) -} - -// NewPoolRecord takes reserve coins and total shares, returning -// a new pool record with a id -func NewPoolRecord(reserves sdk.Coins, totalShares sdkmath.Int) PoolRecord { - if len(reserves) != 2 { - panic("reserves must have two denominations") - } - - poolID := PoolIDFromCoins(reserves) - - return PoolRecord{ - PoolID: poolID, - ReservesA: reserves[0], - ReservesB: reserves[1], - TotalShares: totalShares, - } -} - -// NewPoolRecordFromPool takes a pointer to a denominated pool and returns a -// pool record for storage in state. -func NewPoolRecordFromPool(pool *DenominatedPool) PoolRecord { - reserves := pool.Reserves() - poolID := PoolIDFromCoins(reserves) - - return PoolRecord{ - PoolID: poolID, - ReservesA: reserves[0], - ReservesB: reserves[1], - TotalShares: pool.TotalShares(), - } -} - -// Validate performs basic validation checks of the record data -func (p PoolRecord) Validate() error { - if p.PoolID == "" { - return errors.New("poolID must be set") - } - - tokens := strings.Split(p.PoolID, PoolIDSep) - if len(tokens) != 2 || tokens[0] == "" || tokens[1] == "" || tokens[1] < tokens[0] || tokens[0] == tokens[1] { - return fmt.Errorf("poolID '%s' is invalid", p.PoolID) - } - if sdk.ValidateDenom(tokens[0]) != nil || sdk.ValidateDenom(tokens[1]) != nil { - return fmt.Errorf("poolID '%s' is invalid", p.PoolID) - } - if tokens[0] != p.ReservesA.Denom || tokens[1] != p.ReservesB.Denom { - return fmt.Errorf("poolID '%s' does not match reserves", p.PoolID) - } - - if !p.ReservesA.IsPositive() { - return fmt.Errorf("pool '%s' has invalid reserves: %s", p.PoolID, p.ReservesA) - } - - if !p.ReservesB.IsPositive() { - return fmt.Errorf("pool '%s' has invalid reserves: %s", p.PoolID, p.ReservesB) - } - - if !p.TotalShares.IsPositive() { - return fmt.Errorf("pool '%s' has invalid total shares: %s", p.PoolID, p.TotalShares) - } - - return nil -} - -// Reserves returns the total reserves for a pool -func (p PoolRecord) Reserves() sdk.Coins { - return sdk.NewCoins(p.ReservesA, p.ReservesB) -} - -// PoolRecords is a slice of PoolRecord -type PoolRecords []PoolRecord - -// Validate performs basic validation checks on all records in the slice -func (prs PoolRecords) Validate() error { - seenPoolIDs := make(map[string]bool) - - for _, p := range prs { - if err := p.Validate(); err != nil { - return err - } - - if seenPoolIDs[p.PoolID] { - return fmt.Errorf("duplicate poolID '%s'", p.PoolID) - } - - seenPoolIDs[p.PoolID] = true - } - - return nil -} - -// NewShareRecord takes a depositor, poolID, and shares and returns -// a new share record for storage in state. -func NewShareRecord(depositor sdk.AccAddress, poolID string, sharesOwned sdkmath.Int) ShareRecord { - return ShareRecord{ - Depositor: depositor, - PoolID: poolID, - SharesOwned: sharesOwned, - } -} - -// Validate performs basic validation checks of the record data -func (sr ShareRecord) Validate() error { - if sr.PoolID == "" { - return errors.New("poolID must be set") - } - - tokens := strings.Split(sr.PoolID, PoolIDSep) - if len(tokens) != 2 || tokens[0] == "" || tokens[1] == "" || tokens[1] < tokens[0] || tokens[0] == tokens[1] { - return fmt.Errorf("poolID '%s' is invalid", sr.PoolID) - } - if sdk.ValidateDenom(tokens[0]) != nil || sdk.ValidateDenom(tokens[1]) != nil { - return fmt.Errorf("poolID '%s' is invalid", sr.PoolID) - } - - if sr.Depositor.Empty() { - return fmt.Errorf("share record cannot have empty depositor address") - } - - if !sr.SharesOwned.IsPositive() { - return fmt.Errorf("depositor '%s' and pool '%s' has invalid total shares: %s", sr.Depositor, sr.PoolID, sr.SharesOwned.String()) - } - - return nil -} - -// ShareRecords is a slice of ShareRecord -type ShareRecords []ShareRecord - -// Validate performs basic validation checks on all records in the slice -func (srs ShareRecords) Validate() error { - seenDepositors := make(map[string]map[string]bool) - - for _, sr := range srs { - if err := sr.Validate(); err != nil { - return err - } - - if seenPools, found := seenDepositors[sr.Depositor.String()]; found { - if seenPools[sr.PoolID] { - return fmt.Errorf("duplicate depositor '%s' and poolID '%s'", sr.Depositor, sr.PoolID) - } - seenPools[sr.PoolID] = true - } else { - seenPools := make(map[string]bool) - seenPools[sr.PoolID] = true - seenDepositors[sr.Depositor.String()] = seenPools - } - } - - return nil -} diff --git a/x/swap/types/state_test.go b/x/swap/types/state_test.go deleted file mode 100644 index 9471662a..00000000 --- a/x/swap/types/state_test.go +++ /dev/null @@ -1,531 +0,0 @@ -package types_test - -import ( - "encoding/json" - "testing" - - types "github.com/kava-labs/kava/x/swap/types" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "sigs.k8s.io/yaml" -) - -func TestState_PoolID(t *testing.T) { - testCases := []struct { - reserveA string - reserveB string - expectedID string - }{ - {"atoken", "btoken", "atoken:btoken"}, - {"btoken", "atoken", "atoken:btoken"}, - {"aaa", "aaaa", "aaa:aaaa"}, - {"aaaa", "aaa", "aaa:aaaa"}, - {"aaaa", "aaab", "aaaa:aaab"}, - {"aaab", "aaaa", "aaaa:aaab"}, - {"a001", "a002", "a001:a002"}, - {"a002", "a001", "a001:a002"}, - {"AAAA", "aaaa", "AAAA:aaaa"}, - {"aaaa", "AAAA", "AAAA:aaaa"}, - } - - for _, tc := range testCases { - assert.Equal(t, tc.expectedID, types.PoolID(tc.reserveA, tc.reserveB)) - assert.Equal(t, tc.expectedID, types.PoolID(tc.reserveB, tc.reserveA)) - - assert.Equal(t, tc.expectedID, types.PoolIDFromCoins(sdk.NewCoins(sdk.NewCoin(tc.reserveA, i(1)), sdk.NewCoin(tc.reserveB, i(1))))) - assert.Equal(t, tc.expectedID, types.PoolIDFromCoins(sdk.NewCoins(sdk.NewCoin(tc.reserveB, i(1)), sdk.NewCoin(tc.reserveA, i(1))))) - } -} - -func TestState_NewPoolRecord(t *testing.T) { - reserves := sdk.NewCoins(usdx(50e6), ukava(10e6)) - totalShares := sdkmath.NewInt(30e6) - - poolRecord := types.NewPoolRecord(reserves, totalShares) - - assert.Equal(t, reserves[0], poolRecord.ReservesA) - assert.Equal(t, reserves[1], poolRecord.ReservesB) - assert.Equal(t, reserves, poolRecord.Reserves()) - assert.Equal(t, totalShares, poolRecord.TotalShares) - - assert.PanicsWithValue(t, "reserves must have two denominations", func() { - reserves := sdk.NewCoins(ukava(10e6)) - _ = types.NewPoolRecord(reserves, totalShares) - }, "expected panic with 1 coin in reserves") - - assert.PanicsWithValue(t, "reserves must have two denominations", func() { - reserves := sdk.NewCoins(ukava(10e6), hard(1e6), usdx(20e6)) - _ = types.NewPoolRecord(reserves, totalShares) - }, "expected panic with 3 coins in reserves") -} - -func TestState_NewPoolRecordFromPool(t *testing.T) { - reserves := sdk.NewCoins(usdx(50e6), ukava(10e6)) - - pool, err := types.NewDenominatedPool(reserves) - require.NoError(t, err) - - record := types.NewPoolRecordFromPool(pool) - - assert.Equal(t, types.PoolID("ukava", "usdx"), record.PoolID) - assert.Equal(t, ukava(10e6), record.ReservesA) - assert.Equal(t, record.ReservesB, usdx(50e6)) - assert.Equal(t, pool.TotalShares(), record.TotalShares) - assert.Equal(t, sdk.NewCoins(ukava(10e6), usdx(50e6)), record.Reserves()) - assert.Nil(t, record.Validate()) -} - -func TestState_PoolRecord_JSONEncoding(t *testing.T) { - raw := `{ - "pool_id": "ukava:usdx", - "reserves_a": { "denom": "ukava", "amount": "1000000" }, - "reserves_b": { "denom": "usdx", "amount": "5000000" }, - "total_shares": "3000000" - }` - - var record types.PoolRecord - err := json.Unmarshal([]byte(raw), &record) - require.NoError(t, err) - - assert.Equal(t, types.PoolID("ukava", "usdx"), record.PoolID) - assert.Equal(t, ukava(1e6), record.ReservesA) - assert.Equal(t, usdx(5e6), record.ReservesB) - assert.Equal(t, i(3e6), record.TotalShares) -} - -func TestState_PoolRecord_YamlEncoding(t *testing.T) { - expected := `pool_id: ukava:usdx -reserves_a: - amount: "1000000" - denom: ukava -reserves_b: - amount: "5000000" - denom: usdx -total_shares: "3000000" -` - record := types.NewPoolRecord(sdk.NewCoins(ukava(1e6), usdx(5e6)), i(3e6)) - data, err := yaml.Marshal(record) - require.NoError(t, err) - - assert.Equal(t, expected, string(data)) -} - -func TestState_PoolRecord_Validations(t *testing.T) { - validRecord := types.NewPoolRecord( - sdk.NewCoins(usdx(500e6), ukava(100e6)), - i(300e6), - ) - testCases := []struct { - name string - poolID string - reservesA sdk.Coin - reservesB sdk.Coin - totalShares sdkmath.Int - expectedErr string - }{ - { - name: "empty pool id", - poolID: "", - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "poolID must be set", - }, - { - name: "no poolID tokens", - poolID: "ukavausdx", - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "poolID 'ukavausdx' is invalid", - }, - { - name: "poolID empty tokens", - poolID: ":", - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "poolID ':' is invalid", - }, - { - name: "poolID empty token a", - poolID: ":usdx", - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "poolID ':usdx' is invalid", - }, - { - name: "poolID empty token b", - poolID: "ukava:", - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "poolID 'ukava:' is invalid", - }, - { - name: "poolID is not sorted", - poolID: "usdx:ukava", - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "poolID 'usdx:ukava' is invalid", - }, - { - name: "poolID has duplicate denoms", - poolID: "ukava:ukava", - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "poolID 'ukava:ukava' is invalid", - }, - { - name: "poolID does not match reserve A", - poolID: "ukava:usdx", - reservesA: hard(5e6), - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "poolID 'ukava:usdx' does not match reserves", - }, - { - name: "poolID does not match reserve B", - poolID: "ukava:usdx", - reservesA: validRecord.ReservesA, - reservesB: hard(5e6), - totalShares: validRecord.TotalShares, - expectedErr: "poolID 'ukava:usdx' does not match reserves", - }, - { - name: "negative reserve a", - poolID: "ukava:usdx", - reservesA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "pool 'ukava:usdx' has invalid reserves: -1ukava", - }, - { - name: "zero reserve a", - poolID: "ukava:usdx", - reservesA: sdk.Coin{Denom: "ukava", Amount: sdk.ZeroInt()}, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "pool 'ukava:usdx' has invalid reserves: 0ukava", - }, - { - name: "negative reserve b", - poolID: "ukava:usdx", - reservesA: validRecord.ReservesA, - reservesB: sdk.Coin{Denom: "usdx", Amount: sdkmath.NewInt(-1)}, - totalShares: validRecord.TotalShares, - expectedErr: "pool 'ukava:usdx' has invalid reserves: -1usdx", - }, - { - name: "zero reserve b", - poolID: "ukava:usdx", - reservesA: validRecord.ReservesA, - reservesB: sdk.Coin{Denom: "usdx", Amount: sdk.ZeroInt()}, - totalShares: validRecord.TotalShares, - expectedErr: "pool 'ukava:usdx' has invalid reserves: 0usdx", - }, - { - name: "negative total shares", - poolID: validRecord.PoolID, - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: sdkmath.NewInt(-1), - expectedErr: "pool 'ukava:usdx' has invalid total shares: -1", - }, - { - name: "zero total shares", - poolID: validRecord.PoolID, - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: sdk.ZeroInt(), - expectedErr: "pool 'ukava:usdx' has invalid total shares: 0", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - record := types.PoolRecord{ - PoolID: tc.poolID, - ReservesA: tc.reservesA, - ReservesB: tc.reservesB, - TotalShares: tc.totalShares, - } - err := record.Validate() - assert.EqualError(t, err, tc.expectedErr) - }) - } -} - -func TestState_PoolRecord_OrderedReserves(t *testing.T) { - invalidOrder := types.NewPoolRecord( - // force order to not be sorted - sdk.Coins{usdx(500e6), ukava(100e6)}, - i(300e6), - ) - assert.Error(t, invalidOrder.Validate()) - - validOrder := types.NewPoolRecord( - // force order to not be sorted - sdk.Coins{ukava(500e6), usdx(100e6)}, - i(300e6), - ) - assert.NoError(t, validOrder.Validate()) - - record_1 := types.NewPoolRecord(sdk.NewCoins(usdx(500e6), ukava(100e6)), i(300e6)) - record_2 := types.NewPoolRecord(sdk.NewCoins(ukava(100e6), usdx(500e6)), i(300e6)) - // ensure no regresssions in NewCoins ordering - assert.Equal(t, record_1, record_2) - assert.Equal(t, types.PoolID("ukava", "usdx"), record_1.PoolID) - assert.Equal(t, types.PoolID("ukava", "usdx"), record_2.PoolID) -} - -func TestState_PoolRecords_Validation(t *testing.T) { - validRecord := types.NewPoolRecord( - sdk.NewCoins(usdx(500e6), ukava(100e6)), - i(300e6), - ) - - invalidRecord := types.NewPoolRecord( - sdk.NewCoins(usdx(500e6), ukava(100e6)), - i(-1), - ) - - records := types.PoolRecords{ - validRecord, - } - assert.NoError(t, records.Validate()) - - records = append(records, invalidRecord) - err := records.Validate() - assert.Error(t, err) - assert.EqualError(t, err, "pool 'ukava:usdx' has invalid total shares: -1") -} - -func TestState_PoolRecords_ValidateUniquePools(t *testing.T) { - record_1 := types.NewPoolRecord( - sdk.NewCoins(usdx(500e6), ukava(100e6)), - i(300e6), - ) - - record_2 := types.NewPoolRecord( - sdk.NewCoins(usdx(5000e6), ukava(1000e6)), - i(3000e6), - ) - - record_3 := types.NewPoolRecord( - sdk.NewCoins(usdx(5000e6), hard(1000e6)), - i(3000e6), - ) - - validRecords := types.PoolRecords{record_1, record_3} - assert.NoError(t, validRecords.Validate()) - - invalidRecords := types.PoolRecords{record_1, record_2} - assert.EqualError(t, invalidRecords.Validate(), "duplicate poolID 'ukava:usdx'") -} - -func TestState_NewShareRecord(t *testing.T) { - depositor := sdk.AccAddress("some user") - poolID := types.PoolID("ukava", "usdx") - shares := sdkmath.NewInt(1e6) - - record := types.NewShareRecord(depositor, poolID, shares) - - assert.Equal(t, depositor, record.Depositor) - assert.Equal(t, poolID, record.PoolID) - assert.Equal(t, shares, record.SharesOwned) -} - -func TestState_ShareRecord_JSONEncoding(t *testing.T) { - raw := `{ - "depositor": "kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w", - "pool_id": "ukava:usdx", - "shares_owned": "3000000" - }` - - var record types.ShareRecord - err := json.Unmarshal([]byte(raw), &record) - require.NoError(t, err) - - assert.Equal(t, "kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w", record.Depositor.String()) - assert.Equal(t, types.PoolID("ukava", "usdx"), record.PoolID) - assert.Equal(t, i(3e6), record.SharesOwned) -} - -func TestState_ShareRecord_YamlEncoding(t *testing.T) { - expected := `depositor: kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w -pool_id: ukava:usdx -shares_owned: "3000000" -` - depositor, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - require.NoError(t, err) - - record := types.NewShareRecord(depositor, "ukava:usdx", i(3e6)) - data, err := yaml.Marshal(record) - require.NoError(t, err) - - assert.Equal(t, expected, string(data)) -} - -func TestState_InvalidShareRecordEmptyDepositor(t *testing.T) { - record := types.ShareRecord{ - Depositor: sdk.AccAddress{}, - PoolID: types.PoolID("ukava", "usdx"), - SharesOwned: sdkmath.NewInt(1e6), - } - require.Error(t, record.Validate()) -} - -func TestState_InvalidShareRecordNegativeShares(t *testing.T) { - record := types.ShareRecord{ - Depositor: sdk.AccAddress("some user ----------------"), - PoolID: types.PoolID("ukava", "usdx"), - SharesOwned: sdkmath.NewInt(-1e6), - } - require.Error(t, record.Validate()) -} - -func TestState_ShareRecord_Validations(t *testing.T) { - depositor, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - require.NoError(t, err) - validRecord := types.NewShareRecord( - depositor, - types.PoolID("ukava", "usdx"), - i(30e6), - ) - testCases := []struct { - name string - depositor sdk.AccAddress - poolID string - sharesOwned sdkmath.Int - expectedErr string - }{ - { - name: "empty pool id", - depositor: validRecord.Depositor, - poolID: "", - sharesOwned: validRecord.SharesOwned, - expectedErr: "poolID must be set", - }, - { - name: "no poolID tokens", - depositor: validRecord.Depositor, - poolID: "ukavausdx", - sharesOwned: validRecord.SharesOwned, - expectedErr: "poolID 'ukavausdx' is invalid", - }, - { - name: "poolID empty tokens", - depositor: validRecord.Depositor, - poolID: ":", - sharesOwned: validRecord.SharesOwned, - expectedErr: "poolID ':' is invalid", - }, - { - name: "poolID empty token a", - depositor: validRecord.Depositor, - poolID: ":usdx", - sharesOwned: validRecord.SharesOwned, - expectedErr: "poolID ':usdx' is invalid", - }, - { - name: "poolID empty token b", - depositor: validRecord.Depositor, - poolID: "ukava:", - sharesOwned: validRecord.SharesOwned, - expectedErr: "poolID 'ukava:' is invalid", - }, - { - name: "poolID is not sorted", - depositor: validRecord.Depositor, - poolID: "usdx:ukava", - sharesOwned: validRecord.SharesOwned, - expectedErr: "poolID 'usdx:ukava' is invalid", - }, - { - name: "poolID has duplicate denoms", - depositor: validRecord.Depositor, - poolID: "ukava:ukava", - sharesOwned: validRecord.SharesOwned, - expectedErr: "poolID 'ukava:ukava' is invalid", - }, - { - name: "negative total shares", - depositor: validRecord.Depositor, - poolID: validRecord.PoolID, - sharesOwned: sdkmath.NewInt(-1), - expectedErr: "depositor 'kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w' and pool 'ukava:usdx' has invalid total shares: -1", - }, - { - name: "zero total shares", - depositor: validRecord.Depositor, - poolID: validRecord.PoolID, - sharesOwned: sdk.ZeroInt(), - expectedErr: "depositor 'kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w' and pool 'ukava:usdx' has invalid total shares: 0", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - record := types.ShareRecord{ - Depositor: tc.depositor, - PoolID: tc.poolID, - SharesOwned: tc.sharesOwned, - } - err := record.Validate() - assert.EqualError(t, err, tc.expectedErr) - }) - } -} - -func TestState_ShareRecords_Validation(t *testing.T) { - depositor, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - require.NoError(t, err) - - validRecord := types.NewShareRecord( - depositor, - types.PoolID("hard", "usdx"), - i(300e6), - ) - - invalidRecord := types.NewShareRecord( - depositor, - types.PoolID("hard", "usdx"), - i(-1), - ) - - records := types.ShareRecords{ - validRecord, - } - assert.NoError(t, records.Validate()) - - records = append(records, invalidRecord) - err = records.Validate() - assert.Error(t, err) - assert.EqualError(t, err, "depositor 'kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w' and pool 'hard:usdx' has invalid total shares: -1") -} - -func TestState_ShareRecords_ValidateUniqueShareRecords(t *testing.T) { - depositor_1, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - require.NoError(t, err) - - depositor_2, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") - require.NoError(t, err) - - record_1 := types.NewShareRecord(depositor_1, "ukava:usdx", i(20e6)) - record_2 := types.NewShareRecord(depositor_1, "ukava:usdx", i(10e6)) - record_3 := types.NewShareRecord(depositor_1, "hard:usdx", i(20e6)) - record_4 := types.NewShareRecord(depositor_2, "ukava:usdx", i(20e6)) - - validRecords := types.ShareRecords{record_1, record_3, record_4} - assert.NoError(t, validRecords.Validate()) - - invalidRecords := types.ShareRecords{record_1, record_3, record_2, record_4} - assert.EqualError(t, invalidRecords.Validate(), "duplicate depositor 'kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w' and poolID 'ukava:usdx'") -} diff --git a/x/swap/types/swap.pb.go b/x/swap/types/swap.pb.go deleted file mode 100644 index e1a71cd7..00000000 --- a/x/swap/types/swap.pb.go +++ /dev/null @@ -1,1227 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/swap/v1beta1/swap.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" - 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 swap module. -type Params struct { - // allowed_pools defines that pools that are allowed to be created - AllowedPools AllowedPools `protobuf:"bytes,1,rep,name=allowed_pools,json=allowedPools,proto3,castrepeated=AllowedPools" json:"allowed_pools"` - // swap_fee defines the swap fee for all pools - SwapFee github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=swap_fee,json=swapFee,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"swap_fee"` -} - -func (m *Params) Reset() { *m = Params{} } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_9df359be90eb28cb, []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 (m *Params) GetAllowedPools() AllowedPools { - if m != nil { - return m.AllowedPools - } - return nil -} - -// AllowedPool defines a pool that is allowed to be created -type AllowedPool struct { - // token_a represents the a token allowed - TokenA string `protobuf:"bytes,1,opt,name=token_a,json=tokenA,proto3" json:"token_a,omitempty"` - // token_b represents the b token allowed - TokenB string `protobuf:"bytes,2,opt,name=token_b,json=tokenB,proto3" json:"token_b,omitempty"` -} - -func (m *AllowedPool) Reset() { *m = AllowedPool{} } -func (*AllowedPool) ProtoMessage() {} -func (*AllowedPool) Descriptor() ([]byte, []int) { - return fileDescriptor_9df359be90eb28cb, []int{1} -} -func (m *AllowedPool) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AllowedPool) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AllowedPool.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 *AllowedPool) XXX_Merge(src proto.Message) { - xxx_messageInfo_AllowedPool.Merge(m, src) -} -func (m *AllowedPool) XXX_Size() int { - return m.Size() -} -func (m *AllowedPool) XXX_DiscardUnknown() { - xxx_messageInfo_AllowedPool.DiscardUnknown(m) -} - -var xxx_messageInfo_AllowedPool proto.InternalMessageInfo - -func (m *AllowedPool) GetTokenA() string { - if m != nil { - return m.TokenA - } - return "" -} - -func (m *AllowedPool) GetTokenB() string { - if m != nil { - return m.TokenB - } - return "" -} - -// PoolRecord represents the state of a liquidity pool -// and is used to store the state of a denominated pool -type PoolRecord struct { - // pool_id represents the unique id of the pool - PoolID string `protobuf:"bytes,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` - // reserves_a is the a token coin reserves - ReservesA types.Coin `protobuf:"bytes,2,opt,name=reserves_a,json=reservesA,proto3" json:"reserves_a"` - // reserves_b is the a token coin reserves - ReservesB types.Coin `protobuf:"bytes,3,opt,name=reserves_b,json=reservesB,proto3" json:"reserves_b"` - // total_shares is the total distrubuted shares of the pool - TotalShares github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,4,opt,name=total_shares,json=totalShares,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"total_shares"` -} - -func (m *PoolRecord) Reset() { *m = PoolRecord{} } -func (m *PoolRecord) String() string { return proto.CompactTextString(m) } -func (*PoolRecord) ProtoMessage() {} -func (*PoolRecord) Descriptor() ([]byte, []int) { - return fileDescriptor_9df359be90eb28cb, []int{2} -} -func (m *PoolRecord) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *PoolRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PoolRecord.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 *PoolRecord) XXX_Merge(src proto.Message) { - xxx_messageInfo_PoolRecord.Merge(m, src) -} -func (m *PoolRecord) XXX_Size() int { - return m.Size() -} -func (m *PoolRecord) XXX_DiscardUnknown() { - xxx_messageInfo_PoolRecord.DiscardUnknown(m) -} - -var xxx_messageInfo_PoolRecord proto.InternalMessageInfo - -func (m *PoolRecord) GetPoolID() string { - if m != nil { - return m.PoolID - } - return "" -} - -func (m *PoolRecord) GetReservesA() types.Coin { - if m != nil { - return m.ReservesA - } - return types.Coin{} -} - -func (m *PoolRecord) GetReservesB() types.Coin { - if m != nil { - return m.ReservesB - } - return types.Coin{} -} - -// ShareRecord stores the shares owned for a depositor and pool -type ShareRecord struct { - // depositor represents the owner of the shares - Depositor github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=depositor,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"depositor,omitempty"` - // pool_id represents the pool the shares belong to - PoolID string `protobuf:"bytes,2,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` - // shares_owned represents the number of shares owned by depsoitor for the pool_id - SharesOwned github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=shares_owned,json=sharesOwned,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"shares_owned"` -} - -func (m *ShareRecord) Reset() { *m = ShareRecord{} } -func (m *ShareRecord) String() string { return proto.CompactTextString(m) } -func (*ShareRecord) ProtoMessage() {} -func (*ShareRecord) Descriptor() ([]byte, []int) { - return fileDescriptor_9df359be90eb28cb, []int{3} -} -func (m *ShareRecord) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ShareRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ShareRecord.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 *ShareRecord) XXX_Merge(src proto.Message) { - xxx_messageInfo_ShareRecord.Merge(m, src) -} -func (m *ShareRecord) XXX_Size() int { - return m.Size() -} -func (m *ShareRecord) XXX_DiscardUnknown() { - xxx_messageInfo_ShareRecord.DiscardUnknown(m) -} - -var xxx_messageInfo_ShareRecord proto.InternalMessageInfo - -func (m *ShareRecord) GetDepositor() github_com_cosmos_cosmos_sdk_types.AccAddress { - if m != nil { - return m.Depositor - } - return nil -} - -func (m *ShareRecord) GetPoolID() string { - if m != nil { - return m.PoolID - } - return "" -} - -func init() { - proto.RegisterType((*Params)(nil), "kava.swap.v1beta1.Params") - proto.RegisterType((*AllowedPool)(nil), "kava.swap.v1beta1.AllowedPool") - proto.RegisterType((*PoolRecord)(nil), "kava.swap.v1beta1.PoolRecord") - proto.RegisterType((*ShareRecord)(nil), "kava.swap.v1beta1.ShareRecord") -} - -func init() { proto.RegisterFile("kava/swap/v1beta1/swap.proto", fileDescriptor_9df359be90eb28cb) } - -var fileDescriptor_9df359be90eb28cb = []byte{ - // 521 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x53, 0x3f, 0x6f, 0xd3, 0x5e, - 0x14, 0x8d, 0xd3, 0x28, 0xf9, 0xe5, 0x25, 0xbf, 0x01, 0x53, 0x89, 0xb4, 0x42, 0x76, 0x15, 0x24, - 0xd4, 0x25, 0xb6, 0x5a, 0x36, 0x84, 0x10, 0x31, 0x01, 0x91, 0x89, 0xca, 0x0c, 0x08, 0x96, 0xa7, - 0x67, 0xfb, 0x36, 0xb5, 0xe2, 0xf8, 0x5a, 0x7e, 0x8f, 0x84, 0x7e, 0x0b, 0xc4, 0xc4, 0xc8, 0xcc, - 0xdc, 0x4f, 0xc0, 0xd4, 0xb1, 0xea, 0x84, 0x18, 0x02, 0x4a, 0xbe, 0x05, 0x2c, 0xe8, 0xfd, 0xa1, - 0x35, 0x42, 0x48, 0x54, 0x4c, 0xbe, 0xf7, 0x9e, 0x77, 0xce, 0xbd, 0xf7, 0x58, 0x97, 0xdc, 0x9c, - 0xb2, 0x39, 0xf3, 0xf9, 0x82, 0x15, 0xfe, 0x7c, 0x2f, 0x02, 0xc1, 0xf6, 0x54, 0xe2, 0x15, 0x25, - 0x0a, 0xb4, 0xaf, 0x49, 0xd4, 0x53, 0x05, 0x83, 0x6e, 0x3b, 0x31, 0xf2, 0x19, 0x72, 0x3f, 0x62, - 0x1c, 0x2e, 0x28, 0x31, 0xa6, 0xb9, 0xa6, 0x6c, 0x6f, 0x69, 0x9c, 0xaa, 0xcc, 0xd7, 0x89, 0x81, - 0x36, 0x27, 0x38, 0x41, 0x5d, 0x97, 0x91, 0xae, 0xf6, 0x3f, 0x5a, 0xa4, 0x79, 0xc0, 0x4a, 0x36, - 0xe3, 0xf6, 0x0b, 0xf2, 0x3f, 0xcb, 0x32, 0x5c, 0x40, 0x42, 0x0b, 0xc4, 0x8c, 0xf7, 0xac, 0x9d, - 0x8d, 0xdd, 0xce, 0xbe, 0xe3, 0xfd, 0x36, 0x86, 0x37, 0xd4, 0xef, 0x0e, 0x10, 0xb3, 0x60, 0xf3, - 0x74, 0xe9, 0xd6, 0x3e, 0x7c, 0x71, 0xbb, 0x95, 0x22, 0x0f, 0xbb, 0xac, 0x92, 0xd9, 0xcf, 0xc9, - 0x7f, 0x92, 0x4f, 0x0f, 0x01, 0x7a, 0xf5, 0x1d, 0x6b, 0xb7, 0x1d, 0xdc, 0x93, 0xac, 0xcf, 0x4b, - 0xf7, 0xf6, 0x24, 0x15, 0x47, 0xaf, 0x22, 0x2f, 0xc6, 0x99, 0x19, 0xd7, 0x7c, 0x06, 0x3c, 0x99, - 0xfa, 0xe2, 0xb8, 0x00, 0xee, 0x8d, 0x20, 0x3e, 0x3f, 0x19, 0x10, 0xb3, 0xcd, 0x08, 0xe2, 0xb0, - 0x25, 0xd5, 0x1e, 0x03, 0xdc, 0x6d, 0xbc, 0x7b, 0xef, 0xd6, 0xfa, 0x8f, 0x48, 0xa7, 0xd2, 0xdc, - 0xbe, 0x41, 0x5a, 0x02, 0xa7, 0x90, 0x53, 0xd6, 0xb3, 0x64, 0xb3, 0xb0, 0xa9, 0xd2, 0xe1, 0x25, - 0x10, 0xe9, 0x29, 0x0c, 0x10, 0x18, 0x99, 0xb7, 0x75, 0x42, 0xa4, 0x40, 0x08, 0x31, 0x96, 0x89, - 0x7d, 0x8b, 0xb4, 0xa4, 0x0f, 0x34, 0x4d, 0xb4, 0x4c, 0x40, 0x56, 0x4b, 0xb7, 0x29, 0x1f, 0x8c, - 0x47, 0x61, 0x53, 0x42, 0xe3, 0xc4, 0xbe, 0x4f, 0x48, 0x09, 0x1c, 0xca, 0x39, 0x70, 0xca, 0x94, - 0x6a, 0x67, 0x7f, 0xcb, 0x33, 0xa3, 0xca, 0xbf, 0x74, 0xe1, 0xd9, 0x43, 0x4c, 0xf3, 0xa0, 0x21, - 0xd7, 0x0e, 0xdb, 0x3f, 0x29, 0xc3, 0x5f, 0xf8, 0x51, 0x6f, 0xe3, 0x8a, 0xfc, 0xc0, 0xa6, 0xa4, - 0x2b, 0x50, 0xb0, 0x8c, 0xf2, 0x23, 0x56, 0x02, 0xef, 0x35, 0xae, 0xec, 0xee, 0x38, 0x17, 0x15, - 0x77, 0xc7, 0xb9, 0x08, 0x3b, 0x4a, 0xf1, 0x99, 0x12, 0xec, 0x7f, 0xb7, 0x48, 0x47, 0x85, 0xc6, - 0x95, 0x43, 0xd2, 0x4e, 0xa0, 0x40, 0x9e, 0x0a, 0x2c, 0x95, 0x2f, 0xdd, 0xe0, 0xc9, 0xb7, 0xa5, - 0x3b, 0xf8, 0x8b, 0x4e, 0xc3, 0x38, 0x1e, 0x26, 0x49, 0x09, 0x9c, 0x9f, 0x9f, 0x0c, 0xae, 0x9b, - 0x86, 0xa6, 0x12, 0x1c, 0x0b, 0xe0, 0xe1, 0xa5, 0x74, 0xd5, 0xfd, 0xfa, 0x1f, 0xdd, 0xa7, 0xa4, - 0xab, 0xf7, 0xa6, 0xb8, 0xc8, 0x21, 0x51, 0xfe, 0xfd, 0xf3, 0xf6, 0x5a, 0xf1, 0xa9, 0x14, 0x0c, - 0x1e, 0x9c, 0xae, 0x1c, 0xeb, 0x6c, 0xe5, 0x58, 0x5f, 0x57, 0x8e, 0xf5, 0x66, 0xed, 0xd4, 0xce, - 0xd6, 0x4e, 0xed, 0xd3, 0xda, 0xa9, 0xbd, 0xac, 0x8a, 0xcb, 0x03, 0x19, 0x64, 0x2c, 0xe2, 0x2a, - 0xf2, 0x5f, 0xeb, 0x8b, 0x56, 0x0d, 0xa2, 0xa6, 0xba, 0xb3, 0x3b, 0x3f, 0x02, 0x00, 0x00, 0xff, - 0xff, 0xee, 0x4a, 0x16, 0x69, 0xeb, 0x03, 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 - { - size := m.SwapFee.Size() - i -= size - if _, err := m.SwapFee.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintSwap(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.AllowedPools) > 0 { - for iNdEx := len(m.AllowedPools) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.AllowedPools[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintSwap(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *AllowedPool) 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 *AllowedPool) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AllowedPool) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.TokenB) > 0 { - i -= len(m.TokenB) - copy(dAtA[i:], m.TokenB) - i = encodeVarintSwap(dAtA, i, uint64(len(m.TokenB))) - i-- - dAtA[i] = 0x12 - } - if len(m.TokenA) > 0 { - i -= len(m.TokenA) - copy(dAtA[i:], m.TokenA) - i = encodeVarintSwap(dAtA, i, uint64(len(m.TokenA))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *PoolRecord) 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 *PoolRecord) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PoolRecord) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.TotalShares.Size() - i -= size - if _, err := m.TotalShares.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintSwap(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.ReservesB.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintSwap(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.ReservesA.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintSwap(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.PoolID) > 0 { - i -= len(m.PoolID) - copy(dAtA[i:], m.PoolID) - i = encodeVarintSwap(dAtA, i, uint64(len(m.PoolID))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *ShareRecord) 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 *ShareRecord) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ShareRecord) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.SharesOwned.Size() - i -= size - if _, err := m.SharesOwned.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintSwap(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.PoolID) > 0 { - i -= len(m.PoolID) - copy(dAtA[i:], m.PoolID) - i = encodeVarintSwap(dAtA, i, uint64(len(m.PoolID))) - i-- - dAtA[i] = 0x12 - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintSwap(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintSwap(dAtA []byte, offset int, v uint64) int { - offset -= sovSwap(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 - if len(m.AllowedPools) > 0 { - for _, e := range m.AllowedPools { - l = e.Size() - n += 1 + l + sovSwap(uint64(l)) - } - } - l = m.SwapFee.Size() - n += 1 + l + sovSwap(uint64(l)) - return n -} - -func (m *AllowedPool) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.TokenA) - if l > 0 { - n += 1 + l + sovSwap(uint64(l)) - } - l = len(m.TokenB) - if l > 0 { - n += 1 + l + sovSwap(uint64(l)) - } - return n -} - -func (m *PoolRecord) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.PoolID) - if l > 0 { - n += 1 + l + sovSwap(uint64(l)) - } - l = m.ReservesA.Size() - n += 1 + l + sovSwap(uint64(l)) - l = m.ReservesB.Size() - n += 1 + l + sovSwap(uint64(l)) - l = m.TotalShares.Size() - n += 1 + l + sovSwap(uint64(l)) - return n -} - -func (m *ShareRecord) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovSwap(uint64(l)) - } - l = len(m.PoolID) - if l > 0 { - n += 1 + l + sovSwap(uint64(l)) - } - l = m.SharesOwned.Size() - n += 1 + l + sovSwap(uint64(l)) - return n -} - -func sovSwap(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozSwap(x uint64) (n int) { - return sovSwap(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 ErrIntOverflowSwap - } - 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 { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AllowedPools", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthSwap - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AllowedPools = append(m.AllowedPools, AllowedPool{}) - if err := m.AllowedPools[len(m.AllowedPools)-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 SwapFee", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - 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 ErrInvalidLengthSwap - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SwapFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipSwap(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthSwap - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *AllowedPool) 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 ErrIntOverflowSwap - } - 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: AllowedPool: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AllowedPool: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenA", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - 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 ErrInvalidLengthSwap - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TokenA = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenB", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - 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 ErrInvalidLengthSwap - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TokenB = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipSwap(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthSwap - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *PoolRecord) 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 ErrIntOverflowSwap - } - 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: PoolRecord: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PoolRecord: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - 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 ErrInvalidLengthSwap - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PoolID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ReservesA", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthSwap - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ReservesA.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ReservesB", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthSwap - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ReservesB.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalShares", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - 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 ErrInvalidLengthSwap - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TotalShares.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipSwap(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthSwap - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ShareRecord) 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 ErrIntOverflowSwap - } - 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: ShareRecord: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ShareRecord: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthSwap - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = append(m.Depositor[:0], dAtA[iNdEx:postIndex]...) - if m.Depositor == nil { - m.Depositor = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - 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 ErrInvalidLengthSwap - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PoolID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SharesOwned", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - 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 ErrInvalidLengthSwap - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SharesOwned.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipSwap(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthSwap - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipSwap(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, ErrIntOverflowSwap - } - 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, ErrIntOverflowSwap - } - 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, ErrIntOverflowSwap - } - 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, ErrInvalidLengthSwap - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupSwap - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthSwap - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthSwap = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowSwap = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupSwap = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/swap/types/tx.pb.go b/x/swap/types/tx.pb.go deleted file mode 100644 index 0eea5aa7..00000000 --- a/x/swap/types/tx.pb.go +++ /dev/null @@ -1,2205 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/swap/v1beta1/tx.proto - -package types - -import ( - context "context" - 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" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - 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 - -// MsgDeposit represents a message for depositing liquidity into a pool -type MsgDeposit struct { - // depositor represents the address to deposit funds from - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - // token_a represents one token of deposit pair - TokenA types.Coin `protobuf:"bytes,2,opt,name=token_a,json=tokenA,proto3" json:"token_a"` - // token_b represents one token of deposit pair - TokenB types.Coin `protobuf:"bytes,3,opt,name=token_b,json=tokenB,proto3" json:"token_b"` - // slippage represents the max decimal percentage price change - Slippage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=slippage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"slippage"` - // deadline represents the unix timestamp to complete the deposit by - Deadline int64 `protobuf:"varint,5,opt,name=deadline,proto3" json:"deadline,omitempty"` -} - -func (m *MsgDeposit) Reset() { *m = MsgDeposit{} } -func (m *MsgDeposit) String() string { return proto.CompactTextString(m) } -func (*MsgDeposit) ProtoMessage() {} -func (*MsgDeposit) Descriptor() ([]byte, []int) { - return fileDescriptor_5b753029ccc8a1ef, []int{0} -} -func (m *MsgDeposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDeposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDeposit.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 *MsgDeposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDeposit.Merge(m, src) -} -func (m *MsgDeposit) XXX_Size() int { - return m.Size() -} -func (m *MsgDeposit) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDeposit.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDeposit proto.InternalMessageInfo - -// MsgDepositResponse defines the Msg/Deposit response type. -type MsgDepositResponse struct { -} - -func (m *MsgDepositResponse) Reset() { *m = MsgDepositResponse{} } -func (m *MsgDepositResponse) String() string { return proto.CompactTextString(m) } -func (*MsgDepositResponse) ProtoMessage() {} -func (*MsgDepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5b753029ccc8a1ef, []int{1} -} -func (m *MsgDepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDepositResponse.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 *MsgDepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDepositResponse.Merge(m, src) -} -func (m *MsgDepositResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgDepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDepositResponse proto.InternalMessageInfo - -// MsgWithdraw represents a message for withdrawing liquidity from a pool -type MsgWithdraw struct { - // from represents the address we are withdrawing for - From string `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` - // shares represents the amount of shares to withdraw - Shares github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=shares,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"shares"` - // min_token_a represents the minimum a token to withdraw - MinTokenA types.Coin `protobuf:"bytes,3,opt,name=min_token_a,json=minTokenA,proto3" json:"min_token_a"` - // min_token_a represents the minimum a token to withdraw - MinTokenB types.Coin `protobuf:"bytes,4,opt,name=min_token_b,json=minTokenB,proto3" json:"min_token_b"` - // deadline represents the unix timestamp to complete the withdraw by - Deadline int64 `protobuf:"varint,5,opt,name=deadline,proto3" json:"deadline,omitempty"` -} - -func (m *MsgWithdraw) Reset() { *m = MsgWithdraw{} } -func (m *MsgWithdraw) String() string { return proto.CompactTextString(m) } -func (*MsgWithdraw) ProtoMessage() {} -func (*MsgWithdraw) Descriptor() ([]byte, []int) { - return fileDescriptor_5b753029ccc8a1ef, []int{2} -} -func (m *MsgWithdraw) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdraw) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdraw.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 *MsgWithdraw) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdraw.Merge(m, src) -} -func (m *MsgWithdraw) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdraw) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdraw.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdraw proto.InternalMessageInfo - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -type MsgWithdrawResponse struct { -} - -func (m *MsgWithdrawResponse) Reset() { *m = MsgWithdrawResponse{} } -func (m *MsgWithdrawResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawResponse) ProtoMessage() {} -func (*MsgWithdrawResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5b753029ccc8a1ef, []int{3} -} -func (m *MsgWithdrawResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawResponse.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 *MsgWithdrawResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawResponse.Merge(m, src) -} -func (m *MsgWithdrawResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawResponse proto.InternalMessageInfo - -// MsgSwapExactForTokens represents a message for trading exact coinA for coinB -type MsgSwapExactForTokens struct { - // represents the address swaping the tokens - Requester string `protobuf:"bytes,1,opt,name=requester,proto3" json:"requester,omitempty"` - // exact_token_a represents the exact amount to swap for token_b - ExactTokenA types.Coin `protobuf:"bytes,2,opt,name=exact_token_a,json=exactTokenA,proto3" json:"exact_token_a"` - // token_b represents the desired token_b to swap for - TokenB types.Coin `protobuf:"bytes,3,opt,name=token_b,json=tokenB,proto3" json:"token_b"` - // slippage represents the maximum change in token_b allowed - Slippage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=slippage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"slippage"` - // deadline represents the unix timestamp to complete the swap by - Deadline int64 `protobuf:"varint,5,opt,name=deadline,proto3" json:"deadline,omitempty"` -} - -func (m *MsgSwapExactForTokens) Reset() { *m = MsgSwapExactForTokens{} } -func (m *MsgSwapExactForTokens) String() string { return proto.CompactTextString(m) } -func (*MsgSwapExactForTokens) ProtoMessage() {} -func (*MsgSwapExactForTokens) Descriptor() ([]byte, []int) { - return fileDescriptor_5b753029ccc8a1ef, []int{4} -} -func (m *MsgSwapExactForTokens) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSwapExactForTokens) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSwapExactForTokens.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 *MsgSwapExactForTokens) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSwapExactForTokens.Merge(m, src) -} -func (m *MsgSwapExactForTokens) XXX_Size() int { - return m.Size() -} -func (m *MsgSwapExactForTokens) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSwapExactForTokens.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSwapExactForTokens proto.InternalMessageInfo - -// MsgSwapExactForTokensResponse defines the Msg/SwapExactForTokens response -// type. -type MsgSwapExactForTokensResponse struct { -} - -func (m *MsgSwapExactForTokensResponse) Reset() { *m = MsgSwapExactForTokensResponse{} } -func (m *MsgSwapExactForTokensResponse) String() string { return proto.CompactTextString(m) } -func (*MsgSwapExactForTokensResponse) ProtoMessage() {} -func (*MsgSwapExactForTokensResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5b753029ccc8a1ef, []int{5} -} -func (m *MsgSwapExactForTokensResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSwapExactForTokensResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSwapExactForTokensResponse.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 *MsgSwapExactForTokensResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSwapExactForTokensResponse.Merge(m, src) -} -func (m *MsgSwapExactForTokensResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgSwapExactForTokensResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSwapExactForTokensResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSwapExactForTokensResponse proto.InternalMessageInfo - -// MsgSwapForExactTokens represents a message for trading coinA for an exact -// coinB -type MsgSwapForExactTokens struct { - // represents the address swaping the tokens - Requester string `protobuf:"bytes,1,opt,name=requester,proto3" json:"requester,omitempty"` - // token_a represents the desired token_a to swap for - TokenA types.Coin `protobuf:"bytes,2,opt,name=token_a,json=tokenA,proto3" json:"token_a"` - // exact_token_b represents the exact token b amount to swap for token a - ExactTokenB types.Coin `protobuf:"bytes,3,opt,name=exact_token_b,json=exactTokenB,proto3" json:"exact_token_b"` - // slippage represents the maximum change in token_a allowed - Slippage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=slippage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"slippage"` - // deadline represents the unix timestamp to complete the swap by - Deadline int64 `protobuf:"varint,5,opt,name=deadline,proto3" json:"deadline,omitempty"` -} - -func (m *MsgSwapForExactTokens) Reset() { *m = MsgSwapForExactTokens{} } -func (m *MsgSwapForExactTokens) String() string { return proto.CompactTextString(m) } -func (*MsgSwapForExactTokens) ProtoMessage() {} -func (*MsgSwapForExactTokens) Descriptor() ([]byte, []int) { - return fileDescriptor_5b753029ccc8a1ef, []int{6} -} -func (m *MsgSwapForExactTokens) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSwapForExactTokens) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSwapForExactTokens.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 *MsgSwapForExactTokens) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSwapForExactTokens.Merge(m, src) -} -func (m *MsgSwapForExactTokens) XXX_Size() int { - return m.Size() -} -func (m *MsgSwapForExactTokens) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSwapForExactTokens.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSwapForExactTokens proto.InternalMessageInfo - -// MsgSwapForExactTokensResponse defines the Msg/SwapForExactTokensResponse -// response type. -type MsgSwapForExactTokensResponse struct { -} - -func (m *MsgSwapForExactTokensResponse) Reset() { *m = MsgSwapForExactTokensResponse{} } -func (m *MsgSwapForExactTokensResponse) String() string { return proto.CompactTextString(m) } -func (*MsgSwapForExactTokensResponse) ProtoMessage() {} -func (*MsgSwapForExactTokensResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5b753029ccc8a1ef, []int{7} -} -func (m *MsgSwapForExactTokensResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSwapForExactTokensResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSwapForExactTokensResponse.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 *MsgSwapForExactTokensResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSwapForExactTokensResponse.Merge(m, src) -} -func (m *MsgSwapForExactTokensResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgSwapForExactTokensResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSwapForExactTokensResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSwapForExactTokensResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgDeposit)(nil), "kava.swap.v1beta1.MsgDeposit") - proto.RegisterType((*MsgDepositResponse)(nil), "kava.swap.v1beta1.MsgDepositResponse") - proto.RegisterType((*MsgWithdraw)(nil), "kava.swap.v1beta1.MsgWithdraw") - proto.RegisterType((*MsgWithdrawResponse)(nil), "kava.swap.v1beta1.MsgWithdrawResponse") - proto.RegisterType((*MsgSwapExactForTokens)(nil), "kava.swap.v1beta1.MsgSwapExactForTokens") - proto.RegisterType((*MsgSwapExactForTokensResponse)(nil), "kava.swap.v1beta1.MsgSwapExactForTokensResponse") - proto.RegisterType((*MsgSwapForExactTokens)(nil), "kava.swap.v1beta1.MsgSwapForExactTokens") - proto.RegisterType((*MsgSwapForExactTokensResponse)(nil), "kava.swap.v1beta1.MsgSwapForExactTokensResponse") -} - -func init() { proto.RegisterFile("kava/swap/v1beta1/tx.proto", fileDescriptor_5b753029ccc8a1ef) } - -var fileDescriptor_5b753029ccc8a1ef = []byte{ - // 613 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x55, 0xcd, 0x6a, 0xdb, 0x4c, - 0x14, 0xb5, 0x6c, 0x7f, 0x89, 0x3d, 0xe6, 0x5b, 0x74, 0xea, 0x80, 0x22, 0x88, 0x6c, 0x0c, 0x0d, - 0x5e, 0xd4, 0x52, 0x93, 0x42, 0x29, 0xa5, 0xd0, 0x46, 0x71, 0x0c, 0x5d, 0x98, 0x82, 0x12, 0x68, - 0xe9, 0xc6, 0x8c, 0xa4, 0xa9, 0x2c, 0x6c, 0x6b, 0x54, 0xcd, 0x24, 0x76, 0xdf, 0xa0, 0xab, 0xd2, - 0x47, 0xe8, 0xae, 0x2f, 0xe0, 0x87, 0x08, 0x5d, 0x85, 0xac, 0x4a, 0x17, 0xa1, 0xd8, 0x2f, 0x52, - 0x34, 0xfa, 0xf1, 0x4f, 0x84, 0x6b, 0x67, 0xd5, 0xae, 0x3c, 0xa3, 0x73, 0xcf, 0xb9, 0x33, 0xe7, - 0x5e, 0xdf, 0x01, 0x52, 0x0f, 0x5d, 0x20, 0x95, 0x0e, 0x91, 0xa7, 0x5e, 0x1c, 0x18, 0x98, 0xa1, - 0x03, 0x95, 0x8d, 0x14, 0xcf, 0x27, 0x8c, 0xc0, 0x7b, 0x01, 0xa6, 0x04, 0x98, 0x12, 0x61, 0x92, - 0x6c, 0x12, 0x3a, 0x20, 0x54, 0x35, 0x10, 0xc5, 0x09, 0xc1, 0x24, 0x8e, 0x1b, 0x52, 0xa4, 0xdd, - 0x10, 0xef, 0xf0, 0x9d, 0x1a, 0x6e, 0x22, 0xa8, 0x6c, 0x13, 0x9b, 0x84, 0xdf, 0x83, 0x55, 0xf8, - 0xb5, 0x36, 0xce, 0x02, 0xd0, 0xa6, 0x76, 0x13, 0x7b, 0x84, 0x3a, 0x0c, 0x3e, 0x01, 0x45, 0x2b, - 0x5c, 0x12, 0x5f, 0x14, 0xaa, 0x42, 0xbd, 0xa8, 0x89, 0xd7, 0xe3, 0x46, 0x39, 0x52, 0x3a, 0xb2, - 0x2c, 0x1f, 0x53, 0x7a, 0xca, 0x7c, 0xc7, 0xb5, 0xf5, 0x59, 0x28, 0x7c, 0x0a, 0xb6, 0x19, 0xe9, - 0x61, 0xb7, 0x83, 0xc4, 0x6c, 0x55, 0xa8, 0x97, 0x0e, 0x77, 0x95, 0x88, 0x12, 0x9c, 0x34, 0x3e, - 0xbe, 0x72, 0x4c, 0x1c, 0x57, 0xcb, 0x5f, 0xde, 0x54, 0x32, 0xfa, 0x16, 0x8f, 0x3f, 0x9a, 0x31, - 0x0d, 0x31, 0xb7, 0x09, 0x53, 0x83, 0x6f, 0x41, 0x81, 0xf6, 0x1d, 0xcf, 0x43, 0x36, 0x16, 0xf3, - 0xfc, 0xa8, 0xcf, 0x03, 0xfc, 0xe7, 0x4d, 0x65, 0xdf, 0x76, 0x58, 0xf7, 0xdc, 0x50, 0x4c, 0x32, - 0x88, 0x3c, 0x88, 0x7e, 0x1a, 0xd4, 0xea, 0xa9, 0xec, 0xa3, 0x87, 0xa9, 0xd2, 0xc4, 0xe6, 0xf5, - 0xb8, 0x01, 0xa2, 0x5c, 0x4d, 0x6c, 0xea, 0x89, 0x1a, 0x94, 0x40, 0xc1, 0xc2, 0xc8, 0xea, 0x3b, - 0x2e, 0x16, 0xff, 0xab, 0x0a, 0xf5, 0x9c, 0x9e, 0xec, 0x9f, 0xe5, 0x3f, 0x7d, 0xad, 0x64, 0x6a, - 0x65, 0x00, 0x67, 0xae, 0xe9, 0x98, 0x7a, 0xc4, 0xa5, 0xb8, 0xf6, 0x2d, 0x0b, 0x4a, 0x6d, 0x6a, - 0xbf, 0x71, 0x58, 0xd7, 0xf2, 0xd1, 0x10, 0x3e, 0x04, 0xf9, 0xf7, 0x3e, 0x19, 0xfc, 0xd1, 0x48, - 0x1e, 0x05, 0x5b, 0x60, 0x8b, 0x76, 0x91, 0x8f, 0x29, 0xb7, 0xb0, 0xa8, 0x29, 0x1b, 0xdc, 0xe6, - 0x95, 0xcb, 0xf4, 0x88, 0x0d, 0x5f, 0x80, 0xd2, 0xc0, 0x71, 0x3b, 0x71, 0x3d, 0xd6, 0x74, 0xb5, - 0x38, 0x70, 0xdc, 0xb3, 0xb0, 0x24, 0x0b, 0x02, 0x06, 0xf7, 0x76, 0x13, 0x01, 0x6d, 0x0d, 0xff, - 0x76, 0xc0, 0xfd, 0x39, 0xa3, 0x12, 0x03, 0xbf, 0x67, 0xc1, 0x4e, 0x9b, 0xda, 0xa7, 0x43, 0xe4, - 0x9d, 0x8c, 0x90, 0xc9, 0x5a, 0xc4, 0xe7, 0x92, 0x34, 0x68, 0x4c, 0x1f, 0x7f, 0x38, 0xc7, 0x94, - 0xe1, 0x35, 0x1a, 0x33, 0x09, 0x85, 0xc7, 0xe0, 0x7f, 0x1c, 0x28, 0x75, 0x36, 0x6c, 0xcf, 0x12, - 0x67, 0x9d, 0xfd, 0xcb, 0x3d, 0x5a, 0x01, 0x7b, 0xa9, 0x5e, 0xa6, 0xb9, 0xdd, 0x22, 0xfe, 0x49, - 0x72, 0xe1, 0xbb, 0xbb, 0x7d, 0xf7, 0x31, 0xb0, 0x54, 0xa7, 0xb5, 0x8d, 0x9e, 0xab, 0xd3, 0xdf, - 0xe2, 0xf6, 0xa2, 0x97, 0xb1, 0xdb, 0x87, 0x9f, 0x73, 0x20, 0xd7, 0xa6, 0x36, 0x7c, 0x0d, 0xb6, - 0xe3, 0x69, 0xbb, 0xa7, 0xdc, 0x9a, 0xf0, 0xca, 0x6c, 0xac, 0x48, 0x0f, 0x56, 0xc2, 0xb1, 0x30, - 0xd4, 0x41, 0x21, 0x99, 0x38, 0x72, 0x3a, 0x25, 0xc6, 0xa5, 0xfd, 0xd5, 0x78, 0xa2, 0xe9, 0x01, - 0x98, 0xf2, 0x27, 0xac, 0xa7, 0xb3, 0x6f, 0x47, 0x4a, 0x8f, 0xd6, 0x8d, 0x5c, 0xce, 0xb8, 0xd4, - 0x88, 0x2b, 0x32, 0x2e, 0x46, 0xae, 0xca, 0x98, 0x5e, 0x10, 0xed, 0xe5, 0xe5, 0x44, 0x16, 0xae, - 0x26, 0xb2, 0xf0, 0x6b, 0x22, 0x0b, 0x5f, 0xa6, 0x72, 0xe6, 0x6a, 0x2a, 0x67, 0x7e, 0x4c, 0xe5, - 0xcc, 0xbb, 0xf9, 0x6e, 0x09, 0x54, 0x1b, 0x7d, 0x64, 0x50, 0xbe, 0x52, 0x47, 0xe1, 0x5b, 0xcd, - 0x3b, 0xc6, 0xd8, 0xe2, 0x6f, 0xe8, 0xe3, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xd0, 0xde, 0xef, - 0x15, 0xc5, 0x07, 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 { - // Deposit defines a method for depositing liquidity into a pool - Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) - // Withdraw defines a method for withdrawing liquidity into a pool - Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) - // SwapExactForTokens represents a message for trading exact coinA for coinB - SwapExactForTokens(ctx context.Context, in *MsgSwapExactForTokens, opts ...grpc.CallOption) (*MsgSwapExactForTokensResponse, error) - // SwapForExactTokens represents a message for trading coinA for an exact coinB - SwapForExactTokens(ctx context.Context, in *MsgSwapForExactTokens, opts ...grpc.CallOption) (*MsgSwapForExactTokensResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) { - out := new(MsgDepositResponse) - err := c.cc.Invoke(ctx, "/kava.swap.v1beta1.Msg/Deposit", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) { - out := new(MsgWithdrawResponse) - err := c.cc.Invoke(ctx, "/kava.swap.v1beta1.Msg/Withdraw", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) SwapExactForTokens(ctx context.Context, in *MsgSwapExactForTokens, opts ...grpc.CallOption) (*MsgSwapExactForTokensResponse, error) { - out := new(MsgSwapExactForTokensResponse) - err := c.cc.Invoke(ctx, "/kava.swap.v1beta1.Msg/SwapExactForTokens", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) SwapForExactTokens(ctx context.Context, in *MsgSwapForExactTokens, opts ...grpc.CallOption) (*MsgSwapForExactTokensResponse, error) { - out := new(MsgSwapForExactTokensResponse) - err := c.cc.Invoke(ctx, "/kava.swap.v1beta1.Msg/SwapForExactTokens", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // Deposit defines a method for depositing liquidity into a pool - Deposit(context.Context, *MsgDeposit) (*MsgDepositResponse, error) - // Withdraw defines a method for withdrawing liquidity into a pool - Withdraw(context.Context, *MsgWithdraw) (*MsgWithdrawResponse, error) - // SwapExactForTokens represents a message for trading exact coinA for coinB - SwapExactForTokens(context.Context, *MsgSwapExactForTokens) (*MsgSwapExactForTokensResponse, error) - // SwapForExactTokens represents a message for trading coinA for an exact coinB - SwapForExactTokens(context.Context, *MsgSwapForExactTokens) (*MsgSwapForExactTokensResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Deposit(ctx context.Context, req *MsgDeposit) (*MsgDepositResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposit not implemented") -} -func (*UnimplementedMsgServer) Withdraw(ctx context.Context, req *MsgWithdraw) (*MsgWithdrawResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Withdraw not implemented") -} -func (*UnimplementedMsgServer) SwapExactForTokens(ctx context.Context, req *MsgSwapExactForTokens) (*MsgSwapExactForTokensResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SwapExactForTokens not implemented") -} -func (*UnimplementedMsgServer) SwapForExactTokens(ctx context.Context, req *MsgSwapForExactTokens) (*MsgSwapForExactTokensResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SwapForExactTokens not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Deposit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgDeposit) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Deposit(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.swap.v1beta1.Msg/Deposit", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Deposit(ctx, req.(*MsgDeposit)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Withdraw_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdraw) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Withdraw(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.swap.v1beta1.Msg/Withdraw", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Withdraw(ctx, req.(*MsgWithdraw)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_SwapExactForTokens_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgSwapExactForTokens) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).SwapExactForTokens(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.swap.v1beta1.Msg/SwapExactForTokens", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).SwapExactForTokens(ctx, req.(*MsgSwapExactForTokens)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_SwapForExactTokens_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgSwapForExactTokens) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).SwapForExactTokens(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.swap.v1beta1.Msg/SwapForExactTokens", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).SwapForExactTokens(ctx, req.(*MsgSwapForExactTokens)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.swap.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Deposit", - Handler: _Msg_Deposit_Handler, - }, - { - MethodName: "Withdraw", - Handler: _Msg_Withdraw_Handler, - }, - { - MethodName: "SwapExactForTokens", - Handler: _Msg_SwapExactForTokens_Handler, - }, - { - MethodName: "SwapForExactTokens", - Handler: _Msg_SwapForExactTokens_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/swap/v1beta1/tx.proto", -} - -func (m *MsgDeposit) 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 *MsgDeposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDeposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Deadline != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Deadline)) - i-- - dAtA[i] = 0x28 - } - { - size := m.Slippage.Size() - i -= size - if _, err := m.Slippage.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.TokenB.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.TokenA.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgDepositResponse) 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 *MsgDepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgWithdraw) 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 *MsgWithdraw) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdraw) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Deadline != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Deadline)) - i-- - dAtA[i] = 0x28 - } - { - size, err := m.MinTokenB.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.MinTokenA.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.Shares.Size() - i -= size - if _, err := m.Shares.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.From) > 0 { - i -= len(m.From) - copy(dAtA[i:], m.From) - i = encodeVarintTx(dAtA, i, uint64(len(m.From))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawResponse) 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 *MsgWithdrawResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgSwapExactForTokens) 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 *MsgSwapExactForTokens) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSwapExactForTokens) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Deadline != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Deadline)) - i-- - dAtA[i] = 0x28 - } - { - size := m.Slippage.Size() - i -= size - if _, err := m.Slippage.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.TokenB.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.ExactTokenA.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Requester) > 0 { - i -= len(m.Requester) - copy(dAtA[i:], m.Requester) - i = encodeVarintTx(dAtA, i, uint64(len(m.Requester))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgSwapExactForTokensResponse) 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 *MsgSwapExactForTokensResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSwapExactForTokensResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgSwapForExactTokens) 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 *MsgSwapForExactTokens) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSwapForExactTokens) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Deadline != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Deadline)) - i-- - dAtA[i] = 0x28 - } - { - size := m.Slippage.Size() - i -= size - if _, err := m.Slippage.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.ExactTokenB.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.TokenA.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Requester) > 0 { - i -= len(m.Requester) - copy(dAtA[i:], m.Requester) - i = encodeVarintTx(dAtA, i, uint64(len(m.Requester))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgSwapForExactTokensResponse) 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 *MsgSwapForExactTokensResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSwapForExactTokensResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgDeposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.TokenA.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.TokenB.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.Slippage.Size() - n += 1 + l + sovTx(uint64(l)) - if m.Deadline != 0 { - n += 1 + sovTx(uint64(m.Deadline)) - } - return n -} - -func (m *MsgDepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgWithdraw) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.From) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Shares.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.MinTokenA.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.MinTokenB.Size() - n += 1 + l + sovTx(uint64(l)) - if m.Deadline != 0 { - n += 1 + sovTx(uint64(m.Deadline)) - } - return n -} - -func (m *MsgWithdrawResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgSwapExactForTokens) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Requester) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.ExactTokenA.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.TokenB.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.Slippage.Size() - n += 1 + l + sovTx(uint64(l)) - if m.Deadline != 0 { - n += 1 + sovTx(uint64(m.Deadline)) - } - return n -} - -func (m *MsgSwapExactForTokensResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgSwapForExactTokens) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Requester) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.TokenA.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.ExactTokenB.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.Slippage.Size() - n += 1 + l + sovTx(uint64(l)) - if m.Deadline != 0 { - n += 1 + sovTx(uint64(m.Deadline)) - } - return n -} - -func (m *MsgSwapForExactTokensResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgDeposit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDeposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDeposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenA", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TokenA.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenB", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TokenB.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Slippage", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Slippage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Deadline", wireType) - } - m.Deadline = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Deadline |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDepositResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdraw) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdraw: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdraw: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.From = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Shares", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Shares.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MinTokenA", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MinTokenA.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MinTokenB", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MinTokenB.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Deadline", wireType) - } - m.Deadline = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Deadline |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgSwapExactForTokens) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgSwapExactForTokens: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSwapExactForTokens: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Requester", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Requester = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExactTokenA", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ExactTokenA.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenB", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TokenB.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Slippage", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Slippage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Deadline", wireType) - } - m.Deadline = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Deadline |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgSwapExactForTokensResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgSwapExactForTokensResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSwapExactForTokensResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgSwapForExactTokens) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgSwapForExactTokens: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSwapForExactTokens: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Requester", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Requester = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenA", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TokenA.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExactTokenB", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ExactTokenB.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Slippage", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Slippage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Deadline", wireType) - } - m.Deadline = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Deadline |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgSwapForExactTokensResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgSwapForExactTokensResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSwapForExactTokensResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/validator-vesting/client/cli/query.go b/x/validator-vesting/client/cli/query.go index 748d21b2..ad52ca20 100644 --- a/x/validator-vesting/client/cli/query.go +++ b/x/validator-vesting/client/cli/query.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/kava-labs/kava/x/validator-vesting/types" + "github.com/0glabs/0g-chain/x/validator-vesting/types" ) // GetQueryCmd returns the cli query commands for the kavadist module @@ -40,7 +40,7 @@ func queryCirculatingSupply() *cobra.Command { return &cobra.Command{ Use: "circulating-supply", Short: "Get circulating supply", - Long: "Get the current circulating supply of kava tokens", + Long: "Get the current circulating supply of 0g tokens", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { cliCtx, err := client.GetClientQueryContext(cmd) @@ -62,7 +62,7 @@ func queryTotalSupply() *cobra.Command { return &cobra.Command{ Use: "total-supply", Short: "Get total supply", - Long: "Get the current total supply of kava tokens", + Long: "Get the current total supply of 0g tokens", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { cliCtx, err := client.GetClientQueryContext(cmd) diff --git a/x/validator-vesting/client/rest/query.go b/x/validator-vesting/client/rest/query.go index 005546ec..af098eca 100644 --- a/x/validator-vesting/client/rest/query.go +++ b/x/validator-vesting/client/rest/query.go @@ -8,10 +8,10 @@ import ( "github.com/gorilla/mux" + "github.com/0glabs/0g-chain/client/rest" "github.com/cosmos/cosmos-sdk/client" - "github.com/kava-labs/kava/client/rest" - "github.com/kava-labs/kava/x/validator-vesting/types" + "github.com/0glabs/0g-chain/x/validator-vesting/types" ) func registerQueryRoutes(cliCtx client.Context, r *mux.Router) { diff --git a/x/validator-vesting/keeper/grpc_query.go b/x/validator-vesting/keeper/grpc_query.go index c633638f..31b7274c 100644 --- a/x/validator-vesting/keeper/grpc_query.go +++ b/x/validator-vesting/keeper/grpc_query.go @@ -5,8 +5,9 @@ import ( "time" sdkmath "cosmossdk.io/math" + "github.com/0glabs/0g-chain/chaincfg" + "github.com/0glabs/0g-chain/x/validator-vesting/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/kava-labs/kava/x/validator-vesting/types" ) type queryServer struct { @@ -20,23 +21,23 @@ func NewQueryServerImpl(bk types.BankKeeper) types.QueryServer { return &queryServer{bk: bk} } -// CirculatingSupply implements the gRPC service handler for querying the circulating supply of the kava token. +// CirculatingSupply implements the gRPC service handler for querying the circulating supply of the 0g token. func (s queryServer) CirculatingSupply(c context.Context, req *types.QueryCirculatingSupplyRequest) (*types. QueryCirculatingSupplyResponse, error) { ctx := sdk.UnwrapSDKContext(c) - totalSupply := s.bk.GetSupply(ctx, "ukava").Amount + totalSupply := s.bk.GetSupply(ctx, chaincfg.DisplayDenom).Amount supplyInt := getCirculatingSupply(ctx.BlockTime(), totalSupply) return &types.QueryCirculatingSupplyResponse{ Amount: supplyInt, }, nil } -// TotalSupply returns the total amount of ukava tokens +// TotalSupply returns the total amount of a0gi tokens func (s queryServer) TotalSupply(c context.Context, req *types.QueryTotalSupplyRequest) (*types.QueryTotalSupplyResponse, error) { ctx := sdk.UnwrapSDKContext(c) - totalSupply := s.bk.GetSupply(ctx, "ukava").Amount + totalSupply := s.bk.GetSupply(ctx, chaincfg.DisplayDenom).Amount supplyInt := sdk.NewDecFromInt(totalSupply).Mul(sdk.MustNewDecFromStr("0.000001")).TruncateInt() return &types.QueryTotalSupplyResponse{ Amount: supplyInt, @@ -255,7 +256,7 @@ func (s queryServer) CirculatingSupplySWP(c context.Context, req *types.QueryCir monthlyStakersSwp := int64(520_833) monthlyLPIncentivesSwp := int64(2_343_750) - // []{Ecosystem, Team, Treasury, Kava Stakers, LP Incentives} + // []{Ecosystem, Team, Treasury, 0gChain Stakers, LP Incentives} scheduleAmounts := [][]int64{ {12_500_000, 0, 15_625_000, monthlyStakersSwp, monthlyLPIncentivesSwp}, // *** Year ONE *** {0, 0, 0, monthlyStakersSwp, monthlyLPIncentivesSwp}, // 1 diff --git a/x/validator-vesting/keeper/grpc_query_test.go b/x/validator-vesting/keeper/grpc_query_test.go index b6c22c0e..79026e38 100644 --- a/x/validator-vesting/keeper/grpc_query_test.go +++ b/x/validator-vesting/keeper/grpc_query_test.go @@ -11,9 +11,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" - "github.com/kava-labs/kava/app" - "github.com/kava-labs/kava/x/validator-vesting/keeper" - "github.com/kava-labs/kava/x/validator-vesting/types" + "github.com/0glabs/0g-chain/app" + "github.com/0glabs/0g-chain/chaincfg" + "github.com/0glabs/0g-chain/x/validator-vesting/keeper" + "github.com/0glabs/0g-chain/x/validator-vesting/types" ) type grpcQueryTestSuite struct { @@ -52,7 +53,7 @@ func TestGrpcQueryTestSuite(t *testing.T) { func (suite *grpcQueryTestSuite) TestCirculatingSupply() { suite.Run("vesting period supply", func() { - suite.bk.SetSupply(suite.ctx, "ukava", sdkmath.NewInt(2_500_000_000_000)) + suite.bk.SetSupply(suite.ctx, chaincfg.DisplayDenom, sdkmath.NewInt(2_500_000_000_000)) lastVestingPeriod := time.Date(2022, 8, 5, 24, 0, 0, 0, time.UTC) queryClient := suite.queryClientWithBlockTime(lastVestingPeriod) res, err := queryClient.CirculatingSupply(context.Background(), &types.QueryCirculatingSupplyRequest{}) @@ -61,7 +62,7 @@ func (suite *grpcQueryTestSuite) TestCirculatingSupply() { }) suite.Run("supply after last vesting period", func() { - suite.bk.SetSupply(suite.ctx, "ukava", sdkmath.NewInt(100_000_000)) + suite.bk.SetSupply(suite.ctx, chaincfg.DisplayDenom, sdkmath.NewInt(100_000_000)) res, err := suite.queryClient.CirculatingSupply(context.Background(), &types.QueryCirculatingSupplyRequest{}) suite.Require().NoError(err) suite.Require().Equal(sdkmath.NewInt(100), res.Amount) @@ -69,7 +70,7 @@ func (suite *grpcQueryTestSuite) TestCirculatingSupply() { } func (suite *grpcQueryTestSuite) TestTotalSupply() { - suite.bk.SetSupply(suite.ctx, "ukava", sdkmath.NewInt(100_000_000)) + suite.bk.SetSupply(suite.ctx, chaincfg.DisplayDenom, sdkmath.NewInt(100_000_000)) res, err := suite.queryClient.TotalSupply(context.Background(), &types.QueryTotalSupplyRequest{}) suite.Require().NoError(err) suite.Require().Equal(sdkmath.NewInt(100), res.Amount) diff --git a/x/validator-vesting/module.go b/x/validator-vesting/module.go index 39fa0c61..2bf8f6b2 100644 --- a/x/validator-vesting/module.go +++ b/x/validator-vesting/module.go @@ -15,9 +15,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/kava-labs/kava/x/validator-vesting/client/cli" - "github.com/kava-labs/kava/x/validator-vesting/keeper" - "github.com/kava-labs/kava/x/validator-vesting/types" + "github.com/0glabs/0g-chain/x/validator-vesting/client/cli" + "github.com/0glabs/0g-chain/x/validator-vesting/keeper" + "github.com/0glabs/0g-chain/x/validator-vesting/types" ) var ( diff --git a/x/validator-vesting/types/query.pb.go b/x/validator-vesting/types/query.pb.go index b8a8442d..9bd4278c 100644 --- a/x/validator-vesting/types/query.pb.go +++ b/x/validator-vesting/types/query.pb.go @@ -1,5 +1,5 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/validatorvesting/v1beta1/query.proto +// source: zgc/validatorvesting/v1beta1/query.proto package types @@ -39,7 +39,7 @@ func (m *QueryCirculatingSupplyRequest) Reset() { *m = QueryCirculatingS func (m *QueryCirculatingSupplyRequest) String() string { return proto.CompactTextString(m) } func (*QueryCirculatingSupplyRequest) ProtoMessage() {} func (*QueryCirculatingSupplyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_2198ebff70588a65, []int{0} + return fileDescriptor_4eb4aa17850547e7, []int{0} } func (m *QueryCirculatingSupplyRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -77,7 +77,7 @@ func (m *QueryCirculatingSupplyResponse) Reset() { *m = QueryCirculating func (m *QueryCirculatingSupplyResponse) String() string { return proto.CompactTextString(m) } func (*QueryCirculatingSupplyResponse) ProtoMessage() {} func (*QueryCirculatingSupplyResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2198ebff70588a65, []int{1} + return fileDescriptor_4eb4aa17850547e7, []int{1} } func (m *QueryCirculatingSupplyResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -114,7 +114,7 @@ func (m *QueryTotalSupplyRequest) Reset() { *m = QueryTotalSupplyRequest func (m *QueryTotalSupplyRequest) String() string { return proto.CompactTextString(m) } func (*QueryTotalSupplyRequest) ProtoMessage() {} func (*QueryTotalSupplyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_2198ebff70588a65, []int{2} + return fileDescriptor_4eb4aa17850547e7, []int{2} } func (m *QueryTotalSupplyRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -152,7 +152,7 @@ func (m *QueryTotalSupplyResponse) Reset() { *m = QueryTotalSupplyRespon func (m *QueryTotalSupplyResponse) String() string { return proto.CompactTextString(m) } func (*QueryTotalSupplyResponse) ProtoMessage() {} func (*QueryTotalSupplyResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2198ebff70588a65, []int{3} + return fileDescriptor_4eb4aa17850547e7, []int{3} } func (m *QueryTotalSupplyResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -189,7 +189,7 @@ func (m *QueryCirculatingSupplyHARDRequest) Reset() { *m = QueryCirculat func (m *QueryCirculatingSupplyHARDRequest) String() string { return proto.CompactTextString(m) } func (*QueryCirculatingSupplyHARDRequest) ProtoMessage() {} func (*QueryCirculatingSupplyHARDRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_2198ebff70588a65, []int{4} + return fileDescriptor_4eb4aa17850547e7, []int{4} } func (m *QueryCirculatingSupplyHARDRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -227,7 +227,7 @@ func (m *QueryCirculatingSupplyHARDResponse) Reset() { *m = QueryCircula func (m *QueryCirculatingSupplyHARDResponse) String() string { return proto.CompactTextString(m) } func (*QueryCirculatingSupplyHARDResponse) ProtoMessage() {} func (*QueryCirculatingSupplyHARDResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2198ebff70588a65, []int{5} + return fileDescriptor_4eb4aa17850547e7, []int{5} } func (m *QueryCirculatingSupplyHARDResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -264,7 +264,7 @@ func (m *QueryCirculatingSupplyUSDXRequest) Reset() { *m = QueryCirculat func (m *QueryCirculatingSupplyUSDXRequest) String() string { return proto.CompactTextString(m) } func (*QueryCirculatingSupplyUSDXRequest) ProtoMessage() {} func (*QueryCirculatingSupplyUSDXRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_2198ebff70588a65, []int{6} + return fileDescriptor_4eb4aa17850547e7, []int{6} } func (m *QueryCirculatingSupplyUSDXRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -302,7 +302,7 @@ func (m *QueryCirculatingSupplyUSDXResponse) Reset() { *m = QueryCircula func (m *QueryCirculatingSupplyUSDXResponse) String() string { return proto.CompactTextString(m) } func (*QueryCirculatingSupplyUSDXResponse) ProtoMessage() {} func (*QueryCirculatingSupplyUSDXResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2198ebff70588a65, []int{7} + return fileDescriptor_4eb4aa17850547e7, []int{7} } func (m *QueryCirculatingSupplyUSDXResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -339,7 +339,7 @@ func (m *QueryCirculatingSupplySWPRequest) Reset() { *m = QueryCirculati func (m *QueryCirculatingSupplySWPRequest) String() string { return proto.CompactTextString(m) } func (*QueryCirculatingSupplySWPRequest) ProtoMessage() {} func (*QueryCirculatingSupplySWPRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_2198ebff70588a65, []int{8} + return fileDescriptor_4eb4aa17850547e7, []int{8} } func (m *QueryCirculatingSupplySWPRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -377,7 +377,7 @@ func (m *QueryCirculatingSupplySWPResponse) Reset() { *m = QueryCirculat func (m *QueryCirculatingSupplySWPResponse) String() string { return proto.CompactTextString(m) } func (*QueryCirculatingSupplySWPResponse) ProtoMessage() {} func (*QueryCirculatingSupplySWPResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2198ebff70588a65, []int{9} + return fileDescriptor_4eb4aa17850547e7, []int{9} } func (m *QueryCirculatingSupplySWPResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -414,7 +414,7 @@ func (m *QueryTotalSupplyHARDRequest) Reset() { *m = QueryTotalSupplyHAR func (m *QueryTotalSupplyHARDRequest) String() string { return proto.CompactTextString(m) } func (*QueryTotalSupplyHARDRequest) ProtoMessage() {} func (*QueryTotalSupplyHARDRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_2198ebff70588a65, []int{10} + return fileDescriptor_4eb4aa17850547e7, []int{10} } func (m *QueryTotalSupplyHARDRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -452,7 +452,7 @@ func (m *QueryTotalSupplyHARDResponse) Reset() { *m = QueryTotalSupplyHA func (m *QueryTotalSupplyHARDResponse) String() string { return proto.CompactTextString(m) } func (*QueryTotalSupplyHARDResponse) ProtoMessage() {} func (*QueryTotalSupplyHARDResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2198ebff70588a65, []int{11} + return fileDescriptor_4eb4aa17850547e7, []int{11} } func (m *QueryTotalSupplyHARDResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -489,7 +489,7 @@ func (m *QueryTotalSupplyUSDXRequest) Reset() { *m = QueryTotalSupplyUSD func (m *QueryTotalSupplyUSDXRequest) String() string { return proto.CompactTextString(m) } func (*QueryTotalSupplyUSDXRequest) ProtoMessage() {} func (*QueryTotalSupplyUSDXRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_2198ebff70588a65, []int{12} + return fileDescriptor_4eb4aa17850547e7, []int{12} } func (m *QueryTotalSupplyUSDXRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -527,7 +527,7 @@ func (m *QueryTotalSupplyUSDXResponse) Reset() { *m = QueryTotalSupplyUS func (m *QueryTotalSupplyUSDXResponse) String() string { return proto.CompactTextString(m) } func (*QueryTotalSupplyUSDXResponse) ProtoMessage() {} func (*QueryTotalSupplyUSDXResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2198ebff70588a65, []int{13} + return fileDescriptor_4eb4aa17850547e7, []int{13} } func (m *QueryTotalSupplyUSDXResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -557,67 +557,67 @@ func (m *QueryTotalSupplyUSDXResponse) XXX_DiscardUnknown() { var xxx_messageInfo_QueryTotalSupplyUSDXResponse proto.InternalMessageInfo func init() { - proto.RegisterType((*QueryCirculatingSupplyRequest)(nil), "kava.validatorvesting.v1beta1.QueryCirculatingSupplyRequest") - proto.RegisterType((*QueryCirculatingSupplyResponse)(nil), "kava.validatorvesting.v1beta1.QueryCirculatingSupplyResponse") - proto.RegisterType((*QueryTotalSupplyRequest)(nil), "kava.validatorvesting.v1beta1.QueryTotalSupplyRequest") - proto.RegisterType((*QueryTotalSupplyResponse)(nil), "kava.validatorvesting.v1beta1.QueryTotalSupplyResponse") - proto.RegisterType((*QueryCirculatingSupplyHARDRequest)(nil), "kava.validatorvesting.v1beta1.QueryCirculatingSupplyHARDRequest") - proto.RegisterType((*QueryCirculatingSupplyHARDResponse)(nil), "kava.validatorvesting.v1beta1.QueryCirculatingSupplyHARDResponse") - proto.RegisterType((*QueryCirculatingSupplyUSDXRequest)(nil), "kava.validatorvesting.v1beta1.QueryCirculatingSupplyUSDXRequest") - proto.RegisterType((*QueryCirculatingSupplyUSDXResponse)(nil), "kava.validatorvesting.v1beta1.QueryCirculatingSupplyUSDXResponse") - proto.RegisterType((*QueryCirculatingSupplySWPRequest)(nil), "kava.validatorvesting.v1beta1.QueryCirculatingSupplySWPRequest") - proto.RegisterType((*QueryCirculatingSupplySWPResponse)(nil), "kava.validatorvesting.v1beta1.QueryCirculatingSupplySWPResponse") - proto.RegisterType((*QueryTotalSupplyHARDRequest)(nil), "kava.validatorvesting.v1beta1.QueryTotalSupplyHARDRequest") - proto.RegisterType((*QueryTotalSupplyHARDResponse)(nil), "kava.validatorvesting.v1beta1.QueryTotalSupplyHARDResponse") - proto.RegisterType((*QueryTotalSupplyUSDXRequest)(nil), "kava.validatorvesting.v1beta1.QueryTotalSupplyUSDXRequest") - proto.RegisterType((*QueryTotalSupplyUSDXResponse)(nil), "kava.validatorvesting.v1beta1.QueryTotalSupplyUSDXResponse") + proto.RegisterType((*QueryCirculatingSupplyRequest)(nil), "zgc.validatorvesting.v1beta1.QueryCirculatingSupplyRequest") + proto.RegisterType((*QueryCirculatingSupplyResponse)(nil), "zgc.validatorvesting.v1beta1.QueryCirculatingSupplyResponse") + proto.RegisterType((*QueryTotalSupplyRequest)(nil), "zgc.validatorvesting.v1beta1.QueryTotalSupplyRequest") + proto.RegisterType((*QueryTotalSupplyResponse)(nil), "zgc.validatorvesting.v1beta1.QueryTotalSupplyResponse") + proto.RegisterType((*QueryCirculatingSupplyHARDRequest)(nil), "zgc.validatorvesting.v1beta1.QueryCirculatingSupplyHARDRequest") + proto.RegisterType((*QueryCirculatingSupplyHARDResponse)(nil), "zgc.validatorvesting.v1beta1.QueryCirculatingSupplyHARDResponse") + proto.RegisterType((*QueryCirculatingSupplyUSDXRequest)(nil), "zgc.validatorvesting.v1beta1.QueryCirculatingSupplyUSDXRequest") + proto.RegisterType((*QueryCirculatingSupplyUSDXResponse)(nil), "zgc.validatorvesting.v1beta1.QueryCirculatingSupplyUSDXResponse") + proto.RegisterType((*QueryCirculatingSupplySWPRequest)(nil), "zgc.validatorvesting.v1beta1.QueryCirculatingSupplySWPRequest") + proto.RegisterType((*QueryCirculatingSupplySWPResponse)(nil), "zgc.validatorvesting.v1beta1.QueryCirculatingSupplySWPResponse") + proto.RegisterType((*QueryTotalSupplyHARDRequest)(nil), "zgc.validatorvesting.v1beta1.QueryTotalSupplyHARDRequest") + proto.RegisterType((*QueryTotalSupplyHARDResponse)(nil), "zgc.validatorvesting.v1beta1.QueryTotalSupplyHARDResponse") + proto.RegisterType((*QueryTotalSupplyUSDXRequest)(nil), "zgc.validatorvesting.v1beta1.QueryTotalSupplyUSDXRequest") + proto.RegisterType((*QueryTotalSupplyUSDXResponse)(nil), "zgc.validatorvesting.v1beta1.QueryTotalSupplyUSDXResponse") } func init() { - proto.RegisterFile("kava/validatorvesting/v1beta1/query.proto", fileDescriptor_2198ebff70588a65) + proto.RegisterFile("zgc/validatorvesting/v1beta1/query.proto", fileDescriptor_4eb4aa17850547e7) } -var fileDescriptor_2198ebff70588a65 = []byte{ - // 619 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x96, 0xcb, 0x6e, 0xd3, 0x4c, - 0x14, 0xc7, 0x33, 0x9f, 0xf4, 0x55, 0x62, 0xba, 0x40, 0x8c, 0x8a, 0x68, 0x4d, 0xe3, 0x14, 0x23, - 0x21, 0x90, 0x88, 0xad, 0x34, 0x55, 0x4b, 0x2f, 0xd0, 0x0b, 0x5d, 0xd0, 0x1d, 0x4d, 0x8a, 0x40, - 0x6c, 0xa2, 0x49, 0x62, 0xb9, 0x56, 0x1d, 0x8f, 0xeb, 0x19, 0x9b, 0x86, 0x25, 0x4f, 0x80, 0xc4, - 0xab, 0x74, 0xc3, 0x03, 0x20, 0x65, 0xc1, 0xa2, 0x82, 0x0d, 0x20, 0x51, 0x41, 0xc2, 0x83, 0x20, - 0x8f, 0x27, 0xaa, 0xeb, 0xb8, 0x29, 0x76, 0x14, 0x58, 0x25, 0xb1, 0xcf, 0xe5, 0xf7, 0xf7, 0x39, - 0xf3, 0x77, 0xe0, 0xbd, 0x03, 0xec, 0x63, 0xcd, 0xc7, 0x96, 0xd9, 0xc4, 0x8c, 0xb8, 0xbe, 0x4e, - 0x99, 0x69, 0x1b, 0x9a, 0x5f, 0xaa, 0xeb, 0x0c, 0x97, 0xb4, 0x43, 0x4f, 0x77, 0xdb, 0xaa, 0xe3, - 0x12, 0x46, 0x50, 0x3e, 0x08, 0x55, 0xe3, 0xa1, 0xaa, 0x08, 0x95, 0x66, 0x1a, 0x84, 0xb6, 0x08, - 0xad, 0xf1, 0x60, 0x2d, 0xfc, 0x11, 0x66, 0x4a, 0x53, 0x06, 0x31, 0x48, 0x78, 0x3d, 0xf8, 0x26, - 0xae, 0xce, 0x1a, 0x84, 0x18, 0x96, 0xae, 0x61, 0xc7, 0xd4, 0xb0, 0x6d, 0x13, 0x86, 0x99, 0x49, - 0x6c, 0x91, 0xa3, 0x14, 0x60, 0x7e, 0x37, 0x68, 0xfe, 0xd8, 0x74, 0x1b, 0x9e, 0x85, 0x83, 0x56, - 0x55, 0xcf, 0x71, 0xac, 0x76, 0x45, 0x3f, 0xf4, 0x74, 0xca, 0x14, 0x1f, 0xca, 0x17, 0x05, 0x50, - 0x87, 0xd8, 0x54, 0x47, 0x7b, 0x70, 0x02, 0xb7, 0x88, 0x67, 0xb3, 0x69, 0x30, 0x07, 0xee, 0x5e, - 0xd9, 0x5a, 0xeb, 0x9c, 0x16, 0x72, 0xdf, 0x4e, 0x0b, 0x77, 0x0c, 0x93, 0xed, 0x7b, 0x75, 0xb5, - 0x41, 0x5a, 0x82, 0x53, 0x7c, 0x14, 0x69, 0xf3, 0x40, 0x63, 0x6d, 0x47, 0xa7, 0xea, 0x8e, 0xcd, - 0x3e, 0x1d, 0x17, 0xa1, 0x90, 0xb1, 0x63, 0xb3, 0x8a, 0xa8, 0xa5, 0xcc, 0xc0, 0x1b, 0xbc, 0xef, - 0x1e, 0x61, 0xd8, 0x3a, 0x8f, 0xe4, 0xc0, 0xe9, 0xc1, 0x5b, 0x63, 0x85, 0xb9, 0x0d, 0x6f, 0x25, - 0x3f, 0x84, 0x27, 0x9b, 0x95, 0xed, 0x3e, 0xd6, 0x6b, 0xa8, 0x0c, 0x0b, 0xfa, 0x37, 0x80, 0xcf, - 0xaa, 0xdb, 0x2f, 0x2e, 0x05, 0x0c, 0x83, 0xc6, 0x0a, 0xa8, 0xc0, 0xb9, 0xe4, 0xde, 0xd5, 0xe7, - 0x4f, 0xfb, 0x7c, 0xed, 0x8b, 0x44, 0xf0, 0x98, 0xb1, 0xe2, 0xe5, 0xe1, 0xcd, 0xf8, 0x4a, 0x45, - 0x47, 0xcb, 0xe0, 0x6c, 0xf2, 0xed, 0xbf, 0x0d, 0x15, 0x1d, 0x67, 0x02, 0xd4, 0xf8, 0x07, 0x39, - 0xff, 0x7e, 0x12, 0xfe, 0xcf, 0xdb, 0xa2, 0x8f, 0x00, 0x5e, 0x1b, 0x18, 0x15, 0x5a, 0x53, 0x87, - 0xfa, 0x97, 0x3a, 0xd4, 0x6d, 0xa4, 0x87, 0x19, 0xb3, 0x43, 0xc9, 0xca, 0xca, 0x9b, 0xcf, 0xbf, - 0xde, 0xfd, 0xb7, 0x80, 0xe6, 0xb5, 0xf3, 0x7e, 0x5b, 0x8c, 0x1b, 0x6e, 0xe3, 0xac, 0x44, 0x8d, - 0x86, 0xe0, 0xc7, 0x00, 0x4e, 0x46, 0x1e, 0x25, 0x5a, 0xfc, 0x13, 0x94, 0x41, 0x77, 0x92, 0x96, - 0x52, 0xe7, 0x09, 0xf8, 0x05, 0x0e, 0xaf, 0xa2, 0xfb, 0x97, 0xc1, 0xb3, 0x20, 0xb9, 0x8f, 0xfd, - 0x1d, 0xc0, 0xeb, 0x89, 0x8e, 0x83, 0x36, 0x32, 0x3d, 0xcb, 0xc8, 0xda, 0x4b, 0x9b, 0x23, 0x54, - 0x10, 0xa2, 0xd6, 0xb9, 0xa8, 0x65, 0xb4, 0x94, 0x7e, 0x22, 0xb5, 0x7d, 0xec, 0x36, 0x93, 0xf5, - 0x05, 0x7b, 0x9e, 0x51, 0x5f, 0xe4, 0x04, 0x65, 0xd4, 0x17, 0x3d, 0x64, 0x23, 0xe9, 0xf3, 0x68, - 0xf3, 0x08, 0x7d, 0x05, 0x70, 0x2a, 0xc9, 0xf0, 0xd0, 0x7a, 0x26, 0xb8, 0x33, 0x3b, 0x95, 0x36, - 0xb2, 0x17, 0x10, 0xe2, 0x1e, 0x71, 0x71, 0x0f, 0xd0, 0x62, 0x06, 0x71, 0xf4, 0x95, 0x83, 0x3e, - 0x00, 0x78, 0x35, 0x66, 0x99, 0x68, 0x25, 0xe5, 0xf1, 0x88, 0xee, 0xe3, 0x6a, 0xa6, 0x5c, 0x21, - 0x66, 0x99, 0x8b, 0x29, 0xa3, 0x52, 0x9a, 0xe3, 0x15, 0xee, 0x60, 0x4c, 0x07, 0xdf, 0xbe, 0xb4, - 0x3a, 0xa2, 0x7b, 0xb7, 0x9a, 0x29, 0x77, 0x24, 0x1d, 0xc1, 0xae, 0x6d, 0xed, 0x76, 0x7e, 0xca, - 0xb9, 0x4e, 0x57, 0x06, 0x27, 0x5d, 0x19, 0xfc, 0xe8, 0xca, 0xe0, 0x6d, 0x4f, 0xce, 0x9d, 0xf4, - 0xe4, 0xdc, 0x97, 0x9e, 0x9c, 0x7b, 0x59, 0x8e, 0xbc, 0x17, 0x82, 0xd2, 0x45, 0x0b, 0xd7, 0x69, - 0xd8, 0xe4, 0x28, 0xa1, 0x0d, 0x7f, 0x51, 0xd4, 0x27, 0xf8, 0xdf, 0xc8, 0xf2, 0xef, 0x00, 0x00, - 0x00, 0xff, 0xff, 0xbd, 0x0f, 0x0a, 0x7d, 0xe1, 0x0a, 0x00, 0x00, +var fileDescriptor_4eb4aa17850547e7 = []byte{ + // 621 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x96, 0x41, 0x6f, 0xd3, 0x30, + 0x14, 0xc7, 0x1b, 0x24, 0x26, 0xe1, 0x1d, 0x10, 0xd6, 0x10, 0x5b, 0xe8, 0xd2, 0x11, 0x24, 0xb4, + 0x4b, 0x93, 0x6e, 0xb0, 0x31, 0xba, 0x6e, 0x83, 0x6e, 0x07, 0x76, 0x83, 0x76, 0x08, 0xc4, 0xa5, + 0x72, 0xd3, 0x28, 0x8d, 0x48, 0xe3, 0xac, 0x76, 0xca, 0xda, 0x23, 0x9f, 0x00, 0x89, 0xaf, 0x82, + 0xf8, 0x0a, 0xeb, 0x09, 0x4d, 0x70, 0x41, 0x20, 0x0d, 0x68, 0xf9, 0x20, 0x28, 0x8e, 0xab, 0x86, + 0x34, 0x2b, 0xab, 0xa7, 0xc2, 0xa9, 0x6d, 0xf2, 0x9e, 0xdf, 0xef, 0xef, 0xf7, 0xfc, 0x77, 0xc1, + 0x72, 0xc7, 0x32, 0xf4, 0x16, 0x72, 0xec, 0x1a, 0xa2, 0xb8, 0xd9, 0x32, 0x09, 0xb5, 0x5d, 0x4b, + 0x6f, 0xad, 0x54, 0x4d, 0x8a, 0x56, 0xf4, 0x43, 0xdf, 0x6c, 0xb6, 0x35, 0xaf, 0x89, 0x29, 0x86, + 0xe9, 0x8e, 0x65, 0x68, 0xf1, 0x48, 0x8d, 0x47, 0xca, 0x0b, 0x06, 0x26, 0x0d, 0x4c, 0x2a, 0x2c, + 0x56, 0x0f, 0x7f, 0x84, 0x89, 0xf2, 0x9c, 0x85, 0x2d, 0x1c, 0x3e, 0x0f, 0xbe, 0xf1, 0xa7, 0x69, + 0x0b, 0x63, 0xcb, 0x31, 0x75, 0xe4, 0xd9, 0x3a, 0x72, 0x5d, 0x4c, 0x11, 0xb5, 0xb1, 0xcb, 0x73, + 0xd4, 0x0c, 0x58, 0x7c, 0x1a, 0xd4, 0xde, 0xb5, 0x9b, 0x86, 0xef, 0xa0, 0xa0, 0x54, 0xd9, 0xf7, + 0x3c, 0xa7, 0x5d, 0x32, 0x0f, 0x7d, 0x93, 0x50, 0xb5, 0x05, 0x94, 0xb3, 0x02, 0x88, 0x87, 0x5d, + 0x62, 0xc2, 0x03, 0x30, 0x83, 0x1a, 0xd8, 0x77, 0xe9, 0xbc, 0xb4, 0x24, 0x2d, 0x5f, 0x29, 0x16, + 0xba, 0xa7, 0x99, 0xd4, 0xd7, 0xd3, 0xcc, 0x1d, 0xcb, 0xa6, 0x75, 0xbf, 0xaa, 0x19, 0xb8, 0xc1, + 0x39, 0xf9, 0x47, 0x96, 0xd4, 0x5e, 0xe9, 0xb4, 0xed, 0x99, 0x44, 0xdb, 0x77, 0xe9, 0xa7, 0xf7, + 0x59, 0xc0, 0x65, 0xec, 0xbb, 0xb4, 0xc4, 0xd7, 0x52, 0x17, 0xc0, 0x0d, 0x56, 0xf7, 0x00, 0x53, + 0xe4, 0xfc, 0x89, 0xe4, 0x81, 0xf9, 0xd1, 0x57, 0x53, 0x85, 0xb9, 0x0d, 0x6e, 0x25, 0x6f, 0xc2, + 0xe3, 0x47, 0xa5, 0xbd, 0x01, 0x56, 0x07, 0xa8, 0xe3, 0x82, 0xfe, 0x0f, 0xe0, 0xb3, 0xf2, 0xde, + 0x8b, 0xbf, 0x02, 0x86, 0x41, 0x53, 0x05, 0x54, 0xc1, 0x52, 0x72, 0xed, 0xf2, 0xf3, 0x27, 0x03, + 0xbe, 0xf6, 0x59, 0x22, 0x58, 0xcc, 0x54, 0xf1, 0x16, 0xc1, 0xcd, 0xf8, 0x48, 0x45, 0x5b, 0x4b, + 0x41, 0x3a, 0xf9, 0xf5, 0xbf, 0x86, 0x8a, 0xb6, 0x33, 0x01, 0x6a, 0xfa, 0x8d, 0x5c, 0x3d, 0x9e, + 0x05, 0x97, 0x59, 0x59, 0xf8, 0x51, 0x02, 0xd7, 0x46, 0x5a, 0x05, 0x37, 0xb5, 0x71, 0xf6, 0xa5, + 0x8d, 0x35, 0x1b, 0xb9, 0x20, 0x96, 0x1c, 0x0a, 0x56, 0xb7, 0xdf, 0x7c, 0xfe, 0xf5, 0xee, 0xd2, + 0x06, 0x5c, 0xd7, 0x73, 0x56, 0xd6, 0xa8, 0x23, 0xdb, 0x1d, 0x1a, 0x6e, 0x36, 0xee, 0xb8, 0xc6, + 0x70, 0x99, 0x0a, 0x09, 0xd1, 0x3f, 0x48, 0x60, 0x36, 0xb2, 0x99, 0x70, 0xed, 0x1c, 0x34, 0xa3, + 0xf6, 0x24, 0xaf, 0x4f, 0x9a, 0xc6, 0xf1, 0x37, 0x18, 0xfe, 0x2a, 0xcc, 0x9d, 0x07, 0x9f, 0x06, + 0x0b, 0x0c, 0xc0, 0xbf, 0x4b, 0xe0, 0x7a, 0xa2, 0xeb, 0xc0, 0x1d, 0x91, 0x0d, 0x8d, 0x4c, 0xbe, + 0xfc, 0x50, 0x7c, 0x01, 0x2e, 0x6b, 0x97, 0xc9, 0xda, 0x82, 0x9b, 0x62, 0x5d, 0xa9, 0xd4, 0x51, + 0xb3, 0x96, 0xac, 0x30, 0x98, 0x76, 0x31, 0x85, 0x91, 0x63, 0x24, 0xa6, 0x30, 0x7a, 0xd0, 0x2e, + 0xac, 0xd0, 0x27, 0xb5, 0x23, 0xf8, 0x4d, 0x02, 0x73, 0x49, 0xc6, 0x07, 0xb7, 0x45, 0xf8, 0x86, + 0xae, 0x2a, 0xef, 0x08, 0xe7, 0x73, 0x79, 0x45, 0x26, 0xaf, 0x00, 0xf3, 0x82, 0xf2, 0xc8, 0x6b, + 0x0f, 0x1e, 0x4b, 0xe0, 0x6a, 0xcc, 0x3c, 0xe1, 0x83, 0xc9, 0xce, 0x49, 0x74, 0x2a, 0xf3, 0x22, + 0xa9, 0x5c, 0xce, 0x16, 0x93, 0x73, 0x1f, 0xae, 0x4d, 0x7a, 0xcc, 0xc2, 0x49, 0x8c, 0x29, 0x61, + 0x33, 0x38, 0xa1, 0x92, 0xe8, 0xf4, 0xe5, 0x45, 0x52, 0x2f, 0xac, 0x24, 0x98, 0xb8, 0x62, 0xa9, + 0xfb, 0x53, 0x49, 0x75, 0x7b, 0x8a, 0x74, 0xd2, 0x53, 0xa4, 0x1f, 0x3d, 0x45, 0x7a, 0xdb, 0x57, + 0x52, 0x27, 0x7d, 0x25, 0xf5, 0xa5, 0xaf, 0xa4, 0x5e, 0xde, 0x8b, 0xdc, 0x12, 0x39, 0xcb, 0x41, + 0x55, 0x32, 0xac, 0x72, 0x94, 0x50, 0x87, 0xdd, 0x1b, 0xd5, 0x19, 0xf6, 0xaf, 0xf2, 0xee, 0xef, + 0x00, 0x00, 0x00, 0xff, 0xff, 0x1a, 0x5a, 0x7b, 0xbb, 0xee, 0x0a, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -632,9 +632,9 @@ const _ = grpc.SupportPackageIsVersion4 // // 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 { - // CirculatingSupply returns the total amount of kava tokens in circulation + // CirculatingSupply returns the total amount of 0g-chain tokens in circulation CirculatingSupply(ctx context.Context, in *QueryCirculatingSupplyRequest, opts ...grpc.CallOption) (*QueryCirculatingSupplyResponse, error) - // TotalSupply returns the total amount of kava tokens + // TotalSupply returns the total amount of 0g-chain tokens TotalSupply(ctx context.Context, in *QueryTotalSupplyRequest, opts ...grpc.CallOption) (*QueryTotalSupplyResponse, error) // CirculatingSupplyHARD returns the total amount of hard tokens in circulation CirculatingSupplyHARD(ctx context.Context, in *QueryCirculatingSupplyHARDRequest, opts ...grpc.CallOption) (*QueryCirculatingSupplyHARDResponse, error) @@ -658,7 +658,7 @@ func NewQueryClient(cc grpc1.ClientConn) QueryClient { func (c *queryClient) CirculatingSupply(ctx context.Context, in *QueryCirculatingSupplyRequest, opts ...grpc.CallOption) (*QueryCirculatingSupplyResponse, error) { out := new(QueryCirculatingSupplyResponse) - err := c.cc.Invoke(ctx, "/kava.validatorvesting.v1beta1.Query/CirculatingSupply", in, out, opts...) + err := c.cc.Invoke(ctx, "/zgc.validatorvesting.v1beta1.Query/CirculatingSupply", in, out, opts...) if err != nil { return nil, err } @@ -667,7 +667,7 @@ func (c *queryClient) CirculatingSupply(ctx context.Context, in *QueryCirculatin func (c *queryClient) TotalSupply(ctx context.Context, in *QueryTotalSupplyRequest, opts ...grpc.CallOption) (*QueryTotalSupplyResponse, error) { out := new(QueryTotalSupplyResponse) - err := c.cc.Invoke(ctx, "/kava.validatorvesting.v1beta1.Query/TotalSupply", in, out, opts...) + err := c.cc.Invoke(ctx, "/zgc.validatorvesting.v1beta1.Query/TotalSupply", in, out, opts...) if err != nil { return nil, err } @@ -676,7 +676,7 @@ func (c *queryClient) TotalSupply(ctx context.Context, in *QueryTotalSupplyReque func (c *queryClient) CirculatingSupplyHARD(ctx context.Context, in *QueryCirculatingSupplyHARDRequest, opts ...grpc.CallOption) (*QueryCirculatingSupplyHARDResponse, error) { out := new(QueryCirculatingSupplyHARDResponse) - err := c.cc.Invoke(ctx, "/kava.validatorvesting.v1beta1.Query/CirculatingSupplyHARD", in, out, opts...) + err := c.cc.Invoke(ctx, "/zgc.validatorvesting.v1beta1.Query/CirculatingSupplyHARD", in, out, opts...) if err != nil { return nil, err } @@ -685,7 +685,7 @@ func (c *queryClient) CirculatingSupplyHARD(ctx context.Context, in *QueryCircul func (c *queryClient) CirculatingSupplyUSDX(ctx context.Context, in *QueryCirculatingSupplyUSDXRequest, opts ...grpc.CallOption) (*QueryCirculatingSupplyUSDXResponse, error) { out := new(QueryCirculatingSupplyUSDXResponse) - err := c.cc.Invoke(ctx, "/kava.validatorvesting.v1beta1.Query/CirculatingSupplyUSDX", in, out, opts...) + err := c.cc.Invoke(ctx, "/zgc.validatorvesting.v1beta1.Query/CirculatingSupplyUSDX", in, out, opts...) if err != nil { return nil, err } @@ -694,7 +694,7 @@ func (c *queryClient) CirculatingSupplyUSDX(ctx context.Context, in *QueryCircul func (c *queryClient) CirculatingSupplySWP(ctx context.Context, in *QueryCirculatingSupplySWPRequest, opts ...grpc.CallOption) (*QueryCirculatingSupplySWPResponse, error) { out := new(QueryCirculatingSupplySWPResponse) - err := c.cc.Invoke(ctx, "/kava.validatorvesting.v1beta1.Query/CirculatingSupplySWP", in, out, opts...) + err := c.cc.Invoke(ctx, "/zgc.validatorvesting.v1beta1.Query/CirculatingSupplySWP", in, out, opts...) if err != nil { return nil, err } @@ -703,7 +703,7 @@ func (c *queryClient) CirculatingSupplySWP(ctx context.Context, in *QueryCircula func (c *queryClient) TotalSupplyHARD(ctx context.Context, in *QueryTotalSupplyHARDRequest, opts ...grpc.CallOption) (*QueryTotalSupplyHARDResponse, error) { out := new(QueryTotalSupplyHARDResponse) - err := c.cc.Invoke(ctx, "/kava.validatorvesting.v1beta1.Query/TotalSupplyHARD", in, out, opts...) + err := c.cc.Invoke(ctx, "/zgc.validatorvesting.v1beta1.Query/TotalSupplyHARD", in, out, opts...) if err != nil { return nil, err } @@ -712,7 +712,7 @@ func (c *queryClient) TotalSupplyHARD(ctx context.Context, in *QueryTotalSupplyH func (c *queryClient) TotalSupplyUSDX(ctx context.Context, in *QueryTotalSupplyUSDXRequest, opts ...grpc.CallOption) (*QueryTotalSupplyUSDXResponse, error) { out := new(QueryTotalSupplyUSDXResponse) - err := c.cc.Invoke(ctx, "/kava.validatorvesting.v1beta1.Query/TotalSupplyUSDX", in, out, opts...) + err := c.cc.Invoke(ctx, "/zgc.validatorvesting.v1beta1.Query/TotalSupplyUSDX", in, out, opts...) if err != nil { return nil, err } @@ -721,9 +721,9 @@ func (c *queryClient) TotalSupplyUSDX(ctx context.Context, in *QueryTotalSupplyU // QueryServer is the server API for Query service. type QueryServer interface { - // CirculatingSupply returns the total amount of kava tokens in circulation + // CirculatingSupply returns the total amount of 0g-chain tokens in circulation CirculatingSupply(context.Context, *QueryCirculatingSupplyRequest) (*QueryCirculatingSupplyResponse, error) - // TotalSupply returns the total amount of kava tokens + // TotalSupply returns the total amount of 0g-chain tokens TotalSupply(context.Context, *QueryTotalSupplyRequest) (*QueryTotalSupplyResponse, error) // CirculatingSupplyHARD returns the total amount of hard tokens in circulation CirculatingSupplyHARD(context.Context, *QueryCirculatingSupplyHARDRequest) (*QueryCirculatingSupplyHARDResponse, error) @@ -777,7 +777,7 @@ func _Query_CirculatingSupply_Handler(srv interface{}, ctx context.Context, dec } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/kava.validatorvesting.v1beta1.Query/CirculatingSupply", + FullMethod: "/zgc.validatorvesting.v1beta1.Query/CirculatingSupply", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).CirculatingSupply(ctx, req.(*QueryCirculatingSupplyRequest)) @@ -795,7 +795,7 @@ func _Query_TotalSupply_Handler(srv interface{}, ctx context.Context, dec func(i } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/kava.validatorvesting.v1beta1.Query/TotalSupply", + FullMethod: "/zgc.validatorvesting.v1beta1.Query/TotalSupply", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).TotalSupply(ctx, req.(*QueryTotalSupplyRequest)) @@ -813,7 +813,7 @@ func _Query_CirculatingSupplyHARD_Handler(srv interface{}, ctx context.Context, } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/kava.validatorvesting.v1beta1.Query/CirculatingSupplyHARD", + FullMethod: "/zgc.validatorvesting.v1beta1.Query/CirculatingSupplyHARD", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).CirculatingSupplyHARD(ctx, req.(*QueryCirculatingSupplyHARDRequest)) @@ -831,7 +831,7 @@ func _Query_CirculatingSupplyUSDX_Handler(srv interface{}, ctx context.Context, } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/kava.validatorvesting.v1beta1.Query/CirculatingSupplyUSDX", + FullMethod: "/zgc.validatorvesting.v1beta1.Query/CirculatingSupplyUSDX", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).CirculatingSupplyUSDX(ctx, req.(*QueryCirculatingSupplyUSDXRequest)) @@ -849,7 +849,7 @@ func _Query_CirculatingSupplySWP_Handler(srv interface{}, ctx context.Context, d } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/kava.validatorvesting.v1beta1.Query/CirculatingSupplySWP", + FullMethod: "/zgc.validatorvesting.v1beta1.Query/CirculatingSupplySWP", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).CirculatingSupplySWP(ctx, req.(*QueryCirculatingSupplySWPRequest)) @@ -867,7 +867,7 @@ func _Query_TotalSupplyHARD_Handler(srv interface{}, ctx context.Context, dec fu } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/kava.validatorvesting.v1beta1.Query/TotalSupplyHARD", + FullMethod: "/zgc.validatorvesting.v1beta1.Query/TotalSupplyHARD", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).TotalSupplyHARD(ctx, req.(*QueryTotalSupplyHARDRequest)) @@ -885,7 +885,7 @@ func _Query_TotalSupplyUSDX_Handler(srv interface{}, ctx context.Context, dec fu } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/kava.validatorvesting.v1beta1.Query/TotalSupplyUSDX", + FullMethod: "/zgc.validatorvesting.v1beta1.Query/TotalSupplyUSDX", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).TotalSupplyUSDX(ctx, req.(*QueryTotalSupplyUSDXRequest)) @@ -894,7 +894,7 @@ func _Query_TotalSupplyUSDX_Handler(srv interface{}, ctx context.Context, dec fu } var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.validatorvesting.v1beta1.Query", + ServiceName: "zgc.validatorvesting.v1beta1.Query", HandlerType: (*QueryServer)(nil), Methods: []grpc.MethodDesc{ { @@ -927,7 +927,7 @@ var _Query_serviceDesc = grpc.ServiceDesc{ }, }, Streams: []grpc.StreamDesc{}, - Metadata: "kava/validatorvesting/v1beta1/query.proto", + Metadata: "zgc/validatorvesting/v1beta1/query.proto", } func (m *QueryCirculatingSupplyRequest) Marshal() (dAtA []byte, err error) { diff --git a/x/validator-vesting/types/query.pb.gw.go b/x/validator-vesting/types/query.pb.gw.go index 4b9c0d4f..c43a43c4 100644 --- a/x/validator-vesting/types/query.pb.gw.go +++ b/x/validator-vesting/types/query.pb.gw.go @@ -1,5 +1,5 @@ // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/validatorvesting/v1beta1/query.proto +// source: zgc/validatorvesting/v1beta1/query.proto /* Package types is a reverse proxy. @@ -511,19 +511,19 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } var ( - pattern_Query_CirculatingSupply_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "validator-vesting", "v1beta1", "circulating_supply"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_CirculatingSupply_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"0g-chain", "validator-vesting", "v1beta1", "circulating_supply"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_TotalSupply_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "validator-vesting", "v1beta1", "total_supply"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_TotalSupply_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"0g-chain", "validator-vesting", "v1beta1", "total_supply"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_CirculatingSupplyHARD_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "validator-vesting", "v1beta1", "circulating_supply_hard"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_CirculatingSupplyHARD_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"0g-chain", "validator-vesting", "v1beta1", "circulating_supply_hard"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_CirculatingSupplyUSDX_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "validator-vesting", "v1beta1", "circulating_supply_usdx"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_CirculatingSupplyUSDX_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"0g-chain", "validator-vesting", "v1beta1", "circulating_supply_usdx"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_CirculatingSupplySWP_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "validator-vesting", "v1beta1", "circulating_supply_swp"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_CirculatingSupplySWP_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"0g-chain", "validator-vesting", "v1beta1", "circulating_supply_swp"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_TotalSupplyHARD_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "validator-vesting", "v1beta1", "total_supply_hard"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_TotalSupplyHARD_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"0g-chain", "validator-vesting", "v1beta1", "total_supply_hard"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_TotalSupplyUSDX_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "validator-vesting", "v1beta1", "total_supply_usdx"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_TotalSupplyUSDX_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"0g-chain", "validator-vesting", "v1beta1", "total_supply_usdx"}, "", runtime.AssumeColonVerbOpt(false))) ) var (