From 256e45efacd2f008bc24f75c13abd644fb49d76d Mon Sep 17 00:00:00 2001 From: Ryan Christoffersen <12519942+ryanchristo@users.noreply.github.com> Date: Mon, 22 Aug 2022 12:43:21 -0700 Subject: [PATCH] style: update golangci config and fix lint errors (#1384) * style: update golangci config and fix lint errors * include types package and fix lint errors * include data module and fix lint errors * include ecocredit module and fix lint errors * clean up configuration and update workflow * clean up configuration and update workflow * clean up configuration and update workflow * clean up configuration and update workflow * clean up configuration and update workflow * clean up configuration and update workflow * clean up configuration and update workflow * clean up configuration and update workflow * update format make command and apply fixes * update format make command and make tidy * try without gofmt and only goimports * try without gofmt and goimports * udpate changelog * update workflow and add todo comments --- .github/workflows/lint.yml | 65 +++++-- .golangci.yml | 49 ++--- CHANGELOG.md | 15 ++ Makefile | 21 +- app/app.go | 10 +- app/app_test.go | 3 +- app/client/cli/root.go | 3 +- app/client/cli/testnet.go | 5 +- app/sim_test.go | 11 +- app/test_helpers.go | 3 +- app/testsuite/network_config.go | 6 +- make/proto.mk | 4 + types/go.mod | 2 +- types/json_test.go | 7 +- types/math/dec.go | 9 +- types/math/dec_bench_test.go | 10 +- types/math/dec_test.go | 13 +- types/math/testing.go | 4 +- types/module/client/cli/module.go | 3 +- .../{grpc_gateway => grpcgateway}/module.go | 6 +- types/module/server/manager.go | 6 +- types/module/server/msgs.go | 2 +- types/module/server/root_module_key.go | 5 +- types/module/server/router.go | 7 +- types/module/server/testutil.go | 3 +- types/ormstore/db_test.go | 14 +- types/ormstore/store.go | 6 +- types/ormutil/compatability.go | 5 +- types/testutil/fixture.go | 3 +- types/testutil/network/network.go | 14 +- types/testutil/network/util.go | 7 +- types/timestamp_test.go | 20 +- x/data/client/testsuite/grpc.go | 17 +- x/data/client/testsuite/query.go | 24 +-- x/data/client/testsuite/tx.go | 14 +- x/data/client/tx.go | 24 +-- x/data/iri.go | 9 +- x/data/mocks/expected_keepers.go | 3 +- x/data/module/module.go | 4 +- x/data/server/hasher/doc.go | 1 - x/data/server/hasher/hasher.go | 5 +- x/data/server/hasher/hasher_test.go | 12 +- x/data/server/msg_anchor.go | 56 +++--- x/data/server/msg_anchor_test.go | 8 +- x/data/server/msg_attest.go | 2 +- x/data/server/msg_attest_test.go | 22 +-- x/data/server/msg_define_resolver.go | 4 +- x/data/server/msg_define_resolver_test.go | 8 +- x/data/server/msg_register_resolver_test.go | 19 +- x/data/server/query_anchor_by_hash.go | 4 +- x/data/server/query_anchor_by_iri.go | 4 +- .../server/query_attestations_by_attestor.go | 4 +- x/data/server/query_attestations_by_hash.go | 4 +- x/data/server/query_attestations_by_iri.go | 4 +- x/data/server/query_resolver_test.go | 6 +- x/data/server/query_resolvers_by_hash.go | 4 +- x/data/server/query_resolvers_by_hash_test.go | 8 +- x/data/server/query_resolvers_by_iri.go | 4 +- x/data/server/query_resolvers_by_iri_test.go | 8 +- x/data/server/query_resolvers_by_url_test.go | 10 +- x/data/server/server_test.go | 4 + x/data/server/testsuite/genesis.go | 3 +- x/data/server/testsuite/suite.go | 4 +- x/data/simulation/genesis.go | 17 +- x/data/simulation/operations.go | 28 +-- x/data/types.go | 7 +- x/ecocredit/basket/date_criteria.go | 4 +- x/ecocredit/basket/date_criteria_test.go | 8 +- x/ecocredit/basket/msg_create.go | 2 +- x/ecocredit/client/basket/tx.go | 6 +- x/ecocredit/client/basket/util.go | 2 +- x/ecocredit/client/basket/util_test.go | 16 +- x/ecocredit/client/marketplace/query.go | 7 +- x/ecocredit/client/marketplace/tx.go | 4 +- x/ecocredit/client/marketplace/util.go | 6 +- x/ecocredit/client/marketplace/util_test.go | 48 ++--- x/ecocredit/client/query.go | 6 +- x/ecocredit/client/testsuite/grpc.go | 38 ++-- .../client/testsuite/grpc_marketplace.go | 4 +- x/ecocredit/client/testsuite/query.go | 64 ++++--- x/ecocredit/client/testsuite/query_basket.go | 8 +- .../client/testsuite/query_marketplace.go | 12 +- x/ecocredit/client/testsuite/suite.go | 44 ++--- x/ecocredit/client/testsuite/tx.go | 180 ++++++++++-------- x/ecocredit/client/testsuite/tx_basket.go | 33 ++-- .../client/testsuite/tx_marketplace.go | 93 ++++----- x/ecocredit/client/tx.go | 21 +- x/ecocredit/client/util.go | 2 +- x/ecocredit/client/util_test.go | 44 ++--- x/ecocredit/core/msg_bridge_receive.go | 6 +- x/ecocredit/core/msg_bridge_receive_test.go | 1 + x/ecocredit/core/msg_create_batch.go | 2 +- x/ecocredit/core/msg_create_project.go | 8 +- x/ecocredit/core/msg_create_project_test.go | 1 + x/ecocredit/core/msg_update_class_admin.go | 2 +- x/ecocredit/core/msg_update_class_issuers.go | 2 +- x/ecocredit/core/msg_update_class_metadata.go | 2 +- x/ecocredit/core/msg_update_project_admin.go | 2 +- .../core/msg_update_project_metadata.go | 2 +- x/ecocredit/core/state_class.go | 2 +- x/ecocredit/core/state_origin_tx_index.go | 2 +- .../core/state_origin_tx_index_test.go | 1 + x/ecocredit/core/state_project.go | 2 +- x/ecocredit/core/types_origin_tx.go | 4 +- x/ecocredit/core/utils.go | 74 ++++--- x/ecocredit/core/utils_test.go | 102 +++++----- x/ecocredit/genesis/genesis.go | 58 +++--- x/ecocredit/genesis/genesis_test.go | 8 +- x/ecocredit/mocks/expected_keepers.go | 3 +- x/ecocredit/module/module.go | 2 +- x/ecocredit/module/module_test.go | 3 +- x/ecocredit/orderbook/orderbook.go | 3 +- x/ecocredit/server/basket/invariants.go | 24 +-- x/ecocredit/server/basket/invariants_test.go | 10 +- x/ecocredit/server/basket/keeper_test.go | 15 +- x/ecocredit/server/basket/msg_create.go | 2 +- x/ecocredit/server/basket/msg_create_test.go | 3 +- x/ecocredit/server/basket/msg_put.go | 21 +- x/ecocredit/server/basket/msg_put_test.go | 72 +++---- x/ecocredit/server/basket/msg_take.go | 44 ++--- x/ecocredit/server/basket/msg_take_test.go | 42 ++-- .../server/basket/query_balance_test.go | 2 +- .../server/basket/query_balances_test.go | 7 +- x/ecocredit/server/basket/query_basket.go | 2 +- .../server/basket/query_basket_test.go | 20 +- x/ecocredit/server/basket/query_baskets.go | 2 +- x/ecocredit/server/basket/util_test.go | 32 ++-- x/ecocredit/server/core/invariants.go | 40 ++-- x/ecocredit/server/core/keeper_test.go | 9 +- x/ecocredit/server/core/msg_bridge_receive.go | 6 +- .../server/core/msg_bridge_receive_test.go | 45 +++-- x/ecocredit/server/core/msg_bridge_test.go | 14 +- x/ecocredit/server/core/msg_cancel_test.go | 18 +- .../server/core/msg_create_batch_test.go | 22 +-- x/ecocredit/server/core/msg_create_class.go | 2 +- .../server/core/msg_create_class_test.go | 6 +- x/ecocredit/server/core/msg_create_project.go | 14 +- .../server/core/msg_create_project_test.go | 11 +- .../core/msg_mint_batch_credits_test.go | 5 +- x/ecocredit/server/core/msg_retire_test.go | 18 +- .../server/core/msg_seal_batch_test.go | 5 +- x/ecocredit/server/core/msg_send_test.go | 18 +- .../core/msg_update_class_admin_test.go | 3 +- .../core/msg_update_class_issuers_test.go | 5 +- .../core/msg_update_class_metadata_test.go | 3 +- .../core/msg_update_project_admin_test.go | 3 +- .../core/msg_update_project_metadata_test.go | 3 +- x/ecocredit/server/core/query_balances.go | 3 + .../server/core/query_balances_test.go | 4 +- .../core/query_batches_by_class_test.go | 2 +- .../core/query_batches_by_issuer_test.go | 2 +- .../core/query_batches_by_project_test.go | 2 +- x/ecocredit/server/core/query_batches_test.go | 4 +- .../server/core/query_class_issuers_test.go | 8 +- .../core/query_projects_by_reference_id.go | 6 +- x/ecocredit/server/invariants_test.go | 11 +- .../features/msg_update_sell_orders.feature | 1 - x/ecocredit/server/marketplace/keeper_test.go | 79 +------- .../marketplace/msg_add_allowed_denom.go | 6 +- .../server/marketplace/msg_buy_direct.go | 10 +- .../server/marketplace/msg_buy_direct_test.go | 43 +++-- .../marketplace/msg_cancel_sell_order_test.go | 19 +- .../msg_remove_allowed_denom_test.go | 3 +- x/ecocredit/server/marketplace/msg_sell.go | 14 +- .../server/marketplace/msg_sell_test.go | 28 +-- .../marketplace/msg_update_sell_orders.go | 4 +- .../msg_update_sell_orders_test.go | 49 +++-- .../marketplace/query_allowed_denoms_test.go | 3 +- .../query_sell_orders_by_batch_test.go | 6 +- .../query_sell_orders_by_seller_test.go | 6 +- .../marketplace/query_sell_orders_test.go | 10 +- x/ecocredit/server/marketplace/utils.go | 8 +- x/ecocredit/server/server_test.go | 3 +- x/ecocredit/server/tests/bridge_test.go | 2 +- x/ecocredit/server/testsuite/genesis.go | 5 +- x/ecocredit/server/testsuite/suite.go | 28 +-- x/ecocredit/server/utils/test_utils.go | 3 +- x/ecocredit/server/utils/utils.go | 8 +- x/ecocredit/server/utils/utils_test.go | 5 +- x/ecocredit/simulation/basket/operations.go | 46 ++--- x/ecocredit/simulation/genesis.go | 25 +-- .../simulation/marketplace/operations.go | 13 +- x/ecocredit/simulation/operations.go | 32 ++-- 183 files changed, 1377 insertions(+), 1312 deletions(-) rename types/module/client/{grpc_gateway => grpcgateway}/module.go (94%) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 504706bd27..cdd54ab9d6 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -6,7 +6,7 @@ name: Lint # **Why we have it**: Ensures all go files and proto files are # properly formatted according to lint configuration files. # -# **What does it impact**: Code cleanliness. +# **What does it impact**: Code quality. on: pull_request: @@ -22,54 +22,95 @@ concurrency: jobs: golangci: runs-on: ubuntu-latest + strategy: + matrix: + module: ["app", "types", "x/data", "x/ecocredit"] steps: - uses: actions/checkout@v3 - uses: technote-space/get-diff-action@v6 + id: git-diff-app with: PATTERNS: | - **/**.go - **/go.mod - **/go.sum + app/**/**.go + go.mod + go.sum + if: matrix.module == 'app' + - uses: technote-space/get-diff-action@v6 + id: git-diff-types + with: + PATTERNS: | + types/**/**.go + types/go.mod + types/go.sum + if: matrix.module == 'types' + - uses: technote-space/get-diff-action@v6 + id: git-diff-data + with: + PATTERNS: | + x/data/**/**.go + x/data/go.mod + x/data/go.sum + if: matrix.module == 'x/data' + - uses: technote-space/get-diff-action@v6 + id: git-diff-ecocredit + with: + PATTERNS: | + x/ecocredit/**/**.go + x/ecocredit/go.mod + x/ecocredit/go.sum + if: matrix.module == 'x/ecocredit' - uses: actions/setup-go@v3 with: go-version-file: 'go.mod' if: env.GIT_DIFF - uses: golangci/golangci-lint-action@v3 with: - args: --timeout 5m --verbose - only-new-issues: true - if: env.GIT_DIFF + working-directory: "." + if: steps.git-diff-app.outputs.diff + - uses: golangci/golangci-lint-action@v3 + with: + working-directory: "types" + if: steps.git-diff-types.outputs.diff + - uses: golangci/golangci-lint-action@v3 + with: + working-directory: "x/data" + if: steps.git-diff-data.outputs.diff + - uses: golangci/golangci-lint-action@v3 + with: + working-directory: "x/ecocredit" + if: steps.git-diff-ecocredit.outputs.diff buf-lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: technote-space/get-diff-action@v6 - id: git_diff + id: git-diff-proto with: PATTERNS: | **/**.proto - uses: bufbuild/buf-setup-action@v1 - if: env.GIT_DIFF + if: steps.git-diff-proto.outputs.diff - uses: bufbuild/buf-lint-action@v1 with: input: 'proto' - if: env.GIT_DIFF + if: steps.git-diff-proto.outputs.diff protolint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: technote-space/get-diff-action@v6 + id: git-diff-proto with: PATTERNS: | **/**.proto - uses: actions/setup-go@v3 with: go-version-file: 'go.mod' - if: env.GIT_DIFF + if: steps.git-diff-proto.outputs.diff - name: Run protolint run: | go install github.com/yoheimuta/protolint/cmd/protolint@latest protolint . - if: env.GIT_DIFF + if: steps.git-diff-proto.outputs.diff diff --git a/.golangci.yml b/.golangci.yml index 1a55755611..42ec899b75 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,7 +1,5 @@ run: - tests: false -# # timeout for analysis, e.g. 30s, 5m, default is 1m -# timeout: 5m + timeout: 5m linters: disable-all: true @@ -11,61 +9,36 @@ linters: - depguard - dogsled - errcheck + - exportloopref - goconst - gocritic - - gofmt - - goimports - - golint + # TODO: investigate why golangci-lint-action is producing an error when latest golangci-lint does not locally + # - gofmt + # - goimports - gosec - gosimple - govet - ineffassign - - maligned - misspell - nakedret + - nolintlint - prealloc - - scopelint + - revive - staticcheck - - structcheck - stylecheck - typecheck - unconvert - - unused - unparam - - misspell + - unused + # TODO: consider enabling and resolving # - wsl - - nolintlint issues: exclude-rules: - - text: "Use of weak random number generator" + - text: "G404: Use of weak random number generator" linters: - gosec - - text: "comment on exported var" - linters: - - golint - - text: "don't use an underscore in package name" - linters: - - golint - - text: "ST1003:" - linters: - - stylecheck - # FIXME: Disabled until golangci-lint updates stylecheck with this fix: - # https://github.com/dominikh/go-tools/issues/389 - - text: "ST1016:" - linters: - - stylecheck - max-issues-per-linter: 10000 - max-same-issues: 10000 - + linters-settings: dogsled: max-blank-identifiers: 3 - maligned: - # print struct with more effective memory layout or not, false by default - suggest-new: true - nolintlint: - allow-unused: false - allow-leading-space: true - require-explanation: false - require-specific: false \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 1fa32c8527..80fe45a80b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -59,6 +59,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#1362](https://github.com/regen-network/regen-ledger/pull/1362) Update `ClassIssuer` state validation checks - [#1362](https://github.com/regen-network/regen-ledger/pull/1362) Update `CreditType` state validation checks - [#1362](https://github.com/regen-network/regen-ledger/pull/1362) Update `Project` state validation checks +- [#1384](https://github.com/regen-network/regen-ledger/pull/1384) Renamed `DateCriteria.ToApi` to `DateCriteria.ToAPI` +- [#1384](https://github.com/regen-network/regen-ledger/pull/1384) Renamed `QueryProjectsByReferenceIdCmd` to `QueryProjectsByReferenceIDCmd` +- [#1384](https://github.com/regen-network/regen-ledger/pull/1384) Renamed `FlagReferenceId` to `FlagReferenceID` +- [#1384](https://github.com/regen-network/regen-ledger/pull/1384) Renamed `MaxReferenceIdLength` to `MaxReferenceIDLength` +- [#1384](https://github.com/regen-network/regen-ledger/pull/1384) Renamed `RegexClassId` to `RegexClassID` +- [#1384](https://github.com/regen-network/regen-ledger/pull/1384) Renamed `RegexProjectId` to `RegexProjectID` +- [#1384](https://github.com/regen-network/regen-ledger/pull/1384) Renamed `FormatClassId` to `FormatClassID` +- [#1384](https://github.com/regen-network/regen-ledger/pull/1384) Renamed `FormatProjectId` to `FormatProjectID` +- [#1384](https://github.com/regen-network/regen-ledger/pull/1384) Renamed `ValidateClassId` to `ValidateClassID` +- [#1384](https://github.com/regen-network/regen-ledger/pull/1384) Renamed `ValidateProjectId` to `ValidateProjectID` +- [#1384](https://github.com/regen-network/regen-ledger/pull/1384) Renamed `GetClassIDFromProjectId` to `GetClassIDFromProjectID` +- [#1384](https://github.com/regen-network/regen-ledger/pull/1384) Renamed `GetClassIdFromBatchDenom` to `GetClassIDFromBatchDenom` +- [#1384](https://github.com/regen-network/regen-ledger/pull/1384) Renamed `GetProjectIdFromBatchDenom` to `GetProjectIDFromBatchDenom` +- [#1384](https://github.com/regen-network/regen-ledger/pull/1384) Renamed `GetCreditTypeAbbrevFromClassId` to `GetCreditTypeAbbrevFromClassID` +- [#1384](https://github.com/regen-network/regen-ledger/pull/1384) Renamed `BasketSupplyInvariant` to `SupplyInvariant` #### Removed diff --git a/Makefile b/Makefile index 146e84322a..a880e35964 100644 --- a/Makefile +++ b/Makefile @@ -206,12 +206,12 @@ generate: ############################################################################### lint: - golangci-lint run --out-format=tab - protolint . + @echo "Linting all go modules..." + @find . -name 'go.mod' -type f -execdir golangci-lint run --out-format=tab \; -lint-fix: - golangci-lint run --fix --out-format=tab --issues-exit-code=0 - protolint -fix . +lint-fix: format + @echo "Attempting to fix lint errors in all go modules..." + @find . -name 'go.mod' -type f -execdir golangci-lint run --fix --out-format=tab --issues-exit-code=0 \; format_filter = -name '*.go' -type f \ -not -path '*.git*' \ @@ -221,10 +221,15 @@ format_filter = -name '*.go' -type f \ -not -name '*.cosmos_orm.go' \ -not -name 'statik.go' +format_local = \ + github.com/tendermint/tendermint \ + github.com/cosmos/cosmos-sdk \ + github.com/cosmos/ibc-go \ + github.com/regen-network/regen-ledger + format: - @find . $(format_filter) | xargs gofmt -w -s - @find . $(format_filter) | xargs misspell -w - @find . $(format_filter) | xargs goimports -w + @echo "Formatting imports in all go modules..." + @find . $(format_filter) | xargs goimports -w -local $(subst $(whitespace),$(comma),$(format_local)) .PHONY: lint lint-fix format diff --git a/app/app.go b/app/app.go index 8ae24a0fb2..aa22744df4 100644 --- a/app/app.go +++ b/app/app.go @@ -10,10 +10,11 @@ import ( "github.com/gorilla/mux" "github.com/rakyll/statik/fs" "github.com/spf13/cast" + dbm "github.com/tendermint/tm-db" + abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tmos "github.com/tendermint/tendermint/libs/os" - dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" @@ -63,6 +64,9 @@ import ( govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" 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/group" + groupkeeper "github.com/cosmos/cosmos-sdk/x/group/keeper" + groupmodule "github.com/cosmos/cosmos-sdk/x/group/module" "github.com/cosmos/cosmos-sdk/x/mint" mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper" minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" @@ -80,10 +84,6 @@ import ( upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - "github.com/cosmos/cosmos-sdk/x/group" - groupkeeper "github.com/cosmos/cosmos-sdk/x/group/keeper" - groupmodule "github.com/cosmos/cosmos-sdk/x/group/module" - "github.com/cosmos/ibc-go/v5/modules/apps/transfer" ibctransferkeeper "github.com/cosmos/ibc-go/v5/modules/apps/transfer/keeper" ibctransfertypes "github.com/cosmos/ibc-go/v5/modules/apps/transfer/types" diff --git a/app/app_test.go b/app/app_test.go index 94b07bc338..24aa0e871a 100644 --- a/app/app_test.go +++ b/app/app_test.go @@ -5,8 +5,9 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/libs/log" dbm "github.com/tendermint/tm-db" + + "github.com/tendermint/tendermint/libs/log" ) func TestSimAppExportAndBlockedAddrs(t *testing.T) { diff --git a/app/client/cli/root.go b/app/client/cli/root.go index 283b7aefc6..ed34fff6b5 100644 --- a/app/client/cli/root.go +++ b/app/client/cli/root.go @@ -11,6 +11,8 @@ import ( "github.com/spf13/cast" "github.com/spf13/cobra" + dbm "github.com/tendermint/tm-db" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/config" @@ -35,7 +37,6 @@ import ( tmcfg "github.com/tendermint/tendermint/config" tmcli "github.com/tendermint/tendermint/libs/cli" "github.com/tendermint/tendermint/libs/log" - dbm "github.com/tendermint/tm-db" "github.com/regen-network/regen-ledger/v4/app" ) diff --git a/app/client/cli/testnet.go b/app/client/cli/testnet.go index 14a999e524..584f2bfb89 100644 --- a/app/client/cli/testnet.go +++ b/app/client/cli/testnet.go @@ -476,10 +476,9 @@ func calculateIP(ip string, i int) (string, error) { } func writeFile(name string, dir string, contents []byte) error { - writePath := filepath.Join(dir) - file := filepath.Join(writePath, name) + file := filepath.Join(dir, name) - err := tmos.EnsureDir(writePath, 0755) + err := tmos.EnsureDir(dir, 0755) if err != nil { return err } diff --git a/app/sim_test.go b/app/sim_test.go index 79b9f53cb0..161aa2165d 100644 --- a/app/sim_test.go +++ b/app/sim_test.go @@ -7,14 +7,12 @@ import ( "os" "testing" - ibctransfertypes "github.com/cosmos/ibc-go/v5/modules/apps/transfer/types" - ibchost "github.com/cosmos/ibc-go/v5/modules/core/24-host" - "github.com/regen-network/regen-ledger/x/ecocredit" "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" + abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/simapp" @@ -34,6 +32,11 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + ibctransfertypes "github.com/cosmos/ibc-go/v5/modules/apps/transfer/types" + ibchost "github.com/cosmos/ibc-go/v5/modules/core/24-host" + + "github.com/regen-network/regen-ledger/x/ecocredit" ) // Get flags every time the simulator is run diff --git a/app/test_helpers.go b/app/test_helpers.go index 96d26497bc..1c2523688c 100644 --- a/app/test_helpers.go +++ b/app/test_helpers.go @@ -5,12 +5,13 @@ import ( "time" "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" + abci "github.com/tendermint/tendermint/abci/types" tmjson "github.com/tendermint/tendermint/libs/json" "github.com/tendermint/tendermint/libs/log" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" tmtypes "github.com/tendermint/tendermint/types" - dbm "github.com/tendermint/tm-db" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" diff --git a/app/testsuite/network_config.go b/app/testsuite/network_config.go index 8203be4cdd..199bdbd915 100644 --- a/app/testsuite/network_config.go +++ b/app/testsuite/network_config.go @@ -4,6 +4,10 @@ import ( "fmt" "time" + dbm "github.com/tendermint/tm-db" + + tmrand "github.com/tendermint/tendermint/libs/rand" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -11,8 +15,6 @@ import ( servertypes "github.com/cosmos/cosmos-sdk/server/types" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - tmrand "github.com/tendermint/tendermint/libs/rand" - dbm "github.com/tendermint/tm-db" "github.com/regen-network/regen-ledger/types/testutil/network" "github.com/regen-network/regen-ledger/v4/app" diff --git a/make/proto.mk b/make/proto.mk index 2a196e8c6e..ad6479fc8c 100644 --- a/make/proto.mk +++ b/make/proto.mk @@ -26,6 +26,10 @@ DOCKER_BUF := docker run -v $(shell pwd):/workspace --workdir /workspace bufbuil proto-lint: @$(DOCKER_BUF) lint --error-format=json + @protolint . + +proto-lint-fix: + @protolint -fix . proto-check-breaking: @$(DOCKER_BUF) breaking --against https://github.com/regen-network/regen-ledger.git#branch=main diff --git a/types/go.mod b/types/go.mod index 1770943b54..4d615ccffe 100644 --- a/types/go.mod +++ b/types/go.mod @@ -3,6 +3,7 @@ module github.com/regen-network/regen-ledger/types go 1.18 require ( + cosmossdk.io/math v1.0.0-beta.2 github.com/cockroachdb/apd/v2 v2.0.2 github.com/cosmos/cosmos-sdk v0.46.0 github.com/cosmos/cosmos-sdk/api v0.1.0 @@ -25,7 +26,6 @@ require ( require ( cosmossdk.io/errors v1.0.0-beta.7 // indirect - cosmossdk.io/math v1.0.0-beta.2 // indirect filippo.io/edwards25519 v1.0.0-rc.1 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.1 // indirect diff --git a/types/json_test.go b/types/json_test.go index 0e7896bfb6..d5e7cd6391 100644 --- a/types/json_test.go +++ b/types/json_test.go @@ -44,11 +44,12 @@ func TestCheckDuplicateKey(t *testing.T) { } for _, tc := range testCases { + input, expErr, expErrMsg := tc.input, tc.expErr, tc.expErrMsg t.Run(tc.name, func(t *testing.T) { - err := CheckDuplicateKey(json.NewDecoder(strings.NewReader(tc.input)), nil) - if tc.expErr { + err := CheckDuplicateKey(json.NewDecoder(strings.NewReader(input)), nil) + if expErr { require.Error(t, err) - require.Contains(t, err.Error(), tc.expErrMsg) + require.Contains(t, err.Error(), expErrMsg) } else { require.NoError(t, err) } diff --git a/types/math/dec.go b/types/math/dec.go index 3da6c8f927..27b4bdebe8 100644 --- a/types/math/dec.go +++ b/types/math/dec.go @@ -4,8 +4,9 @@ import ( "fmt" "math/big" + sdkmath "cosmossdk.io/math" "github.com/cockroachdb/apd/v2" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -206,9 +207,9 @@ func (x Dec) BigInt() (*big.Int, error) { return z, nil } -// SdkIntTrim rounds decimal number to the integer towards zero and converts it to `sdk.Int`. +// SdkIntTrim rounds decimal number to the integer towards zero and converts it to `sdkmath.Int`. // Panics if x is bigger the SDK Int max value -func (x Dec) SdkIntTrim() sdk.Int { +func (x Dec) SdkIntTrim() sdkmath.Int { y, _ := x.Reduce() var r = y.dec.Coeff if y.dec.Exponent != 0 { @@ -224,7 +225,7 @@ func (x Dec) SdkIntTrim() sdk.Int { if x.dec.Negative { r.Neg(&r) } - return sdk.NewIntFromBigInt(&r) + return sdkmath.NewIntFromBigInt(&r) } func (x Dec) String() string { diff --git a/types/math/dec_bench_test.go b/types/math/dec_bench_test.go index 9537b7899b..49fb05b879 100644 --- a/types/math/dec_bench_test.go +++ b/types/math/dec_bench_test.go @@ -3,7 +3,7 @@ package math import ( "testing" - sdk "github.com/cosmos/cosmos-sdk/types" + sdkmath "cosmossdk.io/math" ) func BenchmarkSdkIntTrim(b *testing.B) { @@ -33,7 +33,7 @@ func BenchmarkSdkIntTrim(b *testing.B) { } -func sdkIntTrimQuo(d Dec) sdk.Int { +func sdkIntTrimQuo(d Dec) sdkmath.Int { d, err := d.QuoInteger(NewDecFromInt64(1)) if err != nil { panic(err) @@ -43,17 +43,17 @@ func sdkIntTrimQuo(d Dec) sdk.Int { if err != nil { panic(err) } - return sdk.NewIntFromBigInt(i) + return sdkmath.NewIntFromBigInt(i) } -func sdkIntTrimNaive(d Dec) sdk.Int { +func sdkIntTrimNaive(d Dec) sdkmath.Int { d, err := d.QuoInteger(NewDecFromInt64(1)) if err != nil { panic(err) } s := d.String() - i, ok := sdk.NewIntFromString(s) + i, ok := sdkmath.NewIntFromString(s) if !ok { panic("can't convert from string") } diff --git a/types/math/dec_test.go b/types/math/dec_test.go index a799c5336e..25713a92ba 100644 --- a/types/math/dec_test.go +++ b/types/math/dec_test.go @@ -52,7 +52,7 @@ func TestDec(t *testing.T) { t.Run("TestMulQuoExact", rapid.MakeCheck(testMulQuoExact)) t.Run("TestQuoMulExact", rapid.MakeCheck(testQuoMulExact)) - // Properties about comparision and equality + // Properties about comparison and equality t.Run("TestCmpInverse", rapid.MakeCheck(testCmpInverse)) t.Run("TestEqualCommutative", rapid.MakeCheck(testEqualCommutative)) @@ -97,14 +97,14 @@ func TestDec(t *testing.T) { require.NoError(t, err) require.True(t, res.Equal(three)) - res, err = SafeSubBalance(two, five) + _, err = SafeSubBalance(two, five) require.Error(t, err, "Expected insufficient funds error") res, err = SafeAddBalance(three, two) require.NoError(t, err) require.True(t, res.Equal(five)) - res, err = SafeAddBalance(minusFivePointZero, five) + _, err = SafeAddBalance(minusFivePointZero, five) require.Error(t, err, "Expected ErrInvalidRequest") res, err = four.Quo(two) @@ -591,11 +591,12 @@ func floatDecimalPlaces(t *rapid.T, f float64) uint32 { } // Subtract exponent from base and check if negative - if res := basePlaces - exp; res <= 0 { + res := basePlaces - exp + if res <= 0 { return 0 - } else { - return uint32(res) } + + return uint32(res) } func TestIsFinite(t *testing.T) { diff --git a/types/math/testing.go b/types/math/testing.go index 2ac807b890..9418cde04a 100644 --- a/types/math/testing.go +++ b/types/math/testing.go @@ -27,9 +27,9 @@ func (d *decEq) Matches(x interface{}) bool { if y.Cmp(d.dec) != 0 { d.msg = fmt.Sprintf("%s != %s", d.dec, y) return false - } else { - return true } + + return true } func (d *decEq) String() string { diff --git a/types/module/client/cli/module.go b/types/module/client/cli/module.go index 40e67e248d..819b62ac8c 100644 --- a/types/module/client/cli/module.go +++ b/types/module/client/cli/module.go @@ -3,9 +3,10 @@ package cli import ( "encoding/json" + "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" - "github.com/spf13/cobra" "github.com/regen-network/regen-ledger/types/module" ) diff --git a/types/module/client/grpc_gateway/module.go b/types/module/client/grpcgateway/module.go similarity index 94% rename from types/module/client/grpc_gateway/module.go rename to types/module/client/grpcgateway/module.go index 635528f6b7..4a3cf584f6 100644 --- a/types/module/client/grpc_gateway/module.go +++ b/types/module/client/grpcgateway/module.go @@ -1,8 +1,10 @@ -package grpc_gateway +package grpcgateway import ( - "github.com/cosmos/cosmos-sdk/client" "github.com/grpc-ecosystem/grpc-gateway/runtime" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/regen-network/regen-ledger/types/module" ) diff --git a/types/module/server/manager.go b/types/module/server/manager.go index 8382d43d08..6ca7b48639 100644 --- a/types/module/server/manager.go +++ b/types/module/server/manager.go @@ -7,14 +7,16 @@ import ( "reflect" "sort" + gogogrpc "github.com/gogo/protobuf/grpc" + + abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkmodule "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/types/simulation" - gogogrpc "github.com/gogo/protobuf/grpc" - abci "github.com/tendermint/tendermint/abci/types" "github.com/regen-network/regen-ledger/types" "github.com/regen-network/regen-ledger/types/module" diff --git a/types/module/server/msgs.go b/types/module/server/msgs.go index 18ac10f60a..8f6f9bbc14 100644 --- a/types/module/server/msgs.go +++ b/types/module/server/msgs.go @@ -30,7 +30,7 @@ func GetMsgs(anys []*types.Any) ([]sdk.Msg, error) { for i, any := range anys { cached := any.GetCachedValue() if cached == nil { - return nil, fmt.Errorf("any cached value is nil, proposal messages must be correctly packed Any values.") + return nil, fmt.Errorf("any cached value is nil, proposal messages must be correctly packed Any values") } msgs[i] = cached.(sdk.Msg) } diff --git a/types/module/server/root_module_key.go b/types/module/server/root_module_key.go index 2968f6dbf3..494d8eb535 100644 --- a/types/module/server/root_module_key.go +++ b/types/module/server/root_module_key.go @@ -4,11 +4,12 @@ import ( "context" "fmt" - "github.com/regen-network/regen-ledger/types" + "google.golang.org/grpc" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" - "google.golang.org/grpc" + + "github.com/regen-network/regen-ledger/types" ) type RootModuleKey interface { diff --git a/types/module/server/router.go b/types/module/server/router.go index 31530d1dcc..142b5f74d4 100644 --- a/types/module/server/router.go +++ b/types/module/server/router.go @@ -6,13 +6,14 @@ import ( "fmt" "reflect" - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" gogogrpc "github.com/gogo/protobuf/grpc" "github.com/gogo/protobuf/proto" "google.golang.org/grpc" + "github.com/cosmos/cosmos-sdk/baseapp" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/regen-network/regen-ledger/types" ) diff --git a/types/module/server/testutil.go b/types/module/server/testutil.go index 6eef06102d..ac1c2400d3 100644 --- a/types/module/server/testutil.go +++ b/types/module/server/testutil.go @@ -9,10 +9,11 @@ import ( "github.com/stretchr/testify/require" "google.golang.org/grpc" + dbm "github.com/tendermint/tm-db" + abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" diff --git a/types/ormstore/db_test.go b/types/ormstore/db_test.go index 0cd1639a39..081cc1cf7b 100644 --- a/types/ormstore/db_test.go +++ b/types/ormstore/db_test.go @@ -3,17 +3,19 @@ package ormstore import ( "testing" - ormv1alpha1 "github.com/cosmos/cosmos-sdk/api/cosmos/orm/v1alpha1" - ecocreditv1 "github.com/regen-network/regen-ledger/api/regen/ecocredit/v1" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" + + "github.com/tendermint/tendermint/libs/log" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + ormv1alpha1 "github.com/cosmos/cosmos-sdk/api/cosmos/orm/v1alpha1" "github.com/cosmos/cosmos-sdk/orm/model/ormdb" "github.com/cosmos/cosmos-sdk/store" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/libs/log" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" + + ecocreditv1 "github.com/regen-network/regen-ledger/api/regen/ecocredit/v1" ) func sdkContextForStoreKey(key *storetypes.KVStoreKey) sdk.Context { diff --git a/types/ormstore/store.go b/types/ormstore/store.go index bd0785dc7f..5b35117069 100644 --- a/types/ormstore/store.go +++ b/types/ormstore/store.go @@ -1,7 +1,9 @@ package ormstore -import storetypes "github.com/cosmos/cosmos-sdk/types" -import "github.com/cosmos/cosmos-sdk/orm/types/kv" +import ( + "github.com/cosmos/cosmos-sdk/orm/types/kv" + storetypes "github.com/cosmos/cosmos-sdk/types" +) type storeWrapper struct { store storetypes.KVStore diff --git a/types/ormutil/compatability.go b/types/ormutil/compatability.go index 66d22f28d2..2fc3a961db 100644 --- a/types/ormutil/compatability.go +++ b/types/ormutil/compatability.go @@ -1,10 +1,11 @@ package ormutil import ( - queryv1beta1 "github.com/cosmos/cosmos-sdk/api/cosmos/base/query/v1beta1" - "github.com/cosmos/cosmos-sdk/types/query" gogoproto "github.com/gogo/protobuf/proto" "google.golang.org/protobuf/proto" + + queryv1beta1 "github.com/cosmos/cosmos-sdk/api/cosmos/base/query/v1beta1" + "github.com/cosmos/cosmos-sdk/types/query" ) func GogoPageReqToPulsarPageReq(from *query.PageRequest) (*queryv1beta1.PageRequest, error) { diff --git a/types/testutil/fixture.go b/types/testutil/fixture.go index d426329653..1020f5e07d 100644 --- a/types/testutil/fixture.go +++ b/types/testutil/fixture.go @@ -13,10 +13,11 @@ import ( "context" "encoding/json" + "google.golang.org/grpc" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" - "google.golang.org/grpc" ) // FixtureFactory defines an interface for creating server test fixtures diff --git a/types/testutil/network/network.go b/types/testutil/network/network.go index 2b61da71b7..204883993d 100644 --- a/types/testutil/network/network.go +++ b/types/testutil/network/network.go @@ -15,11 +15,13 @@ import ( "testing" "time" + sdkmath "cosmossdk.io/math" "github.com/rs/zerolog" "github.com/spf13/cobra" + "google.golang.org/grpc" + "github.com/tendermint/tendermint/node" tmclient "github.com/tendermint/tendermint/rpc/client" - "google.golang.org/grpc" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" @@ -63,9 +65,9 @@ type Config struct { Mnemonics []string // custom user-provided validator operator mnemonics BondDenom string // the staking bond denomination MinGasPrices string // the minimum gas prices each validator will accept - AccountTokens sdk.Int // the amount of unique validator tokens (e.g. 1000node0) - StakingTokens sdk.Int // the amount of tokens each validator has available to stake - BondedTokens sdk.Int // the amount of tokens each validator stakes + AccountTokens sdkmath.Int // the amount of unique validator tokens (e.g. 1000node0) + StakingTokens sdkmath.Int // the amount of tokens each validator has available to stake + BondedTokens sdkmath.Int // the amount of tokens each validator stakes PruningStrategy string // the pruning strategy each validator will have EnableTMLogging bool // enable Tendermint logging to STDOUT CleanupDir bool // remove base temporary directory during cleanup @@ -356,7 +358,7 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { sdk.NewCoin(cfg.BondDenom, cfg.BondedTokens), stakingtypes.NewDescription(nodeDirName, "", "", "", ""), stakingtypes.NewCommissionRates(commission, sdk.OneDec(), sdk.OneDec()), - sdk.OneInt(), + sdkmath.OneInt(), ) if err != nil { return nil, err @@ -368,7 +370,7 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { } memo := fmt.Sprintf("%s@%s:%s", nodeIDs[i], p2pURL.Hostname(), p2pURL.Port()) - fee := sdk.NewCoins(sdk.NewCoin(fmt.Sprintf("%stoken", nodeDirName), sdk.NewInt(0))) + fee := sdk.NewCoins(sdk.NewCoin(fmt.Sprintf("%stoken", nodeDirName), sdkmath.NewInt(0))) txBuilder := cfg.TxConfig.NewTxBuilder() err = txBuilder.SetMsgs(createValMsg) if err != nil { diff --git a/types/testutil/network/util.go b/types/testutil/network/util.go index 05931dc886..6cce1640a8 100644 --- a/types/testutil/network/util.go +++ b/types/testutil/network/util.go @@ -193,15 +193,14 @@ func initGenFiles(cfg Config, genAccounts []authtypes.GenesisAccount, genBalance } func writeFile(name string, dir string, contents []byte) error { - writePath := filepath.Join(dir) - file := filepath.Join(writePath, name) + file := filepath.Join(dir, name) - err := tmos.EnsureDir(writePath, 0o755) + err := tmos.EnsureDir(dir, 0o755) if err != nil { return err } - err = ioutil.WriteFile(file, contents, 0o644) // nolint: gosec + err = ioutil.WriteFile(file, contents, 0o644) //nolint: gosec if err != nil { return err } diff --git a/types/timestamp_test.go b/types/timestamp_test.go index b271323339..5cb4261428 100644 --- a/types/timestamp_test.go +++ b/types/timestamp_test.go @@ -34,9 +34,10 @@ func TestGogoToProtobufDuration(t *testing.T) { }, } for _, tt := range tests { + args, want := tt.args, tt.want t.Run(tt.name, func(t *testing.T) { - if got := types.GogoToProtobufDuration(tt.args.d); !reflect.DeepEqual(got, tt.want) { - t.Errorf("GogoToProtobufDuration() = %v, want %v", got, tt.want) + if got := types.GogoToProtobufDuration(args.d); !reflect.DeepEqual(got, want) { + t.Errorf("GogoToProtobufDuration() = %v, want %v", got, want) } }) } @@ -63,9 +64,10 @@ func TestGogoToProtobufTimestamp(t *testing.T) { }, } for _, tt := range tests { + args, want := tt.args, tt.want t.Run(tt.name, func(t *testing.T) { - if got := types.GogoToProtobufTimestamp(tt.args.ts); !reflect.DeepEqual(got, tt.want) { - t.Errorf("GogoToProtobufTimestamp() = %v, want %v", got, tt.want) + if got := types.GogoToProtobufTimestamp(args.ts); !reflect.DeepEqual(got, want) { + t.Errorf("GogoToProtobufTimestamp() = %v, want %v", got, want) } }) } @@ -92,9 +94,10 @@ func TestProtobufToGogoTimestamp(t *testing.T) { }, } for _, tt := range tests { + args, want := tt.args, tt.want t.Run(tt.name, func(t *testing.T) { - if got := types.ProtobufToGogoTimestamp(tt.args.ts); !reflect.DeepEqual(got, tt.want) { - t.Errorf("ProtobufToGogoTimestamp() = %v, want %v", got, tt.want) + if got := types.ProtobufToGogoTimestamp(args.ts); !reflect.DeepEqual(got, want) { + t.Errorf("ProtobufToGogoTimestamp() = %v, want %v", got, want) } }) } @@ -110,10 +113,11 @@ func TestParseDate(t *testing.T) { {"bad", "01-2021-20", true}, } for _, tc := range tcs { + date, hasErr := tc.date, tc.hasErr t.Run(tc.name, func(t *testing.T) { require := require.New(t) - tm, err := types.ParseDate(tc.date, tc.date) - if tc.hasErr { + tm, err := types.ParseDate(date, date) + if hasErr { require.Error(err) require.Equal(time.Time{}, tm) } else { diff --git a/x/data/client/testsuite/grpc.go b/x/data/client/testsuite/grpc.go index f2d853d55e..0edceda5a3 100644 --- a/x/data/client/testsuite/grpc.go +++ b/x/data/client/testsuite/grpc.go @@ -11,7 +11,10 @@ import ( "github.com/regen-network/regen-ledger/x/data" ) -const dataRoute = "regen/data/v1" +const ( + dataRoute = "regen/data/v1" + pagination = "pagination.limit=1&pagination.countTotal=true" +) func (s *IntegrationTestSuite) TestQueryAnchorByIRI() { require := s.Require() @@ -84,8 +87,6 @@ func (s *IntegrationTestSuite) TestQueryAnchorByHash() { func (s *IntegrationTestSuite) TestQueryAttestationsByAttestor() { require := s.Require() - pgn := "pagination.limit=1&pagination.countTotal=true" - testCases := []struct { name string url string @@ -106,7 +107,7 @@ func (s *IntegrationTestSuite) TestQueryAttestationsByAttestor() { s.val.APIAddress, dataRoute, s.addr1, - pgn, + pagination, ), }, { @@ -145,8 +146,6 @@ func (s *IntegrationTestSuite) TestQueryAttestationsByAttestor() { func (s *IntegrationTestSuite) TestQueryAttestationsByIRI() { require := s.Require() - pgn := "pagination.limit=1&pagination.countTotal=true" - testCases := []struct { name string url string @@ -167,7 +166,7 @@ func (s *IntegrationTestSuite) TestQueryAttestationsByIRI() { s.val.APIAddress, dataRoute, s.iri2, - pgn, + pagination, ), }, { @@ -293,8 +292,6 @@ func (s *IntegrationTestSuite) TestQueryResolver() { func (s *IntegrationTestSuite) TestQueryResolversByIRI() { require := s.Require() - pgn := "pagination.limit=1&pagination.countTotal=true" - testCases := []struct { name string url string @@ -305,7 +302,7 @@ func (s *IntegrationTestSuite) TestQueryResolversByIRI() { }, { "valid with pagination", - fmt.Sprintf("%s/%s/resolvers-by-iri/%s?%s", s.val.APIAddress, dataRoute, s.iri1, pgn), + fmt.Sprintf("%s/%s/resolvers-by-iri/%s?%s", s.val.APIAddress, dataRoute, s.iri1, pagination), }, { "valid alternative", diff --git a/x/data/client/testsuite/query.go b/x/data/client/testsuite/query.go index c7f5d72ab3..a8f55c40a6 100644 --- a/x/data/client/testsuite/query.go +++ b/x/data/client/testsuite/query.go @@ -12,10 +12,12 @@ import ( "github.com/regen-network/regen-ledger/x/data/client" ) +const outputFormat = "JSON" + func (s *IntegrationTestSuite) TestQueryAnchorByIRICmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -62,7 +64,7 @@ func (s *IntegrationTestSuite) TestQueryAnchorByIRICmd() { func (s *IntegrationTestSuite) TestQueryAnchorByHashCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat bz, err := s.val.ClientCtx.Codec.MarshalJSON(s.hash1) require.NoError(err) @@ -120,7 +122,7 @@ func (s *IntegrationTestSuite) TestQueryAnchorByHashCmd() { func (s *IntegrationTestSuite) TestQueryAttestationsByAttestorCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -181,7 +183,7 @@ func (s *IntegrationTestSuite) TestQueryAttestationsByAttestorCmd() { func (s *IntegrationTestSuite) TestQueryAttestationsByIRICmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -242,7 +244,7 @@ func (s *IntegrationTestSuite) TestQueryAttestationsByIRICmd() { func (s *IntegrationTestSuite) TestQueryAttestationsByHashCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat bz, err := s.val.ClientCtx.Codec.MarshalJSON(s.hash1) require.NoError(err) @@ -314,7 +316,7 @@ func (s *IntegrationTestSuite) TestQueryAttestationsByHashCmd() { func (s *IntegrationTestSuite) TestQueryResolverCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -361,7 +363,7 @@ func (s *IntegrationTestSuite) TestQueryResolverCmd() { func (s *IntegrationTestSuite) TestQueryResolversByIRICmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -422,7 +424,7 @@ func (s *IntegrationTestSuite) TestQueryResolversByIRICmd() { func (s *IntegrationTestSuite) TestQueryResolversByHashCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat bz, err := s.val.ClientCtx.Codec.MarshalJSON(s.hash1) require.NoError(err) @@ -494,7 +496,7 @@ func (s *IntegrationTestSuite) TestQueryResolversByHashCmd() { func (s *IntegrationTestSuite) TestQueryResolversByURLCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -555,7 +557,7 @@ func (s *IntegrationTestSuite) TestQueryResolversByURLCmd() { func (s *IntegrationTestSuite) TestConvertIRIToHashCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -602,7 +604,7 @@ func (s *IntegrationTestSuite) TestConvertIRIToHashCmd() { func (s *IntegrationTestSuite) TestConvertHashToIRICmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat bz, err := s.val.ClientCtx.Codec.MarshalJSON(s.hash1) require.NoError(err) diff --git a/x/data/client/testsuite/tx.go b/x/data/client/testsuite/tx.go index b567445f90..6157027406 100644 --- a/x/data/client/testsuite/tx.go +++ b/x/data/client/testsuite/tx.go @@ -190,12 +190,12 @@ func (s *IntegrationTestSuite) SetupSuite() { s.Require().NoError(s.val.ClientCtx.Codec.UnmarshalJSON(out2.Bytes(), &res2)) id2 := strings.Trim(res2.Logs[0].Events[1].Attributes[0].Value, "\"") - resolverId2, err := strconv.ParseUint(id2, 10, 64) + resolverID2, err := strconv.ParseUint(id2, 10, 64) s.Require().NoError(err) _, err = cli.ExecTestCLICmd(s.val.ClientCtx, client.MsgRegisterResolverCmd(), append( []string{ - fmt.Sprintf("%d", resolverId2), + fmt.Sprintf("%d", resolverID2), filePath, fmt.Sprintf("--%s=%s", flags.FlagFrom, s.addr1.String()), }, @@ -206,8 +206,7 @@ func (s *IntegrationTestSuite) SetupSuite() { func (s *IntegrationTestSuite) TearDownSuite() { s.T().Log("tearing down integration test suite") - - s.network.WaitForNextBlock() + s.Require().NoError(s.network.WaitForNextBlock()) s.network.Cleanup() } @@ -346,7 +345,7 @@ func (s *IntegrationTestSuite) TestDefineResolverCmd() { testCases := []struct { name string - resolverUrl string + resolverURL string expErr bool errMsg string }{ @@ -373,7 +372,7 @@ func (s *IntegrationTestSuite) TestDefineResolverCmd() { cmd := client.MsgDefineResolverCmd() for _, tc := range testCases { s.Run(tc.name, func() { - args := []string{tc.resolverUrl} + args := []string{tc.resolverURL} args = append(args, commonFlags...) _, err := cli.ExecTestCLICmd(clientCtx, cmd, args) if tc.expErr { @@ -445,8 +444,9 @@ func (s *IntegrationTestSuite) TestRegisterResolverCmd() { cmd := client.MsgRegisterResolverCmd() for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { - args := append(tc.args, commonFlags...) + args := append(args, commonFlags...) res, err := cli.ExecTestCLICmd(clientCtx, cmd, args) if tc.expErr { require.Error(err) diff --git a/x/data/client/tx.go b/x/data/client/tx.go index 306cda0b40..d382e86074 100644 --- a/x/data/client/tx.go +++ b/x/data/client/tx.go @@ -7,14 +7,14 @@ import ( "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" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/regen-network/regen-ledger/x/data" - sdkclient "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/spf13/cobra" + "github.com/regen-network/regen-ledger/x/data" ) // TxCmd returns a root CLI command handler for all x/data transaction commands. @@ -24,7 +24,7 @@ func TxCmd(name string) *cobra.Command { Short: "Data transaction subcommands", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, - RunE: sdkclient.ValidateCmd, + RunE: client.ValidateCmd, } cmd.AddCommand( @@ -45,7 +45,7 @@ func MsgAnchorCmd() *cobra.Command { "hash, effectively providing a tamper resistant timestamp.", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := sdkclient.GetClientTxContext(cmd) + clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err } @@ -85,7 +85,7 @@ Attest to the veracity of more than one entry using a comma-separated (no spaces Example: "regen tx data attest regen:13toVgf5aZqSVSeJQv562xkkeoe3rr3bJWa29PHVKVf77VAkVMcDvVd.rdf", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := sdkclient.GetClientTxContext(cmd) + clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err } @@ -140,19 +140,19 @@ Flags: Example: "regen tx data define-resolver https://foo.bar --from manager", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := sdkclient.GetClientTxContext(cmd) + clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err } - resolverUrl := args[0] - if _, err := url.ParseRequestURI(resolverUrl); err != nil { + resolverURL := args[0] + if _, err := url.ParseRequestURI(resolverURL); err != nil { return err } msg := data.MsgDefineResolver{ Manager: clientCtx.GetFromAddress().String(), - ResolverUrl: resolverUrl, + ResolverUrl: resolverURL, } return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) }, @@ -194,7 +194,7 @@ Flags: `, Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := sdkclient.GetClientTxContext(cmd) + clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err } diff --git a/x/data/iri.go b/x/data/iri.go index 7539e2694c..01b8eda87d 100644 --- a/x/data/iri.go +++ b/x/data/iri.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/btcsuite/btcutil/base58" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -27,8 +28,6 @@ const ( IriPrefixRaw byte = 0 IriPrefixGraph byte = 1 - - didVersion0 byte = 0 ) // ToIRI converts the ContentHash_Raw to an IRI (internationalized URI) based on the following @@ -74,10 +73,10 @@ func (chg ContentHash_Graph) ToIRI() (string, error) { } // ToExtension converts the media type to a file extension based on the mediaTypeExtensions map. -func (mt RawMediaType) ToExtension() (string, error) { - ext, ok := mediaExtensionTypeToString[mt] +func (rmt RawMediaType) ToExtension() (string, error) { + ext, ok := mediaExtensionTypeToString[rmt] if !ok { - return "", sdkerrors.ErrInvalidRequest.Wrapf("missing extension for %T %s", mt, mt) + return "", sdkerrors.ErrInvalidRequest.Wrapf("missing extension for %T %s", rmt, rmt) } return ext, nil diff --git a/x/data/mocks/expected_keepers.go b/x/data/mocks/expected_keepers.go index 742a27837c..5eeadd3ebf 100644 --- a/x/data/mocks/expected_keepers.go +++ b/x/data/mocks/expected_keepers.go @@ -7,9 +7,10 @@ package mocks import ( reflect "reflect" + gomock "github.com/golang/mock/gomock" + types "github.com/cosmos/cosmos-sdk/types" types0 "github.com/cosmos/cosmos-sdk/x/auth/types" - gomock "github.com/golang/mock/gomock" ) // MockAccountKeeper is a mock of AccountKeeper interface. diff --git a/x/data/module/module.go b/x/data/module/module.go index cbc1cff549..b66b8a1faa 100644 --- a/x/data/module/module.go +++ b/x/data/module/module.go @@ -19,7 +19,7 @@ import ( simtypes "github.com/cosmos/cosmos-sdk/types/simulation" climodule "github.com/regen-network/regen-ledger/types/module/client/cli" - restmodule "github.com/regen-network/regen-ledger/types/module/client/grpc_gateway" + restmodule "github.com/regen-network/regen-ledger/types/module/client/grpcgateway" servermodule "github.com/regen-network/regen-ledger/types/module/server" "github.com/regen-network/regen-ledger/x/data" "github.com/regen-network/regen-ledger/x/data/client" @@ -57,7 +57,7 @@ func (a Module) RegisterServices(configurator servermodule.Configurator) { server.RegisterServices(configurator, a.ak, a.bk) } -//nolint:errcheck +//nolint func (a Module) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux *runtime.ServeMux) { data.RegisterQueryHandlerClient(context.Background(), mux, data.NewQueryClient(clientCtx)) } diff --git a/x/data/server/hasher/doc.go b/x/data/server/hasher/doc.go index d81df16987..87d05fa190 100644 --- a/x/data/server/hasher/doc.go +++ b/x/data/server/hasher/doc.go @@ -14,5 +14,4 @@ increases the length in the case of collisions. Identifiers will be 4 bytes long majority of cases and will sometimes be 5 and rarely 6 bytes long. In some extremely rare cases (which have not appeared in tests), identifiers may be longer. */ - package hasher diff --git a/x/data/server/hasher/hasher.go b/x/data/server/hasher/hasher.go index 129eb4be13..f5df41ddc7 100644 --- a/x/data/server/hasher/hasher.go +++ b/x/data/server/hasher/hasher.go @@ -4,8 +4,9 @@ import ( "encoding/binary" "hash" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "golang.org/x/crypto/blake2b" + + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) // Hasher generates a unique binary identifier for a longer piece of binary data @@ -84,7 +85,7 @@ func (t hasher) CreateID(value []byte, collisions int) (id []byte) { hashBz := hasher.Sum(nil) id = make([]byte, t.minLen, t.bufLen) - copy(id[:], hashBz[:t.minLen]) + copy(id, hashBz[:t.minLen]) // Deal with collisions by appending the equivalent number of bytes // from hashBz. If using this method will exceed hash length, append diff --git a/x/data/server/hasher/hasher_test.go b/x/data/server/hasher/hasher_test.go index 543566b846..00b1ef150b 100644 --- a/x/data/server/hasher/hasher_test.go +++ b/x/data/server/hasher/hasher_test.go @@ -81,10 +81,10 @@ func testHasher(t *testing.T, h Hasher, k int) { } } if c > 1 { - totalCollisions += 1 + totalCollisions++ } if c > 2 { - secondaryCollisions += 1 + secondaryCollisions++ } } @@ -97,11 +97,11 @@ func testHasher(t *testing.T, h Hasher, k int) { value := data[i] for c := 0; ; c++ { - newId := hasher.CreateID(value, c) - v := store.Get(newId) + newID := hasher.CreateID(value, c) + v := store.Get(newID) if len(v) == 0 { - store.Set(newId, value) - require.Equal(t, id, newId) + store.Set(newID, value) + require.Equal(t, id, newID) break } } diff --git a/x/data/server/msg_anchor.go b/x/data/server/msg_anchor.go index 6610ba6f2d..9b8492dfdc 100644 --- a/x/data/server/msg_anchor.go +++ b/x/data/server/msg_anchor.go @@ -37,7 +37,7 @@ func (s serverImpl) anchorAndGetIRI(ctx context.Context, ch ToIRI) (iri string, return "", nil, nil, err } - id, err = s.getOrCreateDataId(ctx, iri) + id, err = s.getOrCreateDataID(ctx, iri) if err != nil { return "", nil, nil, err } @@ -50,25 +50,25 @@ func (s serverImpl) anchorAndGetIRI(ctx context.Context, ch ToIRI) (iri string, return iri, id, timestamp, err } -func (s serverImpl) getOrCreateDataId(ctx context.Context, iri string) (id []byte, err error) { - dataId := &api.DataID{Iri: ""} +func (s serverImpl) getOrCreateDataID(ctx context.Context, iri string) (id []byte, err error) { + dataID := &api.DataID{Iri: ""} - for collisions := 0; dataId.Iri != iri; collisions++ { + for collisions := 0; dataID.Iri != iri; collisions++ { id = s.iriHasher.CreateID([]byte(iri), collisions) - dataId, err = s.stateStore.DataIDTable().Get(ctx, id) + dataID, err = s.stateStore.DataIDTable().Get(ctx, id) if err != nil { if !ormerrors.IsNotFound(err) { return nil, err - } else { - dataId = &api.DataID{ - Id: id, - Iri: iri, - } - err = s.stateStore.DataIDTable().Insert(ctx, dataId) - if err != nil { - return nil, err - } + } + + dataID = &api.DataID{ + Id: id, + Iri: iri, + } + err = s.stateStore.DataIDTable().Insert(ctx, dataID) + if err != nil { + return nil, err } } @@ -84,24 +84,24 @@ func (s serverImpl) anchorAndGetTimestamp(ctx context.Context, id []byte, iri st if err != nil { if !ormerrors.IsNotFound(err) { return nil, err - } else { - sdkCtx := sdk.UnwrapSDKContext(ctx) + } - timestamp, err := gogotypes.TimestampProto(sdkCtx.BlockTime()) - if err != nil { - return nil, sdkerrors.Wrap(err, "invalid block time") - } + sdkCtx := sdk.UnwrapSDKContext(ctx) - err = s.stateStore.DataAnchorTable().Insert(ctx, &api.DataAnchor{ - Id: id, - Timestamp: types.GogoToProtobufTimestamp(timestamp), - }) - if err != nil { - return nil, err - } + timestamp, err := gogotypes.TimestampProto(sdkCtx.BlockTime()) + if err != nil { + return nil, sdkerrors.Wrap(err, "invalid block time") + } - return timestamp, sdkCtx.EventManager().EmitTypedEvent(&data.EventAnchor{Iri: iri}) + err = s.stateStore.DataAnchorTable().Insert(ctx, &api.DataAnchor{ + Id: id, + Timestamp: types.GogoToProtobufTimestamp(timestamp), + }) + if err != nil { + return nil, err } + + return timestamp, sdkCtx.EventManager().EmitTypedEvent(&data.EventAnchor{Iri: iri}) } return types.ProtobufToGogoTimestamp(dataAnchor.Timestamp), nil diff --git a/x/data/server/msg_anchor_test.go b/x/data/server/msg_anchor_test.go index 73da826620..5198b6ebaa 100644 --- a/x/data/server/msg_anchor_test.go +++ b/x/data/server/msg_anchor_test.go @@ -5,11 +5,11 @@ import ( "github.com/gogo/protobuf/jsonpb" "github.com/regen-network/gocuke" - "github.com/regen-network/regen-ledger/types" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/regen-network/regen-ledger/types" "github.com/regen-network/regen-ledger/x/data" ) @@ -81,11 +81,11 @@ func (s *anchorSuite) TheAnchorEntryExistsWithTimestamp(a string) { require.NoError(s.t, err) require.NotNil(s.t, iri) - dataId, err := s.server.stateStore.DataIDTable().GetByIri(s.ctx, iri) + dataID, err := s.server.stateStore.DataIDTable().GetByIri(s.ctx, iri) require.NoError(s.t, err) - require.NotNil(s.t, dataId) + require.NotNil(s.t, dataID) - dataAnchor, err := s.server.stateStore.DataAnchorTable().Get(s.ctx, dataId.Id) + dataAnchor, err := s.server.stateStore.DataAnchorTable().Get(s.ctx, dataID.Id) require.NoError(s.t, err) require.NotNil(s.t, dataAnchor) require.Equal(s.t, anchorTime, dataAnchor.Timestamp.AsTime()) diff --git a/x/data/server/msg_attest.go b/x/data/server/msg_attest.go index 76717f346c..93a2eea266 100644 --- a/x/data/server/msg_attest.go +++ b/x/data/server/msg_attest.go @@ -17,7 +17,7 @@ func (s serverImpl) Attest(ctx context.Context, request *data.MsgAttest) (*data. sdkCtx := sdk.UnwrapSDKContext(ctx) timestamp := timestamppb.New(sdkCtx.BlockTime()) - var iris []string // only the IRIs for new attestations + iris := make([]string, 0) // only the IRIs for new attestations for _, ch := range request.ContentHashes { iri, id, _, err := s.anchorAndGetIRI(ctx, ch) diff --git a/x/data/server/msg_attest_test.go b/x/data/server/msg_attest_test.go index 46c0fdb6cd..97fa0a75be 100644 --- a/x/data/server/msg_attest_test.go +++ b/x/data/server/msg_attest_test.go @@ -5,11 +5,11 @@ import ( "github.com/gogo/protobuf/jsonpb" "github.com/regen-network/gocuke" - "github.com/regen-network/regen-ledger/types" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/regen-network/regen-ledger/types" "github.com/regen-network/regen-ledger/x/data" ) @@ -89,9 +89,9 @@ func (s *attestSuite) TheAnchorEntryExistsWithTimestamp(a string) { anchorTime, err := types.ParseDate("anchor timestamp", a) require.NoError(s.t, err) - dataId := s.getDataId() + dataID := s.getDataID() - dataAnchor, err := s.server.stateStore.DataAnchorTable().Get(s.ctx, dataId) + dataAnchor, err := s.server.stateStore.DataAnchorTable().Get(s.ctx, dataID) require.NoError(s.t, err) require.Equal(s.t, anchorTime, dataAnchor.Timestamp.AsTime()) } @@ -100,9 +100,9 @@ func (s *attestSuite) TheAttestorEntryForAliceExistsWithTimestamp(a string) { attestTime, err := types.ParseDate("attest timestamp", a) require.NoError(s.t, err) - dataId := s.getDataId() + dataID := s.getDataID() - dataAttestor, err := s.server.stateStore.DataAttestorTable().Get(s.ctx, dataId, s.alice) + dataAttestor, err := s.server.stateStore.DataAttestorTable().Get(s.ctx, dataID, s.alice) require.NoError(s.t, err) require.Equal(s.t, attestTime, dataAttestor.Timestamp.AsTime()) } @@ -111,21 +111,21 @@ func (s *attestSuite) TheAttestorEntryForBobExistsWithTimestamp(a string) { attestTime, err := types.ParseDate("attest timestamp", a) require.NoError(s.t, err) - dataId := s.getDataId() + dataID := s.getDataID() - dataAttestor, err := s.server.stateStore.DataAttestorTable().Get(s.ctx, dataId, s.bob) + dataAttestor, err := s.server.stateStore.DataAttestorTable().Get(s.ctx, dataID, s.bob) require.NoError(s.t, err) require.Equal(s.t, attestTime, dataAttestor.Timestamp.AsTime()) } -func (s *attestSuite) getDataId() []byte { +func (s *attestSuite) getDataID() []byte { iri, err := s.ch.ToIRI() require.NoError(s.t, err) require.NotNil(s.t, iri) - dataId, err := s.server.stateStore.DataIDTable().GetByIri(s.ctx, iri) + dataID, err := s.server.stateStore.DataIDTable().GetByIri(s.ctx, iri) require.NoError(s.t, err) - require.NotNil(s.t, dataId) + require.NotNil(s.t, dataID) - return dataId.Id + return dataID.Id } diff --git a/x/data/server/msg_define_resolver.go b/x/data/server/msg_define_resolver.go index 2804d40878..9fda961f21 100644 --- a/x/data/server/msg_define_resolver.go +++ b/x/data/server/msg_define_resolver.go @@ -23,9 +23,9 @@ func (s serverImpl) DefineResolver(ctx context.Context, msg *data.MsgDefineResol if err != nil { if ormerrors.UniqueKeyViolation.Is(err) { return nil, ormerrors.UniqueKeyViolation.Wrap("a resolver with the same URL and manager already exists") - } else { - return nil, err } + + return nil, err } err = sdk.UnwrapSDKContext(ctx).EventManager().EmitTypedEvent(&data.EventDefineResolver{ diff --git a/x/data/server/msg_define_resolver_test.go b/x/data/server/msg_define_resolver_test.go index 4607c42b50..a694bb7b9d 100644 --- a/x/data/server/msg_define_resolver_test.go +++ b/x/data/server/msg_define_resolver_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package server import ( @@ -14,10 +15,9 @@ import ( type defineResolverSuite struct { *baseSuite - alice sdk.AccAddress - bob sdk.AccAddress - resolverUrl string - err error + alice sdk.AccAddress + bob sdk.AccAddress + err error } func TestDefineResolver(t *testing.T) { diff --git a/x/data/server/msg_register_resolver_test.go b/x/data/server/msg_register_resolver_test.go index 59dc822ecf..3e55885d09 100644 --- a/x/data/server/msg_register_resolver_test.go +++ b/x/data/server/msg_register_resolver_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package server import ( @@ -6,11 +7,11 @@ import ( "github.com/gogo/protobuf/jsonpb" "github.com/regen-network/gocuke" - "github.com/regen-network/regen-ledger/types" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/regen-network/regen-ledger/types" "github.com/regen-network/regen-ledger/x/data" ) @@ -113,18 +114,18 @@ func (s *registerResolverSuite) TheAnchorEntryExistsWithTimestamp(a string) { anchorTime, err := types.ParseDate("anchor timestamp", a) require.NoError(s.t, err) - dataId := s.getDataId() + dataID := s.getDataID() - dataAnchor, err := s.server.stateStore.DataAnchorTable().Get(s.ctx, dataId) + dataAnchor, err := s.server.stateStore.DataAnchorTable().Get(s.ctx, dataID) require.NoError(s.t, err) require.NotNil(s.t, dataAnchor) require.Equal(s.t, anchorTime, dataAnchor.Timestamp.AsTime()) } func (s *registerResolverSuite) TheDataResolverEntryExists() { - dataId := s.getDataId() + dataID := s.getDataID() - dataResolver, err := s.server.stateStore.DataResolverTable().Get(s.ctx, dataId, s.id) + dataResolver, err := s.server.stateStore.DataResolverTable().Get(s.ctx, dataID, s.id) require.NoError(s.t, err) require.NotNil(s.t, dataResolver) } @@ -133,14 +134,14 @@ func (s *registerResolverSuite) ExpectTheError(a string) { require.EqualError(s.t, s.err, a) } -func (s *registerResolverSuite) getDataId() []byte { +func (s *registerResolverSuite) getDataID() []byte { iri, err := s.ch.ToIRI() require.NoError(s.t, err) require.NotNil(s.t, iri) - dataId, err := s.server.stateStore.DataIDTable().GetByIri(s.ctx, iri) + dataID, err := s.server.stateStore.DataIDTable().GetByIri(s.ctx, iri) require.NoError(s.t, err) - require.NotNil(s.t, dataId) + require.NotNil(s.t, dataID) - return dataId.Id + return dataID.Id } diff --git a/x/data/server/query_anchor_by_hash.go b/x/data/server/query_anchor_by_hash.go index 428f9f1c9d..ffcfd25e56 100644 --- a/x/data/server/query_anchor_by_hash.go +++ b/x/data/server/query_anchor_by_hash.go @@ -20,12 +20,12 @@ func (s serverImpl) AnchorByHash(ctx context.Context, request *data.QueryAnchorB return nil, err } - dataId, err := s.stateStore.DataIDTable().GetByIri(ctx, iri) + dataID, err := s.stateStore.DataIDTable().GetByIri(ctx, iri) if err != nil { return nil, sdkerrors.ErrNotFound.Wrap("data record with content hash") } - anchor, err := s.stateStore.DataAnchorTable().Get(ctx, dataId.Id) + anchor, err := s.stateStore.DataAnchorTable().Get(ctx, dataID.Id) if err != nil { return nil, err } diff --git a/x/data/server/query_anchor_by_iri.go b/x/data/server/query_anchor_by_iri.go index 55bb4a217c..874d46fbcc 100644 --- a/x/data/server/query_anchor_by_iri.go +++ b/x/data/server/query_anchor_by_iri.go @@ -20,12 +20,12 @@ func (s serverImpl) AnchorByIRI(ctx context.Context, request *data.QueryAnchorBy return nil, err } - dataId, err := s.stateStore.DataIDTable().GetByIri(ctx, request.Iri) + dataID, err := s.stateStore.DataIDTable().GetByIri(ctx, request.Iri) if err != nil { return nil, sdkerrors.ErrNotFound.Wrapf("data record with IRI") } - anchor, err := s.stateStore.DataAnchorTable().Get(ctx, dataId.Id) + anchor, err := s.stateStore.DataAnchorTable().Get(ctx, dataID.Id) if err != nil { return nil, err } diff --git a/x/data/server/query_attestations_by_attestor.go b/x/data/server/query_attestations_by_attestor.go index a8f9c3e66b..6eb5f38678 100644 --- a/x/data/server/query_attestations_by_attestor.go +++ b/x/data/server/query_attestations_by_attestor.go @@ -46,13 +46,13 @@ func (s serverImpl) AttestationsByAttestor(ctx context.Context, request *data.Qu return nil, err } - dataId, err := s.stateStore.DataIDTable().Get(ctx, dataAttestor.Id) + dataID, err := s.stateStore.DataIDTable().Get(ctx, dataAttestor.Id) if err != nil { return nil, err } attestations = append(attestations, &data.AttestationInfo{ - Iri: dataId.Iri, + Iri: dataID.Iri, Attestor: request.Attestor, Timestamp: types.ProtobufToGogoTimestamp(dataAttestor.Timestamp), }) diff --git a/x/data/server/query_attestations_by_hash.go b/x/data/server/query_attestations_by_hash.go index a107fd08f3..3819bd531e 100644 --- a/x/data/server/query_attestations_by_hash.go +++ b/x/data/server/query_attestations_by_hash.go @@ -24,7 +24,7 @@ func (s serverImpl) AttestationsByHash(ctx context.Context, request *data.QueryA return nil, err } - dataId, err := s.stateStore.DataIDTable().GetByIri(ctx, iri) + dataID, err := s.stateStore.DataIDTable().GetByIri(ctx, iri) if err != nil { return nil, sdkerrors.ErrNotFound.Wrap("data record with content hash") } @@ -36,7 +36,7 @@ func (s serverImpl) AttestationsByHash(ctx context.Context, request *data.QueryA it, err := s.stateStore.DataAttestorTable().List( ctx, - api.DataAttestorIdAttestorIndexKey{}.WithId(dataId.Id), + api.DataAttestorIdAttestorIndexKey{}.WithId(dataID.Id), ormlist.Paginate(pg), ) if err != nil { diff --git a/x/data/server/query_attestations_by_iri.go b/x/data/server/query_attestations_by_iri.go index 5deb85ea77..394a97f1c6 100644 --- a/x/data/server/query_attestations_by_iri.go +++ b/x/data/server/query_attestations_by_iri.go @@ -25,7 +25,7 @@ func (s serverImpl) AttestationsByIRI(ctx context.Context, request *data.QueryAt return nil, err } - dataId, err := s.stateStore.DataIDTable().GetByIri(ctx, request.Iri) + dataID, err := s.stateStore.DataIDTable().GetByIri(ctx, request.Iri) if err != nil { return nil, sdkerrors.ErrNotFound.Wrap("data record with IRI") } @@ -37,7 +37,7 @@ func (s serverImpl) AttestationsByIRI(ctx context.Context, request *data.QueryAt it, err := s.stateStore.DataAttestorTable().List( ctx, - api.DataAttestorIdAttestorIndexKey{}.WithId(dataId.Id), + api.DataAttestorIdAttestorIndexKey{}.WithId(dataID.Id), ormlist.Paginate(pg), ) if err != nil { diff --git a/x/data/server/query_resolver_test.go b/x/data/server/query_resolver_test.go index f663c951c4..5fbd292f3a 100644 --- a/x/data/server/query_resolver_test.go +++ b/x/data/server/query_resolver_test.go @@ -13,11 +13,9 @@ func TestQuery_Resolver(t *testing.T) { t.Parallel() s := setupBase(t) - url := "https://foo.bar" - // insert resolvers id, err := s.server.stateStore.ResolverTable().InsertReturningID(s.ctx, &api.Resolver{ - Url: url, + Url: testURL, Manager: s.addrs[0], }) require.NoError(t, err) @@ -27,7 +25,7 @@ func TestQuery_Resolver(t *testing.T) { require.NoError(t, err) require.Equal(t, id, res.Resolver.Id) require.Equal(t, s.addrs[0].String(), res.Resolver.Manager) - require.Equal(t, url, res.Resolver.Url) + require.Equal(t, testURL, res.Resolver.Url) // query resolvers with id that does not exist _, err = s.server.Resolver(s.ctx, &data.QueryResolverRequest{ diff --git a/x/data/server/query_resolvers_by_hash.go b/x/data/server/query_resolvers_by_hash.go index 6fd330defb..d1e8d73936 100644 --- a/x/data/server/query_resolvers_by_hash.go +++ b/x/data/server/query_resolvers_by_hash.go @@ -23,7 +23,7 @@ func (s serverImpl) ResolversByHash(ctx context.Context, request *data.QueryReso return nil, err } - dataId, err := s.stateStore.DataIDTable().GetByIri(ctx, iri) + dataID, err := s.stateStore.DataIDTable().GetByIri(ctx, iri) if err != nil { return nil, sdkerrors.ErrNotFound.Wrapf("data record with content hash") } @@ -35,7 +35,7 @@ func (s serverImpl) ResolversByHash(ctx context.Context, request *data.QueryReso it, err := s.stateStore.DataResolverTable().List( ctx, - api.DataResolverPrimaryKey{}.WithId(dataId.Id), + api.DataResolverPrimaryKey{}.WithId(dataID.Id), ormlist.Paginate(pg), ) if err != nil { diff --git a/x/data/server/query_resolvers_by_hash_test.go b/x/data/server/query_resolvers_by_hash_test.go index 817cce3601..73a38ba464 100644 --- a/x/data/server/query_resolvers_by_hash_test.go +++ b/x/data/server/query_resolvers_by_hash_test.go @@ -34,8 +34,6 @@ func TestQuery_ResolversByHash(t *testing.T) { iri2, err := ch2.ToIRI() require.NoError(t, err) - url := "https://foo.bar" - // insert data ids err = s.server.stateStore.DataIDTable().Insert(s.ctx, &api.DataID{Id: id1, Iri: iri1}) require.NoError(t, err) @@ -44,12 +42,12 @@ func TestQuery_ResolversByHash(t *testing.T) { // insert resolvers rid1, err := s.server.stateStore.ResolverTable().InsertReturningID(s.ctx, &api.Resolver{ - Url: url, + Url: testURL, Manager: s.addrs[0], }) require.NoError(t, err) rid2, err := s.server.stateStore.ResolverTable().InsertReturningID(s.ctx, &api.Resolver{ - Url: url, + Url: testURL, Manager: s.addrs[1], }) require.NoError(t, err) @@ -80,7 +78,7 @@ func TestQuery_ResolversByHash(t *testing.T) { // check resolver properties require.Equal(t, rid1, res.Resolvers[0].Id) require.Equal(t, s.addrs[0].String(), res.Resolvers[0].Manager) - require.Equal(t, url, res.Resolvers[0].Url) + require.Equal(t, testURL, res.Resolvers[0].Url) // query resolvers with content hash that has not been registered res, err = s.server.ResolversByHash(s.ctx, &data.QueryResolversByHashRequest{ diff --git a/x/data/server/query_resolvers_by_iri.go b/x/data/server/query_resolvers_by_iri.go index 503375b7f5..ee96b292b0 100644 --- a/x/data/server/query_resolvers_by_iri.go +++ b/x/data/server/query_resolvers_by_iri.go @@ -24,7 +24,7 @@ func (s serverImpl) ResolversByIRI(ctx context.Context, request *data.QueryResol return nil, err } - dataId, err := s.stateStore.DataIDTable().GetByIri(ctx, request.Iri) + dataID, err := s.stateStore.DataIDTable().GetByIri(ctx, request.Iri) if err != nil { return nil, sdkerrors.ErrNotFound.Wrap("data record with IRI") } @@ -36,7 +36,7 @@ func (s serverImpl) ResolversByIRI(ctx context.Context, request *data.QueryResol it, err := s.stateStore.DataResolverTable().List( ctx, - api.DataResolverPrimaryKey{}.WithId(dataId.Id), + api.DataResolverPrimaryKey{}.WithId(dataID.Id), ormlist.Paginate(pg), ) if err != nil { diff --git a/x/data/server/query_resolvers_by_iri_test.go b/x/data/server/query_resolvers_by_iri_test.go index 136e161cc7..db59378e52 100644 --- a/x/data/server/query_resolvers_by_iri_test.go +++ b/x/data/server/query_resolvers_by_iri_test.go @@ -34,8 +34,6 @@ func TestQuery_ResolversByIRI(t *testing.T) { iri2, err := ch2.ToIRI() require.NoError(t, err) - url := "https://foo.bar" - // insert data ids err = s.server.stateStore.DataIDTable().Insert(s.ctx, &api.DataID{Id: id1, Iri: iri1}) require.NoError(t, err) @@ -44,12 +42,12 @@ func TestQuery_ResolversByIRI(t *testing.T) { // insert resolvers rid1, err := s.server.stateStore.ResolverTable().InsertReturningID(s.ctx, &api.Resolver{ - Url: url, + Url: testURL, Manager: s.addrs[0], }) require.NoError(t, err) rid2, err := s.server.stateStore.ResolverTable().InsertReturningID(s.ctx, &api.Resolver{ - Url: url, + Url: testURL, Manager: s.addrs[1], }) require.NoError(t, err) @@ -80,7 +78,7 @@ func TestQuery_ResolversByIRI(t *testing.T) { // check resolver properties require.Equal(t, rid1, res.Resolvers[0].Id) require.Equal(t, s.addrs[0].String(), res.Resolvers[0].Manager) - require.Equal(t, url, res.Resolvers[0].Url) + require.Equal(t, testURL, res.Resolvers[0].Url) // query resolvers with iri that has not been registered res, err = s.server.ResolversByIRI(s.ctx, &data.QueryResolversByIRIRequest{ diff --git a/x/data/server/query_resolvers_by_url_test.go b/x/data/server/query_resolvers_by_url_test.go index 61725b861b..2e1ef90a5a 100644 --- a/x/data/server/query_resolvers_by_url_test.go +++ b/x/data/server/query_resolvers_by_url_test.go @@ -15,23 +15,21 @@ func TestQuery_ResolversByURL(t *testing.T) { t.Parallel() s := setupBase(t) - url := "https://foo.bar" - // insert resolvers rid1, err := s.server.stateStore.ResolverTable().InsertReturningID(s.ctx, &api.Resolver{ - Url: url, + Url: testURL, Manager: s.addrs[0], }) require.NoError(t, err) err = s.server.stateStore.ResolverTable().Insert(s.ctx, &api.Resolver{ - Url: url, + Url: testURL, Manager: s.addrs[1], }) require.NoError(t, err) // query resolvers with valid url res, err := s.server.ResolversByURL(s.ctx, &data.QueryResolversByURLRequest{ - Url: url, + Url: testURL, Pagination: &query.PageRequest{Limit: 1, CountTotal: true}, }) require.NoError(t, err) @@ -43,7 +41,7 @@ func TestQuery_ResolversByURL(t *testing.T) { // check resolver properties require.Equal(t, rid1, res.Resolvers[0].Id) require.Equal(t, s.addrs[0].String(), res.Resolvers[0].Manager) - require.Equal(t, url, res.Resolvers[0].Url) + require.Equal(t, testURL, res.Resolvers[0].Url) // query resolvers with url that has no resolvers res, err = s.server.ResolversByURL(s.ctx, &data.QueryResolversByURLRequest{ diff --git a/x/data/server/server_test.go b/x/data/server/server_test.go index 80544da4d0..278dc11d2a 100644 --- a/x/data/server/server_test.go +++ b/x/data/server/server_test.go @@ -21,6 +21,10 @@ import ( "github.com/regen-network/regen-ledger/x/data/mocks" ) +const ( + testURL = "https://foo.bar" +) + type baseSuite struct { t gocuke.TestingT ctx context.Context diff --git a/x/data/server/testsuite/genesis.go b/x/data/server/testsuite/genesis.go index 7bec4ed778..0f5872dd30 100644 --- a/x/data/server/testsuite/genesis.go +++ b/x/data/server/testsuite/genesis.go @@ -5,10 +5,11 @@ import ( "encoding/json" "time" - sdk "github.com/cosmos/cosmos-sdk/types" gogoproto "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/regen-network/regen-ledger/types" "github.com/regen-network/regen-ledger/types/testutil" "github.com/regen-network/regen-ledger/x/data" diff --git a/x/data/server/testsuite/suite.go b/x/data/server/testsuite/suite.go index dceca3b6fa..d56cde47b0 100644 --- a/x/data/server/testsuite/suite.go +++ b/x/data/server/testsuite/suite.go @@ -170,13 +170,13 @@ func (s *IntegrationTestSuite) TestRawDataScenario() { func (s *IntegrationTestSuite) TestResolver() { require := s.Require() - testUrl := "https://foo.bar" + testURL := "https://foo.bar" hashes := []*data.ContentHash{s.hash1, s.hash2} // can define a resolver defineResolver, err := s.msgClient.DefineResolver(s.ctx, &data.MsgDefineResolver{ Manager: s.addr1.String(), - ResolverUrl: testUrl, + ResolverUrl: testURL, }) require.NoError(err) diff --git a/x/data/simulation/genesis.go b/x/data/simulation/genesis.go index f6baf17f51..ee7dcac429 100644 --- a/x/data/simulation/genesis.go +++ b/x/data/simulation/genesis.go @@ -5,13 +5,14 @@ import ( "encoding/json" "math/rand" + dbm "github.com/tendermint/tm-db" + "google.golang.org/protobuf/types/known/timestamppb" + "github.com/cosmos/cosmos-sdk/orm/model/ormdb" "github.com/cosmos/cosmos-sdk/orm/model/ormtable" "github.com/cosmos/cosmos-sdk/orm/types/ormjson" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - dbm "github.com/tendermint/tm-db" - "google.golang.org/protobuf/types/known/timestamppb" api "github.com/regen-network/regen-ledger/api/regen/data/v1" "github.com/regen-network/regen-ledger/x/data" @@ -38,7 +39,7 @@ func RandomizedGenState(simState *module.SimulationState) { panic(err) } - if err := generateGenesisState(r, ormCtx, ss, simState); err != nil { + if err := generateGenesisState(ormCtx, r, ss, simState); err != nil { panic(err) } @@ -47,12 +48,12 @@ func RandomizedGenState(simState *module.SimulationState) { panic(err) } - rawJson, err := jsonTarget.JSON() + rawJSON, err := jsonTarget.JSON() if err != nil { panic(err) } - bz, err := json.Marshal(rawJson) + bz, err := json.Marshal(rawJSON) if err != nil { panic(err) } @@ -60,7 +61,7 @@ func RandomizedGenState(simState *module.SimulationState) { simState.GenState[data.ModuleName] = bz } -func generateGenesisState(r *rand.Rand, ormCtx context.Context, ss api.StateStore, +func generateGenesisState(ormCtx context.Context, r *rand.Rand, ss api.StateStore, simState *module.SimulationState) error { hasher, err := hasher.NewHasher() if err != nil { @@ -103,7 +104,7 @@ func generateGenesisState(r *rand.Rand, ormCtx context.Context, ss api.StateStor } manager, _ := simtypes.RandomAcc(r, simState.Accounts) - resolverId, err := ss.ResolverTable().InsertReturningID(ormCtx, &api.Resolver{ + resolverID, err := ss.ResolverTable().InsertReturningID(ormCtx, &api.Resolver{ Url: "https://foo.bar", Manager: manager.Address, }) @@ -112,7 +113,7 @@ func generateGenesisState(r *rand.Rand, ormCtx context.Context, ss api.StateStor } err = ss.DataResolverTable().Insert(ormCtx, &api.DataResolver{ - ResolverId: resolverId, + ResolverId: resolverID, Id: id, }) if err != nil { diff --git a/x/data/simulation/operations.go b/x/data/simulation/operations.go index 681b479819..dbc2869115 100644 --- a/x/data/simulation/operations.go +++ b/x/data/simulation/operations.go @@ -19,10 +19,10 @@ import ( // Simulation operation weights constants const ( - OpWeightMsgAnchor = "op_weight_msg_anchor" - OpWeightMsgAttest = "op_weight_msg_attest" - OpWeightMsgDefineResolver = "op_weight_msg_define_resolver" - OpWeightMsgRegisterResolver = "op_weight_msg_register_resolver" + OpWeightMsgAnchor = "op_weight_msg_anchor" //nolint: gosec + OpWeightMsgAttest = "op_weight_msg_attest" //nolint: gosec + OpWeightMsgDefineResolver = "op_weight_msg_define_resolver" //nolint: gosec + OpWeightMsgRegisterResolver = "op_weight_msg_register_resolver" //nolint: gosec ) var ( @@ -216,22 +216,22 @@ func SimulateMsgDefineResolver(ak data.AccountKeeper, bk data.BankKeeper, qryCli return simtypes.NoOpMsg(data.ModuleName, TypeMsgDefineResolver, "fee error"), nil, err } - resolverUrl := genResolverUrl(r) + resolverURL := genResolverURL(r) ctx := sdk.WrapSDKContext(sdkCtx) - result, err := qryClient.ResolversByURL(ctx, &data.QueryResolversByURLRequest{Url: resolverUrl}) + result, err := qryClient.ResolversByURL(ctx, &data.QueryResolversByURLRequest{Url: resolverURL}) if err != nil { return simtypes.NoOpMsg(data.ModuleName, TypeMsgDefineResolver, err.Error()), nil, err } for _, resolver := range result.Resolvers { - if resolver.Url == resolverUrl && resolver.Manager == manager.Address.String() { + if resolver.Url == resolverURL && resolver.Manager == manager.Address.String() { return simtypes.NoOpMsg(data.ModuleName, TypeMsgDefineResolver, "resolver with the same URL and manager already exists"), nil, nil } } msg := &data.MsgDefineResolver{ Manager: manager.Address.String(), - ResolverUrl: resolverUrl, + ResolverUrl: resolverURL, } account := ak.GetAccount(sdkCtx, manager.Address) @@ -263,7 +263,7 @@ func SimulateMsgDefineResolver(ak data.AccountKeeper, bk data.BankKeeper, qryCli } } -func genResolverUrl(r *rand.Rand) string { +func genResolverURL(r *rand.Rand) string { return fmt.Sprintf("https://%s.com", simtypes.RandStringOfLength(r, simtypes.RandIntBetween(r, 2, 3))) } @@ -274,8 +274,8 @@ func SimulateMsgRegisterResolver(ak data.AccountKeeper, bk data.BankKeeper, r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { ctx := sdk.WrapSDKContext(sdkCtx) - resolverId := r.Uint64() - res, err := qryClient.Resolver(ctx, &data.QueryResolverRequest{Id: resolverId}) + resolverID := r.Uint64() + res, err := qryClient.Resolver(ctx, &data.QueryResolverRequest{Id: resolverID}) if err != nil { return simtypes.NoOpMsg(data.ModuleName, TypeMsgRegisterResolver, err.Error()), nil, nil // not found } @@ -302,7 +302,7 @@ func SimulateMsgRegisterResolver(ak data.AccountKeeper, bk data.BankKeeper, } msg := &data.MsgRegisterResolver{ Manager: manager.String(), - ResolverId: resolverId, + ResolverId: resolverID, ContentHashes: []*data.ContentHash{contentHash}, } @@ -343,9 +343,9 @@ func getContentHash(r *rand.Rand) (*data.ContentHash, error) { digest := hash.Sum(nil) if r.Float32() < 0.5 { return &data.ContentHash{Graph: getGraph(digest)}, nil - } else { - return &data.ContentHash{Raw: getRaw(digest)}, nil } + + return &data.ContentHash{Raw: getRaw(digest)}, nil } func getGraph(digest []byte) *data.ContentHash_Graph { diff --git a/x/data/types.go b/x/data/types.go index f7acaeeb0a..9734536bb7 100644 --- a/x/data/types.go +++ b/x/data/types.go @@ -14,11 +14,12 @@ func (ch ContentHash) Validate() error { hashRaw := ch.GetRaw() hashGraph := ch.GetGraph() - if hashRaw != nil && hashGraph != nil { + switch { + case hashRaw != nil && hashGraph != nil: return sdkerrors.ErrInvalidRequest.Wrapf("content hash must be one of raw type or graph type") - } else if hashRaw != nil { + case hashRaw != nil: return hashRaw.Validate() - } else if hashGraph != nil { + case hashGraph != nil: return hashGraph.Validate() } diff --git a/x/ecocredit/basket/date_criteria.go b/x/ecocredit/basket/date_criteria.go index 6c7803c47b..ae185ba7be 100644 --- a/x/ecocredit/basket/date_criteria.go +++ b/x/ecocredit/basket/date_criteria.go @@ -7,8 +7,8 @@ import ( "github.com/regen-network/regen-ledger/types" ) -// ToApi converts to pulsar based data structure -func (d *DateCriteria) ToApi() *api.DateCriteria { +// ToAPI converts to pulsar based data structure +func (d *DateCriteria) ToAPI() *api.DateCriteria { if d == nil { return nil } diff --git a/x/ecocredit/basket/date_criteria_test.go b/x/ecocredit/basket/date_criteria_test.go index 57970277e2..9824f637d6 100644 --- a/x/ecocredit/basket/date_criteria_test.go +++ b/x/ecocredit/basket/date_criteria_test.go @@ -8,25 +8,25 @@ import ( "github.com/stretchr/testify/require" ) -func TestDateCriteriaToApi(t *testing.T) { +func TestDateCriteriaToAPI(t *testing.T) { t.Parallel() require := require.New(t) var dc *DateCriteria - require.Nil(dc.ToApi(), "handles nil") + require.Nil(dc.ToAPI(), "handles nil") tstamp := &types.Timestamp{Seconds: 10} dc = &DateCriteria{MinStartDate: tstamp} tstampStd, err := types.TimestampFromProto(tstamp) require.NoError(err) - require.Equal(tstampStd, dc.ToApi().GetMinStartDate().AsTime(), "handles min start date") + require.Equal(tstampStd, dc.ToAPI().GetMinStartDate().AsTime(), "handles min start date") dur := &types.Duration{Seconds: 50} dc = &DateCriteria{StartDateWindow: dur} durStd, err := types.DurationFromProto(dur) require.NoError(err) - dw := dc.ToApi().GetStartDateWindow() + dw := dc.ToAPI().GetStartDateWindow() require.NotNil(dw) require.Equal(durStd, dw.AsDuration(), "handles window date") } diff --git a/x/ecocredit/basket/msg_create.go b/x/ecocredit/basket/msg_create.go index 6159f184a7..d7b229eb24 100644 --- a/x/ecocredit/basket/msg_create.go +++ b/x/ecocredit/basket/msg_create.go @@ -51,7 +51,7 @@ func (m MsgCreate) ValidateBasic() error { } for i := range m.AllowedClasses { - if err := core.ValidateClassId(m.AllowedClasses[i]); err != nil { + if err := core.ValidateClassID(m.AllowedClasses[i]); err != nil { return sdkerrors.ErrInvalidRequest.Wrapf("allowed_classes[%d] is not a valid class ID: %s", i, err) } } diff --git a/x/ecocredit/client/basket/tx.go b/x/ecocredit/client/basket/tx.go index dfb08e2c9d..7b2db219d5 100644 --- a/x/ecocredit/client/basket/tx.go +++ b/x/ecocredit/client/basket/tx.go @@ -19,7 +19,7 @@ import ( const ( FlagDisableAutoRetire = "disable-auto-retire" - FlagCreditTypeAbbrev = "credit-type-abbrev" + FlagCreditTypeAbbrev = "credit-type-abbrev" //nolint:gosec FlagAllowedClasses = "allowed-classes" FlagMinimumStartDate = "minimum-start-date" FlagStartDateWindow = "start-date-window" @@ -161,8 +161,8 @@ Flags: cmd.Flags().String(FlagDenomDescription, "", "the description to be used in the bank denom metadata.") // required flags - cmd.MarkFlagRequired(FlagCreditTypeAbbrev) - cmd.MarkFlagRequired(FlagAllowedClasses) + _ = cmd.MarkFlagRequired(FlagCreditTypeAbbrev) + _ = cmd.MarkFlagRequired(FlagAllowedClasses) return txFlags(cmd) } diff --git a/x/ecocredit/client/basket/util.go b/x/ecocredit/client/basket/util.go index 95cb402c00..b0974deb83 100644 --- a/x/ecocredit/client/basket/util.go +++ b/x/ecocredit/client/basket/util.go @@ -14,7 +14,7 @@ import ( func txFlags(cmd *cobra.Command) *cobra.Command { flags.AddTxFlagsToCmd(cmd) - cmd.MarkFlagRequired(flags.FlagFrom) + _ = cmd.MarkFlagRequired(flags.FlagFrom) return cmd } diff --git a/x/ecocredit/client/basket/util_test.go b/x/ecocredit/client/basket/util_test.go index 7eeb82a34e..0f0cbe72ce 100644 --- a/x/ecocredit/client/basket/util_test.go +++ b/x/ecocredit/client/basket/util_test.go @@ -11,10 +11,10 @@ import ( ) func TestParseBasketCredits(t *testing.T) { - emptyJson := testutil.WriteToNewTempFile(t, `{}`).Name() - invalidJson := testutil.WriteToNewTempFile(t, `{foo:bar}`).Name() - duplicateJson := testutil.WriteToNewTempFile(t, `{"foo":"bar","foo":"baz"}`).Name() - validJson := testutil.WriteToNewTempFile(t, `[ + emptyJSON := testutil.WriteToNewTempFile(t, `{}`).Name() + invalidJSON := testutil.WriteToNewTempFile(t, `{foo:bar}`).Name() + duplicateJSON := testutil.WriteToNewTempFile(t, `{"foo":"bar","foo":"baz"}`).Name() + validJSON := testutil.WriteToNewTempFile(t, `[ { "batch_denom": "C01-001-20210101-20210101-001", "amount": "10" @@ -40,25 +40,25 @@ func TestParseBasketCredits(t *testing.T) { }, { name: "empty json object", - file: emptyJson, + file: emptyJSON, expErr: true, expErrMsg: "cannot unmarshal object", }, { name: "invalid json format", - file: invalidJson, + file: invalidJSON, expErr: true, expErrMsg: "invalid character", }, { name: "duplicate json keys", - file: duplicateJson, + file: duplicateJSON, expErr: true, expErrMsg: "duplicate key", }, { name: "valid test", - file: validJson, + file: validJSON, expRes: []*basket.BasketCredit{ { BatchDenom: "C01-001-20210101-20210101-001", diff --git a/x/ecocredit/client/marketplace/query.go b/x/ecocredit/client/marketplace/query.go index 3567992f08..32bf913203 100644 --- a/x/ecocredit/client/marketplace/query.go +++ b/x/ecocredit/client/marketplace/query.go @@ -3,9 +3,10 @@ package marketplace import ( "strconv" + "github.com/spf13/cobra" + sdkclient "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/spf13/cobra" "github.com/regen-network/regen-ledger/x/ecocredit" "github.com/regen-network/regen-ledger/x/ecocredit/marketplace" @@ -26,12 +27,12 @@ func QuerySellOrderCmd() *cobra.Command { } client := marketplace.NewQueryClient(ctx) - sellOrderId, err := strconv.ParseUint(args[0], 10, 64) + sellOrderID, err := strconv.ParseUint(args[0], 10, 64) if err != nil { return ecocredit.ErrInvalidSellOrder.Wrap(err.Error()) } res, err := client.SellOrder(cmd.Context(), &marketplace.QuerySellOrderRequest{ - SellOrderId: sellOrderId, + SellOrderId: sellOrderID, }) if err != nil { return err diff --git a/x/ecocredit/client/marketplace/tx.go b/x/ecocredit/client/marketplace/tx.go index 48862e8fec..4c912fdc6f 100644 --- a/x/ecocredit/client/marketplace/tx.go +++ b/x/ecocredit/client/marketplace/tx.go @@ -160,7 +160,7 @@ NOTE: The bid price is the price paid PER credit. The total cost will be quantit return err } - sellOrderId, err := strconv.ParseUint(args[0], 10, 64) + sellOrderID, err := strconv.ParseUint(args[0], 10, 64) if err != nil { return err } @@ -185,7 +185,7 @@ NOTE: The bid price is the price paid PER credit. The total cost will be quantit Buyer: clientCtx.GetFromAddress().String(), Orders: []*marketplace.MsgBuyDirect_Order{ { - SellOrderId: sellOrderId, + SellOrderId: sellOrderID, Quantity: args[1], BidPrice: &bidPrice, DisableAutoRetire: disableAutoRetire, diff --git a/x/ecocredit/client/marketplace/util.go b/x/ecocredit/client/marketplace/util.go index 7f86e9dad0..b850f0ca58 100644 --- a/x/ecocredit/client/marketplace/util.go +++ b/x/ecocredit/client/marketplace/util.go @@ -5,15 +5,17 @@ import ( "encoding/json" "io/ioutil" + "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/regen-network/regen-ledger/types" "github.com/regen-network/regen-ledger/x/ecocredit/marketplace" - "github.com/spf13/cobra" ) func txFlags(cmd *cobra.Command) *cobra.Command { flags.AddTxFlagsToCmd(cmd) - cmd.MarkFlagRequired(flags.FlagFrom) + _ = cmd.MarkFlagRequired(flags.FlagFrom) return cmd } diff --git a/x/ecocredit/client/marketplace/util_test.go b/x/ecocredit/client/marketplace/util_test.go index 4eca5bc22a..4a9f6f3f55 100644 --- a/x/ecocredit/client/marketplace/util_test.go +++ b/x/ecocredit/client/marketplace/util_test.go @@ -13,10 +13,10 @@ import ( ) func TestParseSellOrders(t *testing.T) { - emptyJson := testutil.WriteToNewTempFile(t, `{}`).Name() - invalidJson := testutil.WriteToNewTempFile(t, `{foo:bar}`).Name() - duplicateJson := testutil.WriteToNewTempFile(t, `{"foo":"bar","foo":"baz"}`).Name() - validJson := testutil.WriteToNewTempFile(t, `[ + emptyJSON := testutil.WriteToNewTempFile(t, `{}`).Name() + invalidJSON := testutil.WriteToNewTempFile(t, `{foo:bar}`).Name() + duplicateJSON := testutil.WriteToNewTempFile(t, `{"foo":"bar","foo":"baz"}`).Name() + validJSON := testutil.WriteToNewTempFile(t, `[ { "batch_denom": "C01-001-20200101-20210101-001", "quantity": "10", @@ -54,25 +54,25 @@ func TestParseSellOrders(t *testing.T) { }, { name: "empty json object", - file: emptyJson, + file: emptyJSON, expErr: true, expErrMsg: "cannot unmarshal object", }, { name: "invalid json format", - file: invalidJson, + file: invalidJSON, expErr: true, expErrMsg: "invalid character", }, { name: "duplicate json keys", - file: duplicateJson, + file: duplicateJSON, expErr: true, expErrMsg: "duplicate key", }, { name: "valid", - file: validJson, + file: validJSON, expRes: []*marketplace.MsgSell_Order{ { BatchDenom: "C01-001-20200101-20210101-001", @@ -105,10 +105,10 @@ func TestParseSellOrders(t *testing.T) { } func TestParseSellUpdates(t *testing.T) { - emptyJson := testutil.WriteToNewTempFile(t, `{}`).Name() - invalidJson := testutil.WriteToNewTempFile(t, `{foo:bar}`).Name() - duplicateJson := testutil.WriteToNewTempFile(t, `{"foo":"bar","foo":"baz"}`).Name() - validJson := testutil.WriteToNewTempFile(t, `[ + emptyJSON := testutil.WriteToNewTempFile(t, `{}`).Name() + invalidJSON := testutil.WriteToNewTempFile(t, `{foo:bar}`).Name() + duplicateJSON := testutil.WriteToNewTempFile(t, `{"foo":"bar","foo":"baz"}`).Name() + validJSON := testutil.WriteToNewTempFile(t, `[ { "sell_order_id": 1, "new_quantity": "10", @@ -146,25 +146,25 @@ func TestParseSellUpdates(t *testing.T) { }, { name: "empty json object", - file: emptyJson, + file: emptyJSON, expErr: true, expErrMsg: "cannot unmarshal object", }, { name: "invalid json format", - file: invalidJson, + file: invalidJSON, expErr: true, expErrMsg: "invalid character", }, { name: "duplicate json keys", - file: duplicateJson, + file: duplicateJSON, expErr: true, expErrMsg: "duplicate key", }, { name: "valid", - file: validJson, + file: validJSON, expRes: []*marketplace.MsgUpdateSellOrders_Update{ { SellOrderId: 1, @@ -197,10 +197,10 @@ func TestParseSellUpdates(t *testing.T) { } func TestParseBuyOrders(t *testing.T) { - emptyJson := testutil.WriteToNewTempFile(t, `{}`).Name() - invalidJson := testutil.WriteToNewTempFile(t, `{foo:bar}`).Name() - duplicateJson := testutil.WriteToNewTempFile(t, `{"foo":"bar","foo":"baz"}`).Name() - validJson := testutil.WriteToNewTempFile(t, `[ + emptyJSON := testutil.WriteToNewTempFile(t, `{}`).Name() + invalidJSON := testutil.WriteToNewTempFile(t, `{foo:bar}`).Name() + duplicateJSON := testutil.WriteToNewTempFile(t, `{"foo":"bar","foo":"baz"}`).Name() + validJSON := testutil.WriteToNewTempFile(t, `[ { "sell_order_id": 1, "quantity": "10", @@ -236,25 +236,25 @@ func TestParseBuyOrders(t *testing.T) { }, { name: "empty json object", - file: emptyJson, + file: emptyJSON, expErr: true, expErrMsg: "cannot unmarshal object", }, { name: "invalid json format", - file: invalidJson, + file: invalidJSON, expErr: true, expErrMsg: "invalid character", }, { name: "duplicate json keys", - file: duplicateJson, + file: duplicateJSON, expErr: true, expErrMsg: "duplicate key", }, { name: "valid", - file: validJson, + file: validJSON, expRes: []*marketplace.MsgBuyDirect_Order{ { SellOrderId: 1, diff --git a/x/ecocredit/client/query.go b/x/ecocredit/client/query.go index 373162c2ca..6a1c1256a4 100644 --- a/x/ecocredit/client/query.go +++ b/x/ecocredit/client/query.go @@ -35,7 +35,7 @@ func QueryCmd(name string) *cobra.Command { QueryCreditTypesCmd(), QueryProjectsCmd(), QueryProjectsByClassCmd(), - QueryProjectsByReferenceIdCmd(), + QueryProjectsByReferenceIDCmd(), QueryProjectsByAdminCmd(), QueryProjectCmd(), QueryParamsCmd(), @@ -473,8 +473,8 @@ func QueryParamsCmd() *cobra.Command { }) } -// QueryProjectsByReferenceIdCmd returns command that retrieves list of projects by reference id with pagination. -func QueryProjectsByReferenceIdCmd() *cobra.Command { +// QueryProjectsByReferenceIDCmd returns command that retrieves list of projects by reference id with pagination. +func QueryProjectsByReferenceIDCmd() *cobra.Command { cmd := &cobra.Command{ Use: "projects-by-reference-id [reference-id]", Short: "List all projects by reference ID", diff --git a/x/ecocredit/client/testsuite/grpc.go b/x/ecocredit/client/testsuite/grpc.go index b82610985e..250b49b1a9 100644 --- a/x/ecocredit/client/testsuite/grpc.go +++ b/x/ecocredit/client/testsuite/grpc.go @@ -55,11 +55,11 @@ func (s *IntegrationTestSuite) TestQueryClass() { }{ { "valid", - fmt.Sprintf("%s/%s/class/%s", s.val.APIAddress, coreRoute, s.classId), + fmt.Sprintf("%s/%s/class/%s", s.val.APIAddress, coreRoute, s.classID), }, { "valid alternative", - fmt.Sprintf("%s/%s/classes/%s", s.val.APIAddress, coreRoute, s.classId), + fmt.Sprintf("%s/%s/classes/%s", s.val.APIAddress, coreRoute, s.classID), }, } @@ -74,7 +74,7 @@ func (s *IntegrationTestSuite) TestQueryClass() { err = s.val.ClientCtx.Codec.UnmarshalJSON(resp, &res) require.NoError(err) require.NotNil(res.Class) - require.Equal(res.Class.Id, s.classId) + require.Equal(res.Class.Id, s.classID) }) } } @@ -88,11 +88,11 @@ func (s *IntegrationTestSuite) TestQueryProject() { }{ { "valid", - fmt.Sprintf("%s/%s/project/%s", s.val.APIAddress, coreRoute, s.projectId), + fmt.Sprintf("%s/%s/project/%s", s.val.APIAddress, coreRoute, s.projectID), }, { "valid alternative", - fmt.Sprintf("%s/%s/projects/%s", s.val.APIAddress, coreRoute, s.projectId), + fmt.Sprintf("%s/%s/projects/%s", s.val.APIAddress, coreRoute, s.projectID), }, } @@ -162,7 +162,7 @@ func (s *IntegrationTestSuite) TestQueryProjectsByClass() { }{ { "valid", - fmt.Sprintf("%s/%s/projects-by-class/%s", s.val.APIAddress, coreRoute, s.classId), + fmt.Sprintf("%s/%s/projects-by-class/%s", s.val.APIAddress, coreRoute, s.classID), }, { "valid with pagination", @@ -170,16 +170,16 @@ func (s *IntegrationTestSuite) TestQueryProjectsByClass() { "%s/%s/projects-by-class/%s?pagination.limit=1&pagination.countTotal=true", s.val.APIAddress, coreRoute, - s.classId, + s.classID, ), }, { "valid alternative", - fmt.Sprintf("%s/%s/projects/class/%s", s.val.APIAddress, coreRoute, s.classId), + fmt.Sprintf("%s/%s/projects/class/%s", s.val.APIAddress, coreRoute, s.classID), }, { "valid alternative", - fmt.Sprintf("%s/%s/classes/%s/projects", s.val.APIAddress, coreRoute, s.classId), + fmt.Sprintf("%s/%s/classes/%s/projects", s.val.APIAddress, coreRoute, s.classID), }, } @@ -205,7 +205,7 @@ func (s *IntegrationTestSuite) TestQueryProjectsByClass() { } } -func (s *IntegrationTestSuite) TestQueryProjectsByReferenceId() { +func (s *IntegrationTestSuite) TestQueryProjectsByReferenceID() { require := s.Require() testCases := []struct { @@ -218,7 +218,7 @@ func (s *IntegrationTestSuite) TestQueryProjectsByReferenceId() { "%s/%s/projects-by-reference-id/%s", s.val.APIAddress, coreRoute, - s.projectReferenceId, + s.projectReferenceID, ), }, { @@ -227,7 +227,7 @@ func (s *IntegrationTestSuite) TestQueryProjectsByReferenceId() { "%s/%s/projects-by-reference-id/%s?pagination.limit=1&pagination.countTotal=true", s.val.APIAddress, coreRoute, - s.projectReferenceId, + s.projectReferenceID, ), }, { @@ -235,7 +235,7 @@ func (s *IntegrationTestSuite) TestQueryProjectsByReferenceId() { fmt.Sprintf("%s/%s/projects/reference-id/%s", s.val.APIAddress, coreRoute, - s.projectReferenceId, + s.projectReferenceID, ), }, } @@ -349,17 +349,17 @@ func (s *IntegrationTestSuite) TestQueryBatchesByClass() { }{ { "valid", - fmt.Sprintf("%s/%s/batches-by-class/%s", s.val.APIAddress, coreRoute, s.classId), + fmt.Sprintf("%s/%s/batches-by-class/%s", s.val.APIAddress, coreRoute, s.classID), false, }, { "valid with pagination", - fmt.Sprintf("%s/%s/batches-by-class/%s?pagination.limit=2", s.val.APIAddress, coreRoute, s.classId), + fmt.Sprintf("%s/%s/batches-by-class/%s?pagination.limit=2", s.val.APIAddress, coreRoute, s.classID), true, }, { "valid alternative", - fmt.Sprintf("%s/%s/batches/class/%s", s.val.APIAddress, coreRoute, s.classId), + fmt.Sprintf("%s/%s/batches/class/%s", s.val.APIAddress, coreRoute, s.classID), false, }, } @@ -391,17 +391,17 @@ func (s *IntegrationTestSuite) TestQueryBatchesByProject() { }{ { "valid", - fmt.Sprintf("%s/%s/batches-by-project/%s", s.val.APIAddress, coreRoute, s.projectId), + fmt.Sprintf("%s/%s/batches-by-project/%s", s.val.APIAddress, coreRoute, s.projectID), false, }, { "valid with pagination", - fmt.Sprintf("%s/%s/batches-by-project/%s?pagination.limit=2", s.val.APIAddress, coreRoute, s.projectId), + fmt.Sprintf("%s/%s/batches-by-project/%s?pagination.limit=2", s.val.APIAddress, coreRoute, s.projectID), true, }, { "valid alternative", - fmt.Sprintf("%s/%s/batches/project/%s", s.val.APIAddress, coreRoute, s.projectId), + fmt.Sprintf("%s/%s/batches/project/%s", s.val.APIAddress, coreRoute, s.projectID), false, }, } diff --git a/x/ecocredit/client/testsuite/grpc_marketplace.go b/x/ecocredit/client/testsuite/grpc_marketplace.go index 1a67f90392..4094b1787d 100644 --- a/x/ecocredit/client/testsuite/grpc_marketplace.go +++ b/x/ecocredit/client/testsuite/grpc_marketplace.go @@ -20,11 +20,11 @@ func (s *IntegrationTestSuite) TestQuerySellOrder() { }{ { "valid", - fmt.Sprintf("%s/%s/sell-order/%d", s.val.APIAddress, marketplaceRoute, s.sellOrderId), + fmt.Sprintf("%s/%s/sell-order/%d", s.val.APIAddress, marketplaceRoute, s.sellOrderID), }, { "valid alternative", - fmt.Sprintf("%s/%s/sell-orders/%d", s.val.APIAddress, marketplaceRoute, s.sellOrderId), + fmt.Sprintf("%s/%s/sell-orders/%d", s.val.APIAddress, marketplaceRoute, s.sellOrderID), }, } diff --git a/x/ecocredit/client/testsuite/query.go b/x/ecocredit/client/testsuite/query.go index ba361a71d1..5418c2cdd9 100644 --- a/x/ecocredit/client/testsuite/query.go +++ b/x/ecocredit/client/testsuite/query.go @@ -11,12 +11,14 @@ import ( "github.com/regen-network/regen-ledger/x/ecocredit/core" ) +const outputFormat = "JSON" + func (s *IntegrationTestSuite) TestQueryClassesCmd() { val := s.network.Validators[0] val2 := s.network.Validators[1] clientCtx := val.ClientCtx - clientCtx.OutputFormat = "JSON" - classId := s.createClass(clientCtx, &core.MsgCreateClass{ + clientCtx.OutputFormat = outputFormat + classID := s.createClass(clientCtx, &core.MsgCreateClass{ Admin: val.Address.String(), Issuers: []string{val.Address.String()}, Metadata: "metadata", @@ -24,7 +26,7 @@ func (s *IntegrationTestSuite) TestQueryClassesCmd() { Fee: &core.DefaultParams().CreditClassFee[0], }) - classId2 := s.createClass(clientCtx, &core.MsgCreateClass{ + classID2 := s.createClass(clientCtx, &core.MsgCreateClass{ Admin: val.Address.String(), Issuers: []string{val.Address.String(), val2.Address.String()}, Metadata: "metadata2", @@ -32,7 +34,7 @@ func (s *IntegrationTestSuite) TestQueryClassesCmd() { Fee: &core.DefaultParams().CreditClassFee[0], }) - classIds := [2]string{classId, classId2} + classIDs := [2]string{classID, classID2} testCases := []struct { name string @@ -83,7 +85,7 @@ func (s *IntegrationTestSuite) TestQueryClassesCmd() { for i, cls := range res.Classes { resClassIds[i] = cls.Id } - for _, id := range classIds { + for _, id := range classIDs { s.Require().Contains(resClassIds, id) } } @@ -95,7 +97,7 @@ func (s *IntegrationTestSuite) TestQueryClassesCmd() { func (s *IntegrationTestSuite) TestQueryClassCmd() { val := s.network.Validators[0] clientCtx := val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat class := &core.MsgCreateClass{ Admin: val.Address.String(), Issuers: []string{val.Address.String()}, @@ -104,7 +106,7 @@ func (s *IntegrationTestSuite) TestQueryClassCmd() { Fee: &core.DefaultParams().CreditClassFee[0], } - classId := s.createClass(clientCtx, class) + classID := s.createClass(clientCtx, class) testCases := []struct { name string @@ -127,10 +129,10 @@ func (s *IntegrationTestSuite) TestQueryClassCmd() { }, { name: "valid credit class", - args: []string{classId}, + args: []string{classID}, expectErr: false, expectedClass: &core.ClassInfo{ - Id: classId, + Id: classID, Admin: val.Address.String(), Metadata: class.Metadata, CreditTypeAbbrev: class.CreditTypeAbbrev, @@ -158,7 +160,7 @@ func (s *IntegrationTestSuite) TestQueryClassCmd() { func (s *IntegrationTestSuite) TestQueryBatchesCmd() { ctx := s.val.ClientCtx - ctx.OutputFormat = "JSON" + ctx.OutputFormat = outputFormat testCases := []struct { name string @@ -208,7 +210,7 @@ func (s *IntegrationTestSuite) TestQueryBatchesCmd() { func (s *IntegrationTestSuite) TestQueryBatchesByIssuerCmd() { ctx := s.val.ClientCtx - ctx.OutputFormat = "JSON" + ctx.OutputFormat = outputFormat testCases := []struct { name string @@ -265,7 +267,7 @@ func (s *IntegrationTestSuite) TestQueryBatchesByIssuerCmd() { func (s *IntegrationTestSuite) TestQueryBatchesByClassCmd() { ctx := s.val.ClientCtx - ctx.OutputFormat = "JSON" + ctx.OutputFormat = outputFormat testCases := []struct { name string @@ -288,7 +290,7 @@ func (s *IntegrationTestSuite) TestQueryBatchesByClassCmd() { { name: "valid with pagination", args: []string{ - s.classId, + s.classID, fmt.Sprintf("--%s", flags.FlagCountTotal), }, expectErr: false, @@ -322,7 +324,7 @@ func (s *IntegrationTestSuite) TestQueryBatchesByClassCmd() { func (s *IntegrationTestSuite) TestQueryBatchesByProjectCmd() { ctx := s.val.ClientCtx - ctx.OutputFormat = "JSON" + ctx.OutputFormat = outputFormat testCases := []struct { name string @@ -345,7 +347,7 @@ func (s *IntegrationTestSuite) TestQueryBatchesByProjectCmd() { { name: "valid with pagination", args: []string{ - s.projectId, + s.projectID, fmt.Sprintf("--%s", flags.FlagCountTotal), }, expectErr: false, @@ -379,7 +381,7 @@ func (s *IntegrationTestSuite) TestQueryBatchesByProjectCmd() { func (s *IntegrationTestSuite) TestQueryBatchCmd() { ctx := s.val.ClientCtx - ctx.OutputFormat = "JSON" + ctx.OutputFormat = outputFormat testCases := []struct { name string @@ -427,7 +429,7 @@ func (s *IntegrationTestSuite) TestQueryBatchCmd() { func (s *IntegrationTestSuite) TestQueryBalanceCmd() { val := s.network.Validators[0] clientCtx := val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -481,7 +483,7 @@ func (s *IntegrationTestSuite) TestQueryBalanceCmd() { func (s *IntegrationTestSuite) TestQuerySupplyCmd() { val := s.network.Validators[0] clientCtx := val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -530,7 +532,7 @@ func (s *IntegrationTestSuite) TestQuerySupplyCmd() { func (s *IntegrationTestSuite) TestQueryCreditTypesCmd() { val := s.network.Validators[0] clientCtx := val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string args []string @@ -566,7 +568,7 @@ func (s *IntegrationTestSuite) TestQueryCreditTypesCmd() { func (s *IntegrationTestSuite) TestQueryParamsCmd() { val := s.network.Validators[0] clientCtx := val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat require := s.Require() cmd := coreclient.QueryParamsCmd() @@ -583,7 +585,7 @@ func (s *IntegrationTestSuite) TestQueryParamsCmd() { func (s *IntegrationTestSuite) TestQueryProjectsCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -637,7 +639,7 @@ func (s *IntegrationTestSuite) TestQueryProjectsCmd() { func (s *IntegrationTestSuite) TestQueryProjectsByClassCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -659,12 +661,12 @@ func (s *IntegrationTestSuite) TestQueryProjectsByClassCmd() { }, { name: "valid", - args: []string{s.classId}, + args: []string{s.classID}, }, { name: "valid with pagination", args: []string{ - s.classId, + s.classID, fmt.Sprintf("--%s", flags.FlagCountTotal), fmt.Sprintf("--%s=%d", flags.FlagLimit, 1), }, @@ -698,7 +700,7 @@ func (s *IntegrationTestSuite) TestQueryProjectsByClassCmd() { func (s *IntegrationTestSuite) TestQueryProjectCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -720,7 +722,7 @@ func (s *IntegrationTestSuite) TestQueryProjectCmd() { }, { name: "valid query", - args: []string{s.projectId}, + args: []string{s.projectID}, }, } @@ -746,10 +748,10 @@ func (s *IntegrationTestSuite) TestQueryClassIssuersCmd() { val := s.network.Validators[0] val2 := s.network.Validators[1] clientCtx := val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat require := s.Require() - classId := s.createClass(clientCtx, &core.MsgCreateClass{ + classID := s.createClass(clientCtx, &core.MsgCreateClass{ Admin: val.Address.String(), Issuers: []string{val.Address.String(), val2.Address.String()}, Metadata: "metadata", @@ -766,14 +768,14 @@ func (s *IntegrationTestSuite) TestQueryClassIssuersCmd() { }{ { name: "no pagination flags", - args: []string{classId}, + args: []string{classID}, expectErr: false, expectedErrMsg: "", numItems: -1, }, { name: "pagination limit 1", - args: []string{classId, "--limit=1"}, + args: []string{classID, "--limit=1"}, expectErr: false, expectedErrMsg: "", numItems: 1, @@ -811,7 +813,7 @@ func (s *IntegrationTestSuite) TestQueryClassIssuersCmd() { func (s *IntegrationTestSuite) TestQueryCreditTypeCmd() { val := s.network.Validators[0] clientCtx := val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string diff --git a/x/ecocredit/client/testsuite/query_basket.go b/x/ecocredit/client/testsuite/query_basket.go index e6fd72e5ae..f069623c4f 100644 --- a/x/ecocredit/client/testsuite/query_basket.go +++ b/x/ecocredit/client/testsuite/query_basket.go @@ -15,7 +15,7 @@ func (s *IntegrationTestSuite) TestQueryBasketCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -64,7 +64,7 @@ func (s *IntegrationTestSuite) TestQueryBasketsCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -121,7 +121,7 @@ func (s *IntegrationTestSuite) TestQueryBasketBalanceCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -169,7 +169,7 @@ func (s *IntegrationTestSuite) TestQueryBasketBalancesCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string diff --git a/x/ecocredit/client/testsuite/query_marketplace.go b/x/ecocredit/client/testsuite/query_marketplace.go index 1e6c1dba78..101004b361 100644 --- a/x/ecocredit/client/testsuite/query_marketplace.go +++ b/x/ecocredit/client/testsuite/query_marketplace.go @@ -15,7 +15,7 @@ func (s *IntegrationTestSuite) TestQuerySellOrderCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -37,7 +37,7 @@ func (s *IntegrationTestSuite) TestQuerySellOrderCmd() { }, { name: "valid", - args: []string{fmt.Sprint(s.sellOrderId)}, + args: []string{fmt.Sprint(s.sellOrderID)}, }, } @@ -63,7 +63,7 @@ func (s *IntegrationTestSuite) TestQuerySellOrdersCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -118,7 +118,7 @@ func (s *IntegrationTestSuite) TestQuerySellOrdersBySellerCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -180,7 +180,7 @@ func (s *IntegrationTestSuite) TestQuerySellOrdersByBatchCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string @@ -242,7 +242,7 @@ func (s *IntegrationTestSuite) TestQueryAllowedDenomsCmd() { require := s.Require() clientCtx := s.val.ClientCtx - clientCtx.OutputFormat = "JSON" + clientCtx.OutputFormat = outputFormat testCases := []struct { name string diff --git a/x/ecocredit/client/testsuite/suite.go b/x/ecocredit/client/testsuite/suite.go index 9d0029183f..f233bdaeda 100644 --- a/x/ecocredit/client/testsuite/suite.go +++ b/x/ecocredit/client/testsuite/suite.go @@ -52,12 +52,12 @@ type IntegrationTestSuite struct { basketFee sdk.Coins creditTypeAbbrev string allowedDenoms []string - classId string - projectId string - projectReferenceId string + classID string + projectID string + projectReferenceID string batchDenom string basketDenom string - sellOrderId uint64 + sellOrderID uint64 } func NewIntegrationTestSuite(cfg network.Config) *IntegrationTestSuite { @@ -85,7 +85,7 @@ func (s *IntegrationTestSuite) SetupSuite() { s.setupTestAccounts() // create test credit class - s.classId = s.createClass(s.val.ClientCtx, &core.MsgCreateClass{ + s.classID = s.createClass(s.val.ClientCtx, &core.MsgCreateClass{ Admin: s.addr1.String(), Issuers: []string{s.addr1.String()}, Metadata: "metadata", @@ -94,15 +94,15 @@ func (s *IntegrationTestSuite) SetupSuite() { }) // set test reference id - s.projectReferenceId = "VCS-001" + s.projectReferenceID = "VCS-001" // create test project - s.projectId = s.createProject(s.val.ClientCtx, &core.MsgCreateProject{ + s.projectID = s.createProject(s.val.ClientCtx, &core.MsgCreateProject{ Admin: s.addr1.String(), - ClassId: s.classId, + ClassId: s.classID, Metadata: "metadata", Jurisdiction: "US-WA", - ReferenceId: s.projectReferenceId, + ReferenceId: s.projectReferenceID, }) startDate, err := types.ParseDate("start date", "2020-01-01") @@ -114,7 +114,7 @@ func (s *IntegrationTestSuite) SetupSuite() { // create test credit batch s.batchDenom = s.createBatch(s.val.ClientCtx, &core.MsgCreateBatch{ Issuer: s.addr1.String(), - ProjectId: s.projectId, + ProjectId: s.projectID, Issuance: []*core.BatchIssuance{ { Recipient: s.addr1.String(), @@ -132,7 +132,7 @@ func (s *IntegrationTestSuite) SetupSuite() { Curator: s.addr1.String(), Name: "NCT", CreditTypeAbbrev: s.creditTypeAbbrev, - AllowedClasses: []string{s.classId}, + AllowedClasses: []string{s.classID}, Fee: s.basketFee, }) @@ -151,7 +151,7 @@ func (s *IntegrationTestSuite) SetupSuite() { askPrice := sdk.NewInt64Coin(s.allowedDenoms[0], 10) // create sell orders with first test account and set test values - sellOrderIds := s.createSellOrder(s.val.ClientCtx, &marketplace.MsgSell{ + sellOrderIDs := s.createSellOrder(s.val.ClientCtx, &marketplace.MsgSell{ Seller: s.addr1.String(), Orders: []*marketplace.MsgSell_Order{ { @@ -163,12 +163,12 @@ func (s *IntegrationTestSuite) SetupSuite() { }, }) - s.sellOrderId = sellOrderIds[0] + s.sellOrderID = sellOrderIDs[0] } func (s *IntegrationTestSuite) TearDownSuite() { s.T().Log("tearing down integration test suite") - s.network.WaitForNextBlock() + s.Require().NoError(s.network.WaitForNextBlock()) s.network.Cleanup() } @@ -289,7 +289,7 @@ func (s *IntegrationTestSuite) fundAccount(clientCtx client.Context, from, to sd require.Zero(res.Code, res.RawLog) } -func (s *IntegrationTestSuite) createClass(clientCtx client.Context, msg *core.MsgCreateClass) (classId string) { +func (s *IntegrationTestSuite) createClass(clientCtx client.Context, msg *core.MsgCreateClass) (classID string) { require := s.Require() cmd := coreclient.TxCreateClassCmd() @@ -323,7 +323,7 @@ func (s *IntegrationTestSuite) createClass(clientCtx client.Context, msg *core.M return "" } -func (s *IntegrationTestSuite) createProject(clientCtx client.Context, msg *core.MsgCreateProject) (projectId string) { +func (s *IntegrationTestSuite) createProject(clientCtx client.Context, msg *core.MsgCreateProject) (projectID string) { require := s.Require() cmd := coreclient.TxCreateProjectCmd() @@ -451,7 +451,7 @@ func (s *IntegrationTestSuite) putInBasket(clientCtx client.Context, msg *basket require.Zero(res.Code, res.RawLog) } -func (s *IntegrationTestSuite) createSellOrder(clientCtx client.Context, msg *marketplace.MsgSell) (sellOrderIds []uint64) { +func (s *IntegrationTestSuite) createSellOrder(clientCtx client.Context, msg *marketplace.MsgSell) (sellOrderIDs []uint64) { require := s.Require() // using json package because array is not a proto message @@ -473,22 +473,22 @@ func (s *IntegrationTestSuite) createSellOrder(clientCtx client.Context, msg *ma require.NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), &res)) require.Zero(res.Code, res.RawLog) - orderIds := make([]uint64, 0, len(msg.Orders)) + orderIDs := make([]uint64, 0, len(msg.Orders)) for _, event := range res.Logs[0].Events { if event.Type == proto.MessageName(&marketplace.EventSell{}) { for _, attr := range event.Attributes { if attr.Key == "sell_order_id" { - orderId, err := strconv.ParseUint(strings.Trim(attr.Value, "\""), 10, 64) + orderID, err := strconv.ParseUint(strings.Trim(attr.Value, "\""), 10, 64) require.NoError(err) - orderIds = append(orderIds, orderId) + orderIDs = append(orderIDs, orderID) } } } } - if len(orderIds) == 0 { + if len(orderIDs) == 0 { require.Fail("failed to find sell order id(s) in response") } - return orderIds + return orderIDs } diff --git a/x/ecocredit/client/testsuite/tx.go b/x/ecocredit/client/testsuite/tx.go index b08398d7b3..572746b147 100644 --- a/x/ecocredit/client/testsuite/tx.go +++ b/x/ecocredit/client/testsuite/tx.go @@ -95,9 +95,10 @@ func (s *IntegrationTestSuite) TestTxCreateClassCmd() { } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := coreclient.TxCreateClassCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) @@ -139,7 +140,7 @@ func (s *IntegrationTestSuite) TestTxCreateProjectCmd() { { name: "missing from flag", args: []string{ - s.classId, + s.classID, "US-WA", "metadata", }, @@ -149,7 +150,7 @@ func (s *IntegrationTestSuite) TestTxCreateProjectCmd() { { name: "valid", args: []string{ - s.classId, + s.classID, "US-WA", "metadata", fmt.Sprintf("--%s=%s", flags.FlagFrom, admin), @@ -158,7 +159,7 @@ func (s *IntegrationTestSuite) TestTxCreateProjectCmd() { { name: "valid from key-name", args: []string{ - s.classId, + s.classID, "US-WA", "metadata", fmt.Sprintf("--%s=%s", flags.FlagFrom, s.val.Moniker), @@ -167,7 +168,7 @@ func (s *IntegrationTestSuite) TestTxCreateProjectCmd() { { name: "valid with amino-json", args: []string{ - s.classId, + s.classID, "US-WA", "metadata", fmt.Sprintf("--%s=%s", flags.FlagFrom, admin), @@ -177,9 +178,10 @@ func (s *IntegrationTestSuite) TestTxCreateProjectCmd() { } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := coreclient.TxCreateProjectCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) @@ -209,7 +211,7 @@ func (s *IntegrationTestSuite) TestTxCreateBatchCmd() { bz, err := s.val.ClientCtx.Codec.MarshalJSON(&core.MsgCreateBatch{ Issuer: issuer, - ProjectId: s.projectId, + ProjectId: s.projectID, Issuance: []*core.BatchIssuance{ { Recipient: recipient, @@ -230,9 +232,9 @@ func (s *IntegrationTestSuite) TestTxCreateBatchCmd() { }) require.NoError(err) - validJson := testutil.WriteToNewTempFile(s.T(), string(bz)).Name() - invalidJson := testutil.WriteToNewTempFile(s.T(), `{foo:bar}`).Name() - duplicateJson := testutil.WriteToNewTempFile(s.T(), `{"foo":"bar","foo":"bar"`).Name() + validJSON := testutil.WriteToNewTempFile(s.T(), string(bz)).Name() + invalidJSON := testutil.WriteToNewTempFile(s.T(), `{foo:bar}`).Name() + duplicateJSON := testutil.WriteToNewTempFile(s.T(), `{"foo":"bar","foo":"bar"`).Name() testCases := []struct { name string @@ -254,7 +256,7 @@ func (s *IntegrationTestSuite) TestTxCreateBatchCmd() { }, { name: "missing from flag", - args: []string{validJson}, + args: []string{validJSON}, expErr: true, expErrMsg: "Error: required flag(s) \"from\" not set", }, @@ -270,7 +272,7 @@ func (s *IntegrationTestSuite) TestTxCreateBatchCmd() { { name: "invalid json format", args: []string{ - invalidJson, + invalidJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, issuer), }, expErr: true, @@ -279,7 +281,7 @@ func (s *IntegrationTestSuite) TestTxCreateBatchCmd() { { name: "duplicate json key", args: []string{ - duplicateJson, + duplicateJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, issuer), }, expErr: true, @@ -288,21 +290,21 @@ func (s *IntegrationTestSuite) TestTxCreateBatchCmd() { { name: "valid", args: []string{ - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, issuer), }, }, { name: "valid from key-name", args: []string{ - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, s.val.Moniker), }, }, { name: "valid with amino-json", args: []string{ - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, issuer), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), }, @@ -310,9 +312,10 @@ func (s *IntegrationTestSuite) TestTxCreateBatchCmd() { } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := coreclient.TxCreateBatchCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) @@ -386,9 +389,10 @@ func (s *IntegrationTestSuite) TestTxSendCmd() { }, } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := coreclient.TxSendCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) @@ -427,9 +431,9 @@ func (s *IntegrationTestSuite) TestTxSendBulkCmd() { }) require.NoError(err) - validJson := testutil.WriteToNewTempFile(s.T(), string(bz)).Name() - invalidJson := testutil.WriteToNewTempFile(s.T(), "{foo:bar}").Name() - duplicateJson := testutil.WriteToNewTempFile(s.T(), `{"foo":"bar","foo":"bar"`).Name() + validJSON := testutil.WriteToNewTempFile(s.T(), string(bz)).Name() + invalidJSON := testutil.WriteToNewTempFile(s.T(), "{foo:bar}").Name() + duplicateJSON := testutil.WriteToNewTempFile(s.T(), `{"foo":"bar","foo":"bar"`).Name() testCases := []struct { name string @@ -453,7 +457,7 @@ func (s *IntegrationTestSuite) TestTxSendBulkCmd() { name: "missing from flag", args: []string{ recipient, - validJson, + validJSON, }, expErr: true, expErrMsg: "Error: required flag(s) \"from\" not set", @@ -472,7 +476,7 @@ func (s *IntegrationTestSuite) TestTxSendBulkCmd() { name: "invalid json format", args: []string{ recipient, - invalidJson, + invalidJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, sender), }, expErr: true, @@ -482,7 +486,7 @@ func (s *IntegrationTestSuite) TestTxSendBulkCmd() { name: "duplicate json key", args: []string{ recipient, - duplicateJson, + duplicateJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, sender), }, expErr: true, @@ -492,7 +496,7 @@ func (s *IntegrationTestSuite) TestTxSendBulkCmd() { name: "valid", args: []string{ recipient, - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, sender), }, }, @@ -500,7 +504,7 @@ func (s *IntegrationTestSuite) TestTxSendBulkCmd() { name: "valid from key-name", args: []string{ recipient, - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, s.val.Moniker), }, }, @@ -508,7 +512,7 @@ func (s *IntegrationTestSuite) TestTxSendBulkCmd() { name: "valid with amino-json", args: []string{ recipient, - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, sender), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), }, @@ -516,9 +520,10 @@ func (s *IntegrationTestSuite) TestTxSendBulkCmd() { } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := coreclient.TxSendBulkCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) @@ -552,9 +557,9 @@ func (s *IntegrationTestSuite) TestTxRetire() { }) require.NoError(err) - validJson := testutil.WriteToNewTempFile(s.T(), string(bz)).Name() - invalidJson := testutil.WriteToNewTempFile(s.T(), "{foo:bar}").Name() - duplicateJson := testutil.WriteToNewTempFile(s.T(), `{"foo":"bar","foo":"bar"`).Name() + validJSON := testutil.WriteToNewTempFile(s.T(), string(bz)).Name() + invalidJSON := testutil.WriteToNewTempFile(s.T(), "{foo:bar}").Name() + duplicateJSON := testutil.WriteToNewTempFile(s.T(), `{"foo":"bar","foo":"bar"`).Name() testCases := []struct { name string @@ -576,7 +581,7 @@ func (s *IntegrationTestSuite) TestTxRetire() { }, { name: "missing from flag", - args: []string{validJson, "US-WA"}, + args: []string{validJSON, "US-WA"}, expErr: true, expErrMsg: "Error: required flag(s) \"from\" not set", }, @@ -593,7 +598,7 @@ func (s *IntegrationTestSuite) TestTxRetire() { { name: "invalid json format", args: []string{ - invalidJson, + invalidJSON, "US-WA", fmt.Sprintf("--%s=%s", flags.FlagFrom, owner), }, @@ -603,7 +608,7 @@ func (s *IntegrationTestSuite) TestTxRetire() { { name: "duplicate json key", args: []string{ - duplicateJson, + duplicateJSON, "US-WA", fmt.Sprintf("--%s=%s", flags.FlagFrom, owner), }, @@ -613,7 +618,7 @@ func (s *IntegrationTestSuite) TestTxRetire() { { name: "valid", args: []string{ - validJson, + validJSON, "US-WA", fmt.Sprintf("--%s=%s", flags.FlagFrom, owner), }, @@ -621,7 +626,7 @@ func (s *IntegrationTestSuite) TestTxRetire() { { name: "valid from key-name", args: []string{ - validJson, + validJSON, "US-WA", fmt.Sprintf("--%s=%s", flags.FlagFrom, s.val.Moniker), }, @@ -629,7 +634,7 @@ func (s *IntegrationTestSuite) TestTxRetire() { { name: "valid with amino-json", args: []string{ - validJson, + validJSON, "US-WA", fmt.Sprintf("--%s=%s", flags.FlagFrom, owner), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), @@ -638,9 +643,10 @@ func (s *IntegrationTestSuite) TestTxRetire() { } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := coreclient.TxRetireCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) @@ -674,9 +680,9 @@ func (s *IntegrationTestSuite) TestTxCancel() { }) require.NoError(err) - validJson := testutil.WriteToNewTempFile(s.T(), string(bz)).Name() - invalidJson := testutil.WriteToNewTempFile(s.T(), `{foo:bar}`).Name() - duplicateJson := testutil.WriteToNewTempFile(s.T(), `{"foo":"bar","foo":"bar"`).Name() + validJSON := testutil.WriteToNewTempFile(s.T(), string(bz)).Name() + invalidJSON := testutil.WriteToNewTempFile(s.T(), `{foo:bar}`).Name() + duplicateJSON := testutil.WriteToNewTempFile(s.T(), `{"foo":"bar","foo":"bar"`).Name() testCases := []struct { name string @@ -698,7 +704,7 @@ func (s *IntegrationTestSuite) TestTxCancel() { }, { name: "missing from flag", - args: []string{validJson, "reason"}, + args: []string{validJSON, "reason"}, expErr: true, expErrMsg: "Error: required flag(s) \"from\" not set", }, @@ -715,7 +721,7 @@ func (s *IntegrationTestSuite) TestTxCancel() { { name: "invalid json format", args: []string{ - invalidJson, + invalidJSON, "reason", fmt.Sprintf("--%s=%s", flags.FlagFrom, owner), }, @@ -725,7 +731,7 @@ func (s *IntegrationTestSuite) TestTxCancel() { { name: "duplicate json key", args: []string{ - duplicateJson, + duplicateJSON, "reason", fmt.Sprintf("--%s=%s", flags.FlagFrom, owner), }, @@ -735,7 +741,7 @@ func (s *IntegrationTestSuite) TestTxCancel() { { name: "valid", args: []string{ - validJson, + validJSON, "reason", fmt.Sprintf("--%s=%s", flags.FlagFrom, owner), }, @@ -743,7 +749,7 @@ func (s *IntegrationTestSuite) TestTxCancel() { { name: "valid from key-name", args: []string{ - validJson, + validJSON, "reason", fmt.Sprintf("--%s=%s", flags.FlagFrom, s.val.Moniker), }, @@ -751,7 +757,7 @@ func (s *IntegrationTestSuite) TestTxCancel() { { name: "valid with amino-json", args: []string{ - validJson, + validJSON, "reason", fmt.Sprintf("--%s=%s", flags.FlagFrom, owner), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), @@ -760,9 +766,10 @@ func (s *IntegrationTestSuite) TestTxCancel() { } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := coreclient.TxCancelCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) @@ -785,7 +792,7 @@ func (s *IntegrationTestSuite) TestTxUpdateClassAdmin() { newAdmin := s.addr2.String() // create new credit class to not interfere with other tests - classId1 := s.createClass(s.val.ClientCtx, &core.MsgCreateClass{ + classID1 := s.createClass(s.val.ClientCtx, &core.MsgCreateClass{ Admin: admin, Issuers: []string{admin}, Metadata: "metadata", @@ -794,7 +801,7 @@ func (s *IntegrationTestSuite) TestTxUpdateClassAdmin() { }) // create new credit class to not interfere with other tests - classId2 := s.createClass(s.val.ClientCtx, &core.MsgCreateClass{ + classID2 := s.createClass(s.val.ClientCtx, &core.MsgCreateClass{ Admin: admin, Issuers: []string{admin}, Metadata: "metadata", @@ -803,7 +810,7 @@ func (s *IntegrationTestSuite) TestTxUpdateClassAdmin() { }) // create new credit class to not interfere with other tests - classId3 := s.createClass(s.val.ClientCtx, &core.MsgCreateClass{ + classID3 := s.createClass(s.val.ClientCtx, &core.MsgCreateClass{ Admin: admin, Issuers: []string{admin}, Metadata: "metadata", @@ -832,7 +839,7 @@ func (s *IntegrationTestSuite) TestTxUpdateClassAdmin() { { name: "missing from flag", args: []string{ - s.classId, + s.classID, newAdmin, }, expErr: true, @@ -841,7 +848,7 @@ func (s *IntegrationTestSuite) TestTxUpdateClassAdmin() { { name: "valid", args: []string{ - classId1, + classID1, newAdmin, fmt.Sprintf("--%s=%s", flags.FlagFrom, admin), }, @@ -849,7 +856,7 @@ func (s *IntegrationTestSuite) TestTxUpdateClassAdmin() { { name: "valid from key-name", args: []string{ - classId2, + classID2, newAdmin, fmt.Sprintf("--%s=%s", flags.FlagFrom, s.val.Moniker), }, @@ -857,7 +864,7 @@ func (s *IntegrationTestSuite) TestTxUpdateClassAdmin() { { name: "valid with amino-json", args: []string{ - classId3, + classID3, newAdmin, fmt.Sprintf("--%s=%s", flags.FlagFrom, admin), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), @@ -866,9 +873,10 @@ func (s *IntegrationTestSuite) TestTxUpdateClassAdmin() { } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := coreclient.TxUpdateClassAdminCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) @@ -910,14 +918,14 @@ func (s *IntegrationTestSuite) TestTxUpdateIssuers() { }, { name: "missing from flag", - args: []string{s.classId}, + args: []string{s.classID}, expErr: true, expErrMsg: "Error: required flag(s) \"from\" not set", }, { name: "missing add or remove flag", args: []string{ - s.classId, + s.classID, fmt.Sprintf("--%s=%s", flags.FlagFrom, admin), }, expErr: true, @@ -926,7 +934,7 @@ func (s *IntegrationTestSuite) TestTxUpdateIssuers() { { name: "valid add issuer", args: []string{ - s.classId, + s.classID, fmt.Sprintf("--%s=%s", coreclient.FlagAddIssuers, issuer), fmt.Sprintf("--%s=%s", flags.FlagFrom, admin), }, @@ -934,7 +942,7 @@ func (s *IntegrationTestSuite) TestTxUpdateIssuers() { { name: "valid remove issuer", args: []string{ - s.classId, + s.classID, fmt.Sprintf("--%s=%s", coreclient.FlagRemoveIssuers, issuer), fmt.Sprintf("--%s=%s", flags.FlagFrom, admin), }, @@ -942,7 +950,7 @@ func (s *IntegrationTestSuite) TestTxUpdateIssuers() { { name: "valid from key-name", args: []string{ - s.classId, + s.classID, fmt.Sprintf("--%s=%s", coreclient.FlagAddIssuers, issuer), fmt.Sprintf("--%s=%s", flags.FlagFrom, s.val.Moniker), }, @@ -950,7 +958,7 @@ func (s *IntegrationTestSuite) TestTxUpdateIssuers() { { name: "valid with amino-json", args: []string{ - s.classId, + s.classID, fmt.Sprintf("--%s=%s", coreclient.FlagRemoveIssuers, issuer), fmt.Sprintf("--%s=%s", flags.FlagFrom, admin), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), @@ -959,9 +967,10 @@ func (s *IntegrationTestSuite) TestTxUpdateIssuers() { } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := coreclient.TxUpdateClassIssuersCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) @@ -1003,7 +1012,7 @@ func (s *IntegrationTestSuite) TestTxUpdateClassMetadata() { { name: "missing from flag", args: []string{ - s.classId, + s.classID, "metadata", }, expErr: true, @@ -1012,7 +1021,7 @@ func (s *IntegrationTestSuite) TestTxUpdateClassMetadata() { { name: "valid", args: []string{ - s.classId, + s.classID, "metadata", fmt.Sprintf("--%s=%s", flags.FlagFrom, admin), }, @@ -1020,7 +1029,7 @@ func (s *IntegrationTestSuite) TestTxUpdateClassMetadata() { { name: "valid from key-name", args: []string{ - s.classId, + s.classID, "metadata", fmt.Sprintf("--%s=%s", flags.FlagFrom, s.val.Moniker), }, @@ -1028,7 +1037,7 @@ func (s *IntegrationTestSuite) TestTxUpdateClassMetadata() { { name: "valid with amino-json", args: []string{ - s.classId, + s.classID, "metadata", fmt.Sprintf("--%s=%s", flags.FlagFrom, admin), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), @@ -1037,9 +1046,10 @@ func (s *IntegrationTestSuite) TestTxUpdateClassMetadata() { } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := coreclient.TxUpdateClassMetadataCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) @@ -1062,27 +1072,27 @@ func (s *IntegrationTestSuite) TestUpdateProjectAdmin() { newAdmin := s.addr2.String() // create new project in order to not interfere with other tests - projectId1 := s.createProject(s.val.ClientCtx, &core.MsgCreateProject{ + projectID1 := s.createProject(s.val.ClientCtx, &core.MsgCreateProject{ Admin: admin, - ClassId: s.classId, + ClassId: s.classID, Metadata: "metadata", Jurisdiction: "US-WA", ReferenceId: "VCS-002", }) // create new project in order to not interfere with other tests - projectId2 := s.createProject(s.val.ClientCtx, &core.MsgCreateProject{ + projectID2 := s.createProject(s.val.ClientCtx, &core.MsgCreateProject{ Admin: admin, - ClassId: s.classId, + ClassId: s.classID, Metadata: "metadata", Jurisdiction: "US-WA", ReferenceId: "VCS-003", }) // create new project in order to not interfere with other tests - projectId3 := s.createProject(s.val.ClientCtx, &core.MsgCreateProject{ + projectID3 := s.createProject(s.val.ClientCtx, &core.MsgCreateProject{ Admin: admin, - ClassId: s.classId, + ClassId: s.classID, Metadata: "metadata", Jurisdiction: "US-WA", ReferenceId: "VCS-004", @@ -1109,7 +1119,7 @@ func (s *IntegrationTestSuite) TestUpdateProjectAdmin() { { name: "missing from flag", args: []string{ - s.projectId, + s.projectID, newAdmin, }, expErr: true, @@ -1118,7 +1128,7 @@ func (s *IntegrationTestSuite) TestUpdateProjectAdmin() { { name: "valid", args: []string{ - projectId1, + projectID1, newAdmin, fmt.Sprintf("--%s=%s", flags.FlagFrom, admin), }, @@ -1126,7 +1136,7 @@ func (s *IntegrationTestSuite) TestUpdateProjectAdmin() { { name: "valid from key-name", args: []string{ - projectId2, + projectID2, newAdmin, fmt.Sprintf("--%s=%s", flags.FlagFrom, s.val.Moniker), }, @@ -1134,7 +1144,7 @@ func (s *IntegrationTestSuite) TestUpdateProjectAdmin() { { name: "valid with amino-json", args: []string{ - projectId3, + projectID3, newAdmin, fmt.Sprintf("--%s=%s", flags.FlagFrom, admin), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), @@ -1143,9 +1153,10 @@ func (s *IntegrationTestSuite) TestUpdateProjectAdmin() { } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := coreclient.TxUpdateProjectAdminCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) @@ -1187,7 +1198,7 @@ func (s *IntegrationTestSuite) TestUpdateProjectMetadata() { { name: "missing from flag", args: []string{ - s.projectId, + s.projectID, "metadata", }, expErr: true, @@ -1196,7 +1207,7 @@ func (s *IntegrationTestSuite) TestUpdateProjectMetadata() { { name: "valid", args: []string{ - s.projectId, + s.projectID, "metadata", fmt.Sprintf("--%s=%s", flags.FlagFrom, admin), }, @@ -1204,7 +1215,7 @@ func (s *IntegrationTestSuite) TestUpdateProjectMetadata() { { name: "valid from key-name", args: []string{ - s.projectId, + s.projectID, "metadata", fmt.Sprintf("--%s=%s", flags.FlagFrom, s.val.Moniker), }, @@ -1212,7 +1223,7 @@ func (s *IntegrationTestSuite) TestUpdateProjectMetadata() { { name: "valid with amino-json", args: []string{ - s.projectId, + s.projectID, "metadata", fmt.Sprintf("--%s=%s", flags.FlagFrom, admin), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), @@ -1221,9 +1232,10 @@ func (s *IntegrationTestSuite) TestUpdateProjectMetadata() { } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := coreclient.TxUpdateProjectMetadataCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) diff --git a/x/ecocredit/client/testsuite/tx_basket.go b/x/ecocredit/client/testsuite/tx_basket.go index 6cc69623a9..ce98aa6d79 100644 --- a/x/ecocredit/client/testsuite/tx_basket.go +++ b/x/ecocredit/client/testsuite/tx_basket.go @@ -46,7 +46,7 @@ func (s *IntegrationTestSuite) TestTxCreateBasketCmd() { name: "valid", args: []string{ "NCT1", - fmt.Sprintf("--%s=%s", basketclient.FlagAllowedClasses, s.classId), + fmt.Sprintf("--%s=%s", basketclient.FlagAllowedClasses, s.classID), fmt.Sprintf("--%s=%s", basketclient.FlagCreditTypeAbbrev, s.creditTypeAbbrev), fmt.Sprintf("--%s=%s", basketclient.FlagBasketFee, s.basketFee), fmt.Sprintf("--%s=%s", flags.FlagFrom, curator), @@ -56,7 +56,7 @@ func (s *IntegrationTestSuite) TestTxCreateBasketCmd() { name: "valid from key-name", args: []string{ "NCT2", - fmt.Sprintf("--%s=%s", basketclient.FlagAllowedClasses, s.classId), + fmt.Sprintf("--%s=%s", basketclient.FlagAllowedClasses, s.classID), fmt.Sprintf("--%s=%s", basketclient.FlagCreditTypeAbbrev, s.creditTypeAbbrev), fmt.Sprintf("--%s=%s", basketclient.FlagBasketFee, s.basketFee), fmt.Sprintf("--%s=%s", flags.FlagFrom, s.val.Moniker), @@ -66,7 +66,7 @@ func (s *IntegrationTestSuite) TestTxCreateBasketCmd() { name: "valid with amino-json", args: []string{ "NCT3", - fmt.Sprintf("--%s=%s", basketclient.FlagAllowedClasses, s.classId), + fmt.Sprintf("--%s=%s", basketclient.FlagAllowedClasses, s.classID), fmt.Sprintf("--%s=%s", basketclient.FlagCreditTypeAbbrev, s.creditTypeAbbrev), fmt.Sprintf("--%s=%s", basketclient.FlagBasketFee, s.basketFee), fmt.Sprintf("--%s=%s", flags.FlagFrom, curator), @@ -76,9 +76,10 @@ func (s *IntegrationTestSuite) TestTxCreateBasketCmd() { } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := basketclient.TxCreateBasketCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) @@ -108,9 +109,9 @@ func (s *IntegrationTestSuite) TestTxPutInBasketCmd() { }) require.NoError(err) - validJson := testutil.WriteToNewTempFile(s.T(), string(bz)).Name() - invalidJson := testutil.WriteToNewTempFile(s.T(), `{foo:bar}`).Name() - duplicateJson := testutil.WriteToNewTempFile(s.T(), `{"foo":"bar","foo":"bar"`).Name() + validJSON := testutil.WriteToNewTempFile(s.T(), string(bz)).Name() + invalidJSON := testutil.WriteToNewTempFile(s.T(), `{foo:bar}`).Name() + duplicateJSON := testutil.WriteToNewTempFile(s.T(), `{"foo":"bar","foo":"bar"`).Name() testCases := []struct { name string @@ -132,7 +133,7 @@ func (s *IntegrationTestSuite) TestTxPutInBasketCmd() { }, { name: "missing from flag", - args: []string{s.basketDenom, validJson}, + args: []string{s.basketDenom, validJSON}, expErr: true, expErrMsg: "Error: required flag(s) \"from\" not set", }, @@ -150,7 +151,7 @@ func (s *IntegrationTestSuite) TestTxPutInBasketCmd() { name: "invalid json format", args: []string{ s.basketDenom, - invalidJson, + invalidJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, owner), }, expErr: true, @@ -160,7 +161,7 @@ func (s *IntegrationTestSuite) TestTxPutInBasketCmd() { name: "duplicate json key", args: []string{ s.basketDenom, - duplicateJson, + duplicateJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, owner), }, expErr: true, @@ -170,7 +171,7 @@ func (s *IntegrationTestSuite) TestTxPutInBasketCmd() { name: "valid", args: []string{ s.basketDenom, - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, owner), }, }, @@ -178,7 +179,7 @@ func (s *IntegrationTestSuite) TestTxPutInBasketCmd() { name: "valid from key-name", args: []string{ s.basketDenom, - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, s.val.Moniker), }, }, @@ -186,7 +187,7 @@ func (s *IntegrationTestSuite) TestTxPutInBasketCmd() { name: "valid with amino-json", args: []string{ s.basketDenom, - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, owner), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), }, @@ -194,9 +195,10 @@ func (s *IntegrationTestSuite) TestTxPutInBasketCmd() { } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := basketclient.TxPutInBasketCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) @@ -275,9 +277,10 @@ func (s *IntegrationTestSuite) TestTxTakeFromBasketCmd() { } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := basketclient.TxTakeFromBasketCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) diff --git a/x/ecocredit/client/testsuite/tx_marketplace.go b/x/ecocredit/client/testsuite/tx_marketplace.go index f960137e9c..07bdee123f 100644 --- a/x/ecocredit/client/testsuite/tx_marketplace.go +++ b/x/ecocredit/client/testsuite/tx_marketplace.go @@ -35,9 +35,9 @@ func (s *IntegrationTestSuite) TestTxSell() { }) require.NoError(err) - validJson := testutil.WriteToNewTempFile(s.T(), string(bz)).Name() - invalidJson := testutil.WriteToNewTempFile(s.T(), `{foo:bar}`).Name() - duplicateJson := testutil.WriteToNewTempFile(s.T(), `{"foo":"bar","foo":"bar"`).Name() + validJSON := testutil.WriteToNewTempFile(s.T(), string(bz)).Name() + invalidJSON := testutil.WriteToNewTempFile(s.T(), `{foo:bar}`).Name() + duplicateJSON := testutil.WriteToNewTempFile(s.T(), `{"foo":"bar","foo":"bar"`).Name() testCases := []struct { name string @@ -60,7 +60,7 @@ func (s *IntegrationTestSuite) TestTxSell() { { name: "missing from flag", args: []string{ - validJson, + validJSON, }, expErr: true, expErrMsg: "Error: required flag(s) \"from\" not set", @@ -77,7 +77,7 @@ func (s *IntegrationTestSuite) TestTxSell() { { name: "invalid json format", args: []string{ - invalidJson, + invalidJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, seller), }, expErr: true, @@ -86,7 +86,7 @@ func (s *IntegrationTestSuite) TestTxSell() { { name: "duplicate json key", args: []string{ - duplicateJson, + duplicateJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, seller), }, expErr: true, @@ -95,21 +95,21 @@ func (s *IntegrationTestSuite) TestTxSell() { { name: "valid", args: []string{ - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, seller), }, }, { name: "valid from key-name", args: []string{ - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, s.val.Moniker), }, }, { name: "valid with amino-json", args: []string{ - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, seller), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), }, @@ -117,9 +117,10 @@ func (s *IntegrationTestSuite) TestTxSell() { } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := marketplaceclient.TxSellCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) @@ -143,7 +144,7 @@ func (s *IntegrationTestSuite) TestTxUpdateSellOrders() { askPrice := sdk.NewInt64Coin(s.allowedDenoms[0], 10) // create new sell orders to not interfere with other tests - sellOrderIds := s.createSellOrder(s.val.ClientCtx, &marketplace.MsgSell{ + sellOrderIDs := s.createSellOrder(s.val.ClientCtx, &marketplace.MsgSell{ Seller: s.addr1.String(), Orders: []*marketplace.MsgSell_Order{ { @@ -162,21 +163,21 @@ func (s *IntegrationTestSuite) TestTxUpdateSellOrders() { // using json package because array is not a proto message bz, err := json.Marshal([]marketplace.MsgUpdateSellOrders_Update{ { - SellOrderId: sellOrderIds[0], + SellOrderId: sellOrderIDs[0], NewQuantity: "20", NewAskPrice: &askPrice, }, { - SellOrderId: sellOrderIds[1], + SellOrderId: sellOrderIDs[1], NewQuantity: "20", NewAskPrice: &askPrice, }, }) require.NoError(err) - validJson := testutil.WriteToNewTempFile(s.T(), string(bz)).Name() - invalidJson := testutil.WriteToNewTempFile(s.T(), `{foo:bar}`).Name() - duplicateJson := testutil.WriteToNewTempFile(s.T(), `{"foo":"bar","foo":"bar"`).Name() + validJSON := testutil.WriteToNewTempFile(s.T(), string(bz)).Name() + invalidJSON := testutil.WriteToNewTempFile(s.T(), `{foo:bar}`).Name() + duplicateJSON := testutil.WriteToNewTempFile(s.T(), `{"foo":"bar","foo":"bar"`).Name() testCases := []struct { name string @@ -198,7 +199,7 @@ func (s *IntegrationTestSuite) TestTxUpdateSellOrders() { }, { name: "missing from flag", - args: []string{validJson}, + args: []string{validJSON}, expErr: true, expErrMsg: "Error: required flag(s) \"from\" not set", }, @@ -214,7 +215,7 @@ func (s *IntegrationTestSuite) TestTxUpdateSellOrders() { { name: "invalid json format", args: []string{ - invalidJson, + invalidJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, seller), }, expErr: true, @@ -223,7 +224,7 @@ func (s *IntegrationTestSuite) TestTxUpdateSellOrders() { { name: "duplicate json key", args: []string{ - duplicateJson, + duplicateJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, seller), }, expErr: true, @@ -232,21 +233,21 @@ func (s *IntegrationTestSuite) TestTxUpdateSellOrders() { { name: "valid", args: []string{ - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, seller), }, }, { name: "valid from key-name", args: []string{ - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, s.val.Moniker), }, }, { name: "valid with amino-json", args: []string{ - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, seller), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), }, @@ -254,9 +255,10 @@ func (s *IntegrationTestSuite) TestTxUpdateSellOrders() { } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := marketplaceclient.TxUpdateSellOrdersCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) @@ -277,7 +279,7 @@ func (s *IntegrationTestSuite) TestTxBuyDirectCmd() { buyer := s.addr2.String() - sellOrderId := fmt.Sprint(s.sellOrderId) + sellOrderID := fmt.Sprint(s.sellOrderID) bidPrice := sdk.NewInt64Coin(s.allowedDenoms[0], 10).String() testCases := []struct { @@ -301,7 +303,7 @@ func (s *IntegrationTestSuite) TestTxBuyDirectCmd() { { name: "missing from flag", args: []string{ - sellOrderId, + sellOrderID, "10", bidPrice, "true", @@ -312,7 +314,7 @@ func (s *IntegrationTestSuite) TestTxBuyDirectCmd() { { name: "valid", args: []string{ - sellOrderId, + sellOrderID, "10", bidPrice, "true", @@ -322,7 +324,7 @@ func (s *IntegrationTestSuite) TestTxBuyDirectCmd() { { name: "valid from key-name", args: []string{ - sellOrderId, + sellOrderID, "10", bidPrice, "true", @@ -332,7 +334,7 @@ func (s *IntegrationTestSuite) TestTxBuyDirectCmd() { { name: "valid with amino-json", args: []string{ - sellOrderId, + sellOrderID, "10", bidPrice, "true", @@ -343,9 +345,10 @@ func (s *IntegrationTestSuite) TestTxBuyDirectCmd() { } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := marketplaceclient.TxBuyDirectCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) @@ -371,13 +374,13 @@ func (s *IntegrationTestSuite) TestTxBuyDirectBatchCmd() { // using json package because array is not a proto message bz, err := json.Marshal([]marketplace.MsgBuyDirect_Order{ { - SellOrderId: s.sellOrderId, + SellOrderId: s.sellOrderID, Quantity: "10", BidPrice: &bidPrice, DisableAutoRetire: true, }, { - SellOrderId: s.sellOrderId, + SellOrderId: s.sellOrderID, Quantity: "10", BidPrice: &bidPrice, RetirementJurisdiction: "US-WA", @@ -385,9 +388,9 @@ func (s *IntegrationTestSuite) TestTxBuyDirectBatchCmd() { }) require.NoError(err) - validJson := testutil.WriteToNewTempFile(s.T(), string(bz)).Name() - invalidJson := testutil.WriteToNewTempFile(s.T(), `{foo:bar}`).Name() - duplicateJson := testutil.WriteToNewTempFile(s.T(), `{"foo":"bar","foo":"bar"`).Name() + validJSON := testutil.WriteToNewTempFile(s.T(), string(bz)).Name() + invalidJSON := testutil.WriteToNewTempFile(s.T(), `{foo:bar}`).Name() + duplicateJSON := testutil.WriteToNewTempFile(s.T(), `{"foo":"bar","foo":"bar"`).Name() testCases := []struct { name string @@ -409,7 +412,7 @@ func (s *IntegrationTestSuite) TestTxBuyDirectBatchCmd() { }, { name: "missing from flag", - args: []string{validJson}, + args: []string{validJSON}, expErr: true, expErrMsg: "Error: required flag(s) \"from\" not set", }, @@ -425,7 +428,7 @@ func (s *IntegrationTestSuite) TestTxBuyDirectBatchCmd() { { name: "invalid json format", args: []string{ - invalidJson, + invalidJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, buyer), }, expErr: true, @@ -434,7 +437,7 @@ func (s *IntegrationTestSuite) TestTxBuyDirectBatchCmd() { { name: "duplicate json key", args: []string{ - duplicateJson, + duplicateJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, buyer), }, expErr: true, @@ -443,30 +446,31 @@ func (s *IntegrationTestSuite) TestTxBuyDirectBatchCmd() { { name: "valid", args: []string{ - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, buyer), }, }, { name: "valid from key-name", args: []string{ - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, "addr2"), }, }, { name: "valid with amino-json", args: []string{ - validJson, + validJSON, fmt.Sprintf("--%s=%s", flags.FlagFrom, buyer), fmt.Sprintf("--%s=%s", flags.FlagSignMode, flags.SignModeLegacyAminoJSON), }, }, } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := marketplaceclient.TxBuyDirectBulkCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) @@ -508,7 +512,7 @@ func (s *IntegrationTestSuite) TestTxCancelSellOrder() { { name: "missing from flag", args: []string{ - fmt.Sprintf("%d", s.sellOrderId), + fmt.Sprintf("%d", s.sellOrderID), }, expErr: true, expErrMsg: "Error: required flag(s) \"from\" not set", @@ -516,16 +520,17 @@ func (s *IntegrationTestSuite) TestTxCancelSellOrder() { { name: "valid", args: []string{ - fmt.Sprintf("%d", s.sellOrderId), + fmt.Sprintf("%d", s.sellOrderID), fmt.Sprintf("--%s=%s", flags.FlagFrom, seller), }, }, } for _, tc := range testCases { + args := tc.args s.Run(tc.name, func() { cmd := marketplaceclient.TxCancelSellOrderCmd() - args := append(tc.args, s.commonTxFlags()...) + args = append(args, s.commonTxFlags()...) out, err := cli.ExecTestCLICmd(s.val.ClientCtx, cmd, args) if tc.expErr { require.Error(err) diff --git a/x/ecocredit/client/tx.go b/x/ecocredit/client/tx.go index 9507b2eaad..3fd41f1497 100644 --- a/x/ecocredit/client/tx.go +++ b/x/ecocredit/client/tx.go @@ -23,7 +23,7 @@ import ( const ( FlagAddIssuers string = "add-issuers" FlagRemoveIssuers string = "remove-issuers" - FlagReferenceId string = "reference-id" + FlagReferenceID string = "reference-id" FlagRetirementJurisdiction string = "retirement-jurisdiction" ) @@ -104,7 +104,7 @@ regen tx ecocredit create-class regen1elq7ys34gpkj3jyvqee0h6yk4h9wsfxmgqelsw,reg issuers[i] = strings.TrimSpace(issuers[i]) } - // Parse and normalize credit clas fee + // Parse and normalize credit class fee fee, err := sdk.ParseCoinNormalized(args[3]) if err != nil { return err @@ -150,7 +150,7 @@ regen tx ecocredit create-project C01 "US-WA 98225" regen:13toVgf5UjYBz6J29x28pL return err } - referenceId, err := cmd.Flags().GetString(FlagReferenceId) + referenceID, err := cmd.Flags().GetString(FlagReferenceID) if err != nil { return err } @@ -160,7 +160,7 @@ regen tx ecocredit create-project C01 "US-WA 98225" regen:13toVgf5UjYBz6J29x28pL ClassId: args[0], Jurisdiction: args[1], Metadata: args[2], - ReferenceId: referenceId, + ReferenceId: referenceID, } return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) @@ -168,7 +168,7 @@ regen tx ecocredit create-project C01 "US-WA 98225" regen:13toVgf5UjYBz6J29x28pL }, } - cmd.Flags().String(FlagReferenceId, "", "a reference ID for the project") + cmd.Flags().String(FlagReferenceID, "", "a reference ID for the project") return txFlags(cmd) } @@ -225,14 +225,17 @@ Parameters: // Marshal and output JSON of message ctx := sdkclient.GetClientContextFromCmd(cmd) - msgJson, err := ctx.Codec.MarshalJSON(msg) + msgJSON, err := ctx.Codec.MarshalJSON(msg) if err != nil { return err } - var formattedJson bytes.Buffer - json.Indent(&formattedJson, msgJson, "", " ") - fmt.Println(formattedJson.String()) + var formattedJSON bytes.Buffer + err = json.Indent(&formattedJSON, msgJSON, "", " ") + if err != nil { + return err + } + fmt.Println(formattedJSON.String()) return nil }, diff --git a/x/ecocredit/client/util.go b/x/ecocredit/client/util.go index cf2082feff..0fca5ce75b 100644 --- a/x/ecocredit/client/util.go +++ b/x/ecocredit/client/util.go @@ -17,7 +17,7 @@ import ( func txFlags(cmd *cobra.Command) *cobra.Command { flags.AddTxFlagsToCmd(cmd) - cmd.MarkFlagRequired(flags.FlagFrom) + _ = cmd.MarkFlagRequired(flags.FlagFrom) return cmd } diff --git a/x/ecocredit/client/util_test.go b/x/ecocredit/client/util_test.go index 670ba0f57a..bad5d35a39 100644 --- a/x/ecocredit/client/util_test.go +++ b/x/ecocredit/client/util_test.go @@ -16,9 +16,9 @@ import ( func TestParseMsgCreateBatch(t *testing.T) { clientCtx := client.Context{}.WithCodec(&codec.ProtoCodec{}) - invalidJson := testutil.WriteToNewTempFile(t, `{foo:bar}`).Name() - duplicateJson := testutil.WriteToNewTempFile(t, `{"foo":"bar","foo":"baz"}`).Name() - validJson := testutil.WriteToNewTempFile(t, `{ + invalidJSON := testutil.WriteToNewTempFile(t, `{foo:bar}`).Name() + duplicateJSON := testutil.WriteToNewTempFile(t, `{"foo":"bar","foo":"baz"}`).Name() + validJSON := testutil.WriteToNewTempFile(t, `{ "issuer": "regen1", "project_id": "C01-001", "issuance": [ @@ -52,19 +52,19 @@ func TestParseMsgCreateBatch(t *testing.T) { }, { name: "invalid json format", - file: invalidJson, + file: invalidJSON, expErr: true, expErrMsg: "invalid character", }, { name: "duplicate json keys", - file: duplicateJson, + file: duplicateJSON, expErr: true, expErrMsg: "duplicate key", }, { name: "valid test", - file: validJson, + file: validJSON, expRes: &core.MsgCreateBatch{ Issuer: "regen1", ProjectId: "C01-001", @@ -98,10 +98,10 @@ func TestParseMsgCreateBatch(t *testing.T) { } func TestParseSendCredits(t *testing.T) { - emptyJson := testutil.WriteToNewTempFile(t, `{}`).Name() - invalidJson := testutil.WriteToNewTempFile(t, `{foo:bar}`).Name() - duplicateJson := testutil.WriteToNewTempFile(t, `{"foo":"bar","foo":"baz"}`).Name() - validJson := testutil.WriteToNewTempFile(t, `[ + emptyJSON := testutil.WriteToNewTempFile(t, `{}`).Name() + invalidJSON := testutil.WriteToNewTempFile(t, `{foo:bar}`).Name() + duplicateJSON := testutil.WriteToNewTempFile(t, `{"foo":"bar","foo":"baz"}`).Name() + validJSON := testutil.WriteToNewTempFile(t, `[ { "batch_denom": "C01-001-20210101-20210101-001", "tradable_amount": "10" @@ -128,25 +128,25 @@ func TestParseSendCredits(t *testing.T) { }, { name: "empty json object", - file: emptyJson, + file: emptyJSON, expErr: true, expErrMsg: "cannot unmarshal object", }, { name: "invalid json format", - file: invalidJson, + file: invalidJSON, expErr: true, expErrMsg: "invalid character", }, { name: "duplicate json keys", - file: duplicateJson, + file: duplicateJSON, expErr: true, expErrMsg: "duplicate key", }, { name: "valid test", - file: validJson, + file: validJSON, expRes: []*core.MsgSend_SendCredits{ { BatchDenom: "C01-001-20210101-20210101-001", @@ -176,10 +176,10 @@ func TestParseSendCredits(t *testing.T) { } func TestParseCredits(t *testing.T) { - emptyJson := testutil.WriteToNewTempFile(t, `{}`).Name() - invalidJson := testutil.WriteToNewTempFile(t, `{foo:bar}`).Name() - duplicateJson := testutil.WriteToNewTempFile(t, `{"foo":"bar","foo":"baz"}`).Name() - validJson := testutil.WriteToNewTempFile(t, `[ + emptyJSON := testutil.WriteToNewTempFile(t, `{}`).Name() + invalidJSON := testutil.WriteToNewTempFile(t, `{foo:bar}`).Name() + duplicateJSON := testutil.WriteToNewTempFile(t, `{"foo":"bar","foo":"baz"}`).Name() + validJSON := testutil.WriteToNewTempFile(t, `[ { "batch_denom": "C01-001-20210101-20210101-001", "amount": "10" @@ -205,25 +205,25 @@ func TestParseCredits(t *testing.T) { }, { name: "empty json object", - file: emptyJson, + file: emptyJSON, expErr: true, expErrMsg: "cannot unmarshal object", }, { name: "invalid file format", - file: invalidJson, + file: invalidJSON, expErr: true, expErrMsg: "invalid character", }, { name: "duplicate json keys", - file: duplicateJson, + file: duplicateJSON, expErr: true, expErrMsg: "duplicate key", }, { name: "valid test", - file: validJson, + file: validJSON, expRes: []*core.Credits{ { BatchDenom: "C01-001-20210101-20210101-001", diff --git a/x/ecocredit/core/msg_bridge_receive.go b/x/ecocredit/core/msg_bridge_receive.go index a0a3b5e7b4..238d8d5ec7 100644 --- a/x/ecocredit/core/msg_bridge_receive.go +++ b/x/ecocredit/core/msg_bridge_receive.go @@ -29,7 +29,7 @@ func (m *MsgBridgeReceive) ValidateBasic() error { return sdkerrors.ErrInvalidAddress.Wrapf("issuer: %s", err) } - if err := ValidateClassId(m.ClassId); err != nil { + if err := ValidateClassID(m.ClassId); err != nil { return sdkerrors.ErrInvalidRequest.Wrap(err.Error()) } @@ -43,8 +43,8 @@ func (m *MsgBridgeReceive) ValidateBasic() error { return sdkerrors.ErrInvalidRequest.Wrap("project reference id cannot be empty") } - if len(m.Project.ReferenceId) > MaxReferenceIdLength { - return ecocredit.ErrMaxLimit.Wrapf("project reference id: max length %d", MaxReferenceIdLength) + if len(m.Project.ReferenceId) > MaxReferenceIDLength { + return ecocredit.ErrMaxLimit.Wrapf("project reference id: max length %d", MaxReferenceIDLength) } if err := ValidateJurisdiction(m.Project.Jurisdiction); err != nil { diff --git a/x/ecocredit/core/msg_bridge_receive_test.go b/x/ecocredit/core/msg_bridge_receive_test.go index fd9f7bcd3d..d46887c14f 100644 --- a/x/ecocredit/core/msg_bridge_receive_test.go +++ b/x/ecocredit/core/msg_bridge_receive_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package core import ( diff --git a/x/ecocredit/core/msg_create_batch.go b/x/ecocredit/core/msg_create_batch.go index 78aecb5711..7d9f733af0 100644 --- a/x/ecocredit/core/msg_create_batch.go +++ b/x/ecocredit/core/msg_create_batch.go @@ -27,7 +27,7 @@ func (m *MsgCreateBatch) ValidateBasic() error { return sdkerrors.ErrInvalidAddress.Wrapf("issuer: %s", err) } - if err := ValidateProjectId(m.ProjectId); err != nil { + if err := ValidateProjectID(m.ProjectId); err != nil { return sdkerrors.ErrInvalidRequest.Wrap(err.Error()) } diff --git a/x/ecocredit/core/msg_create_project.go b/x/ecocredit/core/msg_create_project.go index a64ed15c52..34d411a65b 100644 --- a/x/ecocredit/core/msg_create_project.go +++ b/x/ecocredit/core/msg_create_project.go @@ -8,7 +8,7 @@ import ( "github.com/regen-network/regen-ledger/x/ecocredit" ) -const MaxReferenceIdLength = 32 +const MaxReferenceIDLength = 32 var _ legacytx.LegacyMsg = &MsgCreateProject{} @@ -29,7 +29,7 @@ func (m *MsgCreateProject) ValidateBasic() error { return sdkerrors.ErrInvalidAddress.Wrapf("admin: %s", err) } - if err := ValidateClassId(m.ClassId); err != nil { + if err := ValidateClassID(m.ClassId); err != nil { return sdkerrors.ErrInvalidRequest.Wrap(err.Error()) } @@ -41,8 +41,8 @@ func (m *MsgCreateProject) ValidateBasic() error { return sdkerrors.ErrInvalidRequest.Wrap(err.Error()) } - if m.ReferenceId != "" && len(m.ReferenceId) > MaxReferenceIdLength { - return ecocredit.ErrMaxLimit.Wrapf("reference id: max length %d", MaxReferenceIdLength) + if m.ReferenceId != "" && len(m.ReferenceId) > MaxReferenceIDLength { + return ecocredit.ErrMaxLimit.Wrapf("reference id: max length %d", MaxReferenceIDLength) } return nil diff --git a/x/ecocredit/core/msg_create_project_test.go b/x/ecocredit/core/msg_create_project_test.go index d3730c6224..b9c5b83056 100644 --- a/x/ecocredit/core/msg_create_project_test.go +++ b/x/ecocredit/core/msg_create_project_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package core import ( diff --git a/x/ecocredit/core/msg_update_class_admin.go b/x/ecocredit/core/msg_update_class_admin.go index bc0d304542..b24ecfa911 100644 --- a/x/ecocredit/core/msg_update_class_admin.go +++ b/x/ecocredit/core/msg_update_class_admin.go @@ -23,7 +23,7 @@ func (m *MsgUpdateClassAdmin) ValidateBasic() error { return sdkerrors.ErrInvalidAddress.Wrapf("admin: %s", err) } - if err := ValidateClassId(m.ClassId); err != nil { + if err := ValidateClassID(m.ClassId); err != nil { return sdkerrors.ErrInvalidRequest.Wrap(err.Error()) } diff --git a/x/ecocredit/core/msg_update_class_issuers.go b/x/ecocredit/core/msg_update_class_issuers.go index 1907271b0f..7b669f5bb9 100644 --- a/x/ecocredit/core/msg_update_class_issuers.go +++ b/x/ecocredit/core/msg_update_class_issuers.go @@ -25,7 +25,7 @@ func (m *MsgUpdateClassIssuers) ValidateBasic() error { return sdkerrors.ErrInvalidAddress.Wrapf("admin: %s", err) } - if err := ValidateClassId(m.ClassId); err != nil { + if err := ValidateClassID(m.ClassId); err != nil { return sdkerrors.ErrInvalidRequest.Wrap(err.Error()) } diff --git a/x/ecocredit/core/msg_update_class_metadata.go b/x/ecocredit/core/msg_update_class_metadata.go index 36fe8a54de..7c27656568 100644 --- a/x/ecocredit/core/msg_update_class_metadata.go +++ b/x/ecocredit/core/msg_update_class_metadata.go @@ -23,7 +23,7 @@ func (m *MsgUpdateClassMetadata) ValidateBasic() error { return sdkerrors.ErrInvalidAddress.Wrapf("admin: %s", err) } - if err := ValidateClassId(m.ClassId); err != nil { + if err := ValidateClassID(m.ClassId); err != nil { return sdkerrors.ErrInvalidRequest.Wrap(err.Error()) } diff --git a/x/ecocredit/core/msg_update_project_admin.go b/x/ecocredit/core/msg_update_project_admin.go index 1ab357495a..d002343d33 100644 --- a/x/ecocredit/core/msg_update_project_admin.go +++ b/x/ecocredit/core/msg_update_project_admin.go @@ -23,7 +23,7 @@ func (m MsgUpdateProjectAdmin) ValidateBasic() error { return sdkerrors.ErrInvalidAddress.Wrapf("admin: %s", err) } - if err := ValidateProjectId(m.ProjectId); err != nil { + if err := ValidateProjectID(m.ProjectId); err != nil { return sdkerrors.ErrInvalidRequest.Wrap(err.Error()) } diff --git a/x/ecocredit/core/msg_update_project_metadata.go b/x/ecocredit/core/msg_update_project_metadata.go index a676bfbda7..1703b1fc38 100644 --- a/x/ecocredit/core/msg_update_project_metadata.go +++ b/x/ecocredit/core/msg_update_project_metadata.go @@ -23,7 +23,7 @@ func (m MsgUpdateProjectMetadata) ValidateBasic() error { return sdkerrors.ErrInvalidAddress.Wrapf("admin: %s", err) } - if err := ValidateProjectId(m.ProjectId); err != nil { + if err := ValidateProjectID(m.ProjectId); err != nil { return sdkerrors.ErrInvalidRequest.Wrap(err.Error()) } diff --git a/x/ecocredit/core/state_class.go b/x/ecocredit/core/state_class.go index c6180e1dbb..7c2382b0f3 100644 --- a/x/ecocredit/core/state_class.go +++ b/x/ecocredit/core/state_class.go @@ -11,7 +11,7 @@ func (m *Class) Validate() error { return ecocredit.ErrParseFailure.Wrapf("key cannot be zero") } - if err := ValidateClassId(m.Id); err != nil { + if err := ValidateClassID(m.Id); err != nil { return err // returns parse error } diff --git a/x/ecocredit/core/state_origin_tx_index.go b/x/ecocredit/core/state_origin_tx_index.go index e6c92a45f0..c0d6a5c4b1 100644 --- a/x/ecocredit/core/state_origin_tx_index.go +++ b/x/ecocredit/core/state_origin_tx_index.go @@ -14,7 +14,7 @@ func (m *OriginTxIndex) Validate() error { return ecocredit.ErrParseFailure.Wrap("id cannot be empty") } - if !reOriginTxId.MatchString(m.Id) { + if !reOriginTxID.MatchString(m.Id) { return ecocredit.ErrParseFailure.Wrap("id must be at most 128 characters long, valid characters: alpha-numberic, space, '-' or '_'") } diff --git a/x/ecocredit/core/state_origin_tx_index_test.go b/x/ecocredit/core/state_origin_tx_index_test.go index 12a48e7470..1257bd9449 100644 --- a/x/ecocredit/core/state_origin_tx_index_test.go +++ b/x/ecocredit/core/state_origin_tx_index_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package core import ( diff --git a/x/ecocredit/core/state_project.go b/x/ecocredit/core/state_project.go index beefa6fd7c..4c76828717 100644 --- a/x/ecocredit/core/state_project.go +++ b/x/ecocredit/core/state_project.go @@ -11,7 +11,7 @@ func (m *Project) Validate() error { return ecocredit.ErrParseFailure.Wrap("key cannot be zero") } - if err := ValidateProjectId(m.Id); err != nil { + if err := ValidateProjectID(m.Id); err != nil { return err // returns parse error } diff --git a/x/ecocredit/core/types_origin_tx.go b/x/ecocredit/core/types_origin_tx.go index a6bc620989..c57d63d914 100644 --- a/x/ecocredit/core/types_origin_tx.go +++ b/x/ecocredit/core/types_origin_tx.go @@ -8,7 +8,7 @@ import ( "github.com/regen-network/regen-ledger/types/eth" ) -var reOriginTxId = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9 _\-]{0,127}$`) +var reOriginTxID = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9 _\-]{0,127}$`) var reOriginTxSource = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9 _\-]{0,31}$`) func (o *OriginTx) Validate() error { @@ -16,7 +16,7 @@ func (o *OriginTx) Validate() error { return sdkerrors.ErrInvalidRequest.Wrap("origin_tx.id cannot be empty") } - if !reOriginTxId.MatchString(o.Id) { + if !reOriginTxID.MatchString(o.Id) { return sdkerrors.ErrInvalidRequest.Wrap("origin_tx.id must be at most 128 characters long, valid characters: alpha-numberic, space, '-' or '_'") } diff --git a/x/ecocredit/core/utils.go b/x/ecocredit/core/utils.go index 80ee34c4f3..febd9982a5 100644 --- a/x/ecocredit/core/utils.go +++ b/x/ecocredit/core/utils.go @@ -13,8 +13,6 @@ import ( "github.com/regen-network/regen-ledger/x/ecocredit" ) -var errBadReq = sdkerrors.ErrInvalidRequest - const ( // BridgePolygon is currently the only allowed target when calling // Msg/Bridge and the only allowed source (provided within OriginTx) @@ -35,18 +33,18 @@ const ( ) var ( - RegexClassId = `[A-Z]{1,3}[0-9]{2,}` - RegexProjectId = fmt.Sprintf(`%s-[A-Z0-9]{2,}`, RegexClassId) - RegexBatchDenom = fmt.Sprintf(`%s-[0-9]{8}-[0-9]{8}-[0-9]{3,}`, RegexProjectId) + RegexClassID = `[A-Z]{1,3}[0-9]{2,}` + RegexProjectID = fmt.Sprintf(`%s-[A-Z0-9]{2,}`, RegexClassID) + RegexBatchDenom = fmt.Sprintf(`%s-[0-9]{8}-[0-9]{8}-[0-9]{3,}`, RegexProjectID) RegexJurisdiction = `([A-Z]{2})(?:-([A-Z0-9]{1,3})(?: ([a-zA-Z0-9 \-]{1,64}))?)?` - regexClassId = regexp.MustCompile(fmt.Sprintf(`^%s$`, RegexClassId)) - regexProjectId = regexp.MustCompile(fmt.Sprintf(`^%s$`, RegexProjectId)) + regexClassID = regexp.MustCompile(fmt.Sprintf(`^%s$`, RegexClassID)) + regexProjectID = regexp.MustCompile(fmt.Sprintf(`^%s$`, RegexProjectID)) regexBatchDenom = regexp.MustCompile(fmt.Sprintf(`^%s$`, RegexBatchDenom)) regexJurisdiction = regexp.MustCompile(fmt.Sprintf(`^%s$`, RegexJurisdiction)) ) -// FormatClassId formats the unique identifier for a new credit class, based +// FormatClassID formats the unique identifier for a new credit class, based // on the credit type abbreviation and the credit class sequence number. This // format may evolve over time, but will maintain backwards compatibility. // @@ -58,24 +56,24 @@ var ( // least three digits // // e.g. C01 -func FormatClassId(creditTypeAbbreviation string, classSeqNo uint64) string { +func FormatClassID(creditTypeAbbreviation string, classSeqNo uint64) string { return fmt.Sprintf("%s%02d", creditTypeAbbreviation, classSeqNo) } -// FormatProjectId formats the unique identifier for a new project, based on +// FormatProjectID formats the unique identifier for a new project, based on // the credit class id and project sequence number. This format may evolve over // time, but will maintain backwards compatibility. // // The current version has the format: // - // -// is the unique identifier of the credit class (see FormatClassId) +// is the unique identifier of the credit class (see FormatClassID) // is the sequence number of the project, padded to at least // three digits // // e.g. C01-001 -func FormatProjectId(classId string, projectSeqNo uint64) string { - return fmt.Sprintf("%s-%03d", classId, projectSeqNo) +func FormatProjectID(classID string, projectSeqNo uint64) string { + return fmt.Sprintf("%s-%03d", classID, projectSeqNo) } // FormatBatchDenom formats the unique denomination for a credit batch. This @@ -84,19 +82,19 @@ func FormatProjectId(classId string, projectSeqNo uint64) string { // The current version has the format: // --- // -// is the unique identifier of the project (see FormatProjectId) +// is the unique identifier of the project (see FormatProjectID) // is the start date of the credit batch with the format YYYYMMDD // is the end date of the credit batch with the format YYYYMMDD // is the sequence number of the credit batch, padded to at least // three digits // // e.g. C01-001-20190101-20200101-001 -func FormatBatchDenom(projectId string, batchSeqNo uint64, startDate, endDate *time.Time) (string, error) { +func FormatBatchDenom(projectID string, batchSeqNo uint64, startDate, endDate *time.Time) (string, error) { return fmt.Sprintf( "%s-%s-%s-%03d", // Project ID string - projectId, + projectID, // Start Date as YYYYMMDD startDate.UTC().Format("20060102"), @@ -122,28 +120,28 @@ func ValidateCreditTypeAbbreviation(abbr string) error { return nil } -// ValidateClassId validates a class ID conforms to the format described in -// FormatClassId. The return is nil if the ID is valid. -func ValidateClassId(classId string) error { - if classId == "" { +// ValidateClassID validates a class ID conforms to the format described in +// FormatClassID. The return is nil if the ID is valid. +func ValidateClassID(classID string) error { + if classID == "" { return ecocredit.ErrParseFailure.Wrap("class id cannot be empty") } - matches := regexClassId.FindStringSubmatch(classId) + matches := regexClassID.FindStringSubmatch(classID) if matches == nil { - return ecocredit.ErrParseFailure.Wrapf("class ID didn't match the format: expected A00, got %s", classId) + return ecocredit.ErrParseFailure.Wrapf("class ID didn't match the format: expected A00, got %s", classID) } return nil } -// ValidateProjectId validates a project ID conforms to the format described -// in FormatProjectId. The return is nil if the ID is valid. -func ValidateProjectId(projectId string) error { - if projectId == "" { +// ValidateProjectID validates a project ID conforms to the format described +// in FormatProjectID. The return is nil if the ID is valid. +func ValidateProjectID(projectID string) error { + if projectID == "" { return ecocredit.ErrParseFailure.Wrap("project id cannot be empty") } - matches := regexProjectId.FindStringSubmatch(projectId) + matches := regexProjectID.FindStringSubmatch(projectID) if matches == nil { - return sdkerrors.Wrapf(ecocredit.ErrParseFailure, "invalid project id: %s", projectId) + return sdkerrors.Wrapf(ecocredit.ErrParseFailure, "invalid project id: %s", projectID) } return nil } @@ -178,10 +176,10 @@ func ValidateJurisdiction(jurisdiction string) error { return nil } -// GetClassIdFromProjectId returns the credit class ID in a project ID. -func GetClassIdFromProjectId(projectId string) string { +// GetClassIDFromProjectID returns the credit class ID in a project ID. +func GetClassIDFromProjectID(projectID string) string { var s strings.Builder - for _, r := range projectId { + for _, r := range projectID { if r != '-' { s.WriteRune(r) continue @@ -191,8 +189,8 @@ func GetClassIdFromProjectId(projectId string) string { return s.String() } -// GetClassIdFromBatchDenom returns the credit class ID in a batch denom. -func GetClassIdFromBatchDenom(denom string) string { +// GetClassIDFromBatchDenom returns the credit class ID in a batch denom. +func GetClassIDFromBatchDenom(denom string) string { var s strings.Builder for _, r := range denom { if r != '-' { @@ -204,8 +202,8 @@ func GetClassIdFromBatchDenom(denom string) string { return s.String() } -// GetProjectIdFromBatchDenom returns the credit project ID in a batch denom. -func GetProjectIdFromBatchDenom(denom string) string { +// GetProjectIDFromBatchDenom returns the credit project ID in a batch denom. +func GetProjectIDFromBatchDenom(denom string) string { var s strings.Builder c := 0 for _, r := range denom { @@ -221,10 +219,10 @@ func GetProjectIdFromBatchDenom(denom string) string { return s.String() } -// GetCreditTypeAbbrevFromClassId returns the credit type abbreviation in a credit class id -func GetCreditTypeAbbrevFromClassId(classId string) string { +// GetCreditTypeAbbrevFromClassID returns the credit type abbreviation in a credit class id +func GetCreditTypeAbbrevFromClassID(classID string) string { var s strings.Builder - for _, r := range classId { + for _, r := range classID { if !unicode.IsNumber(r) { s.WriteRune(r) continue diff --git a/x/ecocredit/core/utils_test.go b/x/ecocredit/core/utils_test.go index fc78bc175d..e1cc13410e 100644 --- a/x/ecocredit/core/utils_test.go +++ b/x/ecocredit/core/utils_test.go @@ -9,52 +9,52 @@ import ( ) func TestUtils(t *testing.T) { - t.Run("TestFormatClassId", rapid.MakeCheck(testFormatClassId)) - t.Run("TestInvalidClassId", rapid.MakeCheck(testInvalidClassId)) - t.Run("TestFormatProjectId", rapid.MakeCheck(testFormatProjectId)) - t.Run("TestInvalidProjectId", rapid.MakeCheck(testInvalidProjectId)) + t.Run("TestFormatClassID", rapid.MakeCheck(testFormatClassID)) + t.Run("TestInvalidClassID", rapid.MakeCheck(testInvalidClassID)) + t.Run("TestFormatProjectID", rapid.MakeCheck(testFormatProjectID)) + t.Run("TestInvalidProjectID", rapid.MakeCheck(testInvalidProjectID)) t.Run("TestFormatBatchDenom", rapid.MakeCheck(testFormatBatchDenom)) t.Run("TestInvalidBatchDenom", rapid.MakeCheck(testInvalidBatchDenom)) - t.Run("TestGetClassIdFromProjectId", rapid.MakeCheck(testGetClassIdFromProjectId)) - t.Run("TestGetClassIdFromBatchDenom", rapid.MakeCheck(testGetClassIdFromBatchDenom)) - t.Run("TestGetProjectIdFromBatchDenom", rapid.MakeCheck(testGetProjectIdFromBatchDenom)) - t.Run("GetCreditTypeAbbrevFromClassId", rapid.MakeCheck(testGetCreditTypeAbbrevFromClassId)) + t.Run("TestGetClassIDFromProjectID", rapid.MakeCheck(testGetClassIDFromProjectID)) + t.Run("TestGetClassIDFromBatchDenom", rapid.MakeCheck(testGetClassIDFromBatchDenom)) + t.Run("TestGetProjectIDFromBatchDenom", rapid.MakeCheck(testGetProjectIDFromBatchDenom)) + t.Run("GetCreditTypeAbbrevFromClassID", rapid.MakeCheck(testGetCreditTypeAbbrevFromClassID)) } -func testFormatClassId(t *rapid.T) { +func testFormatClassID(t *rapid.T) { creditType := genCreditType.Draw(t, "creditType").(*CreditType) classSeq := rapid.Uint64().Draw(t, "classSeq").(uint64) - classId := FormatClassId(creditType.Abbreviation, classSeq) + classID := FormatClassID(creditType.Abbreviation, classSeq) - t.Log(classId) + t.Log(classID) - err := ValidateClassId(classId) + err := ValidateClassID(classID) require.NoError(t, err) } -func testInvalidClassId(t *rapid.T) { - classId := genInvalidClassId.Draw(t, "classId").(string) - require.Error(t, ValidateClassId(classId)) +func testInvalidClassID(t *rapid.T) { + classID := genInvalidClassID.Draw(t, "classID").(string) + require.Error(t, ValidateClassID(classID)) } -func testFormatProjectId(t *rapid.T) { +func testFormatProjectID(t *rapid.T) { creditType := genCreditType.Draw(t, "creditType").(*CreditType) classSeq := rapid.Uint64().Draw(t, "classSeq").(uint64) projectSeq := rapid.Uint64().Draw(t, "projectSeq").(uint64) - classId := FormatClassId(creditType.Abbreviation, classSeq) - projectId := FormatProjectId(classId, projectSeq) + classID := FormatClassID(creditType.Abbreviation, classSeq) + projectID := FormatProjectID(classID, projectSeq) - t.Log(projectId) + t.Log(projectID) - err := ValidateProjectId(projectId) + err := ValidateProjectID(projectID) require.NoError(t, err) } -func testInvalidProjectId(t *rapid.T) { - projectId := genInvalidProjectId.Draw(t, "projectId").(string) - require.Error(t, ValidateProjectId(projectId)) +func testInvalidProjectID(t *rapid.T) { + projectID := genInvalidProjectID.Draw(t, "projectID").(string) + require.Error(t, ValidateProjectID(projectID)) } func testFormatBatchDenom(t *rapid.T) { @@ -65,9 +65,9 @@ func testFormatBatchDenom(t *rapid.T) { startDate := genTime.Draw(t, "startDate").(*time.Time) endDate := genTime.Draw(t, "endDate").(*time.Time) - classId := FormatClassId(creditType.Abbreviation, classSeq) - projectId := FormatProjectId(classId, projectSeq) - denom, err := FormatBatchDenom(projectId, batchSeq, startDate, endDate) + classID := FormatClassID(creditType.Abbreviation, classSeq) + projectID := FormatProjectID(classID, projectSeq) + denom, err := FormatBatchDenom(projectID, batchSeq, startDate, endDate) require.NoError(t, err) t.Log(denom) @@ -81,19 +81,19 @@ func testInvalidBatchDenom(t *rapid.T) { require.Error(t, ValidateBatchDenom(batchDenom)) } -func testGetClassIdFromProjectId(t *rapid.T) { +func testGetClassIDFromProjectID(t *rapid.T) { creditType := genCreditType.Draw(t, "creditType").(*CreditType) classSeq := rapid.Uint64().Draw(t, "classSeq").(uint64) projectSeq := rapid.Uint64().Draw(t, "projectSeq").(uint64) - classId := FormatClassId(creditType.Abbreviation, classSeq) - projectId := FormatProjectId(classId, projectSeq) + classID := FormatClassID(creditType.Abbreviation, classSeq) + projectID := FormatProjectID(classID, projectSeq) - result := GetClassIdFromProjectId(projectId) - require.Equal(t, classId, result) + result := GetClassIDFromProjectID(projectID) + require.Equal(t, classID, result) } -func testGetClassIdFromBatchDenom(t *rapid.T) { +func testGetClassIDFromBatchDenom(t *rapid.T) { creditType := genCreditType.Draw(t, "creditType").(*CreditType) classSeq := rapid.Uint64().Draw(t, "classSeq").(uint64) projectSeq := rapid.Uint64().Draw(t, "projectSeq").(uint64) @@ -101,16 +101,16 @@ func testGetClassIdFromBatchDenom(t *rapid.T) { startDate := genTime.Draw(t, "startDate").(*time.Time) endDate := genTime.Draw(t, "endDate").(*time.Time) - classId := FormatClassId(creditType.Abbreviation, classSeq) - projectId := FormatProjectId(classId, projectSeq) - denom, err := FormatBatchDenom(projectId, batchSeq, startDate, endDate) + classID := FormatClassID(creditType.Abbreviation, classSeq) + projectID := FormatProjectID(classID, projectSeq) + denom, err := FormatBatchDenom(projectID, batchSeq, startDate, endDate) require.NoError(t, err) - result := GetClassIdFromBatchDenom(denom) - require.Equal(t, classId, result) + result := GetClassIDFromBatchDenom(denom) + require.Equal(t, classID, result) } -func testGetProjectIdFromBatchDenom(t *rapid.T) { +func testGetProjectIDFromBatchDenom(t *rapid.T) { creditType := genCreditType.Draw(t, "creditType").(*CreditType) classSeq := rapid.Uint64().Draw(t, "classSeq").(uint64) projectSeq := rapid.Uint64().Draw(t, "projectSeq").(uint64) @@ -118,21 +118,21 @@ func testGetProjectIdFromBatchDenom(t *rapid.T) { startDate := genTime.Draw(t, "startDate").(*time.Time) endDate := genTime.Draw(t, "endDate").(*time.Time) - classId := FormatClassId(creditType.Abbreviation, classSeq) - projectId := FormatProjectId(classId, projectSeq) - denom, err := FormatBatchDenom(projectId, batchSeq, startDate, endDate) + classID := FormatClassID(creditType.Abbreviation, classSeq) + projectID := FormatProjectID(classID, projectSeq) + denom, err := FormatBatchDenom(projectID, batchSeq, startDate, endDate) require.NoError(t, err) - result := GetProjectIdFromBatchDenom(denom) - require.Equal(t, projectId, result) + result := GetProjectIDFromBatchDenom(denom) + require.Equal(t, projectID, result) } -func testGetCreditTypeAbbrevFromClassId(t *rapid.T) { +func testGetCreditTypeAbbrevFromClassID(t *rapid.T) { creditType := genCreditType.Draw(t, "creditType").(*CreditType) classSeq := rapid.Uint64().Draw(t, "classSeq").(uint64) - classId := FormatClassId(creditType.Abbreviation, classSeq) - result := GetCreditTypeAbbrevFromClassId(classId) + classID := FormatClassID(creditType.Abbreviation, classSeq) + result := GetCreditTypeAbbrevFromClassID(classID) require.Equal(t, creditType.Abbreviation, result) } @@ -144,15 +144,15 @@ var genCreditType = rapid.Custom(func(t *rapid.T) *CreditType { } }) -// genInvalidClassId generates strings that don't conform to the class id format -var genInvalidClassId = rapid.OneOf( +// genInvalidClassID generates strings that don't conform to the class id format +var genInvalidClassID = rapid.OneOf( rapid.StringMatching(`[a-zA-Z]*`), rapid.StringMatching(`[0-9]*`), rapid.StringMatching(`[A-Z]{4,}[0-9]*`), ) -// genInvalidProjectId generates strings that don't conform to the project id format -var genInvalidProjectId = rapid.OneOf( +// genInvalidProjectID generates strings that don't conform to the project id format +var genInvalidProjectID = rapid.OneOf( rapid.StringMatching(`[a-zA-Z]*`), rapid.StringMatching(`[0-9]*`), rapid.StringMatching(`[A-Z]{4,}[0-9]*`), @@ -160,7 +160,7 @@ var genInvalidProjectId = rapid.OneOf( // genInvalidBatchDenom generates strings that don't conform to the batch denom format var genInvalidBatchDenom = rapid.OneOf( - genInvalidClassId, + genInvalidClassID, rapid.StringMatching(`[A-Z]{1,3}[0-9]*-[a-zA-Z\-]*`), ) diff --git a/x/ecocredit/genesis/genesis.go b/x/ecocredit/genesis/genesis.go index 837a934ff0..3134a2de55 100644 --- a/x/ecocredit/genesis/genesis.go +++ b/x/ecocredit/genesis/genesis.go @@ -46,9 +46,7 @@ func ValidateGenesis(data json.RawMessage, params core.Params) error { }) ormdb, err := ormdb.NewModuleDB(&ecocredit.ModuleSchema, ormdb.ModuleDBOptions{ - JSONValidator: func(m proto.Message) error { - return validateMsg(m) - }, + JSONValidator: validateMsg, }) if err != nil { return err @@ -125,8 +123,8 @@ func ValidateGenesis(data json.RawMessage, params core.Params) error { projectKeyToClassKey[project.Key] = project.ClassKey } - batchIdToPrecision := make(map[uint64]uint32) // map of batchID to precision - batchDenomToIdMap := make(map[string]uint64) // map of batchDenom to batchId + batchIDToPrecision := make(map[uint64]uint32) // map of batchID to precision + batchDenomToIDMap := make(map[string]uint64) // map of batchDenom to batchID bItr, err := ss.BatchTable().List(ormCtx, api.BatchPrimaryKey{}) if err != nil { return err @@ -140,9 +138,9 @@ func ValidateGenesis(data json.RawMessage, params core.Params) error { return err } - batchDenomToIdMap[batch.Denom] = batch.Key + batchDenomToIDMap[batch.Denom] = batch.Key - if _, exists := batchIdToPrecision[batch.Key]; exists { + if _, exists := batchIDToPrecision[batch.Key]; exists { continue } @@ -152,12 +150,12 @@ func ValidateGenesis(data json.RawMessage, params core.Params) error { } if class.Key == projectKeyToClassKey[batch.ProjectKey] { - batchIdToPrecision[batch.Key] = abbrevToPrecision[class.CreditTypeAbbrev] + batchIDToPrecision[batch.Key] = abbrevToPrecision[class.CreditTypeAbbrev] } } - batchIdToCalSupply := make(map[uint64]math.Dec) // map of batchID to calculated supply - batchIdToSupply := make(map[uint64]math.Dec) // map of batchID to actual supply + batchIDToCalSupply := make(map[uint64]math.Dec) // map of batchID to calculated supply + batchIDToSupply := make(map[uint64]math.Dec) // map of batchID to actual supply bsItr, err := ss.BatchSupplyTable().List(ormCtx, api.BatchSupplyPrimaryKey{}) if err != nil { return err @@ -174,13 +172,13 @@ func ValidateGenesis(data json.RawMessage, params core.Params) error { tSupply := math.NewDecFromInt64(0) rSupply := math.NewDecFromInt64(0) if batchSupply.TradableAmount != "" { - tSupply, err = math.NewNonNegativeFixedDecFromString(batchSupply.TradableAmount, batchIdToPrecision[batchSupply.BatchKey]) + tSupply, err = math.NewNonNegativeFixedDecFromString(batchSupply.TradableAmount, batchIDToPrecision[batchSupply.BatchKey]) if err != nil { return err } } if batchSupply.RetiredAmount != "" { - rSupply, err = math.NewNonNegativeFixedDecFromString(batchSupply.RetiredAmount, batchIdToPrecision[batchSupply.BatchKey]) + rSupply, err = math.NewNonNegativeFixedDecFromString(batchSupply.RetiredAmount, batchIDToPrecision[batchSupply.BatchKey]) if err != nil { return err } @@ -191,11 +189,11 @@ func ValidateGenesis(data json.RawMessage, params core.Params) error { return err } - batchIdToSupply[batchSupply.BatchKey] = total + batchIDToSupply[batchSupply.BatchKey] = total } // calculate credit batch supply from genesis tradable, retired and escrowed balances - if err := calculateSupply(ormCtx, batchIdToPrecision, ss, batchIdToCalSupply); err != nil { + if err := calculateSupply(ormCtx, batchIDToPrecision, ss, batchIDToCalSupply); err != nil { return err } @@ -215,9 +213,9 @@ func ValidateGenesis(data json.RawMessage, params core.Params) error { if err != nil { return err } - batchId, ok := batchDenomToIdMap[bBalance.BatchDenom] + batchID, ok := batchDenomToIDMap[bBalance.BatchDenom] if !ok { - return fmt.Errorf("unknown credit batch %d in basket", batchId) + return fmt.Errorf("unknown credit batch %d in basket", batchID) } bb, err := math.NewNonNegativeDecFromString(bBalance.Balance) @@ -225,19 +223,19 @@ func ValidateGenesis(data json.RawMessage, params core.Params) error { return err } - if amount, ok := batchIdToCalSupply[batchId]; ok { + if amount, ok := batchIDToCalSupply[batchID]; ok { result, err := math.SafeAddBalance(amount, bb) if err != nil { return err } - batchIdToCalSupply[batchId] = result + batchIDToCalSupply[batchID] = result } else { - return fmt.Errorf("unknown credit batch %d in basket", batchId) + return fmt.Errorf("unknown credit batch %d in basket", batchID) } } // verify calculated total amount of each credit batch matches the total supply - if err := validateSupply(batchIdToCalSupply, batchIdToSupply); err != nil { + if err := validateSupply(batchIDToCalSupply, batchIDToSupply); err != nil { return err } @@ -326,7 +324,7 @@ func validateMsg(m proto.Message) error { return nil } -func calculateSupply(ctx context.Context, batchIdToPrecision map[uint64]uint32, ss api.StateStore, batchIdToSupply map[uint64]math.Dec) error { +func calculateSupply(ctx context.Context, batchIDToPrecision map[uint64]uint32, ss api.StateStore, batchIDToSupply map[uint64]math.Dec) error { bbItr, err := ss.BatchBalanceTable().List(ctx, api.BatchBalancePrimaryKey{}) if err != nil { return err @@ -343,7 +341,7 @@ func calculateSupply(ctx context.Context, batchIdToPrecision map[uint64]uint32, return err } - precision, ok := batchIdToPrecision[balance.BatchKey] + precision, ok := batchIDToPrecision[balance.BatchKey] if !ok { return sdkerrors.ErrInvalidType.Wrapf("credit type not exist for %d batch", balance.BatchKey) } @@ -379,29 +377,29 @@ func calculateSupply(ctx context.Context, batchIdToPrecision map[uint64]uint32, return err } - if supply, ok := batchIdToSupply[balance.BatchKey]; ok { + if supply, ok := batchIDToSupply[balance.BatchKey]; ok { result, err := math.SafeAddBalance(supply, total) if err != nil { return err } - batchIdToSupply[balance.BatchKey] = result + batchIDToSupply[balance.BatchKey] = result } else { - batchIdToSupply[balance.BatchKey] = total + batchIDToSupply[balance.BatchKey] = total } } return nil } -func validateSupply(batchIdToSupplyCal, batchIdToSupply map[uint64]math.Dec) error { - if len(batchIdToSupplyCal) == 0 && len(batchIdToSupply) > 0 { +func validateSupply(batchIDToSupplyCal, batchIDToSupply map[uint64]math.Dec) error { + if len(batchIDToSupplyCal) == 0 && len(batchIDToSupply) > 0 { return sdkerrors.ErrInvalidRequest.Wrap("batch supply was given but no balances were found") } - if len(batchIdToSupply) == 0 && len(batchIdToSupplyCal) > 0 { + if len(batchIDToSupply) == 0 && len(batchIDToSupplyCal) > 0 { return sdkerrors.ErrInvalidRequest.Wrap("batch balances were given but no supplies were found") } - for denom, cs := range batchIdToSupplyCal { - if s, ok := batchIdToSupply[denom]; ok { + for denom, cs := range batchIDToSupplyCal { + if s, ok := batchIDToSupply[denom]; ok { if s.Cmp(cs) != math.EqualTo { return sdkerrors.ErrInvalidCoins.Wrapf("supply is incorrect for %d credit batch, expected %v, got %v", denom, s, cs) } diff --git a/x/ecocredit/genesis/genesis_test.go b/x/ecocredit/genesis/genesis_test.go index 6fe3f55c56..a022717e1c 100644 --- a/x/ecocredit/genesis/genesis_test.go +++ b/x/ecocredit/genesis/genesis_test.go @@ -111,11 +111,11 @@ func TestValidateGenesis(t *testing.T) { target := ormjson.NewRawMessageTarget() require.NoError(t, modDB.ExportJSON(ormCtx, target)) - genesisJson, err := target.JSON() + genesisJSON, err := target.JSON() require.NoError(t, err) params := core.Params{AllowlistEnabled: true} - err = ValidateGenesis(genesisJson, params) + err = ValidateGenesis(genesisJSON, params) require.NoError(t, err) } @@ -606,11 +606,11 @@ func TestValidateGenesisWithBasketBalance(t *testing.T) { target := ormjson.NewRawMessageTarget() require.NoError(t, modDB.ExportJSON(ormCtx, target)) - genesisJson, err := target.JSON() + genesisJSON, err := target.JSON() require.NoError(t, err) params := core.Params{AllowlistEnabled: true} - err = ValidateGenesis(genesisJson, params) + err = ValidateGenesis(genesisJSON, params) require.NoError(t, err) } diff --git a/x/ecocredit/mocks/expected_keepers.go b/x/ecocredit/mocks/expected_keepers.go index 4c7d7f9da8..f3996bbd02 100644 --- a/x/ecocredit/mocks/expected_keepers.go +++ b/x/ecocredit/mocks/expected_keepers.go @@ -7,11 +7,12 @@ package mocks import ( reflect "reflect" + gomock "github.com/golang/mock/gomock" + types "github.com/cosmos/cosmos-sdk/types" types0 "github.com/cosmos/cosmos-sdk/x/auth/types" types1 "github.com/cosmos/cosmos-sdk/x/bank/types" types2 "github.com/cosmos/cosmos-sdk/x/params/types" - gomock "github.com/golang/mock/gomock" ) // MockAccountKeeper is a mock of AccountKeeper interface. diff --git a/x/ecocredit/module/module.go b/x/ecocredit/module/module.go index 8edd767944..f8083595ae 100644 --- a/x/ecocredit/module/module.go +++ b/x/ecocredit/module/module.go @@ -26,7 +26,7 @@ import ( paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" climodule "github.com/regen-network/regen-ledger/types/module/client/cli" - restmodule "github.com/regen-network/regen-ledger/types/module/client/grpc_gateway" + restmodule "github.com/regen-network/regen-ledger/types/module/client/grpcgateway" servermodule "github.com/regen-network/regen-ledger/types/module/server" "github.com/regen-network/regen-ledger/x/ecocredit" baskettypes "github.com/regen-network/regen-ledger/x/ecocredit/basket" diff --git a/x/ecocredit/module/module_test.go b/x/ecocredit/module/module_test.go index cd2af018f4..1e11ef4699 100644 --- a/x/ecocredit/module/module_test.go +++ b/x/ecocredit/module/module_test.go @@ -3,9 +3,10 @@ package module import ( "testing" + "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/stretchr/testify/require" ) func TestHybridORMLegacyGenesis(t *testing.T) { diff --git a/x/ecocredit/orderbook/orderbook.go b/x/ecocredit/orderbook/orderbook.go index 24f9f13ba9..7af985ea24 100644 --- a/x/ecocredit/orderbook/orderbook.go +++ b/x/ecocredit/orderbook/orderbook.go @@ -44,7 +44,7 @@ func NewOrderBook(db ormdb.ModuleDB) (OrderBook, error) { type OrderBook interface { // OnInsertBuyOrder gets called whenever a buy order is inserted into the marketplace state. - //OnInsertBuyOrder(ctx context.Context, buyOrder *marketplacev1.BuyOrder) error + // OnInsertBuyOrder(ctx context.Context, buyOrder *marketplacev1.BuyOrder) error // OnInsertSellOrder gets called whenever a sell order is inserted into the marketplace state. OnInsertSellOrder(ctx context.Context, sellOrder *marketplacev1.SellOrder, batch *ecocreditv1.Batch) error @@ -61,6 +61,7 @@ func (o orderbook) OnInsertBuyOrder(ctx context.Context, buyOrder *marketplacev1 return nil } */ + func (o orderbook) OnInsertSellOrder(ctx context.Context, sellOrder *marketplacev1.SellOrder, batch *ecocreditv1.Batch) error { return nil } diff --git a/x/ecocredit/server/basket/invariants.go b/x/ecocredit/server/basket/invariants.go index dab6893b7a..6eed010108 100644 --- a/x/ecocredit/server/basket/invariants.go +++ b/x/ecocredit/server/basket/invariants.go @@ -25,7 +25,7 @@ func (k Keeper) basketSupplyInvariant() sdk.Invariant { if err != nil { return err.Error(), true } - return BasketSupplyInvariant(ctx, k.stateStore.BasketTable(), k.bankKeeper, bals) + return SupplyInvariant(ctx, k.stateStore.BasketTable(), k.bankKeeper, bals) } } @@ -33,8 +33,8 @@ type bankSupplyStore interface { GetSupply(ctx sdk.Context, denom string) sdk.Coin } -// BasketSupplyInvariant cross check the balance of baskets and bank -func BasketSupplyInvariant(ctx sdk.Context, store api.BasketTable, bank bankSupplyStore, basketBalances map[uint64]math.Dec) (string, bool) { +// SupplyInvariant cross check the balance of baskets and bank +func SupplyInvariant(ctx sdk.Context, store api.BasketTable, bank bankSupplyStore, basketBalances map[uint64]math.Dec) (string, bool) { goCtx := sdk.WrapSDKContext(ctx) bids := make([]uint64, len(basketBalances)) @@ -49,22 +49,22 @@ func BasketSupplyInvariant(ctx sdk.Context, store api.BasketTable, bank bankSupp for _, bid := range bids { b, err := store.Get(goCtx, bid) if err != nil { - return fmt.Sprintf("Can't get basket %v: %v", bid, err), true + return fmt.Sprintf("failed to get basket %v: %v", bid, err), true } bal := basketBalances[bid] - exp := math.NewDecFinite(1, int32(b.Exponent)) + exp := math.NewDecFinite(1, int32(b.Exponent)) //nolint:staticcheck mul, err := bal.Mul(exp) if err != nil { - return fmt.Sprintf("Can't multiply balance by exponent, %v", err), true + return fmt.Sprintf("failed to multiply balance by exponent, %v", err), true } balInt, err := mul.BigInt() if err != nil { - return fmt.Sprintf("Can't convert Dec to big.Int, %v", err), true + return fmt.Sprintf("failed to convert Dec to big.Int, %v", err), true } c := bank.GetSupply(ctx, b.BasketDenom) balSdkInt := sdk.NewIntFromBigInt(balInt) if !c.Amount.Equal(balSdkInt) { - inbalances = append(inbalances, fmt.Sprintf("Basket denom %s is imbalanced, expected: %v, got %v", + inbalances = append(inbalances, fmt.Sprintf("basket denom %s is imbalanced, expected: %v, got %v", b.BasketDenom, balSdkInt, c.Amount)) } } @@ -78,22 +78,22 @@ func BasketSupplyInvariant(ctx sdk.Context, store api.BasketTable, bank bankSupp func (k Keeper) computeBasketBalances(ctx context.Context) (map[uint64]math.Dec, error) { it, err := k.stateStore.BasketBalanceTable().List(ctx, &api.BasketBalancePrimaryKey{}) if err != nil { - return nil, fmt.Errorf("can't create basket balance iterator, %w", err) + return nil, fmt.Errorf("failed to create basket balance iterator: %w", err) } defer it.Close() balances := map[uint64]math.Dec{} for it.Next() { b, err := it.Value() if err != nil { - return nil, fmt.Errorf("Can't get basket balance %w", err) + return nil, fmt.Errorf("failed to get basket balance: %w", err) } bal, err := math.NewDecFromString(b.Balance) if err != nil { - return nil, fmt.Errorf("Can't decode balance %s as math.Dec: %w", b.Balance, err) + return nil, fmt.Errorf("failed to decode balance %s as math.Dec: %w", b.Balance, err) } if a, ok := balances[b.BasketId]; ok { if a, err = a.Add(bal); err != nil { - return nil, fmt.Errorf("Can't add balances: %w", err) + return nil, fmt.Errorf("failed to add balances: %w", err) } balances[b.BasketId] = a } else { diff --git a/x/ecocredit/server/basket/invariants_test.go b/x/ecocredit/server/basket/invariants_test.go index 1fb97cccfa..da48300250 100644 --- a/x/ecocredit/server/basket/invariants_test.go +++ b/x/ecocredit/server/basket/invariants_test.go @@ -14,7 +14,7 @@ import ( type BasketWithSupply struct { supply int64 - b api.Basket + b *api.Basket } type BankSupplyMock map[string]sdk.Coin @@ -31,14 +31,14 @@ func TestBasketSupplyInvarint(t *testing.T) { s := setupBase(t) baskets := []BasketWithSupply{ - {10, api.Basket{BasketDenom: "bb1", Name: "b1"}}, - {20, api.Basket{BasketDenom: "bb2", Name: "b2"}}, + {10, &api.Basket{BasketDenom: "bb1", Name: "b1"}}, + {20, &api.Basket{BasketDenom: "bb2", Name: "b2"}}, } store := s.stateStore.BasketTable() basketBalances := map[uint64]math.Dec{} correctBalances := BankSupplyMock{} for _, b := range baskets { - id, err := store.InsertReturningID(s.ctx, &b.b) + id, err := store.InsertReturningID(s.ctx, b.b) require.NoError(err) basketBalances[id] = math.NewDecFromInt64(b.supply) correctBalances[b.b.BasketDenom] = sdk.NewInt64Coin(b.b.BasketDenom, b.supply) @@ -69,7 +69,7 @@ func TestBasketSupplyInvarint(t *testing.T) { for _, tc := range tcs { tc.bank.GetSupply(s.sdkCtx, "abc") - msg, _ := basket.BasketSupplyInvariant(s.sdkCtx, store, tc.bank, basketBalances) + msg, _ := basket.SupplyInvariant(s.sdkCtx, store, tc.bank, basketBalances) if tc.msg != "" { require.Contains(msg, tc.msg, tc.name) } else { diff --git a/x/ecocredit/server/basket/keeper_test.go b/x/ecocredit/server/basket/keeper_test.go index 8cdfb02c54..d447d00921 100644 --- a/x/ecocredit/server/basket/keeper_test.go +++ b/x/ecocredit/server/basket/keeper_test.go @@ -7,9 +7,10 @@ import ( "github.com/regen-network/gocuke" "gotest.tools/v3/assert" + dbm "github.com/tendermint/tm-db" + "github.com/tendermint/tendermint/libs/log" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/orm/model/ormdb" "github.com/cosmos/cosmos-sdk/orm/model/ormtable" @@ -21,16 +22,14 @@ import ( api "github.com/regen-network/regen-ledger/api/regen/ecocredit/basket/v1" ecoApi "github.com/regen-network/regen-ledger/api/regen/ecocredit/v1" - ecocreditApi "github.com/regen-network/regen-ledger/api/regen/ecocredit/v1" "github.com/regen-network/regen-ledger/x/ecocredit" - "github.com/regen-network/regen-ledger/x/ecocredit/core" "github.com/regen-network/regen-ledger/x/ecocredit/mocks" "github.com/regen-network/regen-ledger/x/ecocredit/server/basket" ) -var ( - gmAny = gomock.Any() - defaultParams = core.DefaultParams() +const ( + testClassID = "C01" + testBasketDenom = "eco.uC.NCT" ) type baseSuite struct { @@ -41,7 +40,7 @@ type baseSuite struct { ctrl *gomock.Controller addrs []sdk.AccAddress stateStore api.StateStore - coreStore ecocreditApi.StateStore + coreStore ecoApi.StateStore bankKeeper *mocks.MockBankKeeper paramsKeeper *mocks.MockParamKeeper storeKey *storetypes.KVStoreKey @@ -56,7 +55,7 @@ func setupBase(t gocuke.TestingT) *baseSuite { assert.NilError(t, err) s.stateStore, err = api.NewStateStore(s.db) assert.NilError(t, err) - s.coreStore, err = ecocreditApi.NewStateStore(s.db) + s.coreStore, err = ecoApi.NewStateStore(s.db) assert.NilError(t, err) db := dbm.NewMemDB() diff --git a/x/ecocredit/server/basket/msg_create.go b/x/ecocredit/server/basket/msg_create.go index 6524069cca..8046467273 100644 --- a/x/ecocredit/server/basket/msg_create.go +++ b/x/ecocredit/server/basket/msg_create.go @@ -113,7 +113,7 @@ func (k Keeper) Create(ctx context.Context, msg *basket.MsgCreate) (*basket.MsgC BasketDenom: denom, DisableAutoRetire: msg.DisableAutoRetire, CreditTypeAbbrev: msg.CreditTypeAbbrev, - DateCriteria: msg.DateCriteria.ToApi(), + DateCriteria: msg.DateCriteria.ToAPI(), Exponent: creditType.Precision, // exponent is no longer used but set until removed Name: msg.Name, }) diff --git a/x/ecocredit/server/basket/msg_create_test.go b/x/ecocredit/server/basket/msg_create_test.go index 1424e13d56..8ee8e01155 100644 --- a/x/ecocredit/server/basket/msg_create_test.go +++ b/x/ecocredit/server/basket/msg_create_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package basket_test import ( @@ -97,7 +98,7 @@ func (s *createSuite) ACreditTypeWithAbbreviationAndPrecision(a string, b string } func (s *createSuite) ACreditClassWithId(a string) { - creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassId(a) + creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassID(a) err := s.coreStore.ClassTable().Insert(s.ctx, &coreapi.Class{ Id: a, diff --git a/x/ecocredit/server/basket/msg_put.go b/x/ecocredit/server/basket/msg_put.go index 899cfae6f8..21cc318bde 100644 --- a/x/ecocredit/server/basket/msg_put.go +++ b/x/ecocredit/server/basket/msg_put.go @@ -123,12 +123,13 @@ func (k Keeper) canBasketAcceptCredit(ctx context.Context, basket *api.Basket, b // check time window match var minStartDate time.Time var criteria = basket.DateCriteria - if criteria.MinStartDate != nil { + switch { + case criteria.MinStartDate != nil: minStartDate = criteria.MinStartDate.AsTime() - } else if criteria.StartDateWindow != nil { + case criteria.StartDateWindow != nil: window := criteria.StartDateWindow.AsDuration() minStartDate = blockTime.Add(-window) - } else if criteria.YearsInThePast != 0 { + case criteria.YearsInThePast != 0: year := blockTime.Year() - int(criteria.YearsInThePast) minStartDate = time.Date(year, 1, 1, 0, 0, 0, 0, time.UTC) } @@ -141,19 +142,19 @@ func (k Keeper) canBasketAcceptCredit(ctx context.Context, basket *api.Basket, b } - classId := core.GetClassIdFromBatchDenom(batch.Denom) + classID := core.GetClassIDFromBatchDenom(batch.Denom) // check credit class match - found, err := k.stateStore.BasketClassTable().Has(ctx, basket.Id, classId) + found, err := k.stateStore.BasketClassTable().Has(ctx, basket.Id, classID) if err != nil { return err } if !found { - return errInvalidReq.Wrapf("credit class %s is not allowed in this basket", classId) + return errInvalidReq.Wrapf("credit class %s is not allowed in this basket", classID) } // check credit type match - class, err := k.coreStore.ClassTable().GetById(ctx, classId) + class, err := k.coreStore.ClassTable().GetById(ctx, classID) if err != nil { return err } @@ -165,7 +166,7 @@ func (k Keeper) canBasketAcceptCredit(ctx context.Context, basket *api.Basket, b } // transferToBasket moves credits from the user's tradable balance, into the basket's balance -func (k Keeper) transferToBasket(ctx context.Context, sender sdk.AccAddress, amt regenmath.Dec, basketId uint64, batch *ecoApi.Batch, exponent uint32) error { +func (k Keeper) transferToBasket(ctx context.Context, sender sdk.AccAddress, amt regenmath.Dec, basketID uint64, batch *ecoApi.Batch, exponent uint32) error { // update user balance, subtracting from their tradable balance userBal, err := k.coreStore.BatchBalanceTable().Get(ctx, sender, batch.Key) if err != nil { @@ -186,11 +187,11 @@ func (k Keeper) transferToBasket(ctx context.Context, sender sdk.AccAddress, amt // update basket balance with amount sent, adding to the basket's balance. var bal *api.BasketBalance - bal, err = k.stateStore.BasketBalanceTable().Get(ctx, basketId, batch.Denom) + bal, err = k.stateStore.BasketBalanceTable().Get(ctx, basketID, batch.Denom) if err != nil { if ormerrors.IsNotFound(err) { bal = &api.BasketBalance{ - BasketId: basketId, + BasketId: basketID, BatchDenom: batch.Denom, Balance: amt.String(), BatchStartDate: batch.StartDate, diff --git a/x/ecocredit/server/basket/msg_put_test.go b/x/ecocredit/server/basket/msg_put_test.go index 6660d70ca8..7d7faa1967 100644 --- a/x/ecocredit/server/basket/msg_put_test.go +++ b/x/ecocredit/server/basket/msg_put_test.go @@ -26,7 +26,7 @@ type putSuite struct { alice sdk.AccAddress aliceTokenBalance sdk.Coin basketTokenSupply sdk.Coin - classId string + classID string creditTypeAbbrev string creditTypePrecision uint32 batchDenom string @@ -51,7 +51,7 @@ func (s *putSuite) Before(t gocuke.TestingT) { Denom: "eco.uC.NCT", Amount: sdk.NewInt(100), } - s.classId = "C01" + s.classID = testClassID s.creditTypeAbbrev = "C" s.creditTypePrecision = 6 s.batchDenom = "C01-001-20200101-20210101-001" @@ -92,15 +92,15 @@ func (s *putSuite) ACreditTypeWithAbbreviationAndPrecision(a string, b string) { } func (s *putSuite) ABasket() { - basketId, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ + basketID, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ BasketDenom: s.basketDenom, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) err = s.stateStore.BasketClassTable().Insert(s.ctx, &api.BasketClass{ - BasketId: basketId, - ClassId: s.classId, + BasketId: basketID, + ClassId: s.classID, }) require.NoError(s.t, err) } @@ -108,44 +108,44 @@ func (s *putSuite) ABasket() { func (s *putSuite) ABasketWithCreditType(a string) { s.creditTypeAbbrev = a - basketId, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ + basketID, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ BasketDenom: s.basketDenom, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) err = s.stateStore.BasketClassTable().Insert(s.ctx, &api.BasketClass{ - BasketId: basketId, - ClassId: s.classId, + BasketId: basketID, + ClassId: s.classID, }) require.NoError(s.t, err) } func (s *putSuite) ABasketWithDenom(a string) { - basketId, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ + basketID, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ BasketDenom: a, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) err = s.stateStore.BasketClassTable().Insert(s.ctx, &api.BasketClass{ - BasketId: basketId, - ClassId: s.classId, + BasketId: basketID, + ClassId: s.classID, }) require.NoError(s.t, err) } func (s *putSuite) ABasketWithAllowedCreditClass(a string) { - creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassId(a) + creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassID(a) - basketId, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ + basketID, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ BasketDenom: s.basketDenom, CreditTypeAbbrev: creditTypeAbbrev, }) require.NoError(s.t, err) err = s.stateStore.BasketClassTable().Insert(s.ctx, &api.BasketClass{ - BasketId: basketId, + BasketId: basketID, ClassId: a, }) require.NoError(s.t, err) @@ -155,7 +155,7 @@ func (s *putSuite) ABasketWithMinimumStartDate(a string) { minStartDate, err := types.ParseDate("start date", a) require.NoError(s.t, err) - basketId, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ + basketID, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ BasketDenom: s.basketDenom, CreditTypeAbbrev: s.creditTypeAbbrev, DateCriteria: &api.DateCriteria{ @@ -165,8 +165,8 @@ func (s *putSuite) ABasketWithMinimumStartDate(a string) { require.NoError(s.t, err) err = s.stateStore.BasketClassTable().Insert(s.ctx, &api.BasketClass{ - BasketId: basketId, - ClassId: s.classId, + BasketId: basketID, + ClassId: s.classID, }) require.NoError(s.t, err) } @@ -175,7 +175,7 @@ func (s *putSuite) ABasketWithStartDateWindow(a string) { startDateWindow, err := strconv.ParseInt(a, 10, 32) require.NoError(s.t, err) - basketId, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ + basketID, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ BasketDenom: s.basketDenom, CreditTypeAbbrev: s.creditTypeAbbrev, DateCriteria: &api.DateCriteria{ @@ -187,8 +187,8 @@ func (s *putSuite) ABasketWithStartDateWindow(a string) { require.NoError(s.t, err) err = s.stateStore.BasketClassTable().Insert(s.ctx, &api.BasketClass{ - BasketId: basketId, - ClassId: s.classId, + BasketId: basketID, + ClassId: s.classID, }) require.NoError(s.t, err) } @@ -197,7 +197,7 @@ func (s *putSuite) ABasketWithYearsInThePast(a string) { yearsInThePast, err := strconv.ParseUint(a, 10, 32) require.NoError(s.t, err) - basketId, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ + basketID, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ BasketDenom: s.basketDenom, CreditTypeAbbrev: s.creditTypeAbbrev, DateCriteria: &api.DateCriteria{ @@ -207,18 +207,18 @@ func (s *putSuite) ABasketWithYearsInThePast(a string) { require.NoError(s.t, err) err = s.stateStore.BasketClassTable().Insert(s.ctx, &api.BasketClass{ - BasketId: basketId, - ClassId: s.classId, + BasketId: basketID, + ClassId: s.classID, }) require.NoError(s.t, err) } func (s *putSuite) ACreditBatchWithDenom(a string) { - classId := core.GetClassIdFromBatchDenom(a) - creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassId(classId) + classID := core.GetClassIDFromBatchDenom(a) + creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassID(classID) classKey, err := s.coreStore.ClassTable().InsertReturningID(s.ctx, &coreapi.Class{ - Id: classId, + Id: classID, CreditTypeAbbrev: creditTypeAbbrev, }) require.NoError(s.t, err) @@ -236,11 +236,11 @@ func (s *putSuite) ACreditBatchWithDenom(a string) { } func (s *putSuite) AliceOwnsCredits() { - classId := core.GetClassIdFromBatchDenom(s.batchDenom) - creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassId(classId) + classID := core.GetClassIDFromBatchDenom(s.batchDenom) + creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassID(classID) classKey, err := s.coreStore.ClassTable().InsertReturningID(s.ctx, &coreapi.Class{ - Id: classId, + Id: classID, CreditTypeAbbrev: creditTypeAbbrev, }) require.NoError(s.t, err) @@ -265,11 +265,11 @@ func (s *putSuite) AliceOwnsCredits() { } func (s *putSuite) AliceOwnsCreditAmount(a string) { - classId := core.GetClassIdFromBatchDenom(s.batchDenom) - creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassId(classId) + classID := core.GetClassIDFromBatchDenom(s.batchDenom) + creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassID(classID) classKey, err := s.coreStore.ClassTable().InsertReturningID(s.ctx, &coreapi.Class{ - Id: classId, + Id: classID, CreditTypeAbbrev: creditTypeAbbrev, }) require.NoError(s.t, err) @@ -294,11 +294,11 @@ func (s *putSuite) AliceOwnsCreditAmount(a string) { } func (s *putSuite) AliceOwnsCreditsFromCreditBatch(a string) { - classId := core.GetClassIdFromBatchDenom(a) - creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassId(classId) + classID := core.GetClassIDFromBatchDenom(a) + creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassID(classID) classKey, err := s.coreStore.ClassTable().InsertReturningID(s.ctx, &coreapi.Class{ - Id: classId, + Id: classID, CreditTypeAbbrev: creditTypeAbbrev, }) require.NoError(s.t, err) @@ -327,7 +327,7 @@ func (s *putSuite) AliceOwnsCreditsWithStartDate(a string) { require.NoError(s.t, err) classKey, err := s.coreStore.ClassTable().InsertReturningID(s.ctx, &coreapi.Class{ - Id: s.classId, + Id: s.classID, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) diff --git a/x/ecocredit/server/basket/msg_take.go b/x/ecocredit/server/basket/msg_take.go index 90361f6255..e18e6acf15 100644 --- a/x/ecocredit/server/basket/msg_take.go +++ b/x/ecocredit/server/basket/msg_take.go @@ -202,27 +202,27 @@ func (k Keeper) addCreditBalance(ctx context.Context, owner sdk.AccAddress, batc BatchDenom: batchDenom, TradableAmount: amount.String(), }) - } else { - if err = core.RetireAndSaveBalance(ctx, k.coreStore.BatchBalanceTable(), owner, batch.Key, amount); err != nil { - return err - } - if err = core.RetireSupply(ctx, k.coreStore.BatchSupplyTable(), batch.Key, amount); err != nil { - return err - } - err = sdkCtx.EventManager().EmitTypedEvent(&coretypes.EventTransfer{ - Sender: k.moduleAddress.String(), // basket submodule - Recipient: owner.String(), - BatchDenom: batchDenom, - RetiredAmount: amount.String(), - }) - if err != nil { - return err - } - return sdkCtx.EventManager().EmitTypedEvent(&coretypes.EventRetire{ - Owner: owner.String(), - BatchDenom: batchDenom, - Amount: amount.String(), - Jurisdiction: jurisdiction, - }) } + + if err = core.RetireAndSaveBalance(ctx, k.coreStore.BatchBalanceTable(), owner, batch.Key, amount); err != nil { + return err + } + if err = core.RetireSupply(ctx, k.coreStore.BatchSupplyTable(), batch.Key, amount); err != nil { + return err + } + err = sdkCtx.EventManager().EmitTypedEvent(&coretypes.EventTransfer{ + Sender: k.moduleAddress.String(), // basket submodule + Recipient: owner.String(), + BatchDenom: batchDenom, + RetiredAmount: amount.String(), + }) + if err != nil { + return err + } + return sdkCtx.EventManager().EmitTypedEvent(&coretypes.EventRetire{ + Owner: owner.String(), + BatchDenom: batchDenom, + Amount: amount.String(), + Jurisdiction: jurisdiction, + }) } diff --git a/x/ecocredit/server/basket/msg_take_test.go b/x/ecocredit/server/basket/msg_take_test.go index 4cd657e9d8..8feea8b30b 100644 --- a/x/ecocredit/server/basket/msg_take_test.go +++ b/x/ecocredit/server/basket/msg_take_test.go @@ -21,7 +21,7 @@ type takeSuite struct { alice sdk.AccAddress aliceTokenBalance sdk.Coin basketTokenSupply sdk.Coin - classId string + classID string creditTypeAbbrev string creditTypePrecision uint32 batchDenom string @@ -47,7 +47,7 @@ func (s *takeSuite) Before(t gocuke.TestingT) { Denom: "eco.uC.NCT", Amount: sdk.NewInt(100), } - s.classId = "C01" + s.classID = testClassID s.creditTypeAbbrev = "C" s.creditTypePrecision = 6 s.batchDenom = "C01-001-20200101-20210101-001" @@ -89,34 +89,34 @@ func (s *takeSuite) ACreditTypeWithAbbreviationAndPrecision(a string, b string) } func (s *takeSuite) ABasket() { - basketId, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ + basketID, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ BasketDenom: s.basketDenom, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) // add balance with credit amount = token amount - s.addBasketClassAndBalance(basketId, s.tokenAmount) + s.addBasketClassAndBalance(basketID, s.tokenAmount) } func (s *takeSuite) ABasketWithDenom(a string) { s.basketDenom = a - basketId, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ + basketID, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ BasketDenom: s.basketDenom, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) // add balance with credit amount = token amount - s.addBasketClassAndBalance(basketId, s.tokenAmount) + s.addBasketClassAndBalance(basketID, s.tokenAmount) } func (s *takeSuite) ABasketWithDisableAutoRetire(a string) { disableAutoRetire, err := strconv.ParseBool(a) require.NoError(s.t, err) - basketId, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ + basketID, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ BasketDenom: s.basketDenom, CreditTypeAbbrev: s.creditTypeAbbrev, DisableAutoRetire: disableAutoRetire, @@ -124,17 +124,17 @@ func (s *takeSuite) ABasketWithDisableAutoRetire(a string) { require.NoError(s.t, err) // add balance with credit amount = token amount - s.addBasketClassAndBalance(basketId, s.tokenAmount) + s.addBasketClassAndBalance(basketID, s.tokenAmount) } func (s *takeSuite) ABasketWithCreditBalance(a string) { - basketId, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ + basketID, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ BasketDenom: s.basketDenom, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) - s.addBasketClassAndBalance(basketId, a) + s.addBasketClassAndBalance(basketID, a) } func (s *takeSuite) ABasketWithCreditTypeAndDisableAutoRetire(a string, b string) { @@ -143,7 +143,7 @@ func (s *takeSuite) ABasketWithCreditTypeAndDisableAutoRetire(a string, b string disableAutoRetire, err := strconv.ParseBool(b) require.NoError(s.t, err) - basketId, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ + basketID, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ BasketDenom: s.basketDenom, CreditTypeAbbrev: s.creditTypeAbbrev, DisableAutoRetire: disableAutoRetire, @@ -151,19 +151,19 @@ func (s *takeSuite) ABasketWithCreditTypeAndDisableAutoRetire(a string, b string require.NoError(s.t, err) // add balance with credit amount = token amount - s.addBasketClassAndBalance(basketId, s.tokenAmount) + s.addBasketClassAndBalance(basketID, s.tokenAmount) } func (s *takeSuite) ABasketWithCreditTypeAndCreditBalance(a string, b string) { s.creditTypeAbbrev = a - basketId, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ + basketID, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ BasketDenom: s.basketDenom, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) - s.addBasketClassAndBalance(basketId, b) + s.addBasketClassAndBalance(basketID, b) } func (s *takeSuite) AliceOwnsBasketTokens() { @@ -320,18 +320,18 @@ func (s *takeSuite) ExpectTheResponse(a gocuke.DocString) { require.Equal(s.t, res, s.res) } -func (s *takeSuite) addBasketClassAndBalance(basketId uint64, creditAmount string) { +func (s *takeSuite) addBasketClassAndBalance(basketID uint64, creditAmount string) { err := s.stateStore.BasketClassTable().Insert(s.ctx, &api.BasketClass{ - BasketId: basketId, - ClassId: s.classId, + BasketId: basketID, + ClassId: s.classID, }) require.NoError(s.t, err) - classId := core.GetClassIdFromBatchDenom(s.batchDenom) - creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassId(classId) + classID := core.GetClassIDFromBatchDenom(s.batchDenom) + creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassID(classID) classKey, err := s.coreStore.ClassTable().InsertReturningID(s.ctx, &coreapi.Class{ - Id: classId, + Id: classID, CreditTypeAbbrev: creditTypeAbbrev, }) require.NoError(s.t, err) @@ -354,7 +354,7 @@ func (s *takeSuite) addBasketClassAndBalance(basketId uint64, creditAmount strin require.NoError(s.t, err) err = s.stateStore.BasketBalanceTable().Insert(s.ctx, &api.BasketBalance{ - BasketId: basketId, + BasketId: basketID, BatchDenom: s.batchDenom, Balance: creditAmount, }) diff --git a/x/ecocredit/server/basket/query_balance_test.go b/x/ecocredit/server/basket/query_balance_test.go index b619611b89..c1e436cd84 100644 --- a/x/ecocredit/server/basket/query_balance_test.go +++ b/x/ecocredit/server/basket/query_balance_test.go @@ -15,7 +15,7 @@ func TestKeeper_BasketBalance(t *testing.T) { s := setupBase(t) // add a basket - basketDenom := "foo" + basketDenom := testBasketDenom batchDenom := "bar" balance := "5.3" id, err := s.stateStore.BasketTable().InsertReturningID(s.ctx, &api.Basket{ diff --git a/x/ecocredit/server/basket/query_balances_test.go b/x/ecocredit/server/basket/query_balances_test.go index 9a2abedc51..3f45d8e2a4 100644 --- a/x/ecocredit/server/basket/query_balances_test.go +++ b/x/ecocredit/server/basket/query_balances_test.go @@ -16,10 +16,9 @@ func TestQueryBalances(t *testing.T) { s := setupBase(t) // add some baskets - basketDenom := "foo" batchDenoms := []string{"bar", "baz", "qux"} require.NoError(t, s.stateStore.BasketTable().Insert(s.ctx, &api.Basket{ - BasketDenom: basketDenom, + BasketDenom: testBasketDenom, })) require.NoError(t, s.stateStore.BasketBalanceTable().Insert(s.ctx, &api.BasketBalance{ BasketId: 1, @@ -43,7 +42,7 @@ func TestQueryBalances(t *testing.T) { // setup test keeper // query all - res, err := s.k.BasketBalances(s.ctx, &baskettypes.QueryBasketBalancesRequest{BasketDenom: basketDenom}) + res, err := s.k.BasketBalances(s.ctx, &baskettypes.QueryBasketBalancesRequest{BasketDenom: testBasketDenom}) require.NoError(t, err) require.Len(t, res.Balances, 3) require.Equal(t, "100.50", res.Balances[0].Balance) @@ -52,7 +51,7 @@ func TestQueryBalances(t *testing.T) { // paginate res, err = s.k.BasketBalances(s.ctx, &baskettypes.QueryBasketBalancesRequest{ - BasketDenom: basketDenom, + BasketDenom: testBasketDenom, Pagination: &query.PageRequest{ Limit: 2, CountTotal: true, diff --git a/x/ecocredit/server/basket/query_basket.go b/x/ecocredit/server/basket/query_basket.go index f473986323..81c2a99dbc 100644 --- a/x/ecocredit/server/basket/query_basket.go +++ b/x/ecocredit/server/basket/query_basket.go @@ -56,7 +56,7 @@ func (k Keeper) Basket(ctx context.Context, request *baskettypes.QueryBasketRequ Name: basket.Name, CreditTypeAbbrev: basket.CreditTypeAbbrev, DisableAutoRetire: basket.DisableAutoRetire, - Exponent: basket.Exponent, + Exponent: basket.Exponent, //nolint:staticcheck Curator: sdk.AccAddress(basket.Curator).String(), } diff --git a/x/ecocredit/server/basket/query_basket_test.go b/x/ecocredit/server/basket/query_basket_test.go index 506ca0ce7b..e867e0cbde 100644 --- a/x/ecocredit/server/basket/query_basket_test.go +++ b/x/ecocredit/server/basket/query_basket_test.go @@ -14,19 +14,18 @@ func TestKeeper_Basket(t *testing.T) { s := setupBase(t) // add a basket - basketDenom := "foo" batchDenom := "bar" err := s.stateStore.BasketTable().Insert(s.ctx, &api.Basket{ - BasketDenom: basketDenom, + BasketDenom: testBasketDenom, }) require.NoError(t, err) // query res, err := s.k.Basket(s.ctx, &baskettypes.QueryBasketRequest{ - BasketDenom: basketDenom, + BasketDenom: testBasketDenom, }) require.NoError(t, err) - require.Equal(t, basketDenom, res.Basket.BasketDenom) + require.Equal(t, testBasketDenom, res.Basket.BasketDenom) // bad query _, err = s.k.Basket(s.ctx, &baskettypes.QueryBasketRequest{ @@ -40,27 +39,26 @@ func TestKeeper_BasketClasses(t *testing.T) { s := setupBase(t) // add a basket - basketDenom := "foo" err := s.stateStore.BasketTable().Insert(s.ctx, &api.Basket{ - BasketDenom: basketDenom, + BasketDenom: testBasketDenom, }) require.NoError(t, err) // add a basket class - classId := "C01" + classID := "C01" err = s.stateStore.BasketClassTable().Insert(s.ctx, &api.BasketClass{ BasketId: 1, - ClassId: classId, + ClassId: classID, }) require.NoError(t, err) // query res, err := s.k.Basket(s.ctx, &baskettypes.QueryBasketRequest{ - BasketDenom: basketDenom, + BasketDenom: testBasketDenom, }) require.NoError(t, err) - require.Equal(t, basketDenom, res.Basket.BasketDenom) - require.Equal(t, []string{classId}, res.Classes) + require.Equal(t, testBasketDenom, res.Basket.BasketDenom) + require.Equal(t, []string{classID}, res.Classes) // query unknown basket _, err = s.k.Basket(s.ctx, &baskettypes.QueryBasketRequest{ diff --git a/x/ecocredit/server/basket/query_baskets.go b/x/ecocredit/server/basket/query_baskets.go index 9cc8b498d4..8ffe89cce1 100644 --- a/x/ecocredit/server/basket/query_baskets.go +++ b/x/ecocredit/server/basket/query_baskets.go @@ -58,7 +58,7 @@ func (k Keeper) Baskets(ctx context.Context, request *baskettypes.QueryBasketsRe Name: basket.Name, DisableAutoRetire: basket.DisableAutoRetire, CreditTypeAbbrev: basket.CreditTypeAbbrev, - Exponent: basket.Exponent, + Exponent: basket.Exponent, //nolint:staticcheck Curator: sdk.AccAddress(basket.Curator).String(), DateCriteria: criteria, }) diff --git a/x/ecocredit/server/basket/util_test.go b/x/ecocredit/server/basket/util_test.go index c29708d296..bbe4ef8be5 100644 --- a/x/ecocredit/server/basket/util_test.go +++ b/x/ecocredit/server/basket/util_test.go @@ -3,23 +3,25 @@ package basket_test import ( "testing" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/golang/mock/gomock" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/types/known/timestamppb" + "gotest.tools/v3/assert" + + sdk "github.com/cosmos/cosmos-sdk/types" + api "github.com/regen-network/regen-ledger/api/regen/ecocredit/basket/v1" ecoApi "github.com/regen-network/regen-ledger/api/regen/ecocredit/v1" "github.com/regen-network/regen-ledger/types/math" "github.com/regen-network/regen-ledger/x/ecocredit/basket" - "github.com/stretchr/testify/require" - "google.golang.org/protobuf/types/known/timestamppb" - "gotest.tools/v3/assert" ) func TestGetBasketBalances(t *testing.T) { t.Parallel() s := setupBase(t) gmAny := gomock.Any() - batchDenom1, classId1 := "C01-001-0000000-0000000-001", "C01" - batchDenom2, classId2 := "C02-001-0000000-0000000-002", "C02" + batchDenom1, classID1 := "C01-001-0000000-0000000-001", "C01" + batchDenom2, classID2 := "C02-001-0000000-0000000-002", "C02" userStartingBalance, amtToDeposit := math.NewDecFromInt64(10), math.NewDecFromInt64(3) err := s.coreStore.CreditTypeTable().Insert(s.ctx, &ecoApi.CreditType{ @@ -30,8 +32,8 @@ func TestGetBasketBalances(t *testing.T) { insertClass(t, s, "C01", "C") insertClass(t, s, "C02", "C") - insertBasket(t, s, "foo", "basket", "C", &api.DateCriteria{YearsInThePast: 3}, []string{classId1}) - insertBasket(t, s, "bar", "basket1", "C", &api.DateCriteria{YearsInThePast: 3}, []string{classId1, classId2}) + insertBasket(t, s, "foo", "basket", "C", &api.DateCriteria{YearsInThePast: 3}, []string{classID1}) + insertBasket(t, s, "bar", "basket1", "C", &api.DateCriteria{YearsInThePast: 3}, []string{classID1, classID2}) initBatch(t, s, 1, batchDenom1, timestamppb.Now()) initBatch(t, s, 2, batchDenom2, timestamppb.Now()) @@ -51,10 +53,10 @@ func TestGetBasketBalances(t *testing.T) { }) assert.NilError(t, err) - bIdToBalance, err := s.k.GetBasketBalanceMap(s.ctx) + IDToBalance, err := s.k.GetBasketBalanceMap(s.ctx) require.NoError(t, err) - require.Len(t, bIdToBalance, 1) - require.Equal(t, bIdToBalance[1], amtToDeposit) + require.Len(t, IDToBalance, 1) + require.Equal(t, IDToBalance[1], amtToDeposit) _, err = s.k.Put(s.ctx, &basket.MsgPut{ Owner: s.addrs[0].String(), @@ -74,15 +76,15 @@ func TestGetBasketBalances(t *testing.T) { }) assert.NilError(t, err) - bIdToBalance, err = s.k.GetBasketBalanceMap(s.ctx) + IDToBalance, err = s.k.GetBasketBalanceMap(s.ctx) require.NoError(t, err) - require.Len(t, bIdToBalance, 2) + require.Len(t, IDToBalance, 2) expBatch1Amount, err := amtToDeposit.Add(amtToDeposit) require.NoError(t, err) - require.Equal(t, bIdToBalance[1], expBatch1Amount) - require.Equal(t, bIdToBalance[2], amtToDeposit) + require.Equal(t, IDToBalance[1], expBatch1Amount) + require.Equal(t, IDToBalance[2], amtToDeposit) } func initBatch(t *testing.T, s *baseSuite, pid uint64, denom string, startDate *timestamppb.Timestamp) { diff --git a/x/ecocredit/server/core/invariants.go b/x/ecocredit/server/core/invariants.go index b0f7c23e16..9a8e0198cc 100644 --- a/x/ecocredit/server/core/invariants.go +++ b/x/ecocredit/server/core/invariants.go @@ -13,8 +13,8 @@ import ( // - calculated total retired balance of each credit batch matches the total retired supply func BatchSupplyInvariant(ctx context.Context, k Keeper, basketBalances map[uint64]math.Dec) (msg string, broken bool) { // sum of tradeable ecocredits with credits locked in baskets - batchIdToBalanceTradable := make(map[uint64]math.Dec) // map batch id => tradable balance - batchIdToBalanceRetired := make(map[uint64]math.Dec) // map batch id => retired balance + batchIDToBalanceTradable := make(map[uint64]math.Dec) // map batch id => tradable balance + batchIDToBalanceRetired := make(map[uint64]math.Dec) // map batch id => retired balance itr, err := k.stateStore.BatchBalanceTable().List(ctx, ecocreditv1.BatchBalancePrimaryKey{}) if err != nil { @@ -22,62 +22,62 @@ func BatchSupplyInvariant(ctx context.Context, k Keeper, basketBalances map[uint } defer itr.Close() - balanceFunc := func(name string, batchIdToBalance map[uint64]math.Dec, bID uint64, amount string) { + balanceFunc := func(name string, batchIDToBalance map[uint64]math.Dec, bID uint64, amount string) { amt, err := math.NewNonNegativeDecFromString(amount) if err != nil { broken = true msg += fmt.Sprintf("error while parsing %s balance %v", name, err) } - if val, ok := batchIdToBalance[bID]; ok { + if val, ok := batchIDToBalance[bID]; ok { result, err := math.SafeAddBalance(val, amt) if err != nil { broken = true msg += fmt.Sprintf("error adding credit batch %s supply %v", name, err) } - batchIdToBalance[bID] = result + batchIDToBalance[bID] = result } else { - batchIdToBalance[bID] = amt + batchIDToBalance[bID] = amt } } for itr.Next() { - bBalance, err := itr.Value() + balance, err := itr.Value() if err != nil { return err.Error(), true } // tradable balance - balanceFunc("tradable", batchIdToBalanceTradable, bBalance.BatchKey, bBalance.TradableAmount) + balanceFunc("tradable", batchIDToBalanceTradable, balance.BatchKey, balance.TradableAmount) - //escrowed balance - balanceFunc("tradable", batchIdToBalanceTradable, bBalance.BatchKey, bBalance.EscrowedAmount) + // escrowed balance + balanceFunc("tradable", batchIDToBalanceTradable, balance.BatchKey, balance.EscrowedAmount) // retired balance - balanceFunc("retired", batchIdToBalanceRetired, bBalance.BatchKey, bBalance.RetiredAmount) + balanceFunc("retired", batchIDToBalanceRetired, balance.BatchKey, balance.RetiredAmount) } - for batchId, amt := range basketBalances { - if amount, ok := batchIdToBalanceTradable[batchId]; ok { + for batchID, amt := range basketBalances { + if amount, ok := batchIDToBalanceTradable[batchID]; ok { result, err := math.SafeAddBalance(amount, amt) if err != nil { broken = true - msg += fmt.Sprintf("\tfailed to add %v amount to %v for credit batch %d\n", amt, amount, batchId) + msg += fmt.Sprintf("\tfailed to add %v amount to %v for credit batch %d\n", amt, amount, batchID) return msg, broken } - batchIdToBalanceTradable[batchId] = result + batchIDToBalanceTradable[batchID] = result } else { - msg += fmt.Sprintf("\tunknown credit batch %d in basket", batchId) + msg += fmt.Sprintf("\tunknown credit batch %d in basket", batchID) return msg, true } } - supplyFunc := func(name string, batchIdToBalance map[uint64]math.Dec, batchKey uint64, amount string) { + supplyFunc := func(name string, batchIDToBalance map[uint64]math.Dec, batchKey uint64, amount string) { expected, err := math.NewNonNegativeDecFromString(amount) if err != nil { broken = true msg += fmt.Sprintf("\terror while parsing %s supply for batch id: %d\n", name, batchKey) } - if actual, ok := batchIdToBalance[batchKey]; ok { + if actual, ok := batchIDToBalance[batchKey]; ok { if expected.Cmp(actual) != math.EqualTo { broken = true msg += fmt.Sprintf("\t%s supply is incorrect for %d credit batch, expected %v, got %v\n", name, batchKey, expected, actual) @@ -101,10 +101,10 @@ func BatchSupplyInvariant(ctx context.Context, k Keeper, basketBalances map[uint } // tradable supply invariant check - supplyFunc("tradable", batchIdToBalanceTradable, supply.BatchKey, supply.TradableAmount) + supplyFunc("tradable", batchIDToBalanceTradable, supply.BatchKey, supply.TradableAmount) // retired supply invariant check - supplyFunc("retired", batchIdToBalanceRetired, supply.BatchKey, supply.RetiredAmount) + supplyFunc("retired", batchIDToBalanceRetired, supply.BatchKey, supply.RetiredAmount) } return msg, broken diff --git a/x/ecocredit/server/core/keeper_test.go b/x/ecocredit/server/core/keeper_test.go index d7b155de00..82511985e8 100644 --- a/x/ecocredit/server/core/keeper_test.go +++ b/x/ecocredit/server/core/keeper_test.go @@ -9,9 +9,10 @@ import ( "github.com/stretchr/testify/require" "gotest.tools/v3/assert" + dbm "github.com/tendermint/tm-db" + "github.com/tendermint/tendermint/libs/log" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/orm/model/ormdb" "github.com/cosmos/cosmos-sdk/orm/model/ormtable" @@ -26,6 +27,12 @@ import ( "github.com/regen-network/regen-ledger/x/ecocredit/mocks" ) +const ( + testClassID = "C01" + testProjectID = "C01-001" + testBatchDenom = "C01-001-20200101-20210101-001" +) + type baseSuite struct { t gocuke.TestingT db ormdb.ModuleDB diff --git a/x/ecocredit/server/core/msg_bridge_receive.go b/x/ecocredit/server/core/msg_bridge_receive.go index 6b5b89c0cc..86125b4eec 100644 --- a/x/ecocredit/server/core/msg_bridge_receive.go +++ b/x/ecocredit/server/core/msg_bridge_receive.go @@ -151,10 +151,10 @@ func (k Keeper) BridgeReceive(ctx context.Context, req *core.MsgBridgeReceive) ( // class id and reference id because we enforce uniqueness on non-empty reference ids within the scope // of a credit class (and we do this at the message server level and not the ORM level because reference // id is optional when using Msg/CreateProject). If no project is found, nil is returned for both values. -func (k Keeper) getProjectFromBridgeReq(ctx context.Context, req *core.MsgBridgeReceive_Project, classId string) (*api.Project, error) { - class, err := k.stateStore.ClassTable().GetById(ctx, classId) +func (k Keeper) getProjectFromBridgeReq(ctx context.Context, req *core.MsgBridgeReceive_Project, classID string) (*api.Project, error) { + class, err := k.stateStore.ClassTable().GetById(ctx, classID) if err != nil { - return nil, sdkerrors.ErrInvalidRequest.Wrapf("could not get class with id %s: %s", classId, err.Error()) + return nil, sdkerrors.ErrInvalidRequest.Wrapf("could not get class with id %s: %s", classID, err.Error()) } // first we check if there is an existing project diff --git a/x/ecocredit/server/core/msg_bridge_receive_test.go b/x/ecocredit/server/core/msg_bridge_receive_test.go index d26fcd6b81..513c0942fa 100644 --- a/x/ecocredit/server/core/msg_bridge_receive_test.go +++ b/x/ecocredit/server/core/msg_bridge_receive_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package core import ( @@ -22,10 +23,10 @@ type bridgeReceiveSuite struct { alice sdk.AccAddress bob sdk.AccAddress creditTypeAbbrev string - classId string + classID string classKey uint64 projectKey uint64 - referenceId string + referenceID string metadata string jurisdiction string batchKey uint64 @@ -45,9 +46,9 @@ func (s *bridgeReceiveSuite) Before(t gocuke.TestingT) { s.baseSuite = setupBase(t) s.alice = s.addr s.bob = s.addr2 - s.classId = "C01" + s.classID = testClassID s.jurisdiction = "US-WA" - s.referenceId = "VCS-001" + s.referenceID = "VCS-001" s.metadata = "regen:113gdjFKcVCt13Za6vN7TtbgMM6LMSjRnu89BMCxeuHdkJ1hWUmy.rdf" s.tradableAmount = "10" @@ -102,10 +103,11 @@ func (s *bridgeReceiveSuite) AProjectWithId(a string) { seq := s.getProjectSequence(a) - s.k.stateStore.ProjectSequenceTable().Insert(s.ctx, &api.ProjectSequence{ + err = s.k.stateStore.ProjectSequenceTable().Insert(s.ctx, &api.ProjectSequence{ ClassKey: s.classKey, NextSequence: seq + 1, }) + require.NoError(s.t, err) s.projectKey = pKey } @@ -120,18 +122,19 @@ func (s *bridgeReceiveSuite) AProjectWithIdAndReferenceId(a, b string) { seq := s.getProjectSequence(a) - s.k.stateStore.ProjectSequenceTable().Insert(s.ctx, &api.ProjectSequence{ + err = s.k.stateStore.ProjectSequenceTable().Insert(s.ctx, &api.ProjectSequence{ ClassKey: s.classKey, NextSequence: seq + 1, }) + require.NoError(s.t, err) s.projectKey = pKey } func (s *bridgeReceiveSuite) ACreditBatchWithDenomAndIssuerAlice(a string) { - projectId := core.GetProjectIdFromBatchDenom(a) + projectID := core.GetProjectIDFromBatchDenom(a) - project, err := s.k.stateStore.ProjectTable().GetById(s.ctx, projectId) + project, err := s.k.stateStore.ProjectTable().GetById(s.ctx, projectID) require.NoError(s.t, err) bKey, err := s.k.stateStore.BatchTable().InsertReturningID(s.ctx, &api.Batch{ @@ -175,7 +178,7 @@ func (s *bridgeReceiveSuite) AliceAttemptsToBridgeCreditsWithClassId(a string) { Issuer: s.alice.String(), ClassId: a, Project: &core.MsgBridgeReceive_Project{ - ReferenceId: s.referenceId, + ReferenceId: s.referenceID, Jurisdiction: s.jurisdiction, Metadata: s.metadata, }, @@ -195,7 +198,7 @@ func (s *bridgeReceiveSuite) BobAttemptsToBridgeCreditsWithClassId(a string) { Issuer: s.bob.String(), ClassId: a, Project: &core.MsgBridgeReceive_Project{ - ReferenceId: s.referenceId, + ReferenceId: s.referenceID, Jurisdiction: s.jurisdiction, Metadata: s.metadata, }, @@ -213,9 +216,9 @@ func (s *bridgeReceiveSuite) BobAttemptsToBridgeCreditsWithClassId(a string) { func (s *bridgeReceiveSuite) AliceAttemptsToBridgeCreditsWithContract(a string) { s.res, s.err = s.k.BridgeReceive(s.ctx, &core.MsgBridgeReceive{ Issuer: s.alice.String(), - ClassId: s.classId, + ClassId: s.classID, Project: &core.MsgBridgeReceive_Project{ - ReferenceId: s.referenceId, + ReferenceId: s.referenceID, Jurisdiction: s.jurisdiction, Metadata: s.metadata, }, @@ -237,9 +240,9 @@ func (s *bridgeReceiveSuite) AliceAttemptsToBridgeCreditsWithContract(a string) func (s *bridgeReceiveSuite) BobAttemptsToBridgeCreditsWithContract(a string) { s.res, s.err = s.k.BridgeReceive(s.ctx, &core.MsgBridgeReceive{ Issuer: s.bob.String(), - ClassId: s.classId, + ClassId: s.classID, Project: &core.MsgBridgeReceive_Project{ - ReferenceId: s.referenceId, + ReferenceId: s.referenceID, Jurisdiction: s.jurisdiction, Metadata: s.metadata, }, @@ -285,7 +288,7 @@ func (s *bridgeReceiveSuite) AliceAttemptsToBridgeCreditsWithProjectProperties(a s.res, s.err = s.k.BridgeReceive(s.ctx, &core.MsgBridgeReceive{ Issuer: s.alice.String(), - ClassId: s.classId, + ClassId: s.classID, Project: &core.MsgBridgeReceive_Project{ ReferenceId: project.ReferenceId, Jurisdiction: project.Jurisdiction, @@ -311,9 +314,9 @@ func (s *bridgeReceiveSuite) AliceAttemptsToBridgeCreditsWithBatchProperties(a g s.res, s.err = s.k.BridgeReceive(s.ctx, &core.MsgBridgeReceive{ Issuer: s.alice.String(), - ClassId: s.classId, + ClassId: s.classID, Project: &core.MsgBridgeReceive_Project{ - ReferenceId: s.referenceId, + ReferenceId: s.referenceID, Jurisdiction: s.jurisdiction, Metadata: s.metadata, }, @@ -333,9 +336,9 @@ func (s *bridgeReceiveSuite) AliceAttemptsToBridgeCreditsWithBatchProperties(a g func (s *bridgeReceiveSuite) AliceAttemptsToBridgeCreditsToBobWithTradableAmount(a string) { s.res, s.err = s.k.BridgeReceive(s.ctx, &core.MsgBridgeReceive{ Issuer: s.alice.String(), - ClassId: s.classId, + ClassId: s.classID, Project: &core.MsgBridgeReceive_Project{ - ReferenceId: s.referenceId, + ReferenceId: s.referenceID, Jurisdiction: s.jurisdiction, Metadata: s.metadata, }, @@ -454,8 +457,8 @@ func (s *bridgeReceiveSuite) ExpectBatchSupply(a gocuke.DocString) { require.Equal(s.t, expected.CancelledAmount, balance.CancelledAmount) } -func (s *bridgeReceiveSuite) getProjectSequence(projectId string) uint64 { - str := strings.Split(projectId, "-") +func (s *bridgeReceiveSuite) getProjectSequence(projectID string) uint64 { + str := strings.Split(projectID, "-") seq, err := strconv.ParseUint(str[1], 10, 32) require.NoError(s.t, err) return seq diff --git a/x/ecocredit/server/core/msg_bridge_test.go b/x/ecocredit/server/core/msg_bridge_test.go index 1af4077cf6..f0587b3c33 100644 --- a/x/ecocredit/server/core/msg_bridge_test.go +++ b/x/ecocredit/server/core/msg_bridge_test.go @@ -17,9 +17,9 @@ type bridgeSuite struct { *baseSuite alice sdk.AccAddress creditTypeAbbrev string - classId string + classID string classKey uint64 - projectId string + projectID string batchDenom string batchKey uint64 tradableAmount string @@ -39,9 +39,9 @@ func (s *bridgeSuite) Before(t gocuke.TestingT) { s.baseSuite = setupBase(t) s.alice = s.addr s.creditTypeAbbrev = "C" - s.classId = "C01" - s.projectId = "C01-001" - s.batchDenom = "C01-001-20200101-20210101-001" + s.classID = testClassID + s.projectID = testProjectID + s.batchDenom = testBatchDenom s.tradableAmount = "10" s.target = "polygon" s.contract = "0x01" @@ -175,7 +175,7 @@ func (s *bridgeSuite) creditBatchSetup() { require.NoError(s.t, err) cKey, err := s.k.stateStore.ClassTable().InsertReturningID(s.ctx, &api.Class{ - Id: s.classId, + Id: s.classID, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) @@ -183,7 +183,7 @@ func (s *bridgeSuite) creditBatchSetup() { s.classKey = cKey pKey, err := s.k.stateStore.ProjectTable().InsertReturningID(s.ctx, &api.Project{ - Id: s.projectId, + Id: s.projectID, ClassKey: cKey, }) require.NoError(s.t, err) diff --git a/x/ecocredit/server/core/msg_cancel_test.go b/x/ecocredit/server/core/msg_cancel_test.go index e4d4a761f7..688e9f180c 100644 --- a/x/ecocredit/server/core/msg_cancel_test.go +++ b/x/ecocredit/server/core/msg_cancel_test.go @@ -18,9 +18,9 @@ type cancel struct { *baseSuite alice sdk.AccAddress creditTypeAbbrev string - classId string + classID string classKey uint64 - projectId string + projectID string projectKey uint64 batchDenom string batchKey uint64 @@ -37,9 +37,9 @@ func (s *cancel) Before(t gocuke.TestingT) { s.baseSuite = setupBase(t) s.alice = s.addr s.creditTypeAbbrev = "C" - s.classId = "C01" - s.projectId = "C01-001" - s.batchDenom = "C01-001-20200101-20210101-001" + s.classID = testClassID + s.projectID = testProjectID + s.batchDenom = testBatchDenom s.tradableAmount = "10" } @@ -82,7 +82,7 @@ func (s *cancel) ACreditBatchWithDenom(a string) { func (s *cancel) ACreditBatchFromCreditClassWithCreditType(a string) { cKey, err := s.k.stateStore.ClassTable().InsertReturningID(s.ctx, &api.Class{ - Id: s.classId, + Id: s.classID, CreditTypeAbbrev: a, }) require.NoError(s.t, err) @@ -90,7 +90,7 @@ func (s *cancel) ACreditBatchFromCreditClassWithCreditType(a string) { s.classKey = cKey pKey, err := s.k.stateStore.ProjectTable().InsertReturningID(s.ctx, &api.Project{ - Id: s.projectId, + Id: s.projectID, ClassKey: cKey, }) require.NoError(s.t, err) @@ -224,7 +224,7 @@ func (s *cancel) projectSetup() { require.NoError(s.t, err) cKey, err := s.k.stateStore.ClassTable().InsertReturningID(s.ctx, &api.Class{ - Id: s.classId, + Id: s.classID, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) @@ -232,7 +232,7 @@ func (s *cancel) projectSetup() { s.classKey = cKey pKey, err := s.k.stateStore.ProjectTable().InsertReturningID(s.ctx, &api.Project{ - Id: s.projectId, + Id: s.projectID, ClassKey: cKey, }) require.NoError(s.t, err) diff --git a/x/ecocredit/server/core/msg_create_batch_test.go b/x/ecocredit/server/core/msg_create_batch_test.go index 62f03073b9..447593bf4b 100644 --- a/x/ecocredit/server/core/msg_create_batch_test.go +++ b/x/ecocredit/server/core/msg_create_batch_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package core import ( @@ -24,11 +25,10 @@ type createBatchSuite struct { alice sdk.AccAddress bob sdk.AccAddress creditTypeAbbrev string - classId string + classID string classKey uint64 - projectId string + projectID string projectKey uint64 - batchKey uint64 tradableAmount string startDate *time.Time endDate *time.Time @@ -45,8 +45,8 @@ func (s *createBatchSuite) Before(t gocuke.TestingT) { s.alice = s.addr s.bob = s.addr2 s.creditTypeAbbrev = "C" - s.classId = "C01" - s.projectId = "C01-001" + s.classID = testClassID + s.projectID = testProjectID s.tradableAmount = "10" startDate, err := types.ParseDate("start date", "2020-01-01") @@ -85,7 +85,7 @@ func (s *createBatchSuite) ACreditTypeWithAbbreviationAndPrecision(a string, b s func (s *createBatchSuite) ACreditClassWithIssuerAlice() { cKey, err := s.k.stateStore.ClassTable().InsertReturningID(s.ctx, &api.Class{ - Id: s.classId, + Id: s.classID, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) @@ -100,7 +100,7 @@ func (s *createBatchSuite) ACreditClassWithIssuerAlice() { } func (s *createBatchSuite) ACreditClassWithClassIdAndIssuerAlice(a string) { - creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassId(a) + creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassID(a) cKey, err := s.k.stateStore.ClassTable().InsertReturningID(s.ctx, &api.Class{ Id: a, @@ -118,9 +118,9 @@ func (s *createBatchSuite) ACreditClassWithClassIdAndIssuerAlice(a string) { } func (s *createBatchSuite) AProjectWithProjectId(a string) { - classId := core.GetClassIdFromProjectId(a) + classID := core.GetClassIDFromProjectID(a) - class, err := s.k.stateStore.ClassTable().GetById(s.ctx, classId) + class, err := s.k.stateStore.ClassTable().GetById(s.ctx, classID) require.NoError(s.t, err) pKey, err := s.k.stateStore.ProjectTable().InsertReturningID(s.ctx, &api.Project{ @@ -397,8 +397,8 @@ func (s *createBatchSuite) ExpectTheResponse(a gocuke.DocString) { require.Equal(s.t, &res, s.res) } -func (s *createBatchSuite) getProjectSequence(projectId string) uint64 { - str := strings.Split(projectId, "-") +func (s *createBatchSuite) getProjectSequence(projectID string) uint64 { + str := strings.Split(projectID, "-") seq, err := strconv.ParseUint(str[1], 10, 32) require.NoError(s.t, err) return seq diff --git a/x/ecocredit/server/core/msg_create_class.go b/x/ecocredit/server/core/msg_create_class.go index ca8d0ace5a..23a91b53fb 100644 --- a/x/ecocredit/server/core/msg_create_class.go +++ b/x/ecocredit/server/core/msg_create_class.go @@ -106,7 +106,7 @@ func (k Keeper) CreateClass(goCtx context.Context, req *core.MsgCreateClass) (*c return nil, err } - classID := core.FormatClassId(creditType.Abbreviation, seq) + classID := core.FormatClassID(creditType.Abbreviation, seq) key, err := k.stateStore.ClassTable().InsertReturningID(goCtx, &api.Class{ Id: classID, diff --git a/x/ecocredit/server/core/msg_create_class_test.go b/x/ecocredit/server/core/msg_create_class_test.go index 711784c4df..fb3ba2ee4b 100644 --- a/x/ecocredit/server/core/msg_create_class_test.go +++ b/x/ecocredit/server/core/msg_create_class_test.go @@ -21,7 +21,7 @@ type createClassSuite struct { aliceBalance sdk.Coin params core.Params creditTypeAbbrev string - classId string + classID string res *core.MsgCreateClassResponse err error } @@ -34,7 +34,7 @@ func (s *createClassSuite) Before(t gocuke.TestingT) { s.baseSuite = setupBase(t) s.alice = s.addr s.creditTypeAbbrev = "C" - s.classId = "C01" + s.classID = testClassID } func (s *createClassSuite) ACreditType() { @@ -176,7 +176,7 @@ func (s *createClassSuite) ExpectClassIssuers(a gocuke.DocString) { err := json.Unmarshal([]byte(a.Content), &issuers) require.NoError(s.t, err) - class, err := s.stateStore.ClassTable().GetById(s.ctx, s.classId) + class, err := s.stateStore.ClassTable().GetById(s.ctx, s.classID) require.NoError(s.t, err) for _, issuer := range issuers { diff --git a/x/ecocredit/server/core/msg_create_project.go b/x/ecocredit/server/core/msg_create_project.go index b793cd7fc1..a64f5ea7d2 100644 --- a/x/ecocredit/server/core/msg_create_project.go +++ b/x/ecocredit/server/core/msg_create_project.go @@ -36,7 +36,7 @@ func (k Keeper) CreateProject(ctx context.Context, req *core.MsgCreateProject) ( } // check if non-empty reference id is unique within the scope of the credit class - err = k.verifyReferenceId(ctx, classInfo.Key, req.ReferenceId) + err = k.verifyReferenceID(ctx, classInfo.Key, req.ReferenceId) if err != nil { return nil, err } @@ -84,20 +84,20 @@ func (k Keeper) genProjectID(ctx context.Context, classKey uint64, classID strin return "", err } - return core.FormatProjectId(classID, nextSeq), nil + return core.FormatProjectID(classID, nextSeq), nil } -// verifyReferenceId prevents multiple projects from having the same reference id within the +// verifyReferenceID prevents multiple projects from having the same reference id within the // scope of a credit class. We verify this here at the message server level rather than at the // ORM level because reference id is optional and therefore multiple projects within the scope // of a credit class can have an empty reference id (see BridgeReceive for more information) -func (k Keeper) verifyReferenceId(ctx context.Context, classKey uint64, referenceId string) error { - if referenceId == "" { +func (k Keeper) verifyReferenceID(ctx context.Context, classKey uint64, referenceID string) error { + if referenceID == "" { // reference id is optional so an empty reference id is valid return nil } - key := api.ProjectClassKeyReferenceIdIndexKey{}.WithClassKeyReferenceId(classKey, referenceId) + key := api.ProjectClassKeyReferenceIdIndexKey{}.WithClassKeyReferenceId(classKey, referenceID) it, err := k.stateStore.ProjectTable().List(ctx, key) if err != nil { return err @@ -105,7 +105,7 @@ func (k Keeper) verifyReferenceId(ctx context.Context, classKey uint64, referenc defer it.Close() if it.Next() { return sdkerrors.ErrInvalidRequest.Wrapf( - "a project with reference id %s already exists within this credit class", referenceId, + "a project with reference id %s already exists within this credit class", referenceID, ) } diff --git a/x/ecocredit/server/core/msg_create_project_test.go b/x/ecocredit/server/core/msg_create_project_test.go index ecd9b27f03..99985cdbf5 100644 --- a/x/ecocredit/server/core/msg_create_project_test.go +++ b/x/ecocredit/server/core/msg_create_project_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package core import ( @@ -42,7 +43,7 @@ func (s *createProjectSuite) ACreditTypeWithAbbreviation(a string) { } func (s *createProjectSuite) ACreditClassWithClassIdAndIssuerAlice(a string) { - creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassId(a) + creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassID(a) cKey, err := s.k.stateStore.ClassTable().InsertReturningID(s.ctx, &api.Class{ Id: a, @@ -72,9 +73,9 @@ func (s *createProjectSuite) AProjectSequenceWithClassIdAndNextSequence(a, b str } func (s *createProjectSuite) AProjectWithProjectIdAndReferenceId(a, b string) { - classId := core.GetClassIdFromProjectId(a) + classID := core.GetClassIDFromProjectID(a) - class, err := s.k.stateStore.ClassTable().GetById(s.ctx, classId) + class, err := s.k.stateStore.ClassTable().GetById(s.ctx, classID) require.NoError(s.t, err) err = s.k.stateStore.ProjectTable().Insert(s.ctx, &api.Project{ @@ -176,8 +177,8 @@ func (s *createProjectSuite) ExpectTheResponse(a gocuke.DocString) { require.Equal(s.t, &res, s.res) } -func (s *createProjectSuite) getProjectSequence(projectId string) uint64 { - str := strings.Split(projectId, "-") +func (s *createProjectSuite) getProjectSequence(projectID string) uint64 { + str := strings.Split(projectID, "-") seq, err := strconv.ParseUint(str[1], 10, 32) require.NoError(s.t, err) return seq diff --git a/x/ecocredit/server/core/msg_mint_batch_credits_test.go b/x/ecocredit/server/core/msg_mint_batch_credits_test.go index 19e2a6a7be..12147ee432 100644 --- a/x/ecocredit/server/core/msg_mint_batch_credits_test.go +++ b/x/ecocredit/server/core/msg_mint_batch_credits_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package core import ( @@ -80,9 +81,9 @@ func (s *mintBatchCredits) AProjectWithId(a string) { } func (s *mintBatchCredits) ACreditBatchWithDenomAndIssuerAlice(a string) { - projectId := core.GetProjectIdFromBatchDenom(a) + projectID := core.GetProjectIDFromBatchDenom(a) - project, err := s.k.stateStore.ProjectTable().GetById(s.ctx, projectId) + project, err := s.k.stateStore.ProjectTable().GetById(s.ctx, projectID) require.NoError(s.t, err) bKey, err := s.k.stateStore.BatchTable().InsertReturningID(s.ctx, &api.Batch{ diff --git a/x/ecocredit/server/core/msg_retire_test.go b/x/ecocredit/server/core/msg_retire_test.go index 1836e9e9a7..65e654a7fd 100644 --- a/x/ecocredit/server/core/msg_retire_test.go +++ b/x/ecocredit/server/core/msg_retire_test.go @@ -18,9 +18,9 @@ type retire struct { *baseSuite alice sdk.AccAddress creditTypeAbbrev string - classId string + classID string classKey uint64 - projectId string + projectID string projectKey uint64 batchDenom string batchKey uint64 @@ -37,9 +37,9 @@ func (s *retire) Before(t gocuke.TestingT) { s.baseSuite = setupBase(t) s.alice = s.addr s.creditTypeAbbrev = "C" - s.classId = "C01" - s.projectId = "C01-001" - s.batchDenom = "C01-001-20200101-20210101-001" + s.classID = testClassID + s.projectID = testProjectID + s.batchDenom = testBatchDenom s.tradableAmount = "10" } @@ -82,7 +82,7 @@ func (s *retire) ACreditBatchWithDenom(a string) { func (s *retire) ACreditBatchFromCreditClassWithCreditType(a string) { cKey, err := s.k.stateStore.ClassTable().InsertReturningID(s.ctx, &api.Class{ - Id: s.classId, + Id: s.classID, CreditTypeAbbrev: a, }) require.NoError(s.t, err) @@ -90,7 +90,7 @@ func (s *retire) ACreditBatchFromCreditClassWithCreditType(a string) { s.classKey = cKey pKey, err := s.k.stateStore.ProjectTable().InsertReturningID(s.ctx, &api.Project{ - Id: s.projectId, + Id: s.projectID, ClassKey: cKey, }) require.NoError(s.t, err) @@ -224,7 +224,7 @@ func (s *retire) projectSetup() { require.NoError(s.t, err) cKey, err := s.k.stateStore.ClassTable().InsertReturningID(s.ctx, &api.Class{ - Id: s.classId, + Id: s.classID, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) @@ -232,7 +232,7 @@ func (s *retire) projectSetup() { s.classKey = cKey pKey, err := s.k.stateStore.ProjectTable().InsertReturningID(s.ctx, &api.Project{ - Id: s.projectId, + Id: s.projectID, ClassKey: cKey, }) require.NoError(s.t, err) diff --git a/x/ecocredit/server/core/msg_seal_batch_test.go b/x/ecocredit/server/core/msg_seal_batch_test.go index 9bd9a34b45..2683d46171 100644 --- a/x/ecocredit/server/core/msg_seal_batch_test.go +++ b/x/ecocredit/server/core/msg_seal_batch_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package core import ( @@ -67,9 +68,9 @@ func (s *sealBatch) AProjectWithId(a string) { } func (s *sealBatch) ACreditBatchWithDenomAndIssuerAlice(a string) { - projectId := core.GetProjectIdFromBatchDenom(a) + projectID := core.GetProjectIDFromBatchDenom(a) - project, err := s.k.stateStore.ProjectTable().GetById(s.ctx, projectId) + project, err := s.k.stateStore.ProjectTable().GetById(s.ctx, projectID) require.NoError(s.t, err) bKey, err := s.k.stateStore.BatchTable().InsertReturningID(s.ctx, &api.Batch{ diff --git a/x/ecocredit/server/core/msg_send_test.go b/x/ecocredit/server/core/msg_send_test.go index 0b56276d9a..7369d169fa 100644 --- a/x/ecocredit/server/core/msg_send_test.go +++ b/x/ecocredit/server/core/msg_send_test.go @@ -19,9 +19,9 @@ type send struct { alice sdk.AccAddress bob sdk.AccAddress creditTypeAbbrev string - classId string + classID string classKey uint64 - projectId string + projectID string projectKey uint64 batchDenom string batchKey uint64 @@ -39,9 +39,9 @@ func (s *send) Before(t gocuke.TestingT) { s.alice = s.addr s.bob = s.addr2 s.creditTypeAbbrev = "C" - s.classId = "C01" - s.projectId = "C01-001" - s.batchDenom = "C01-001-20200101-20210101-001" + s.classID = testClassID + s.projectID = testProjectID + s.batchDenom = testBatchDenom s.tradableAmount = "10" } @@ -84,7 +84,7 @@ func (s *send) ACreditBatchWithDenom(a string) { func (s *send) ACreditBatchFromCreditClassWithCreditType(a string) { cKey, err := s.k.stateStore.ClassTable().InsertReturningID(s.ctx, &api.Class{ - Id: s.classId, + Id: s.classID, CreditTypeAbbrev: a, }) require.NoError(s.t, err) @@ -92,7 +92,7 @@ func (s *send) ACreditBatchFromCreditClassWithCreditType(a string) { s.classKey = cKey pKey, err := s.k.stateStore.ProjectTable().InsertReturningID(s.ctx, &api.Project{ - Id: s.projectId, + Id: s.projectID, ClassKey: cKey, }) require.NoError(s.t, err) @@ -267,7 +267,7 @@ func (s *send) projectSetup() { require.NoError(s.t, err) cKey, err := s.k.stateStore.ClassTable().InsertReturningID(s.ctx, &api.Class{ - Id: s.classId, + Id: s.classID, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) @@ -275,7 +275,7 @@ func (s *send) projectSetup() { s.classKey = cKey pKey, err := s.k.stateStore.ProjectTable().InsertReturningID(s.ctx, &api.Project{ - Id: s.projectId, + Id: s.projectID, ClassKey: cKey, }) require.NoError(s.t, err) diff --git a/x/ecocredit/server/core/msg_update_class_admin_test.go b/x/ecocredit/server/core/msg_update_class_admin_test.go index ec9bf2d3f1..a61d8a2a8c 100644 --- a/x/ecocredit/server/core/msg_update_class_admin_test.go +++ b/x/ecocredit/server/core/msg_update_class_admin_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package core import ( @@ -40,7 +41,7 @@ func (s *updateClassAdmin) ACreditTypeWithAbbreviation(a string) { } func (s *updateClassAdmin) ACreditClassWithClassIdAndAdminAlice(a string) { - creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassId(a) + creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassID(a) err := s.k.stateStore.ClassTable().Insert(s.ctx, &api.Class{ Id: a, diff --git a/x/ecocredit/server/core/msg_update_class_issuers_test.go b/x/ecocredit/server/core/msg_update_class_issuers_test.go index 11e890676b..8117aed5c6 100644 --- a/x/ecocredit/server/core/msg_update_class_issuers_test.go +++ b/x/ecocredit/server/core/msg_update_class_issuers_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package core import ( @@ -45,7 +46,7 @@ func (s *updateClassIssuers) ACreditTypeWithAbbreviation(a string) { } func (s *updateClassIssuers) ACreditClassWithClassIdAndAdminAlice(a string) { - creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassId(a) + creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassID(a) err := s.k.stateStore.ClassTable().Insert(s.ctx, &api.Class{ Id: a, @@ -56,7 +57,7 @@ func (s *updateClassIssuers) ACreditClassWithClassIdAndAdminAlice(a string) { } func (s *updateClassIssuers) ACreditClassWithClassIdAdminAliceAndIssuers(a string, b gocuke.DocString) { - creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassId(a) + creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassID(a) cKey, err := s.k.stateStore.ClassTable().InsertReturningID(s.ctx, &api.Class{ Id: a, diff --git a/x/ecocredit/server/core/msg_update_class_metadata_test.go b/x/ecocredit/server/core/msg_update_class_metadata_test.go index 33cbc325e3..646f60ace2 100644 --- a/x/ecocredit/server/core/msg_update_class_metadata_test.go +++ b/x/ecocredit/server/core/msg_update_class_metadata_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package core import ( @@ -40,7 +41,7 @@ func (s *updateClassMetadata) ACreditTypeWithAbbreviation(a string) { } func (s *updateClassMetadata) ACreditClassWithClassIdAndAdminAlice(a string) { - creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassId(a) + creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassID(a) err := s.k.stateStore.ClassTable().Insert(s.ctx, &api.Class{ Id: a, diff --git a/x/ecocredit/server/core/msg_update_project_admin_test.go b/x/ecocredit/server/core/msg_update_project_admin_test.go index 5a471c3f85..fc0ea2dd9a 100644 --- a/x/ecocredit/server/core/msg_update_project_admin_test.go +++ b/x/ecocredit/server/core/msg_update_project_admin_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package core import ( @@ -40,7 +41,7 @@ func (s *updateProjectAdmin) ACreditTypeWithAbbreviation(a string) { } func (s *updateProjectAdmin) ACreditClassWithClassId(a string) { - creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassId(a) + creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassID(a) err := s.k.stateStore.ClassTable().Insert(s.ctx, &api.Class{ Id: a, diff --git a/x/ecocredit/server/core/msg_update_project_metadata_test.go b/x/ecocredit/server/core/msg_update_project_metadata_test.go index ddd6b81a31..6ac1e7179d 100644 --- a/x/ecocredit/server/core/msg_update_project_metadata_test.go +++ b/x/ecocredit/server/core/msg_update_project_metadata_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package core import ( @@ -40,7 +41,7 @@ func (s *updateProjectMetadata) ACreditTypeWithAbbreviation(a string) { } func (s *updateProjectMetadata) ACreditClassWithClassId(a string) { - creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassId(a) + creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassID(a) err := s.k.stateStore.ClassTable().Insert(s.ctx, &api.Class{ Id: a, diff --git a/x/ecocredit/server/core/query_balances.go b/x/ecocredit/server/core/query_balances.go index 03e3a3d46e..7f1c99a0aa 100644 --- a/x/ecocredit/server/core/query_balances.go +++ b/x/ecocredit/server/core/query_balances.go @@ -36,6 +36,9 @@ func (k Keeper) Balances(ctx context.Context, req *core.QueryBalancesRequest) (* } batch, err := k.stateStore.BatchTable().Get(ctx, balance.BatchKey) + if err != nil { + return nil, err + } info := core.BatchBalanceInfo{ Address: addr.String(), diff --git a/x/ecocredit/server/core/query_balances_test.go b/x/ecocredit/server/core/query_balances_test.go index 9eec618aad..ed41523a40 100644 --- a/x/ecocredit/server/core/query_balances_test.go +++ b/x/ecocredit/server/core/query_balances_test.go @@ -36,7 +36,7 @@ func TestQuery_Balances(t *testing.T) { }) assert.NilError(t, err) assert.Equal(t, 1, len(res.Balances)) - assertBalanceEqual(t, s.ctx, s.k, res.Balances[0], balance1) + assertBalanceEqual(s.ctx, t, s.k, res.Balances[0], balance1) assert.Equal(t, uint64(2), res.Pagination.Total) _, _, noBalAddr := testdata.KeyTestPubAddr() @@ -49,7 +49,7 @@ func TestQuery_Balances(t *testing.T) { assert.Equal(t, 0, len(res.Balances)) } -func assertBalanceEqual(t *testing.T, ctx context.Context, k Keeper, received *core.BatchBalanceInfo, balance *api.BatchBalance) { +func assertBalanceEqual(ctx context.Context, t *testing.T, k Keeper, received *core.BatchBalanceInfo, balance *api.BatchBalance) { addr := sdk.AccAddress(balance.Address) batch, err := k.stateStore.BatchTable().Get(ctx, balance.BatchKey) diff --git a/x/ecocredit/server/core/query_batches_by_class_test.go b/x/ecocredit/server/core/query_batches_by_class_test.go index 0acf3b10ee..eb8e4f227c 100644 --- a/x/ecocredit/server/core/query_batches_by_class_test.go +++ b/x/ecocredit/server/core/query_batches_by_class_test.go @@ -63,7 +63,7 @@ func TestQuery_BatchesByClass(t *testing.T) { }) assert.NilError(t, err) assert.Equal(t, 1, len(res.Batches)) - assertBatchEqual(t, s.ctx, s.k, res.Batches[0], batch1) + assertBatchEqual(s.ctx, t, s.k, res.Batches[0], batch1) assert.Equal(t, uint64(2), res.Pagination.Total) // query batches by unknown credit class diff --git a/x/ecocredit/server/core/query_batches_by_issuer_test.go b/x/ecocredit/server/core/query_batches_by_issuer_test.go index 1ea3c5f8e2..7278a2153d 100644 --- a/x/ecocredit/server/core/query_batches_by_issuer_test.go +++ b/x/ecocredit/server/core/query_batches_by_issuer_test.go @@ -59,7 +59,7 @@ func TestQueryBatchesByIssuer(t *testing.T) { assert.NilError(t, err) assert.Equal(t, 1, len(res.Batches)) assert.Equal(t, uint64(2), res.Pagination.Total) - assertBatchEqual(t, s.ctx, s.k, res.Batches[0], batch1) + assertBatchEqual(s.ctx, t, s.k, res.Batches[0], batch1) _, _, notIssuer := testdata.KeyTestPubAddr() diff --git a/x/ecocredit/server/core/query_batches_by_project_test.go b/x/ecocredit/server/core/query_batches_by_project_test.go index f14cf43e3e..948c9f9455 100644 --- a/x/ecocredit/server/core/query_batches_by_project_test.go +++ b/x/ecocredit/server/core/query_batches_by_project_test.go @@ -44,7 +44,7 @@ func TestQuery_BatchesByProject(t *testing.T) { }) assert.NilError(t, err) assert.Equal(t, 1, len(res.Batches)) - assertBatchEqual(t, s.ctx, s.k, res.Batches[0], batch) + assertBatchEqual(s.ctx, t, s.k, res.Batches[0], batch) assert.Equal(t, uint64(2), res.Pagination.Total) // query batches by unknown project diff --git a/x/ecocredit/server/core/query_batches_test.go b/x/ecocredit/server/core/query_batches_test.go index 6151d3b742..2e809685a2 100644 --- a/x/ecocredit/server/core/query_batches_test.go +++ b/x/ecocredit/server/core/query_batches_test.go @@ -57,11 +57,11 @@ func TestQuery_Batches(t *testing.T) { }) assert.NilError(t, err) assert.Equal(t, 1, len(res.Batches)) - assertBatchEqual(t, s.ctx, s.k, res.Batches[0], batch) + assertBatchEqual(s.ctx, t, s.k, res.Batches[0], batch) assert.Equal(t, uint64(2), res.Pagination.Total) } -func assertBatchEqual(t *testing.T, ctx context.Context, k Keeper, received *core.BatchInfo, batch *api.Batch) { +func assertBatchEqual(ctx context.Context, t *testing.T, k Keeper, received *core.BatchInfo, batch *api.Batch) { issuer := sdk.AccAddress(batch.Issuer) project, err := k.stateStore.ProjectTable().Get(ctx, batch.ProjectKey) diff --git a/x/ecocredit/server/core/query_class_issuers_test.go b/x/ecocredit/server/core/query_class_issuers_test.go index 24c0ce86ae..9223418bae 100644 --- a/x/ecocredit/server/core/query_class_issuers_test.go +++ b/x/ecocredit/server/core/query_class_issuers_test.go @@ -19,8 +19,8 @@ func TestQuery_ClassIssuers(t *testing.T) { s := setupBase(t) // make a class with 3 issuers. - addrs := genAddrs(2) - issuers := append(addrs, s.addr) + issuers := genAddrs(2) + issuers = append(issuers, s.addr) err := s.stateStore.ClassTable().Insert(s.ctx, &ecocreditv1.Class{ Id: "C01", Admin: s.addr, @@ -34,11 +34,11 @@ func TestQuery_ClassIssuers(t *testing.T) { })) assert.NilError(t, s.stateStore.ClassIssuerTable().Insert(s.ctx, &ecocreditv1.ClassIssuer{ ClassKey: 1, - Issuer: addrs[0], + Issuer: issuers[0], })) assert.NilError(t, s.stateStore.ClassIssuerTable().Insert(s.ctx, &ecocreditv1.ClassIssuer{ ClassKey: 1, - Issuer: addrs[1], + Issuer: issuers[1], })) // base request diff --git a/x/ecocredit/server/core/query_projects_by_reference_id.go b/x/ecocredit/server/core/query_projects_by_reference_id.go index 5a6d332edc..95e16dd130 100644 --- a/x/ecocredit/server/core/query_projects_by_reference_id.go +++ b/x/ecocredit/server/core/query_projects_by_reference_id.go @@ -3,17 +3,19 @@ package core import ( "context" - "github.com/cosmos/cosmos-sdk/orm/model/ormlist" - sdk "github.com/cosmos/cosmos-sdk/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "github.com/cosmos/cosmos-sdk/orm/model/ormlist" + sdk "github.com/cosmos/cosmos-sdk/types" + api "github.com/regen-network/regen-ledger/api/regen/ecocredit/v1" "github.com/regen-network/regen-ledger/types/ormutil" "github.com/regen-network/regen-ledger/x/ecocredit/core" ) // ProjectsByReferenceId queries projects by reference id. +//nolint:revive,stylecheck func (k Keeper) ProjectsByReferenceId(ctx context.Context, req *core.QueryProjectsByReferenceIdRequest) (*core.QueryProjectsByReferenceIdResponse, error) { if req.ReferenceId == "" { return nil, status.Errorf(codes.InvalidArgument, "reference-id is empty") diff --git a/x/ecocredit/server/invariants_test.go b/x/ecocredit/server/invariants_test.go index be3855699d..05f447f792 100644 --- a/x/ecocredit/server/invariants_test.go +++ b/x/ecocredit/server/invariants_test.go @@ -8,9 +8,10 @@ import ( "github.com/stretchr/testify/require" "gotest.tools/v3/assert" + dbm "github.com/tendermint/tm-db" + "github.com/tendermint/tendermint/libs/log" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/orm/model/ormdb" "github.com/cosmos/cosmos-sdk/orm/model/ormtable" @@ -270,8 +271,8 @@ func TestBatchSupplyInvariant(t *testing.T) { tc := tc suite := setupBase(t) t.Run(tc.msg, func(t *testing.T) { - initBalances(t, suite.ctx, suite.stateStore, tc.balances) - initSupply(t, suite.ctx, suite.stateStore, tc.supply) + initBalances(suite.ctx, t, suite.stateStore, tc.balances) + initSupply(suite.ctx, t, suite.stateStore, tc.supply) msg, broken := coreserver.BatchSupplyInvariant(suite.ctx, suite.k, tc.basketBalance) if tc.expBroken { @@ -283,7 +284,7 @@ func TestBatchSupplyInvariant(t *testing.T) { } } -func initBalances(t *testing.T, ctx context.Context, ss api.StateStore, balances []*core.BatchBalance) { +func initBalances(ctx context.Context, t *testing.T, ss api.StateStore, balances []*core.BatchBalance) { for _, b := range balances { _, err := math.NewNonNegativeDecFromString(b.TradableAmount) require.NoError(t, err) @@ -298,7 +299,7 @@ func initBalances(t *testing.T, ctx context.Context, ss api.StateStore, balances } } -func initSupply(t *testing.T, ctx context.Context, ss api.StateStore, supply []*core.BatchSupply) { +func initSupply(ctx context.Context, t *testing.T, ss api.StateStore, supply []*core.BatchSupply) { for _, s := range supply { err := ss.BatchSupplyTable().Insert(ctx, &api.BatchSupply{ BatchKey: s.BatchKey, diff --git a/x/ecocredit/server/marketplace/features/msg_update_sell_orders.feature b/x/ecocredit/server/marketplace/features/msg_update_sell_orders.feature index de01ed2b67..a50927e2a7 100644 --- a/x/ecocredit/server/marketplace/features/msg_update_sell_orders.feature +++ b/x/ecocredit/server/marketplace/features/msg_update_sell_orders.feature @@ -147,7 +147,6 @@ Feature: Msg/UpdateSellOrders And an allowed denom with bank denom "regen" And an allowed denom with bank denom "atom" And alice created a sell order with batch denom "C01-001-20200101-20210101-001" and ask denom "regen" - And a market with credit type "C" and bank denom "regen" Scenario: credit type and bank denom pair is unique When alice attempts to update the sell order with ask denom "atom" diff --git a/x/ecocredit/server/marketplace/keeper_test.go b/x/ecocredit/server/marketplace/keeper_test.go index 58650159a3..b5b356c16c 100644 --- a/x/ecocredit/server/marketplace/keeper_test.go +++ b/x/ecocredit/server/marketplace/keeper_test.go @@ -8,9 +8,10 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" "gotest.tools/v3/assert" + dbm "github.com/tendermint/tm-db" + "github.com/tendermint/tendermint/libs/log" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/orm/model/ormdb" "github.com/cosmos/cosmos-sdk/orm/model/ormtable" @@ -25,13 +26,13 @@ import ( "github.com/regen-network/regen-ledger/types/math" "github.com/regen-network/regen-ledger/x/ecocredit" "github.com/regen-network/regen-ledger/x/ecocredit/core" - "github.com/regen-network/regen-ledger/x/ecocredit/marketplace" "github.com/regen-network/regen-ledger/x/ecocredit/mocks" "github.com/regen-network/regen-ledger/x/ecocredit/server/utils" ) -var ( - gmAny = gomock.Any() +const ( + testClassID = "C01" + testBatchDenom = "C01-001-20200101-20210101-001" ) type baseSuite struct { @@ -88,72 +89,6 @@ func setupBase(t gocuke.TestingT, numAddresses int) *baseSuite { return s } -func (s *baseSuite) createSellOrder(msg *marketplace.MsgSell) []uint64 { - res, err := s.k.Sell(s.ctx, msg) - assert.NilError(s.t, err) - return res.SellOrderIds -} - -func (s *baseSuite) getBalanceAndSupply(batchKey uint64, addr sdk.AccAddress) (*ecoApi.BatchBalance, *ecoApi.BatchSupply) { - bal, err := utils.GetBalance(s.ctx, s.coreStore.BatchBalanceTable(), addr, batchKey) - assert.NilError(s.t, err) - sup, err := s.coreStore.BatchSupplyTable().Get(s.ctx, batchKey) - assert.NilError(s.t, err) - return bal, sup -} - -func (s *baseSuite) assertBalanceAndSupplyUpdated(orders []*marketplace.MsgBuyDirect_Order, b1, b2 *ecoApi.BatchBalance, s1, s2 *ecoApi.BatchSupply) { - purchaseTradable := math.NewDecFromInt64(0) - purchaseRetired := math.NewDecFromInt64(0) - for _, order := range orders { - if order.DisableAutoRetire { - qty, err := math.NewDecFromString(order.Quantity) - assert.NilError(s.t, err) - purchaseTradable, err = purchaseTradable.Add(qty) - assert.NilError(s.t, err) - } else { - qty, err := math.NewDecFromString(order.Quantity) - assert.NilError(s.t, err) - purchaseRetired, err = purchaseRetired.Add(qty) - assert.NilError(s.t, err) - } - } - - balBeforeT, balBeforeR, _ := extractBalanceDecs(s.t, b1) - balAfterT, balAfterR, _ := extractBalanceDecs(s.t, b2) - - supBeforeT, supBeforeR, _ := extractSupplyDecs(s.t, s1) - supAfterT, supAfterR, _ := extractSupplyDecs(s.t, s2) - - expectedTradableBal, err := balBeforeT.Add(purchaseTradable) - assert.NilError(s.t, err) - expectedRetiredBal, err := balBeforeR.Add(purchaseRetired) - assert.NilError(s.t, err) - assert.Check(s.t, balAfterT.Equal(expectedTradableBal)) - assert.Check(s.t, balAfterR.Equal(expectedRetiredBal)) - - expectedTradableSup, err := supBeforeT.Sub(purchaseRetired) - assert.NilError(s.t, err) - expectedRetiredSup, err := supBeforeR.Add(purchaseRetired) - assert.NilError(s.t, err) - - assert.Check(s.t, expectedTradableSup.Equal(supAfterT)) - assert.Check(s.t, expectedRetiredSup.Equal(supAfterR)) - -} - -func extractBalanceDecs(t gocuke.TestingT, b *ecoApi.BatchBalance) (tradable, retired, escrowed math.Dec) { - decs, err := utils.GetNonNegativeFixedDecs(6, b.TradableAmount, b.RetiredAmount, b.EscrowedAmount) - assert.NilError(t, err) - return decs[0], decs[1], decs[2] -} - -func extractSupplyDecs(t gocuke.TestingT, s *ecoApi.BatchSupply) (tradable, retired, cancelled math.Dec) { - decs, err := utils.GetNonNegativeFixedDecs(6, s.TradableAmount, s.RetiredAmount, s.CancelledAmount) - assert.NilError(t, err) - return decs[0], decs[1], decs[2] -} - // assertCreditsEscrowed adds orderAmt to tradable, subtracts from escrowed in before balance/supply and checks that it is equal to after balance/supply. func assertCreditsEscrowed(t gocuke.TestingT, balanceBefore, balanceAfter *ecoApi.BatchBalance, orderAmt math.Dec) { decs, err := utils.GetNonNegativeFixedDecs(6, balanceBefore.TradableAmount, balanceAfter.TradableAmount, @@ -174,7 +109,7 @@ func assertCreditsEscrowed(t gocuke.TestingT, balanceBefore, balanceAfter *ecoAp } // testSellSetup sets up a batch, class, market, and issues a balance of 100 retired and tradable to the base suite's addr. -func (s *baseSuite) testSellSetup(batchDenom, bankDenom, displayDenom, classId string, start, end *timestamppb.Timestamp, creditType core.CreditType) { +func (s *baseSuite) testSellSetup(batchDenom, bankDenom, displayDenom, classID string, start, end *timestamppb.Timestamp, creditType core.CreditType) { assert.Check(s.t, len(s.addrs) > 0, "When calling `testSellSetup`, the base suite must have a non-empty `addrs`.") assert.NilError(s.t, s.coreStore.CreditTypeTable().Insert(s.ctx, &ecoApi.CreditType{ Abbreviation: "C", @@ -184,7 +119,7 @@ func (s *baseSuite) testSellSetup(batchDenom, bankDenom, displayDenom, classId s })) assert.NilError(s.t, s.coreStore.ClassTable().Insert(s.ctx, &ecoApi.Class{ - Id: classId, + Id: classID, Admin: s.addrs[0], Metadata: "", CreditTypeAbbrev: creditType.Abbreviation, diff --git a/x/ecocredit/server/marketplace/msg_add_allowed_denom.go b/x/ecocredit/server/marketplace/msg_add_allowed_denom.go index cb0a86f409..e3afd67b41 100644 --- a/x/ecocredit/server/marketplace/msg_add_allowed_denom.go +++ b/x/ecocredit/server/marketplace/msg_add_allowed_denom.go @@ -34,7 +34,11 @@ func (k Keeper) AddAllowedDenom(ctx context.Context, req *marketplace.MsgAddAllo } sdkCtx := sdk.UnwrapSDKContext(ctx) - sdkCtx.EventManager().EmitTypedEvent(&marketplace.EventAllowDenom{Denom: req.BankDenom}) + if err := sdkCtx.EventManager().EmitTypedEvent(&marketplace.EventAllowDenom{ + Denom: req.BankDenom, + }); err != nil { + return nil, err + } return &marketplace.MsgAddAllowedDenomResponse{}, nil } diff --git a/x/ecocredit/server/marketplace/msg_buy_direct.go b/x/ecocredit/server/marketplace/msg_buy_direct.go index 5b3502acf4..3026c72b53 100644 --- a/x/ecocredit/server/marketplace/msg_buy_direct.go +++ b/x/ecocredit/server/marketplace/msg_buy_direct.go @@ -4,12 +4,14 @@ import ( "context" "fmt" - "github.com/regen-network/regen-ledger/types/math" - "github.com/regen-network/regen-ledger/x/ecocredit/marketplace" - "github.com/regen-network/regen-ledger/x/ecocredit/server/utils" + sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/regen-network/regen-ledger/types/math" + "github.com/regen-network/regen-ledger/x/ecocredit/marketplace" + "github.com/regen-network/regen-ledger/x/ecocredit/server/utils" ) // BuyDirect allows for the purchase of credits directly from sell orders. @@ -77,7 +79,7 @@ func (k Keeper) BuyDirect(ctx context.Context, req *marketplace.MsgBuyDirect) (* // check that bid price >= sell price sellOrderAskAmount, ok := sdk.NewIntFromString(sellOrder.AskAmount) if !ok { - return nil, sdkerrors.ErrInvalidType.Wrapf("could not convert %s to %T", sellOrder.AskAmount, sdk.Int{}) + return nil, sdkerrors.ErrInvalidType.Wrapf("could not convert %s to %T", sellOrder.AskAmount, sdkmath.Int{}) } sellOrderPriceCoin := sdk.Coin{Denom: market.BankDenom, Amount: sellOrderAskAmount} if sellOrderAskAmount.GT(order.BidPrice.Amount) { diff --git a/x/ecocredit/server/marketplace/msg_buy_direct_test.go b/x/ecocredit/server/marketplace/msg_buy_direct_test.go index 31a9656009..3b98d435e2 100644 --- a/x/ecocredit/server/marketplace/msg_buy_direct_test.go +++ b/x/ecocredit/server/marketplace/msg_buy_direct_test.go @@ -1,18 +1,21 @@ +//nolint:revive,stylecheck package marketplace import ( "strconv" "testing" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - sdk "github.com/cosmos/cosmos-sdk/types" + sdkmath "cosmossdk.io/math" "github.com/gogo/protobuf/jsonpb" "github.com/regen-network/gocuke" - "github.com/regen-network/regen-ledger/types/math" "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + sdk "github.com/cosmos/cosmos-sdk/types" + api "github.com/regen-network/regen-ledger/api/regen/ecocredit/marketplace/v1" coreapi "github.com/regen-network/regen-ledger/api/regen/ecocredit/v1" + "github.com/regen-network/regen-ledger/types/math" "github.com/regen-network/regen-ledger/x/ecocredit/marketplace" ) @@ -23,9 +26,9 @@ type buyDirectSuite struct { bob sdk.AccAddress bobBankBalance sdk.Coin creditTypeAbbrev string - classId string + classID string batchDenom string - sellOrderId uint64 + sellOrderID uint64 disableAutoRetire bool quantity string askPrice sdk.Coin @@ -51,9 +54,9 @@ func (s *buyDirectSuite) Before(t gocuke.TestingT) { Amount: sdk.NewInt(100), } s.creditTypeAbbrev = "C" - s.classId = "C01" - s.batchDenom = "C01-001-20200101-20210101-001" - s.sellOrderId = 1 + s.classID = testClassID + s.batchDenom = testBatchDenom + s.sellOrderID = 1 s.quantity = "10" s.askPrice = sdk.Coin{ Denom: "regen", @@ -158,7 +161,7 @@ func (s *buyDirectSuite) AliceCreatedASellOrderWithId(a string) { id, err := strconv.ParseUint(a, 10, 32) require.NoError(s.t, err) - s.sellOrderId = id + s.sellOrderID = id s.createSellOrders(1) } @@ -276,7 +279,7 @@ func (s *buyDirectSuite) BobAttemptsToBuyCreditsWithBidDenom(a string) { Buyer: s.bob.String(), Orders: []*marketplace.MsgBuyDirect_Order{ { - SellOrderId: s.sellOrderId, + SellOrderId: s.sellOrderID, Quantity: s.quantity, BidPrice: &sdk.Coin{ Denom: a, @@ -297,7 +300,7 @@ func (s *buyDirectSuite) BobAttemptsToBuyCreditsWithDisableAutoRetire(a string) Buyer: s.bob.String(), Orders: []*marketplace.MsgBuyDirect_Order{ { - SellOrderId: s.sellOrderId, + SellOrderId: s.sellOrderID, Quantity: s.quantity, BidPrice: &s.bidPrice, DisableAutoRetire: disableAutoRetire, @@ -315,7 +318,7 @@ func (s *buyDirectSuite) BobAttemptsToBuyCreditsWithQuantity(a string) { Buyer: s.bob.String(), Orders: []*marketplace.MsgBuyDirect_Order{ { - SellOrderId: s.sellOrderId, + SellOrderId: s.sellOrderID, Quantity: a, BidPrice: &s.bidPrice, }, @@ -333,7 +336,7 @@ func (s *buyDirectSuite) BobAttemptsToBuyCreditsWithQuantityAndBidAmount(a strin Buyer: s.bob.String(), Orders: []*marketplace.MsgBuyDirect_Order{ { - SellOrderId: s.sellOrderId, + SellOrderId: s.sellOrderID, Quantity: a, BidPrice: &sdk.Coin{ Denom: s.bidPrice.Denom, @@ -354,7 +357,7 @@ func (s *buyDirectSuite) BobAttemptsToBuyCreditsWithQuantityAndBidPrice(a string Buyer: s.bob.String(), Orders: []*marketplace.MsgBuyDirect_Order{ { - SellOrderId: s.sellOrderId, + SellOrderId: s.sellOrderID, Quantity: a, BidPrice: &bidPrice, }, @@ -372,7 +375,7 @@ func (s *buyDirectSuite) BobAttemptsToBuyCreditsWithQuantityAndDisableAutoRetire Buyer: s.bob.String(), Orders: []*marketplace.MsgBuyDirect_Order{ { - SellOrderId: s.sellOrderId, + SellOrderId: s.sellOrderID, Quantity: a, BidPrice: &s.bidPrice, DisableAutoRetire: disableAutoRetire, @@ -431,7 +434,7 @@ func (s *buyDirectSuite) ExpectSellOrderWithId(a string) { } func (s *buyDirectSuite) ExpectSellOrderWithQuantity(a string) { - order, err := s.marketStore.SellOrderTable().Get(s.ctx, s.sellOrderId) + order, err := s.marketStore.SellOrderTable().Get(s.ctx, s.sellOrderID) require.NoError(s.t, err) require.Equal(s.t, order.Quantity, a) @@ -522,7 +525,7 @@ func (s *buyDirectSuite) createSellOrders(count int) { } err := s.coreStore.ClassTable().Insert(s.ctx, &coreapi.Class{ - Id: s.classId, + Id: s.classID, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) @@ -560,9 +563,9 @@ func (s *buyDirectSuite) createSellOrders(count int) { DisableAutoRetire: s.disableAutoRetire, } - sellOrderId, err := s.marketStore.SellOrderTable().InsertReturningID(s.ctx, order) + sellOrderID, err := s.marketStore.SellOrderTable().InsertReturningID(s.ctx, order) require.NoError(s.t, err) - require.Equal(s.t, sellOrderId, s.sellOrderId) + require.Equal(s.t, sellOrderID, s.sellOrderID) for i := 1; i < count; i++ { order.Id = 0 // reset sell order id @@ -614,7 +617,7 @@ func (s *buyDirectSuite) multipleBuyOrderExpectCalls() { AnyTimes() // not expected on failed attempt } -func (s *buyDirectSuite) calculateAskTotal(quantity string, amount string) sdk.Int { +func (s *buyDirectSuite) calculateAskTotal(quantity string, amount string) sdkmath.Int { q, err := math.NewDecFromString(quantity) require.NoError(s.t, err) diff --git a/x/ecocredit/server/marketplace/msg_cancel_sell_order_test.go b/x/ecocredit/server/marketplace/msg_cancel_sell_order_test.go index cf57c52d44..aae0a9c087 100644 --- a/x/ecocredit/server/marketplace/msg_cancel_sell_order_test.go +++ b/x/ecocredit/server/marketplace/msg_cancel_sell_order_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package marketplace import ( @@ -21,9 +22,9 @@ type cancelSellOrder struct { alice sdk.AccAddress bob sdk.AccAddress creditTypeAbbrev string - classId string + classID string batchDenom string - sellOrderId uint64 + sellOrderID uint64 askPrice *sdk.Coin quantity string res *marketplace.MsgCancelSellOrderResponse @@ -39,8 +40,8 @@ func (s *cancelSellOrder) Before(t gocuke.TestingT) { s.alice = s.addrs[0] s.bob = s.addrs[1] s.creditTypeAbbrev = "C" - s.classId = "C01" - s.batchDenom = "C01-001-20200101-20210101-001" + s.classID = testClassID + s.batchDenom = testBatchDenom s.askPrice = &sdk.Coin{ Denom: "regen", Amount: sdk.NewInt(100), @@ -52,7 +53,7 @@ func (s *cancelSellOrder) AliceCreatedASellOrderWithId(a string) { id, err := strconv.ParseUint(a, 10, 32) require.NoError(s.t, err) - s.sellOrderId = id + s.sellOrderID = id s.sellOrderSetup() } @@ -61,7 +62,7 @@ func (s *cancelSellOrder) AliceCreatedASellOrderWithIdAndQuantity(a string, b st id, err := strconv.ParseUint(a, 10, 32) require.NoError(s.t, err) - s.sellOrderId = id + s.sellOrderID = id s.quantity = b s.sellOrderSetup() @@ -137,7 +138,7 @@ func (s *cancelSellOrder) ExpectNoSellOrderWithId(a string) { func (s *cancelSellOrder) sellOrderSetup() { err := s.coreStore.ClassTable().Insert(s.ctx, &coreapi.Class{ - Id: s.classId, + Id: s.classID, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) @@ -166,7 +167,7 @@ func (s *cancelSellOrder) sellOrderSetup() { }) require.NoError(s.t, err) - sellOrderId, err := s.marketStore.SellOrderTable().InsertReturningID(s.ctx, &api.SellOrder{ + sellOrderID, err := s.marketStore.SellOrderTable().InsertReturningID(s.ctx, &api.SellOrder{ Seller: s.alice, BatchKey: batchKey, Quantity: s.quantity, @@ -174,5 +175,5 @@ func (s *cancelSellOrder) sellOrderSetup() { AskAmount: s.askPrice.Amount.String(), }) require.NoError(s.t, err) - require.Equal(s.t, sellOrderId, s.sellOrderId) + require.Equal(s.t, sellOrderID, s.sellOrderID) } diff --git a/x/ecocredit/server/marketplace/msg_remove_allowed_denom_test.go b/x/ecocredit/server/marketplace/msg_remove_allowed_denom_test.go index a9d0df2bb2..3faf7b9cae 100644 --- a/x/ecocredit/server/marketplace/msg_remove_allowed_denom_test.go +++ b/x/ecocredit/server/marketplace/msg_remove_allowed_denom_test.go @@ -4,10 +4,11 @@ import ( "encoding/json" "testing" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" "github.com/regen-network/gocuke" "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + api "github.com/regen-network/regen-ledger/api/regen/ecocredit/marketplace/v1" "github.com/regen-network/regen-ledger/x/ecocredit/marketplace" ) diff --git a/x/ecocredit/server/marketplace/msg_sell.go b/x/ecocredit/server/marketplace/msg_sell.go index 3df667dc60..8581b35a99 100644 --- a/x/ecocredit/server/marketplace/msg_sell.go +++ b/x/ecocredit/server/marketplace/msg_sell.go @@ -26,7 +26,7 @@ func (k Keeper) Sell(ctx context.Context, req *marketplace.MsgSell) (*marketplac return nil, err } - sellOrderIds := make([]uint64, len(req.Orders)) + sellOrderIDs := make([]uint64, len(req.Orders)) for i, order := range req.Orders { // orderIndex is used for more granular error messages when @@ -45,7 +45,7 @@ func (k Keeper) Sell(ctx context.Context, req *marketplace.MsgSell) (*marketplac return nil, err } - marketId, err := k.getOrCreateMarketId(ctx, creditType.Abbreviation, order.AskPrice.Denom) + marketID, err := k.getOrCreateMarketID(ctx, creditType.Abbreviation, order.AskPrice.Denom) if err != nil { return nil, err } @@ -85,7 +85,7 @@ func (k Keeper) Sell(ctx context.Context, req *marketplace.MsgSell) (*marketplac Seller: sellerAcc, BatchKey: batch.Key, Quantity: order.Quantity, - MarketId: marketId, + MarketId: marketID, AskAmount: order.AskPrice.Amount.String(), DisableAutoRetire: order.DisableAutoRetire, Expiration: expiration, @@ -95,7 +95,7 @@ func (k Keeper) Sell(ctx context.Context, req *marketplace.MsgSell) (*marketplac return nil, err } - sellOrderIds[i] = id + sellOrderIDs[i] = id if err = sdkCtx.EventManager().EmitTypedEvent(&marketplace.EventSell{ SellOrderId: id, @@ -106,11 +106,11 @@ func (k Keeper) Sell(ctx context.Context, req *marketplace.MsgSell) (*marketplac sdkCtx.GasMeter().ConsumeGas(ecocredit.GasCostPerIteration, "ecocredit/core/MsgSell order iteration") } - return &marketplace.MsgSellResponse{SellOrderIds: sellOrderIds}, nil + return &marketplace.MsgSellResponse{SellOrderIds: sellOrderIDs}, nil } -// getOrCreateMarketId attempts to get a market, creating one otherwise, and return the Id. -func (k Keeper) getOrCreateMarketId(ctx context.Context, creditTypeAbbrev, bankDenom string) (uint64, error) { +// getOrCreateMarketID attempts to get a market, creating one otherwise, and return the Id. +func (k Keeper) getOrCreateMarketID(ctx context.Context, creditTypeAbbrev, bankDenom string) (uint64, error) { market, err := k.stateStore.MarketTable().GetByCreditTypeAbbrevBankDenom(ctx, creditTypeAbbrev, bankDenom) switch err { case nil: diff --git a/x/ecocredit/server/marketplace/msg_sell_test.go b/x/ecocredit/server/marketplace/msg_sell_test.go index 1c98724e5f..9d1e874601 100644 --- a/x/ecocredit/server/marketplace/msg_sell_test.go +++ b/x/ecocredit/server/marketplace/msg_sell_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package marketplace import ( @@ -7,7 +8,6 @@ import ( "github.com/gogo/protobuf/jsonpb" "github.com/regen-network/gocuke" - "github.com/regen-network/regen-ledger/types" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" @@ -15,6 +15,7 @@ import ( api "github.com/regen-network/regen-ledger/api/regen/ecocredit/marketplace/v1" coreapi "github.com/regen-network/regen-ledger/api/regen/ecocredit/v1" + "github.com/regen-network/regen-ledger/types" "github.com/regen-network/regen-ledger/x/ecocredit/core" "github.com/regen-network/regen-ledger/x/ecocredit/marketplace" ) @@ -24,7 +25,7 @@ type sellSuite struct { alice sdk.AccAddress aliceTradableAmount string creditTypeAbbrev string - classId string + classID string batchDenom string askPrice *sdk.Coin quantity string @@ -42,8 +43,8 @@ func (s *sellSuite) Before(t gocuke.TestingT) { s.alice = s.addrs[0] s.aliceTradableAmount = "200" s.creditTypeAbbrev = "C" - s.classId = "C01" - s.batchDenom = "C01-001-20200101-20210101-001" + s.classID = testClassID + s.batchDenom = testBatchDenom s.askPrice = &sdk.Coin{ Denom: "regen", Amount: sdk.NewInt(100), @@ -104,11 +105,11 @@ func (s *sellSuite) AnAllowedDenomWithBankDenom(a string) { } func (s *sellSuite) ACreditBatchWithBatchDenom(a string) { - classId := core.GetClassIdFromBatchDenom(a) - creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassId(classId) + classID := core.GetClassIDFromBatchDenom(a) + creditTypeAbbrev := core.GetCreditTypeAbbrevFromClassID(classID) classKey, err := s.coreStore.ClassTable().InsertReturningID(s.ctx, &coreapi.Class{ - Id: classId, + Id: classID, CreditTypeAbbrev: creditTypeAbbrev, }) require.NoError(s.t, err) @@ -126,10 +127,11 @@ func (s *sellSuite) ACreditBatchWithBatchDenom(a string) { } func (s *sellSuite) AMarketWithCreditTypeAndBankDenom(a string, b string) { - s.marketStore.MarketTable().Insert(s.ctx, &api.Market{ + err := s.marketStore.MarketTable().Insert(s.ctx, &api.Market{ CreditTypeAbbrev: a, BankDenom: b, }) + require.NoError(s.t, err) } func (s *sellSuite) AliceHasATradableBatchBalance() { @@ -138,8 +140,8 @@ func (s *sellSuite) AliceHasATradableBatchBalance() { func (s *sellSuite) AliceHasATradableBatchBalanceWithDenom(a string) { s.batchDenom = a - s.classId = core.GetClassIdFromBatchDenom(s.batchDenom) - s.creditTypeAbbrev = core.GetCreditTypeAbbrevFromClassId(s.classId) + s.classID = core.GetClassIDFromBatchDenom(s.batchDenom) + s.creditTypeAbbrev = core.GetCreditTypeAbbrevFromClassID(s.classID) s.aliceTradableBatchBalance() } @@ -152,8 +154,8 @@ func (s *sellSuite) AliceHasATradableBatchBalanceWithAmount(a string) { func (s *sellSuite) AliceHasATradableBatchBalanceWithDenomAndAmount(a string, b string) { s.batchDenom = a - s.classId = core.GetClassIdFromBatchDenom(s.batchDenom) - s.creditTypeAbbrev = core.GetCreditTypeAbbrevFromClassId(s.classId) + s.classID = core.GetClassIDFromBatchDenom(s.batchDenom) + s.creditTypeAbbrev = core.GetCreditTypeAbbrevFromClassID(s.classID) s.aliceTradableAmount = b s.aliceTradableBatchBalance() @@ -406,7 +408,7 @@ func (s *sellSuite) ExpectTheResponse(a gocuke.DocString) { func (s *sellSuite) aliceTradableBatchBalance() { classKey, err := s.coreStore.ClassTable().InsertReturningID(s.ctx, &coreapi.Class{ - Id: s.classId, + Id: s.classID, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) diff --git a/x/ecocredit/server/marketplace/msg_update_sell_orders.go b/x/ecocredit/server/marketplace/msg_update_sell_orders.go index ae44c3481a..43a7a3c43c 100644 --- a/x/ecocredit/server/marketplace/msg_update_sell_orders.go +++ b/x/ecocredit/server/marketplace/msg_update_sell_orders.go @@ -78,11 +78,11 @@ func (k Keeper) applySellOrderUpdates(ctx context.Context, updateIndex string, o if err != nil { return err } - marketId, err := k.getOrCreateMarketId(ctx, creditType.Abbreviation, update.NewAskPrice.Denom) + marketID, err := k.getOrCreateMarketID(ctx, creditType.Abbreviation, update.NewAskPrice.Denom) if err != nil { return err } - order.MarketId = marketId + order.MarketId = marketID } order.AskAmount = update.NewAskPrice.Amount.String() diff --git a/x/ecocredit/server/marketplace/msg_update_sell_orders_test.go b/x/ecocredit/server/marketplace/msg_update_sell_orders_test.go index bf7e4a8829..7513f74d91 100644 --- a/x/ecocredit/server/marketplace/msg_update_sell_orders_test.go +++ b/x/ecocredit/server/marketplace/msg_update_sell_orders_test.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck package marketplace import ( @@ -5,17 +6,18 @@ import ( "testing" "time" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/gogo/protobuf/jsonpb" "github.com/regen-network/gocuke" - "github.com/regen-network/regen-ledger/types" - "github.com/regen-network/regen-ledger/types/math" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/timestamppb" + "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + sdk "github.com/cosmos/cosmos-sdk/types" + api "github.com/regen-network/regen-ledger/api/regen/ecocredit/marketplace/v1" coreapi "github.com/regen-network/regen-ledger/api/regen/ecocredit/v1" + "github.com/regen-network/regen-ledger/types" + "github.com/regen-network/regen-ledger/types/math" "github.com/regen-network/regen-ledger/x/ecocredit/marketplace" ) @@ -26,9 +28,9 @@ type updateSellOrdersSuite struct { aliceTradableAmount string aliceEscrowedAmount string creditTypeAbbrev string - classId string + classID string batchDenom string - sellOrderId uint64 + sellOrderID uint64 askPrice *sdk.Coin quantity string disableAutoRetire bool @@ -47,9 +49,9 @@ func (s *updateSellOrdersSuite) Before(t gocuke.TestingT) { s.bob = s.addrs[1] s.aliceTradableAmount = "200" s.creditTypeAbbrev = "C" - s.classId = "C01" - s.batchDenom = "C01-001-20200101-20210101-001" - s.sellOrderId = 1 + s.classID = testClassID + s.batchDenom = testBatchDenom + s.sellOrderID = 1 s.askPrice = &sdk.Coin{ Denom: "regen", Amount: sdk.NewInt(100), @@ -105,13 +107,6 @@ func (s *updateSellOrdersSuite) AnAllowedDenomWithBankDenom(a string) { require.NoError(s.t, err) } -func (s *updateSellOrdersSuite) AMarketWithCreditTypeAndBankDenom(a string, b string) { - s.marketStore.MarketTable().Insert(s.ctx, &api.Market{ - CreditTypeAbbrev: a, - BankDenom: b, - }) -} - func (s *updateSellOrdersSuite) AliceCreatedASellOrder() { s.sellOrderSetup(1) } @@ -120,7 +115,7 @@ func (s *updateSellOrdersSuite) AliceCreatedASellOrderWithId(a string) { id, err := strconv.ParseUint(a, 10, 32) require.NoError(s.t, err) - s.sellOrderId = id + s.sellOrderID = id s.sellOrderSetup(1) } @@ -196,7 +191,7 @@ func (s *updateSellOrdersSuite) AliceAttemptsToUpdateTheSellOrder() { Seller: s.alice.String(), Updates: []*marketplace.MsgUpdateSellOrders_Update{ { - SellOrderId: s.sellOrderId, + SellOrderId: s.sellOrderID, NewQuantity: s.quantity, NewAskPrice: s.askPrice, }, @@ -209,7 +204,7 @@ func (s *updateSellOrdersSuite) BobAttemptsToUpdateTheSellOrder() { Seller: s.bob.String(), Updates: []*marketplace.MsgUpdateSellOrders_Update{ { - SellOrderId: s.sellOrderId, + SellOrderId: s.sellOrderID, NewQuantity: s.quantity, NewAskPrice: s.askPrice, }, @@ -238,7 +233,7 @@ func (s *updateSellOrdersSuite) AliceAttemptsToUpdateTheSellOrderWithQuantity(a Seller: s.alice.String(), Updates: []*marketplace.MsgUpdateSellOrders_Update{ { - SellOrderId: s.sellOrderId, + SellOrderId: s.sellOrderID, NewQuantity: a, NewAskPrice: s.askPrice, }, @@ -269,7 +264,7 @@ func (s *updateSellOrdersSuite) AliceAttemptsToUpdateTheSellOrderWithAskDenom(a Seller: s.alice.String(), Updates: []*marketplace.MsgUpdateSellOrders_Update{ { - SellOrderId: s.sellOrderId, + SellOrderId: s.sellOrderID, NewQuantity: s.quantity, NewAskPrice: &sdk.Coin{ Denom: a, @@ -288,7 +283,7 @@ func (s *updateSellOrdersSuite) AliceAttemptsToUpdateTheSellOrderWithExpiration( Seller: s.alice.String(), Updates: []*marketplace.MsgUpdateSellOrders_Update{ { - SellOrderId: s.sellOrderId, + SellOrderId: s.sellOrderID, NewQuantity: s.quantity, NewAskPrice: s.askPrice, NewExpiration: &expiration, @@ -306,7 +301,7 @@ func (s *updateSellOrdersSuite) AliceAttemptsToUpdateTheSellOrderWithTheProperti Seller: s.alice.String(), Updates: []*marketplace.MsgUpdateSellOrders_Update{ { - SellOrderId: s.sellOrderId, + SellOrderId: s.sellOrderID, NewQuantity: update.NewQuantity, NewAskPrice: update.NewAskPrice, DisableAutoRetire: update.DisableAutoRetire, @@ -424,7 +419,7 @@ func (s *updateSellOrdersSuite) sellOrderSetup(count int) { } err := s.coreStore.ClassTable().Insert(s.ctx, &coreapi.Class{ - Id: s.classId, + Id: s.classID, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) @@ -466,9 +461,9 @@ func (s *updateSellOrdersSuite) sellOrderSetup(count int) { order.Expiration = timestamppb.New(*s.expiration) } - sellOrderId, err := s.marketStore.SellOrderTable().InsertReturningID(s.ctx, order) + sellOrderID, err := s.marketStore.SellOrderTable().InsertReturningID(s.ctx, order) require.NoError(s.t, err) - require.Equal(s.t, sellOrderId, s.sellOrderId) + require.Equal(s.t, sellOrderID, s.sellOrderID) for i := 1; i < count; i++ { order.Id = 0 // reset sell order id @@ -481,7 +476,7 @@ func (s *updateSellOrdersSuite) aliceBatchBalance() { batch, err := s.coreStore.BatchTable().GetByDenom(s.ctx, s.batchDenom) if err == ormerrors.NotFound { classKey, err := s.coreStore.ClassTable().InsertReturningID(s.ctx, &coreapi.Class{ - Id: s.classId, + Id: s.classID, CreditTypeAbbrev: s.creditTypeAbbrev, }) require.NoError(s.t, err) diff --git a/x/ecocredit/server/marketplace/query_allowed_denoms_test.go b/x/ecocredit/server/marketplace/query_allowed_denoms_test.go index 3abec7a9b2..3ef255e4a5 100644 --- a/x/ecocredit/server/marketplace/query_allowed_denoms_test.go +++ b/x/ecocredit/server/marketplace/query_allowed_denoms_test.go @@ -3,9 +3,10 @@ package marketplace import ( "testing" - "github.com/cosmos/cosmos-sdk/types/query" "gotest.tools/v3/assert" + "github.com/cosmos/cosmos-sdk/types/query" + api "github.com/regen-network/regen-ledger/api/regen/ecocredit/marketplace/v1" "github.com/regen-network/regen-ledger/types/ormutil" "github.com/regen-network/regen-ledger/x/ecocredit/marketplace" diff --git a/x/ecocredit/server/marketplace/query_sell_orders_by_batch_test.go b/x/ecocredit/server/marketplace/query_sell_orders_by_batch_test.go index d0c8e6c096..5ccd6f1287 100644 --- a/x/ecocredit/server/marketplace/query_sell_orders_by_batch_test.go +++ b/x/ecocredit/server/marketplace/query_sell_orders_by_batch_test.go @@ -15,7 +15,7 @@ import ( func TestSellOrdersByBatch(t *testing.T) { t.Parallel() s := setupBase(t, 2) - s.testSellSetup(batchDenom, ask.Denom, ask.Denom[1:], classId, start, end, creditType) + s.testSellSetup(batchDenom, ask.Denom, ask.Denom[1:], classID, start, end, creditType) // make another batch otherDenom := "C01-19990101-20290101-001" @@ -37,7 +37,7 @@ func TestSellOrdersByBatch(t *testing.T) { }) assert.NilError(t, err) assert.Equal(t, 1, len(res.SellOrders)) - assertOrderEqual(t, s.ctx, s.k, res.SellOrders[0], order1) + assertOrderEqual(s.ctx, t, s.k, res.SellOrders[0], order1) assert.Equal(t, uint64(1), res.Pagination.Total) // query the second denom @@ -47,7 +47,7 @@ func TestSellOrdersByBatch(t *testing.T) { }) assert.NilError(t, err) assert.Equal(t, 1, len(res.SellOrders)) - assertOrderEqual(t, s.ctx, s.k, res.SellOrders[0], order2) + assertOrderEqual(s.ctx, t, s.k, res.SellOrders[0], order2) assert.Equal(t, uint64(1), res.Pagination.Total) // bad denom should error diff --git a/x/ecocredit/server/marketplace/query_sell_orders_by_seller_test.go b/x/ecocredit/server/marketplace/query_sell_orders_by_seller_test.go index e48f7228f3..21321782c2 100644 --- a/x/ecocredit/server/marketplace/query_sell_orders_by_seller_test.go +++ b/x/ecocredit/server/marketplace/query_sell_orders_by_seller_test.go @@ -13,7 +13,7 @@ import ( func TestSellOrdersBySeller(t *testing.T) { t.Parallel() s := setupBase(t, 3) - s.testSellSetup(batchDenom, ask.Denom, ask.Denom[1:], classId, start, end, creditType) + s.testSellSetup(batchDenom, ask.Denom, ask.Denom[1:], classID, start, end, creditType) otherAddr := s.addrs[1] noOrdersAddr := s.addrs[2] @@ -27,7 +27,7 @@ func TestSellOrdersBySeller(t *testing.T) { }) assert.NilError(t, err) assert.Equal(t, 1, len(res.SellOrders)) - assertOrderEqual(t, s.ctx, s.k, res.SellOrders[0], order1) + assertOrderEqual(s.ctx, t, s.k, res.SellOrders[0], order1) assert.Equal(t, uint64(1), res.Pagination.Total) res, err = s.k.SellOrdersBySeller(s.ctx, &marketplace.QuerySellOrdersBySellerRequest{ @@ -36,7 +36,7 @@ func TestSellOrdersBySeller(t *testing.T) { }) assert.NilError(t, err) assert.Equal(t, 1, len(res.SellOrders)) - assertOrderEqual(t, s.ctx, s.k, res.SellOrders[0], order2) + assertOrderEqual(s.ctx, t, s.k, res.SellOrders[0], order2) assert.Equal(t, uint64(1), res.Pagination.Total) // addr with no sell orders should just return empty slice diff --git a/x/ecocredit/server/marketplace/query_sell_orders_test.go b/x/ecocredit/server/marketplace/query_sell_orders_test.go index 33a91467c9..b0c1f062ff 100644 --- a/x/ecocredit/server/marketplace/query_sell_orders_test.go +++ b/x/ecocredit/server/marketplace/query_sell_orders_test.go @@ -17,7 +17,7 @@ import ( ) var ( - classId = "C01" + classID = "C01" batchDenom = "C01-001-20200101-20200201-001" start, end = timestamppb.Now(), timestamppb.Now() validAskDenom = sdk.DefaultBondDenom @@ -28,7 +28,7 @@ var ( func TestSellOrders(t *testing.T) { t.Parallel() s := setupBase(t, 2) - s.testSellSetup(batchDenom, ask.Denom, ask.Denom[1:], classId, start, end, creditType) + s.testSellSetup(batchDenom, ask.Denom, ask.Denom[1:], classID, start, end, creditType) order1 := insertSellOrder(t, s, s.addrs[0], 1) order2 := insertSellOrder(t, s, s.addrs[1], 1) @@ -39,9 +39,9 @@ func TestSellOrders(t *testing.T) { assert.NilError(t, err) assert.Equal(t, 1, len(res.SellOrders)) if res.SellOrders[0].Id == order1.Id { - assertOrderEqual(t, s.ctx, s.k, res.SellOrders[0], order1) + assertOrderEqual(s.ctx, t, s.k, res.SellOrders[0], order1) } else { - assertOrderEqual(t, s.ctx, s.k, res.SellOrders[0], order2) + assertOrderEqual(s.ctx, t, s.k, res.SellOrders[0], order2) } assert.Equal(t, uint64(2), res.Pagination.Total) } @@ -62,7 +62,7 @@ func insertSellOrder(t *testing.T, s *baseSuite, addr sdk.AccAddress, batchKey u return sellOrder } -func assertOrderEqual(t *testing.T, ctx context.Context, k Keeper, received *marketplace.SellOrderInfo, order *api.SellOrder) { +func assertOrderEqual(ctx context.Context, t *testing.T, k Keeper, received *marketplace.SellOrderInfo, order *api.SellOrder) { seller := sdk.AccAddress(order.Seller) batch, err := k.coreStore.BatchTable().Get(ctx, order.BatchKey) diff --git a/x/ecocredit/server/marketplace/utils.go b/x/ecocredit/server/marketplace/utils.go index 21e2e34e6f..f6fa841b1b 100644 --- a/x/ecocredit/server/marketplace/utils.go +++ b/x/ecocredit/server/marketplace/utils.go @@ -3,6 +3,8 @@ package marketplace import ( "context" + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -157,14 +159,14 @@ func (k Keeper) fillOrder(ctx context.Context, orderIndex string, sellOrder *api // getTotalCost calculates the cost of the order by multiplying the price per credit, and the amount of credits // desired in the order. -func getTotalCost(pricePerCredit sdk.Int, amtCredits math.Dec) (sdk.Int, error) { +func getTotalCost(pricePerCredit sdkmath.Int, amtCredits math.Dec) (sdkmath.Int, error) { unitPrice, err := math.NewPositiveFixedDecFromString(pricePerCredit.String(), amtCredits.NumDecimalPlaces()) if err != nil { - return sdk.Int{}, err + return sdkmath.Int{}, err } cost, err := amtCredits.Mul(unitPrice) if err != nil { - return sdk.Int{}, err + return sdkmath.Int{}, err } return cost.SdkIntTrim(), nil } diff --git a/x/ecocredit/server/server_test.go b/x/ecocredit/server/server_test.go index 7a8ac7a20b..4f3dfc857f 100644 --- a/x/ecocredit/server/server_test.go +++ b/x/ecocredit/server/server_test.go @@ -3,6 +3,8 @@ package server_test import ( "testing" + "github.com/stretchr/testify/suite" + "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -15,7 +17,6 @@ import ( minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" params "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - "github.com/stretchr/testify/suite" "github.com/regen-network/regen-ledger/types/module" "github.com/regen-network/regen-ledger/types/module/server" diff --git a/x/ecocredit/server/tests/bridge_test.go b/x/ecocredit/server/tests/bridge_test.go index 884e9fc6d8..7cdece507f 100644 --- a/x/ecocredit/server/tests/bridge_test.go +++ b/x/ecocredit/server/tests/bridge_test.go @@ -13,7 +13,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" - "github.com/regen-network/regen-ledger/api/regen/ecocredit/v1" + ecocreditv1 "github.com/regen-network/regen-ledger/api/regen/ecocredit/v1" "github.com/regen-network/regen-ledger/types" "github.com/regen-network/regen-ledger/types/module" "github.com/regen-network/regen-ledger/types/module/server" diff --git a/x/ecocredit/server/testsuite/genesis.go b/x/ecocredit/server/testsuite/genesis.go index 574547ec05..1c3cb4b9d1 100644 --- a/x/ecocredit/server/testsuite/genesis.go +++ b/x/ecocredit/server/testsuite/genesis.go @@ -4,11 +4,12 @@ import ( "encoding/json" "time" + "github.com/stretchr/testify/suite" + "google.golang.org/protobuf/proto" + sdk "github.com/cosmos/cosmos-sdk/types" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/stretchr/testify/suite" - "google.golang.org/protobuf/proto" api "github.com/regen-network/regen-ledger/api/regen/ecocredit/v1" "github.com/regen-network/regen-ledger/types" diff --git a/x/ecocredit/server/testsuite/suite.go b/x/ecocredit/server/testsuite/suite.go index 1577567610..7a0d6d45eb 100644 --- a/x/ecocredit/server/testsuite/suite.go +++ b/x/ecocredit/server/testsuite/suite.go @@ -188,7 +188,7 @@ func (s *IntegrationTestSuite) TestBasketScenario() { // create a class and issue a batch userTotalCreditBalance, err := math.NewDecFromString("1000000000000000") require.NoError(err) - classId, batchDenom := s.createClassAndIssueBatch(user, user, "C", userTotalCreditBalance.String(), "2020-01-01", "2022-01-01") + classID, batchDenom := s.createClassAndIssueBatch(user, user, "C", userTotalCreditBalance.String(), "2020-01-01", "2022-01-01") // fund account to create a basket balanceBefore := sdk.NewInt64Coin(s.basketFee.Denom, 30000) @@ -201,7 +201,7 @@ func (s *IntegrationTestSuite) TestBasketScenario() { Exponent: 6, DisableAutoRetire: true, CreditTypeAbbrev: "C", - AllowedClasses: []string{classId}, + AllowedClasses: []string{classID}, DateCriteria: nil, Fee: sdk.NewCoins(s.basketFee), }) @@ -303,7 +303,7 @@ func (s *IntegrationTestSuite) TestBasketScenario() { Exponent: 6, DisableAutoRetire: false, CreditTypeAbbrev: "C", - AllowedClasses: []string{classId}, + AllowedClasses: []string{classID}, DateCriteria: nil, Fee: sdk.NewCoins(s.basketFee), }) @@ -357,14 +357,14 @@ func (s *IntegrationTestSuite) createClassAndIssueBatch(admin, recipient sdk.Acc Fee: &createClassFee, }) require.NoError(err) - classId := cRes.ClassId + classID := cRes.ClassId start, err := types.ParseDate("start date", startStr) require.NoError(err) end, err := types.ParseDate("end date", endStr) require.NoError(err) pRes, err := s.msgClient.CreateProject(s.ctx, &core.MsgCreateProject{ Admin: admin.String(), - ClassId: classId, + ClassId: classID, Metadata: "", Jurisdiction: "US-NY", }) @@ -379,7 +379,7 @@ func (s *IntegrationTestSuite) createClassAndIssueBatch(admin, recipient sdk.Acc }) require.NoError(err) batchDenom := bRes.BatchDenom - return classId, batchDenom + return classID, batchDenom } func (s *IntegrationTestSuite) TestScenario() { @@ -417,7 +417,7 @@ func (s *IntegrationTestSuite) TestScenario() { Fee: &createClassFee, }) s.Require().NoError(err) - classId := createClsRes.ClassId + classID := createClsRes.ClassId adminBalanceAfter := s.bankKeeper.GetBalance(s.sdkCtx, admin, sdk.DefaultBondDenom) expectedBalance := adminBalanceAfter.Add(createClassFee) @@ -425,7 +425,7 @@ func (s *IntegrationTestSuite) TestScenario() { // create project createProjectRes, err := s.msgClient.CreateProject(s.ctx, &core.MsgCreateProject{ - ClassId: classId, + ClassId: classID, Admin: issuer1, Metadata: "metadata", Jurisdiction: "AQ", @@ -433,7 +433,7 @@ func (s *IntegrationTestSuite) TestScenario() { s.Require().NoError(err) s.Require().NotNil(createProjectRes) s.Require().Equal("C02-001", createProjectRes.ProjectId) - projectId := createProjectRes.ProjectId + projectID := createProjectRes.ProjectId // create batch t0, t1, t2 := "10.37", "1007.3869", "100" @@ -447,7 +447,7 @@ func (s *IntegrationTestSuite) TestScenario() { // Batch creation should succeed with StartDate before EndDate, and valid data createBatchRes, err := s.msgClient.CreateBatch(s.ctx, &core.MsgCreateBatch{ Issuer: issuer1, - ProjectId: projectId, + ProjectId: projectID, StartDate: &time1, EndDate: &time2, Issuance: []*core.BatchIssuance{ @@ -1044,8 +1044,8 @@ func (s *IntegrationTestSuite) TestScenario() { }) s.Require().Nil(err) s.Require().Equal(expectedSellOrderIds, createSellOrder.SellOrderIds) - orderId1 := createSellOrder.SellOrderIds[0] - orderId2 := createSellOrder.SellOrderIds[1] + orderID1 := createSellOrder.SellOrderIds[0] + orderID2 := createSellOrder.SellOrderIds[1] // now we buy these orders buyerAcc := acc5 @@ -1060,14 +1060,14 @@ func (s *IntegrationTestSuite) TestScenario() { Buyer: buyerAcc.String(), Orders: []*marketplace.MsgBuyDirect_Order{ { - SellOrderId: orderId1, + SellOrderId: orderID1, Quantity: order1Qty, BidPrice: &coinPrice, DisableAutoRetire: false, RetirementJurisdiction: "US-OR", }, { - SellOrderId: orderId2, + SellOrderId: orderID2, Quantity: order2Qty, BidPrice: &coinPrice, DisableAutoRetire: true, diff --git a/x/ecocredit/server/utils/test_utils.go b/x/ecocredit/server/utils/test_utils.go index cbdbbaab97..2dc0eca76e 100644 --- a/x/ecocredit/server/utils/test_utils.go +++ b/x/ecocredit/server/utils/test_utils.go @@ -1,9 +1,10 @@ package utils import ( - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/golang/mock/gomock" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/regen-network/regen-ledger/x/ecocredit/mocks" ) diff --git a/x/ecocredit/server/utils/utils.go b/x/ecocredit/server/utils/utils.go index 083f170aa5..e97a31fa1f 100644 --- a/x/ecocredit/server/utils/utils.go +++ b/x/ecocredit/server/utils/utils.go @@ -12,12 +12,12 @@ import ( "github.com/regen-network/regen-ledger/x/ecocredit/core" ) -// GetCreditTypeFromBatchDenom extracts the classId from a batch denom string, then retrieves it from the params. +// GetCreditTypeFromBatchDenom extracts the classID from a batch denom string, then retrieves it from the params. func GetCreditTypeFromBatchDenom(ctx context.Context, store api.StateStore, denom string) (*api.CreditType, error) { - classId := core.GetClassIdFromBatchDenom(denom) - classInfo, err := store.ClassTable().GetById(ctx, classId) + classID := core.GetClassIDFromBatchDenom(denom) + classInfo, err := store.ClassTable().GetById(ctx, classID) if err != nil { - return nil, sdkerrors.ErrInvalidRequest.Wrapf("could not get class with ID %s: %s", classId, err.Error()) + return nil, sdkerrors.ErrInvalidRequest.Wrapf("could not get class with ID %s: %s", classID, err.Error()) } return store.CreditTypeTable().Get(ctx, classInfo.CreditTypeAbbrev) } diff --git a/x/ecocredit/server/utils/utils_test.go b/x/ecocredit/server/utils/utils_test.go index a06e398328..6b1c57842f 100644 --- a/x/ecocredit/server/utils/utils_test.go +++ b/x/ecocredit/server/utils/utils_test.go @@ -7,9 +7,10 @@ import ( "github.com/google/go-cmp/cmp/cmpopts" "gotest.tools/v3/assert" + dbm "github.com/tendermint/tm-db" + "github.com/tendermint/tendermint/libs/log" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/orm/model/ormdb" "github.com/cosmos/cosmos-sdk/orm/model/ormtable" @@ -113,6 +114,6 @@ func TestUtils_GetCreditTypeFromBatchDenom(t *testing.T) { assert.DeepEqual(t, ct, creditType, cmpopts.IgnoreUnexported(api.CreditType{})) invalidDenom := "C02-0000000-0000000-001" - ct, err = GetCreditTypeFromBatchDenom(s.ctx, s.stateStore, invalidDenom) + _, err = GetCreditTypeFromBatchDenom(s.ctx, s.stateStore, invalidDenom) assert.ErrorContains(t, err, "could not get class with ID C02") } diff --git a/x/ecocredit/simulation/basket/operations.go b/x/ecocredit/simulation/basket/operations.go index cca9a6ba7d..b1ff3644cd 100644 --- a/x/ecocredit/simulation/basket/operations.go +++ b/x/ecocredit/simulation/basket/operations.go @@ -26,9 +26,9 @@ import ( // Simulation operation weights constants const ( - OpWeightMsgCreate = "op_weight_msg_create_basket" - OpWeightMsgPut = "op_weight_msg_put_into_basket" - OpWeightMsgTake = "op_weight_take_from_basket" + OpWeightMsgCreate = "op_weight_msg_create_basket" //nolint:gosec + OpWeightMsgPut = "op_weight_msg_put_into_basket" //nolint:gosec + OpWeightMsgTake = "op_weight_take_from_basket" //nolint:gosec ) // basket operations weights @@ -110,7 +110,7 @@ func SimulateMsgCreate(ak ecocredit.AccountKeeper, bk ecocredit.BankKeeper, return simtypes.NoOpMsg(ecocredit.ModuleName, TypeMsgCreate, "not enough balance"), nil, nil } - creditType, err := randomCreditType(r, ctx, qryClient) + creditType, err := randomCreditType(ctx, r, qryClient) if err != nil { return simtypes.NoOpMsg(ecocredit.ModuleName, TypeMsgCreate, err.Error()), nil, err } @@ -119,8 +119,8 @@ func SimulateMsgCreate(ak ecocredit.AccountKeeper, bk ecocredit.BankKeeper, return simtypes.NoOpMsg(ecocredit.ModuleName, TypeMsgCreate, "credit type not found"), nil, nil } - classIds, op, err := randomClassIds(r, sdkCtx, qryClient, creditType.Abbreviation, TypeMsgPut) - if len(classIds) == 0 { + classIDs, op, err := randomClassIds(r, sdkCtx, qryClient, creditType.Abbreviation, TypeMsgPut) + if len(classIDs) == 0 { return op, nil, err } @@ -133,7 +133,7 @@ func SimulateMsgCreate(ak ecocredit.AccountKeeper, bk ecocredit.BankKeeper, DisableAutoRetire: r.Float32() < 0.5, Curator: curator.Address.String(), Exponent: utils.RandomExponent(r, precision), - AllowedClasses: classIds, + AllowedClasses: classIDs, CreditTypeAbbrev: creditType.Abbreviation, DateCriteria: dateCriteria, } @@ -188,10 +188,9 @@ func randomDateCriteria(r *rand.Rand, ctx sdk.Context) *basket.DateCriteria { Seconds: seconds, }, } - } else { - return &basket.DateCriteria{ - StartDateWindow: &gogotypes.Duration{Seconds: int64(seconds)}, - } + } + return &basket.DateCriteria{ + StartDateWindow: &gogotypes.Duration{Seconds: seconds}, } } return nil @@ -251,11 +250,9 @@ func SimulateMsgPut(ak ecocredit.AccountKeeper, bk ecocredit.BankKeeper, classInfoList = append(classInfoList, *class) max++ } - } else { - if utils.Contains(issuers, ownerAddr) { - classInfoList = append(classInfoList, *class) - max++ - } + } else if utils.Contains(issuers, ownerAddr) { + classInfoList = append(classInfoList, *class) + max++ } if max == 2 { @@ -422,14 +419,13 @@ func SimulateMsgTake(ak ecocredit.AccountKeeper, bk ecocredit.BankKeeper, return simtypes.NoOpMsg(ecocredit.ModuleName, TypeMsgTake, err.Error()), nil, nil } - if iAmount == 0 { + switch { + case iAmount == 0: continue - } else if iAmount == 1 { + case iAmount == 1: amt = iAmount - break - } else { + default: amt = simtypes.RandIntBetween(r, 1, iAmount) - break } } if amt == 0 { @@ -476,15 +472,15 @@ func randomClassIds(r *rand.Rand, ctx sdk.Context, qryClient core.QueryClient, } max := simtypes.RandIntBetween(r, 1, min(5, len(classes))) - var classIds []string + var classIDs []string for i := 0; i < max; i++ { class := classes[i] if class.CreditTypeAbbrev == creditTypeAbbrev { - classIds = append(classIds, class.Id) + classIDs = append(classIDs, class.Id) } } - return classIds, simtypes.NoOpMsg(ecocredit.ModuleName, msgType, ""), nil + return classIDs, simtypes.NoOpMsg(ecocredit.ModuleName, msgType, ""), nil } func min(x, y int) int { @@ -494,7 +490,7 @@ func min(x, y int) int { return x } -func randomCreditType(r *rand.Rand, ctx context.Context, qryClient core.QueryClient) (*core.CreditType, error) { +func randomCreditType(ctx context.Context, r *rand.Rand, qryClient core.QueryClient) (*core.CreditType, error) { res, err := qryClient.CreditTypes(ctx, &core.QueryCreditTypesRequest{}) if err != nil { return nil, err diff --git a/x/ecocredit/simulation/genesis.go b/x/ecocredit/simulation/genesis.go index b6db331207..26a52b3bc7 100644 --- a/x/ecocredit/simulation/genesis.go +++ b/x/ecocredit/simulation/genesis.go @@ -9,6 +9,8 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" + dbm "github.com/tendermint/tm-db" + "github.com/cosmos/cosmos-sdk/orm/model/ormdb" "github.com/cosmos/cosmos-sdk/orm/model/ormtable" "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" @@ -16,7 +18,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - dbm "github.com/tendermint/tm-db" marketplaceapi "github.com/regen-network/regen-ledger/api/regen/ecocredit/marketplace/v1" api "github.com/regen-network/regen-ledger/api/regen/ecocredit/v1" @@ -78,7 +79,7 @@ func genAllowListEnabled(r *rand.Rand) bool { return r.Int63n(101) <= 90 } -func genCreditTypes(r *rand.Rand) []*core.CreditType { +func genCreditTypes() []*core.CreditType { return []*core.CreditType{ { Name: "carbon", @@ -130,7 +131,7 @@ func RandomizedGenState(simState *module.SimulationState) { simState.AppParams.GetOrGenerate( simState.Cdc, typeCreditTypes, &creditTypes, simState.Rand, - func(r *rand.Rand) { creditTypes = genCreditTypes(r) }, + func(r *rand.Rand) { creditTypes = genCreditTypes() }, ) simState.AppParams.GetOrGenerate( @@ -190,12 +191,12 @@ func RandomizedGenState(simState *module.SimulationState) { panic(err) } - rawJson, err := jsonTarget.JSON() + rawJSON, err := jsonTarget.JSON() if err != nil { panic(err) } - bz, err := json.Marshal(rawJson) + bz, err := json.Marshal(rawJSON) if err != nil { panic(err) } @@ -222,13 +223,13 @@ func createClass(ctx context.Context, sStore api.StateStore, class *api.Class) ( } return 0, err - } else { - if err := sStore.ClassSequenceTable().Update(ctx, &api.ClassSequence{ - CreditTypeAbbrev: class.CreditTypeAbbrev, - NextSequence: seq.NextSequence + 1, - }); err != nil { - return 0, err - } + } + + if err := sStore.ClassSequenceTable().Update(ctx, &api.ClassSequence{ + CreditTypeAbbrev: class.CreditTypeAbbrev, + NextSequence: seq.NextSequence + 1, + }); err != nil { + return 0, err } return cKey, nil diff --git a/x/ecocredit/simulation/marketplace/operations.go b/x/ecocredit/simulation/marketplace/operations.go index 66cd773723..832eeccae6 100644 --- a/x/ecocredit/simulation/marketplace/operations.go +++ b/x/ecocredit/simulation/marketplace/operations.go @@ -21,10 +21,10 @@ import ( // Simulation operation weights constants const ( - OpWeightMsgBuy = "op_weight_msg_buy_direct" - OpWeightMsgSell = "op_weight_msg_sell" - OpWeightMsgUpdateSellOrder = "op_weight_msg_update_sell_order" - OpWeightMsgCancelSellOrder = "op_weight_msg_cancel_sell_order" + OpWeightMsgBuy = "op_weight_msg_buy_direct" //nolint:gosec + OpWeightMsgSell = "op_weight_msg_sell" //nolint:gosec + OpWeightMsgUpdateSellOrder = "op_weight_msg_update_sell_order" //nolint:gosec + OpWeightMsgCancelSellOrder = "op_weight_msg_cancel_sell_order" //nolint:gosec ) // basket operations weights @@ -224,7 +224,7 @@ func SimulateMsgSell(ak ecocredit.AccountKeeper, bk ecocredit.BankKeeper, quantity := int(balInt) if balInt > 1 { - quantity = simtypes.RandIntBetween(r, 1, int(quantity)) + quantity = simtypes.RandIntBetween(r, 1, quantity) } askPrice := sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(simtypes.RandIntBetween(r, 1, 50))) @@ -310,9 +310,8 @@ func SimulateMsgUpdateSellOrder(ak ecocredit.AccountKeeper, bk ecocredit.BankKee // 30% chance of new quantity set to 0 if r.Int63n(101) <= 30 { return "0" - } else { - return fmt.Sprintf("%d", newQuantity) } + return fmt.Sprintf("%d", newQuantity) }(), NewAskPrice: &askPrice, DisableAutoRetire: r.Int63n(101) <= 30, // 30% chance of disable auto-retire diff --git a/x/ecocredit/simulation/operations.go b/x/ecocredit/simulation/operations.go index 4d011aa657..4a83ea757b 100644 --- a/x/ecocredit/simulation/operations.go +++ b/x/ecocredit/simulation/operations.go @@ -28,20 +28,20 @@ import ( // Simulation operation weights constants const ( - OpWeightMsgCreateClass = "op_weight_msg_create_class" - OpWeightMsgCreateBatch = "op_weight_msg_create_batch" - OpWeightMsgSend = "op_weight_msg_send" - OpWeightMsgRetire = "op_weight_msg_retire" - OpWeightMsgCancel = "op_weight_msg_cancel" - OpWeightMsgUpdateClassAdmin = "op_weight_msg_update_class_admin" - OpWeightMsgUpdateClassMetadata = "op_weight_msg_update_class_metadata" - OpWeightMsgUpdateClassIssuers = "op_weight_msg_update_class_issuers" - OpWeightMsgCreateProject = "op_weight_msg_create_project" - OpWeightMsgUpdateProjectAdmin = "op_weight_msg_update_project_admin" - OpWeightMsgUpdateProjectMetadata = "op_weight_msg_update_project_metadata" - OpWeightMsgMintBatchCredits = "op_weight_msg_mint_batch_credits" - OpWeightMsgSealBatch = "op_weight_msg_seal_batch" - OpWeightMsgBridge = "op_weight_msg_bridge" + OpWeightMsgCreateClass = "op_weight_msg_create_class" //nolint:gosec + OpWeightMsgCreateBatch = "op_weight_msg_create_batch" //nolint:gosec + OpWeightMsgSend = "op_weight_msg_send" //nolint:gosec + OpWeightMsgRetire = "op_weight_msg_retire" //nolint:gosec + OpWeightMsgCancel = "op_weight_msg_cancel" //nolint:gosec + OpWeightMsgUpdateClassAdmin = "op_weight_msg_update_class_admin" //nolint:gosec + OpWeightMsgUpdateClassMetadata = "op_weight_msg_update_class_metadata" //nolint:gosec + OpWeightMsgUpdateClassIssuers = "op_weight_msg_update_class_issuers" //nolint:gosec + OpWeightMsgCreateProject = "op_weight_msg_create_project" //nolint:gosec + OpWeightMsgUpdateProjectAdmin = "op_weight_msg_update_project_admin" //nolint:gosec + OpWeightMsgUpdateProjectMetadata = "op_weight_msg_update_project_metadata" //nolint:gosec + OpWeightMsgMintBatchCredits = "op_weight_msg_mint_batch_credits" //nolint:gosec + OpWeightMsgSealBatch = "op_weight_msg_seal_batch" //nolint:gosec + OpWeightMsgBridge = "op_weight_msg_bridge" //nolint:gosec ) // ecocredit operations weights @@ -419,7 +419,7 @@ func SimulateMsgCreateProject(ak ecocredit.AccountKeeper, bk ecocredit.BankKeepe return op, nil, err } - issuers, op, err := getClassIssuers(sdkCtx, r, qryClient, class.Id, TypeMsgCreateProject) + issuers, op, err := getClassIssuers(sdkCtx, qryClient, class.Id, TypeMsgCreateProject) if len(issuers) == 0 { return op, nil, err } @@ -1213,7 +1213,7 @@ func SimulateMsgBridge(ak ecocredit.AccountKeeper, bk ecocredit.BankKeeper, qryC } } -func getClassIssuers(ctx sdk.Context, r *rand.Rand, qryClient core.QueryClient, className string, msgType string) ([]string, simtypes.OperationMsg, error) { +func getClassIssuers(ctx sdk.Context, qryClient core.QueryClient, className string, msgType string) ([]string, simtypes.OperationMsg, error) { classIssuers, err := qryClient.ClassIssuers(sdk.WrapSDKContext(ctx), &core.QueryClassIssuersRequest{ClassId: className}) if err != nil { if ormerrors.IsNotFound(err) {