diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 00000000..94a342a1 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,46 @@ +name: Lint +on: + push: + branches: + - main + - release/** + pull_request: + merge_group: +permissions: + contents: read +jobs: + golangci: + name: golangci-lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v5 + with: + go-version: "1.22.2" + check-latest: true + - uses: technote-space/get-diff-action@v6.1.2 + id: git_diff + with: + PATTERNS: | + Makefile + **/Makefile + .golangci.yml + - name: run linting (long) + if: env.GIT_DIFF + id: lint_long + run: make lint + env: + NIX: 1 + - uses: technote-space/get-diff-action@v6.1.2 + if: steps.lint_long.outcome == 'skipped' + with: + PATTERNS: | + **/*.go + *.go + - name: run linting (short) + if: steps.lint_long.outcome == 'skipped' && env.GIT_DIFF + run: make lint + env: + GIT_DIFF: ${{ env.GIT_DIFF }} + LINT_DIFF: 1 + NIX: 1 \ No newline at end of file diff --git a/.github/workflows/sims.yaml b/.github/workflows/sims.yaml deleted file mode 100644 index 1c729db1..00000000 --- a/.github/workflows/sims.yaml +++ /dev/null @@ -1,37 +0,0 @@ -# name: Simulation Test -# on: [pull_request] - -# jobs: -# test-sim-nondeterminism-fast: -# name: Test AppStateDeterminism -# runs-on: ubuntu-latest -# steps: -# - name: Checkout source code -# uses: actions/checkout@v3 -# - name: Setup go -# uses: actions/setup-go@v3 -# with: -# go-version: '^1.19' # The Go version to download (if necessary) and use. -# - run: make test-sim-nondeterminism-fast - # test-sim-import-export: - # name: Test AppImportExport - # runs-on: ubuntu-latest - # steps: - # - name: Checkout source code - # uses: actions/checkout@v3 - # - name: Setup go - # uses: actions/setup-go@v3 - # with: - # go-version: '^1.19' # The Go version to download (if necessary) and use. - # - run: make test-sim-import-export - # test-sim-after-import: - # name: Test AppSimulationAfterImport - # runs-on: ubuntu-latest - # steps: - # - name: Checkout source code - # uses: actions/checkout@v3 - # - name: Setup go - # uses: actions/setup-go@v3 - # with: - # go-version: '^1.19' # The Go version to download (if necessary) and use. - # - run: make test-sim-after-import \ No newline at end of file diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 6d5c8907..994ec174 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -4,6 +4,8 @@ on: paths: - '**/*.go' - '**/*.mod' + paths-ignore: + - '**/*' # 忽略其他所有文件 jobs: test-unit: name: Test Units diff --git a/e2e/app_config.go b/e2e/app_config.go index 9f5cdabe..8c021939 100644 --- a/e2e/app_config.go +++ b/e2e/app_config.go @@ -25,9 +25,6 @@ import ( upgrademodulev1 "cosmossdk.io/api/cosmos/upgrade/module/v1" vestingmodulev1 "cosmossdk.io/api/cosmos/vesting/module/v1" "cosmossdk.io/core/appconfig" - _ "github.com/cosmos/cosmos-sdk/x/upgrade" // import for side-effects - "google.golang.org/protobuf/types/known/durationpb" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" "github.com/cosmos/cosmos-sdk/x/authz" @@ -45,7 +42,9 @@ import ( paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + _ "github.com/cosmos/cosmos-sdk/x/upgrade" // import for side-effects upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + "google.golang.org/protobuf/types/known/durationpb" coinswapmodule "mods.irisnet.org/api/irismod/coinswap/module/v1" farmmodule "mods.irisnet.org/api/irismod/farm/module/v1" @@ -92,7 +91,7 @@ var ( distrtypes.ModuleName, stakingtypes.ModuleName, slashingtypes.ModuleName, govtypes.ModuleName, minttypes.ModuleName, crisistypes.ModuleName, genutiltypes.ModuleName, evidencetypes.ModuleName, authz.ModuleName, feegrant.ModuleName, group.ModuleName, paramstypes.ModuleName, upgradetypes.ModuleName, - vestingtypes.ModuleName, consensustypes.ModuleName, + vestingtypes.ModuleName, consensustypes.ModuleName, coinswaptypes.ModuleName, farmtypes.ModuleName, htlctypes.ModuleName, @@ -311,7 +310,7 @@ var ( Config: appconfig.WrapAny(&consensusmodulev1.Module{}), }, { - Name: coinswaptypes.ModuleName, + Name: coinswaptypes.ModuleName, Config: appconfig.WrapAny(&coinswapmodule.Module{ FeeCollectorName: authtypes.FeeCollectorName, }), @@ -354,11 +353,11 @@ var ( Config: appconfig.WrapAny(&recordmodule.Module{}), }, { - Name: tokentypes.ModuleName, + Name: tokentypes.ModuleName, Config: appconfig.WrapAny(&tokenmodule.Module{ FeeCollectorName: authtypes.FeeCollectorName, }), }, }, }) -) \ No newline at end of file +) diff --git a/e2e/coinswap/cli_test.go b/e2e/coinswap/cli_test.go index c7a0c161..f366c5f3 100644 --- a/e2e/coinswap/cli_test.go +++ b/e2e/coinswap/cli_test.go @@ -8,4 +8,4 @@ import ( func TestQueryTestSuite(t *testing.T) { suite.Run(t, new(QueryTestSuite)) -} \ No newline at end of file +} diff --git a/e2e/coinswap/query.go b/e2e/coinswap/query.go index 6adeca8f..b5ea32f3 100644 --- a/e2e/coinswap/query.go +++ b/e2e/coinswap/query.go @@ -5,10 +5,9 @@ import ( "fmt" "time" - "github.com/cosmos/gogoproto/proto" - "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/gogoproto/proto" "mods.irisnet.org/e2e" coinswaptypes "mods.irisnet.org/modules/coinswap/types" @@ -60,7 +59,7 @@ func (s *QueryTestSuite) TestCoinswap() { txResult := s.BlockSendMsgs(s.T(), msgIssueToken) s.Require().Equal(uint32(0), txResult.Code, "send issue token msg failed") - //_ = tokentestutil.IssueTokenExec(s.T(), s.Network, clientCtx, from.String(), args...) + // _ = tokentestutil.IssueTokenExec(s.T(), s.Network, clientCtx, from.String(), args...) balances := simapp.QueryBalancesExec(s.T(), s.Network, clientCtx, from.String()) s.Require().Equal("100000000", balances.AmountOf(symbol).String()) diff --git a/e2e/farm/cli_test.go b/e2e/farm/cli_test.go index 0687e53b..703900f0 100644 --- a/e2e/farm/cli_test.go +++ b/e2e/farm/cli_test.go @@ -12,4 +12,4 @@ func TestTxTestSuite(t *testing.T) { func TestQueryTestSuite(t *testing.T) { suite.Run(t, new(QueryTestSuite)) -} \ No newline at end of file +} diff --git a/e2e/farm/query.go b/e2e/farm/query.go index 58578aba..6a7124ec 100644 --- a/e2e/farm/query.go +++ b/e2e/farm/query.go @@ -5,11 +5,10 @@ import ( "fmt" "time" - "github.com/cosmos/gogoproto/proto" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/gogoproto/proto" "mods.irisnet.org/e2e" coinswaptypes "mods.irisnet.org/modules/coinswap/types" @@ -108,7 +107,7 @@ func (s *QueryTestSuite) TestQueryCmd() { _, err = s.WaitForHeight(startHeight) s.Require().NoError(err) - s.WaitForNextBlock() + s.Require().NoError(s.WaitForNextBlock()) lpToken := sdk.NewCoin(lpTokenDenom, sdk.NewInt(100)) txResult = StakeExec( @@ -150,18 +149,17 @@ func (s *QueryTestSuite) latestHeight() int64 { } func (s *QueryTestSuite) setup() { - val := s.Validators[0] clientCtx := val.ClientCtx from := val.Address - symbol := "kitty" - name := "Kitty Token" - minUnit := "kitty" - scale := uint32(0) - initialSupply := uint64(100000000) - maxSupply := uint64(200000000) - mintable := true + const symbol = "kitty" + const name = "Kitty Token" + const minUnit = "kitty" + const scale = uint32(0) + const initialSupply = uint64(100000000) + const maxSupply = uint64(200000000) + const mintable = true // issue token msgIssueToken := &tokentypes.MsgIssueToken{ diff --git a/e2e/farm/test_helper.go b/e2e/farm/test_helper.go index 766c8077..6f4cccbc 100644 --- a/e2e/farm/test_helper.go +++ b/e2e/farm/test_helper.go @@ -5,7 +5,6 @@ import ( "testing" "github.com/cometbft/cometbft/libs/cli" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" @@ -17,7 +16,9 @@ import ( // CreateFarmPoolExec creates a redelegate message. func CreateFarmPoolExec(t *testing.T, network simapp.Network, clientCtx client.Context, creator string, - extraArgs ...string) *simapp.ResponseTx { + extraArgs ...string, +) *simapp.ResponseTx { + t.Helper() args := []string{ fmt.Sprintf("--%s=%s", flags.FlagFrom, creator), } @@ -32,6 +33,7 @@ func QueryFarmPoolsExec( clientCtx client.Context, extraArgs ...string, ) *farmtypes.QueryFarmPoolsResponse { + t.Helper() args := []string{ fmt.Sprintf("--%s=json", cli.OutputFlag), } @@ -50,6 +52,7 @@ func QueryFarmPoolExec( poolID string, extraArgs ...string, ) *farmtypes.QueryFarmPoolResponse { + t.Helper() args := []string{ poolID, fmt.Sprintf("--%s=json", cli.OutputFlag), @@ -64,7 +67,9 @@ func QueryFarmPoolExec( func AppendRewardExec(t *testing.T, network simapp.Network, clientCtx client.Context, creator, poolID string, - extraArgs ...string) *simapp.ResponseTx { + extraArgs ...string, +) *simapp.ResponseTx { + t.Helper() args := []string{ poolID, fmt.Sprintf("--%s=%s", flags.FlagFrom, creator), @@ -78,7 +83,9 @@ func StakeExec(t *testing.T, network simapp.Network, clientCtx client.Context, creator, poolID, lpToken string, - extraArgs ...string) *simapp.ResponseTx { + extraArgs ...string, +) *simapp.ResponseTx { + t.Helper() args := []string{ poolID, lpToken, @@ -93,7 +100,9 @@ func UnstakeExec(t *testing.T, network simapp.Network, clientCtx client.Context, creator, poolID, lpToken string, - extraArgs ...string) *simapp.ResponseTx { + extraArgs ...string, +) *simapp.ResponseTx { + t.Helper() args := []string{ poolID, lpToken, @@ -107,7 +116,9 @@ func UnstakeExec(t *testing.T, network simapp.Network, clientCtx client.Context, func HarvestExec(t *testing.T, network simapp.Network, clientCtx client.Context, creator, poolID string, - extraArgs ...string) *simapp.ResponseTx { + extraArgs ...string, +) *simapp.ResponseTx { + t.Helper() args := []string{ poolID, fmt.Sprintf("--%s=%s", flags.FlagFrom, creator), @@ -120,7 +131,9 @@ func HarvestExec(t *testing.T, network simapp.Network, clientCtx client.Context, func DestroyExec(t *testing.T, network simapp.Network, clientCtx client.Context, creator, poolID string, - extraArgs ...string) *simapp.ResponseTx { + extraArgs ...string, +) *simapp.ResponseTx { + t.Helper() args := []string{ poolID, fmt.Sprintf("--%s=%s", flags.FlagFrom, creator), @@ -132,7 +145,9 @@ func DestroyExec(t *testing.T, network simapp.Network, clientCtx client.Context, // QueryFarmerExec creates a redelegate message. func QueryFarmerExec(t *testing.T, network simapp.Network, clientCtx client.Context, creator string, - extraArgs ...string) *farmtypes.QueryFarmerResponse { + extraArgs ...string, +) *farmtypes.QueryFarmerResponse { + t.Helper() args := []string{ creator, fmt.Sprintf("--%s=json", cli.OutputFlag), diff --git a/e2e/farm/tx.go b/e2e/farm/tx.go index a6a5954a..ed9e44dc 100644 --- a/e2e/farm/tx.go +++ b/e2e/farm/tx.go @@ -22,7 +22,7 @@ type TxTestSuite struct { // TestTxCmd tests all tx command in the nft module func (s *TxTestSuite) TestTxCmd() { - val := s.Network.Validators[0] + val := s.Network.Validators[0] clientCtx := val.ClientCtx s.setup() @@ -185,7 +185,6 @@ func (s *TxTestSuite) latestHeight() int64 { } func (s *TxTestSuite) setup() { - val := s.Network.Validators[0] clientCtx := val.ClientCtx @@ -226,4 +225,4 @@ func (s *TxTestSuite) setup() { } res = s.Network.BlockSendMsgs(s.T(), msgAddLiquidity) s.Require().Equal(uint32(0), res.Code, res.Log) -} \ No newline at end of file +} diff --git a/e2e/htlc/cli_test.go b/e2e/htlc/cli_test.go index d84ce707..76e94a38 100644 --- a/e2e/htlc/cli_test.go +++ b/e2e/htlc/cli_test.go @@ -12,4 +12,4 @@ func TestTxTestSuite(t *testing.T) { func TestQueryTestSuite(t *testing.T) { suite.Run(t, new(QueryTestSuite)) -} \ No newline at end of file +} diff --git a/e2e/htlc/query.go b/e2e/htlc/query.go index 79aa182b..da10090e 100644 --- a/e2e/htlc/query.go +++ b/e2e/htlc/query.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/cometbft/cometbft/crypto" - "github.com/cosmos/cosmos-sdk/client/flags" sdk "github.com/cosmos/cosmos-sdk/types" @@ -22,7 +21,7 @@ func (s *QueryTestSuite) TestQueryCmd() { val := s.Network.Validators[0] //------test GetCmdCreateHTLC()------------- - //baseURL := val.APIAddress + // baseURL := val.APIAddress from := val.Address to := sdk.AccAddress(crypto.AddressHash([]byte("dgsbl"))) amount := "1000" + sdk.DefaultBondDenom @@ -30,7 +29,7 @@ func (s *QueryTestSuite) TestQueryCmd() { hashLock := "e8d4133e1a82c74e2746e78c19385706ea7958a0ca441a08dacfa10c48ce2561" timeLock := uint64(50) timestamp := uint64(1580000000) - //stateOpen := "HTLC_STATE_OPEN" + // stateOpen := "HTLC_STATE_OPEN" args := []string{ fmt.Sprintf("--%s=%s", htlccli.FlagTo, to), diff --git a/e2e/htlc/test_helper.go b/e2e/htlc/test_helper.go index 9e7e1a73..4687183b 100644 --- a/e2e/htlc/test_helper.go +++ b/e2e/htlc/test_helper.go @@ -5,7 +5,6 @@ import ( "testing" "github.com/cometbft/cometbft/libs/cli" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" @@ -28,7 +27,9 @@ func CreateHTLCExec(t *testing.T, network simapp.Network, clientCtx client.Context, from string, - extraArgs ...string) *simapp.ResponseTx { + extraArgs ...string, +) *simapp.ResponseTx { + t.Helper() args := []string{ fmt.Sprintf("--%s=%s", flags.FlagFrom, from), } @@ -54,7 +55,9 @@ func ClaimHTLCExec(t *testing.T, from string, id string, secret string, - extraArgs ...string) *simapp.ResponseTx { + extraArgs ...string, +) *simapp.ResponseTx { + t.Helper() args := []string{ id, secret, @@ -78,7 +81,9 @@ func QueryHTLCExec(t *testing.T, network simapp.Network, clientCtx client.Context, id string, - extraArgs ...string) *htlctypes.HTLC { + extraArgs ...string, +) *htlctypes.HTLC { + t.Helper() args := []string{ id, fmt.Sprintf("--%s=json", cli.OutputFlag), diff --git a/e2e/htlc/tx.go b/e2e/htlc/tx.go index e4f32501..aaf963fd 100644 --- a/e2e/htlc/tx.go +++ b/e2e/htlc/tx.go @@ -7,7 +7,6 @@ import ( "time" tmbytes "github.com/cometbft/cometbft/libs/bytes" - "github.com/cosmos/cosmos-sdk/client/flags" sdk "github.com/cosmos/cosmos-sdk/types" @@ -62,16 +61,16 @@ func (s *TxTestSuite) SetupSuite() { s.T().Log("setting up integration test suite") depInjectOptions := simapp.DepinjectOptions{ - Config: e2e.AppConfig, + Config: e2e.AppConfig, Providers: []interface{}{ keeper.ProvideMockEVM(), keeper.ProvideMockICS20(), }, } - cfg,err := simapp.NewConfig(depInjectOptions) + cfg, err := simapp.NewConfig(depInjectOptions) s.Require().NoError(err) - + cfg.NumValidators = 4 Deputy, _ = sdk.AccAddressFromBech32(DEPUTY_ADDR) @@ -264,6 +263,7 @@ func (s *TxTestSuite) TestTxCmd() { testCases[0].args.secret.String(), args..., ) + s.Require().EqualValues(0, txResult.Code) respType = QueryHTLCExec( s.T(), @@ -374,6 +374,7 @@ func (s *TxTestSuite) TestTxCmd() { testCases[1].args.secret.String(), args..., ) + s.Require().EqualValues(0, txResult.Code) respType = QueryHTLCExec( s.T(), @@ -477,6 +478,7 @@ func (s *TxTestSuite) TestTxCmd() { testCases[2].args.secret.String(), args..., ) + s.Require().EqualValues(0, txResult.Code) respType = QueryHTLCExec( s.T(), diff --git a/e2e/mt/cli_test.go b/e2e/mt/cli_test.go index a7c702c9..e4a3cc0a 100644 --- a/e2e/mt/cli_test.go +++ b/e2e/mt/cli_test.go @@ -12,4 +12,4 @@ func TestTxTestSuite(t *testing.T) { func TestQueryTestSuite(t *testing.T) { suite.Run(t, new(QueryTestSuite)) -} \ No newline at end of file +} diff --git a/e2e/mt/test_helper.go b/e2e/mt/test_helper.go index 8092c924..fd687d37 100644 --- a/e2e/mt/test_helper.go +++ b/e2e/mt/test_helper.go @@ -5,10 +5,9 @@ import ( "testing" "github.com/cometbft/cometbft/libs/cli" - "github.com/cosmos/gogoproto/proto" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/gogoproto/proto" mtcli "mods.irisnet.org/modules/mt/client/cli" mttypes "mods.irisnet.org/modules/mt/types" @@ -33,6 +32,7 @@ func IssueDenomExec( from string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ fmt.Sprintf("--%s=%s", flags.FlagFrom, from), } @@ -41,7 +41,6 @@ func IssueDenomExec( return network.ExecTxCmdWithResult(t, clientCtx, mtcli.GetCmdIssueDenom(), args) } - // BurnMTExec executes a burn token transaction. // // Parameters: @@ -65,6 +64,7 @@ func BurnMTExec(t *testing.T, amount string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ denomID, mtID, @@ -95,6 +95,7 @@ func MintMTExec(t *testing.T, denomID string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ denomID, fmt.Sprintf("--%s=%s", flags.FlagFrom, from), @@ -125,6 +126,7 @@ func EditMTExec(t *testing.T, mtID string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ denomID, mtID, @@ -160,6 +162,7 @@ func TransferMTExec(t *testing.T, amount string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ from, recipient, @@ -187,7 +190,9 @@ func QueryDenomExec(t *testing.T, network simapp.Network, clientCtx client.Context, denomID string, - extraArgs ...string) *mttypes.Denom { + extraArgs ...string, +) *mttypes.Denom { + t.Helper() args := []string{ denomID, fmt.Sprintf("--%s=json", cli.OutputFlag), @@ -212,7 +217,9 @@ func QueryDenomExec(t *testing.T, func QueryDenomsExec(t *testing.T, network simapp.Network, clientCtx client.Context, - extraArgs ...string) *mttypes.QueryDenomsResponse { + extraArgs ...string, +) *mttypes.QueryDenomsResponse { + t.Helper() args := []string{ fmt.Sprintf("--%s=json", cli.OutputFlag), } @@ -241,6 +248,7 @@ func QueryMTsExec(t *testing.T, resp proto.Message, extraArgs ...string, ) { + t.Helper() args := []string{ denomID, fmt.Sprintf("--%s=json", cli.OutputFlag), @@ -267,7 +275,9 @@ func QueryMTExec(t *testing.T, clientCtx client.Context, denomID string, mtID string, - extraArgs ...string) *mttypes.MT { + extraArgs ...string, +) *mttypes.MT { + t.Helper() args := []string{ denomID, mtID, @@ -296,7 +306,9 @@ func QueryBlancesExec(t *testing.T, clientCtx client.Context, from string, denomID string, - extraArgs ...string) *mttypes.QueryBalancesResponse { + extraArgs ...string, +) *mttypes.QueryBalancesResponse { + t.Helper() args := []string{ from, denomID, @@ -330,6 +342,7 @@ func TransferDenomExec(t *testing.T, denomID string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ from, recipient, diff --git a/e2e/mt/tx.go b/e2e/mt/tx.go index 49a96ef4..a6ae83c0 100644 --- a/e2e/mt/tx.go +++ b/e2e/mt/tx.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/cometbft/cometbft/crypto" - "github.com/cosmos/cosmos-sdk/client/flags" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/e2e/nft/cli_test.go b/e2e/nft/cli_test.go index d390a2c6..722a2836 100644 --- a/e2e/nft/cli_test.go +++ b/e2e/nft/cli_test.go @@ -12,4 +12,4 @@ func TestTxTestSuite(t *testing.T) { func TestQueryTestSuite(t *testing.T) { suite.Run(t, new(QueryTestSuite)) -} \ No newline at end of file +} diff --git a/e2e/nft/query.go b/e2e/nft/query.go index 1f1081ff..778263be 100644 --- a/e2e/nft/query.go +++ b/e2e/nft/query.go @@ -3,17 +3,32 @@ package nft import ( "fmt" - "github.com/cosmos/gogoproto/proto" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/gogoproto/proto" "mods.irisnet.org/e2e" nftcli "mods.irisnet.org/modules/nft/client/cli" nfttypes "mods.irisnet.org/modules/nft/types" ) +const ( + tokenName = "Kitty Token" + uri = "uri" + uriHash = "uriHash" + description = "description" + data = "{\"key1\":\"value1\",\"key2\":\"value2\"}" + tokenID = "kitty" + // owner := "owner" + denomName = "name" + denomID = "denom" + schema = "schema" + symbol = "symbol" + mintRestricted = true + updateRestricted = false +) + // QueryTestSuite is a suite of end-to-end tests for the nft module type QueryTestSuite struct { e2e.TestSuite @@ -21,26 +36,9 @@ type QueryTestSuite struct { // TestQueryCmd tests all query command in the nft module func (s *QueryTestSuite) TestQueryCmd() { - // s.SetupSuite() - val := s.Network.Validators[0] clientCtx := val.ClientCtx - // --------------------------------------------------------------------------- - from := val.Address - tokenName := "Kitty Token" - uri := "uri" - uriHash := "uriHash" - description := "description" - data := "{\"key1\":\"value1\",\"key2\":\"value2\"}" - tokenID := "kitty" - //owner := "owner" - denomName := "name" - denomID := "denom" - schema := "schema" - symbol := "symbol" - mintRestricted := true - updateRestricted := false baseURL := val.APIAddress //------test GetCmdIssueDenom()------------- diff --git a/e2e/nft/test_helper.go b/e2e/nft/test_helper.go index 3d8d3e29..1a660263 100644 --- a/e2e/nft/test_helper.go +++ b/e2e/nft/test_helper.go @@ -5,7 +5,6 @@ import ( "testing" "github.com/cometbft/cometbft/libs/cli" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" @@ -22,6 +21,7 @@ func IssueDenomExec(t *testing.T, denom string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ denom, fmt.Sprintf("--%s=%s", flags.FlagFrom, from), @@ -31,6 +31,7 @@ func IssueDenomExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, nftcli.GetCmdIssueDenom(), args) } +// BurnNFTExec creates a nft burnt message. func BurnNFTExec(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -39,6 +40,7 @@ func BurnNFTExec(t *testing.T, tokenID string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ denomID, tokenID, @@ -49,6 +51,7 @@ func BurnNFTExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, nftcli.GetCmdBurnNFT(), args) } +// MintNFTExec creates a nft minted message. func MintNFTExec(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -57,6 +60,7 @@ func MintNFTExec(t *testing.T, tokenID string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ denomID, tokenID, @@ -67,6 +71,7 @@ func MintNFTExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, nftcli.GetCmdMintNFT(), args) } +// EditNFTExec creates a nft edited message. func EditNFTExec(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -75,6 +80,7 @@ func EditNFTExec(t *testing.T, tokenID string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ denomID, tokenID, @@ -85,6 +91,7 @@ func EditNFTExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, nftcli.GetCmdEditNFT(), args) } +// TransferNFTExec creates a nft transferred message. func TransferNFTExec(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -94,6 +101,7 @@ func TransferNFTExec(t *testing.T, tokenID string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ recipient, denomID, @@ -105,6 +113,7 @@ func TransferNFTExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, nftcli.GetCmdTransferNFT(), args) } +// TransferDenomExec creates a nft transferred message. func TransferDenomExec(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -113,6 +122,7 @@ func TransferDenomExec(t *testing.T, denomID string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ recipient, denomID, @@ -123,11 +133,14 @@ func TransferDenomExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, nftcli.GetCmdTransferDenom(), args) } +// QueryDenomExec query denom. func QueryDenomExec(t *testing.T, network simapp.Network, clientCtx client.Context, denomID string, - extraArgs ...string) *nfttypes.Denom { + extraArgs ...string, +) *nfttypes.Denom { + t.Helper() args := []string{ denomID, fmt.Sprintf("--%s=json", cli.OutputFlag), @@ -139,11 +152,14 @@ func QueryDenomExec(t *testing.T, return response } +// QueryCollectionExec query collection. func QueryCollectionExec(t *testing.T, network simapp.Network, clientCtx client.Context, denomID string, - extraArgs ...string) *nfttypes.QueryCollectionResponse { + extraArgs ...string, +) *nfttypes.QueryCollectionResponse { + t.Helper() args := []string{ denomID, fmt.Sprintf("--%s=json", cli.OutputFlag), @@ -155,10 +171,13 @@ func QueryCollectionExec(t *testing.T, return response } +// QueryDenomsExec query denoms. func QueryDenomsExec(t *testing.T, network simapp.Network, clientCtx client.Context, - extraArgs ...string) *nfttypes.QueryDenomsResponse { + extraArgs ...string, +) *nfttypes.QueryDenomsResponse { + t.Helper() args := []string{ fmt.Sprintf("--%s=json", cli.OutputFlag), } @@ -169,11 +188,14 @@ func QueryDenomsExec(t *testing.T, return response } +// QuerySupplyExec query supply. func QuerySupplyExec(t *testing.T, network simapp.Network, clientCtx client.Context, denom string, - extraArgs ...string) *nfttypes.QuerySupplyResponse { + extraArgs ...string, +) *nfttypes.QuerySupplyResponse { + t.Helper() args := []string{ denom, fmt.Sprintf("--%s=json", cli.OutputFlag), @@ -185,11 +207,14 @@ func QuerySupplyExec(t *testing.T, return response } +// QueryOwnerExec query owner. func QueryOwnerExec(t *testing.T, network simapp.Network, clientCtx client.Context, address string, - extraArgs ...string) *nfttypes.QueryNFTsOfOwnerResponse { + extraArgs ...string, +) *nfttypes.QueryNFTsOfOwnerResponse { + t.Helper() args := []string{ address, fmt.Sprintf("--%s=json", cli.OutputFlag), @@ -201,12 +226,15 @@ func QueryOwnerExec(t *testing.T, return response } +// QueryNFTExec query nft. func QueryNFTExec(t *testing.T, network simapp.Network, clientCtx client.Context, denomID string, tokenID string, - extraArgs ...string) *nfttypes.BaseNFT { + extraArgs ...string, +) *nfttypes.BaseNFT { + t.Helper() args := []string{ denomID, tokenID, @@ -217,4 +245,4 @@ func QueryNFTExec(t *testing.T, response := &nfttypes.BaseNFT{} network.ExecQueryCmd(t, clientCtx, nftcli.GetCmdQueryNFT(), args, response) return response -} \ No newline at end of file +} diff --git a/e2e/nft/tx.go b/e2e/nft/tx.go index 7d97081d..601119d7 100644 --- a/e2e/nft/tx.go +++ b/e2e/nft/tx.go @@ -32,7 +32,7 @@ func (s *TxTestSuite) TestTxCmd() { description := "description" data := "{\"key1\":\"value1\",\"key2\":\"value2\"}" tokenID := "kitty" - //owner := "owner" + // owner := "owner" denomName := "name" denomID := "denom" schema := "schema" diff --git a/e2e/oracle/cli_test.go b/e2e/oracle/cli_test.go index 473d98ba..4e6c18f0 100644 --- a/e2e/oracle/cli_test.go +++ b/e2e/oracle/cli_test.go @@ -12,4 +12,4 @@ func TestTxTestSuite(t *testing.T) { func TestQueryTestSuite(t *testing.T) { suite.Run(t, new(QueryTestSuite)) -} \ No newline at end of file +} diff --git a/e2e/oracle/query.go b/e2e/oracle/query.go index 5f611c0c..537767cd 100644 --- a/e2e/oracle/query.go +++ b/e2e/oracle/query.go @@ -3,19 +3,17 @@ package oracle import ( "fmt" - "github.com/cosmos/gogoproto/proto" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/gogoproto/proto" "mods.irisnet.org/e2e" + "mods.irisnet.org/e2e/service" oraclecli "mods.irisnet.org/modules/oracle/client/cli" oracletypes "mods.irisnet.org/modules/oracle/types" servicecli "mods.irisnet.org/modules/service/client/cli" servicetypes "mods.irisnet.org/modules/service/types" - - "mods.irisnet.org/e2e/service" ) // QueryTestSuite is a suite of end-to-end tests for the nft module diff --git a/e2e/oracle/test_helper.go b/e2e/oracle/test_helper.go index 6db54c80..fb8a1827 100644 --- a/e2e/oracle/test_helper.go +++ b/e2e/oracle/test_helper.go @@ -5,7 +5,6 @@ import ( "testing" "github.com/cometbft/cometbft/libs/cli" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" @@ -27,7 +26,9 @@ func CreateFeedExec(t *testing.T, network simapp.Network, clientCtx client.Context, from string, - extraArgs ...string) *simapp.ResponseTx { + extraArgs ...string, +) *simapp.ResponseTx { + t.Helper() args := []string{ fmt.Sprintf("--%s=%s", flags.FlagFrom, from), } @@ -53,7 +54,9 @@ func EditFeedExec(t *testing.T, clientCtx client.Context, from string, feedName string, - extraArgs ...string) *simapp.ResponseTx { + extraArgs ...string, +) *simapp.ResponseTx { + t.Helper() args := []string{ feedName, fmt.Sprintf("--%s=%s", flags.FlagFrom, from), @@ -80,7 +83,9 @@ func StartFeedExec(t *testing.T, clientCtx client.Context, from string, feedName string, - extraArgs ...string) *simapp.ResponseTx { + extraArgs ...string, +) *simapp.ResponseTx { + t.Helper() args := []string{ feedName, fmt.Sprintf("--%s=%s", flags.FlagFrom, from), @@ -104,7 +109,9 @@ func PauseFeedExec(t *testing.T, clientCtx client.Context, from string, feedName string, - extraArgs ...string) *simapp.ResponseTx { + extraArgs ...string, +) *simapp.ResponseTx { + t.Helper() args := []string{ feedName, fmt.Sprintf("--%s=%s", flags.FlagFrom, from), @@ -127,7 +134,9 @@ func QueryFeedExec(t *testing.T, network simapp.Network, clientCtx client.Context, feedName string, - extraArgs ...string) *oracletypes.FeedContext { + extraArgs ...string, +) *oracletypes.FeedContext { + t.Helper() args := []string{ feedName, fmt.Sprintf("--%s=json", cli.OutputFlag), @@ -152,7 +161,9 @@ func QueryFeedExec(t *testing.T, func QueryFeedsExec(t *testing.T, network simapp.Network, clientCtx client.Context, - extraArgs ...string) *oracletypes.QueryFeedsResponse { + extraArgs ...string, +) *oracletypes.QueryFeedsResponse { + t.Helper() args := []string{ fmt.Sprintf("--%s=json", cli.OutputFlag), } @@ -176,7 +187,9 @@ func QueryFeedValueExec(t *testing.T, network simapp.Network, clientCtx client.Context, feedName string, - extraArgs ...string) *oracletypes.QueryFeedValueResponse { + extraArgs ...string, +) *oracletypes.QueryFeedValueResponse { + t.Helper() args := []string{ feedName, fmt.Sprintf("--%s=json", cli.OutputFlag), @@ -186,4 +199,4 @@ func QueryFeedValueExec(t *testing.T, response := &oracletypes.QueryFeedValueResponse{} network.ExecQueryCmd(t, clientCtx, oraclecli.GetCmdQueryFeedValue(), args, response) return response -} \ No newline at end of file +} diff --git a/e2e/oracle/tx.go b/e2e/oracle/tx.go index 73f99e22..5690e51a 100644 --- a/e2e/oracle/tx.go +++ b/e2e/oracle/tx.go @@ -10,11 +10,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "mods.irisnet.org/e2e" + "mods.irisnet.org/e2e/service" oraclecli "mods.irisnet.org/modules/oracle/client/cli" servicecli "mods.irisnet.org/modules/service/client/cli" servicetypes "mods.irisnet.org/modules/service/types" - - "mods.irisnet.org/e2e/service" ) // TxTestSuite is a suite of end-to-end tests for the nft module @@ -193,7 +192,7 @@ func (s *TxTestSuite) TestTxCmd() { var requestIds []string var requestsBz []byte for _, attribute := range event.Attributes { - if string(attribute.Key) == servicetypes.AttributeKeyRequests { + if attribute.Key == servicetypes.AttributeKeyRequests { requestsBz = []byte(attribute.GetValue()) found = true } diff --git a/e2e/random/cli_test.go b/e2e/random/cli_test.go index 6a0b9215..cb9c9bcf 100644 --- a/e2e/random/cli_test.go +++ b/e2e/random/cli_test.go @@ -12,4 +12,4 @@ func TestTxTestSuite(t *testing.T) { func TestQueryTestSuite(t *testing.T) { suite.Run(t, new(QueryTestSuite)) -} \ No newline at end of file +} diff --git a/e2e/random/query.go b/e2e/random/query.go index edf415e4..50c2a360 100644 --- a/e2e/random/query.go +++ b/e2e/random/query.go @@ -6,13 +6,12 @@ import ( "fmt" "time" - "github.com/cosmos/gogoproto/proto" - "github.com/tidwall/gjson" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/testutil/network" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/gogoproto/proto" + "github.com/tidwall/gjson" "mods.irisnet.org/e2e" "mods.irisnet.org/e2e/service" @@ -128,13 +127,13 @@ func (s *QueryTestSuite) TestQueryCmd() { s.Require().Len(qrrResp.Requests, 1) // ------get service request------------- - requestHeight = requestHeight + 1 + requestHeight++ _, err = s.Network.WaitForHeightWithTimeout( requestHeight, time.Duration(int64(blockInterval+2)*int64(s.Network.TimeoutCommit)), ) if err != nil { - s.Network.WaitForNBlock(2) + s.Require().NoError(s.Network.WaitForNBlock(2)) } blockResult, err := val.RPCClient.BlockResults(context.Background(), &requestHeight) @@ -146,7 +145,7 @@ func (s *QueryTestSuite) TestQueryCmd() { var requestIds []string var requestsBz []byte for _, attribute := range event.Attributes { - if string(attribute.Key) == servicetypes.AttributeKeyRequests { + if attribute.Key == servicetypes.AttributeKeyRequests { requestsBz = []byte(attribute.Value) found = true } diff --git a/e2e/random/test_helper.go b/e2e/random/test_helper.go index 0eee6081..4b38976a 100644 --- a/e2e/random/test_helper.go +++ b/e2e/random/test_helper.go @@ -5,7 +5,6 @@ import ( "testing" "github.com/cometbft/cometbft/libs/cli" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" @@ -14,13 +13,22 @@ import ( "mods.irisnet.org/simapp" ) -// MsgRedelegateExec creates a redelegate message. +// RequestRandomExec creates a random request execution message. +// +// Parameters: +// - t: The testing context. +// - network: The simulation network. +// - clientCtx: The client context. +// - from: The sender address. +// - extraArgs: Additional arguments. +// Returns a pointer to a simapp.ResponseTx. func RequestRandomExec(t *testing.T, network simapp.Network, clientCtx client.Context, from string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ fmt.Sprintf("--%s=%s", flags.FlagFrom, from), } @@ -29,11 +37,24 @@ func RequestRandomExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, randomcli.GetCmdRequestRandom(), args) } +// QueryRandomExec queries the random number for the given request ID using the provided network, client context, and optional extra arguments. +// +// Parameters: +// - t: The testing context. +// - network: The simulation network. +// - clientCtx: The client context. +// - requestID: The ID of the random request. +// - extraArgs: Optional extra arguments. +// +// Returns: +// - *randomtypes.Random: The response containing the queried random number. func QueryRandomExec(t *testing.T, network simapp.Network, clientCtx client.Context, requestID string, - extraArgs ...string) *randomtypes.Random { + extraArgs ...string, +) *randomtypes.Random { + t.Helper() args := []string{ requestID, fmt.Sprintf("--%s=json", cli.OutputFlag), @@ -45,11 +66,24 @@ func QueryRandomExec(t *testing.T, return response } +// QueryRandomRequestQueueExec queries the random request queue for a given height using the provided network, client context, and optional extra arguments. +// +// Parameters: +// - t: The testing context. +// - network: The simulation network. +// - clientCtx: The client context. +// - genHeight: The height at which to query the random request queue. +// - extraArgs: Optional extra arguments. +// +// Returns: +// - *randomtypes.QueryRandomRequestQueueResponse: The response containing the queried random request queue. func QueryRandomRequestQueueExec(t *testing.T, network simapp.Network, clientCtx client.Context, genHeight string, - extraArgs ...string) *randomtypes.QueryRandomRequestQueueResponse { + extraArgs ...string, +) *randomtypes.QueryRandomRequestQueueResponse { + t.Helper() args := []string{ genHeight, fmt.Sprintf("--%s=json", cli.OutputFlag), @@ -59,4 +93,4 @@ func QueryRandomRequestQueueExec(t *testing.T, response := &randomtypes.QueryRandomRequestQueueResponse{} network.ExecQueryCmd(t, clientCtx, randomcli.GetCmdQueryRandomRequestQueue(), args, response) return response -} \ No newline at end of file +} diff --git a/e2e/random/tx.go b/e2e/random/tx.go index 4fc758a4..17f1753c 100644 --- a/e2e/random/tx.go +++ b/e2e/random/tx.go @@ -124,7 +124,7 @@ func (s *TxTestSuite) TestTxCmd() { s.Require().Len(qrrResp.Requests, 1) // ------get service request------------- - requestHeight = requestHeight + 1 + requestHeight++ _, err := s.WaitForHeightWithTimeout( requestHeight, time.Duration(int64(blockInterval+5)*int64(s.TimeoutCommit)), @@ -140,7 +140,7 @@ func (s *TxTestSuite) TestTxCmd() { var requestIds []string var requestsBz []byte for _, attribute := range event.Attributes { - if string(attribute.Key) == servicetypes.AttributeKeyRequests { + if attribute.Key == servicetypes.AttributeKeyRequests { requestsBz = []byte(attribute.GetValue()) found = true } diff --git a/e2e/record/cli_test.go b/e2e/record/cli_test.go index 3c2709e1..831c8a8c 100644 --- a/e2e/record/cli_test.go +++ b/e2e/record/cli_test.go @@ -12,4 +12,4 @@ func TestTxTestSuite(t *testing.T) { func TestQueryTestSuite(t *testing.T) { suite.Run(t, new(QueryTestSuite)) -} \ No newline at end of file +} diff --git a/e2e/record/test_helper.go b/e2e/record/test_helper.go index e1e265fa..450b327e 100644 --- a/e2e/record/test_helper.go +++ b/e2e/record/test_helper.go @@ -5,7 +5,6 @@ import ( "testing" "github.com/cometbft/cometbft/libs/cli" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/gogoproto/proto" @@ -14,14 +13,26 @@ import ( "mods.irisnet.org/simapp" ) -// CreateRecordExec creates a redelegate message. +// CreateRecordExec creates a record +// +// Parameters: +// - t: *testing.T +// - network: simapp.Network +// - clientCtx: client.Context +// - from: string +// - digest: string +// - digestAlgo: string +// - extraArgs: ...string +// Returns *simapp.ResponseTx func CreateRecordExec(t *testing.T, network simapp.Network, clientCtx client.Context, from string, digest string, digestAlgo string, - extraArgs ...string) *simapp.ResponseTx { + extraArgs ...string, +) *simapp.ResponseTx { + t.Helper() args := []string{ digest, digestAlgo, @@ -33,12 +44,22 @@ func CreateRecordExec(t *testing.T, } // QueryRecordExec queries a record. +// +// Parameters: +// - t: *testing.T +// - network: simapp.Network +// - clientCtx: client.Context +// - recordID: string +// - resp: proto.Message +// - extraArgs: ...string func QueryRecordExec(t *testing.T, network simapp.Network, clientCtx client.Context, recordID string, resp proto.Message, - extraArgs ...string) { + extraArgs ...string, +) { + t.Helper() args := []string{ recordID, fmt.Sprintf("--%s=json", cli.OutputFlag), @@ -46,4 +67,4 @@ func QueryRecordExec(t *testing.T, args = append(args, extraArgs...) network.ExecQueryCmd(t, clientCtx, recordcli.GetCmdQueryRecord(), args, resp) -} \ No newline at end of file +} diff --git a/e2e/service/cli_test.go b/e2e/service/cli_test.go index a8de824d..e51461db 100644 --- a/e2e/service/cli_test.go +++ b/e2e/service/cli_test.go @@ -12,4 +12,4 @@ func TestTxTestSuite(t *testing.T) { func TestQueryTestSuite(t *testing.T) { suite.Run(t, new(QueryTestSuite)) -} \ No newline at end of file +} diff --git a/e2e/service/query.go b/e2e/service/query.go index ce781be8..7c4b1724 100644 --- a/e2e/service/query.go +++ b/e2e/service/query.go @@ -6,18 +6,16 @@ import ( "fmt" "time" - "github.com/cosmos/gogoproto/proto" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/testutil/network" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/gogoproto/proto" "mods.irisnet.org/e2e" servicecli "mods.irisnet.org/modules/service/client/cli" - "mods.irisnet.org/modules/service/types" servicetypes "mods.irisnet.org/modules/service/types" "mods.irisnet.org/simapp" ) @@ -33,8 +31,8 @@ func (s *QueryTestSuite) SetupSuite() { var serviceGenesisState servicetypes.GenesisState cfg.Codec.MustUnmarshalJSON(cfg.GenesisState[servicetypes.ModuleName], &serviceGenesisState) - serviceGenesisState.Params.ArbitrationTimeLimit = time.Duration(time.Second) - serviceGenesisState.Params.ComplaintRetrospect = time.Duration(time.Second) + serviceGenesisState.Params.ArbitrationTimeLimit = time.Second + serviceGenesisState.Params.ComplaintRetrospect = time.Second cfg.GenesisState[servicetypes.ModuleName] = cfg.Codec.MustMarshalJSON(&serviceGenesisState) cfg.NumValidators = 1 }) @@ -76,9 +74,9 @@ func (s *QueryTestSuite) TestQueryCmd() { s.Require().NoError(err) reqServiceFee := fmt.Sprintf("50%s", serviceDenom) - reqInput := `{"header":{},"body":{}}` - respResult := `{"code":200,"message":""}` - respOutput := `{"header":{},"body":{}}` + const reqInput = `{"header":{},"body":{}}` + const respResult = `{"code":200,"message":""}` + const respOutput = `{"header":{},"body":{}}` timeout := qos expectedEarnedFees := fmt.Sprintf("48%s", serviceDenom) @@ -309,11 +307,11 @@ func (s *QueryTestSuite) TestQueryCmd() { var requests []servicetypes.CompactRequest var requestsBz []byte for _, attribute := range event.Attributes { - if string(attribute.Key) == types.AttributeKeyRequests { + if attribute.Key == servicetypes.AttributeKeyRequests { requestsBz = []byte(attribute.Value) } - if string(attribute.Key) == types.AttributeKeyRequestContextID && - string(attribute.GetValue()) == requestContextId { + if attribute.Key == servicetypes.AttributeKeyRequestContextID && + attribute.GetValue() == requestContextId { found = true } } diff --git a/e2e/service/test_helper.go b/e2e/service/test_helper.go index 305a9482..a5473a22 100644 --- a/e2e/service/test_helper.go +++ b/e2e/service/test_helper.go @@ -5,7 +5,6 @@ import ( "testing" "github.com/cometbft/cometbft/libs/cli" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" @@ -14,12 +13,22 @@ import ( "mods.irisnet.org/simapp" ) +// DefineServiceExec defines a service execution. +// +// Parameters: +// - t: *testing.T +// - network: simapp.Network +// - clientCtx: client.Context +// - from: string +// - extraArgs: ...string +// Returns *simapp.ResponseTx func DefineServiceExec(t *testing.T, network simapp.Network, clientCtx client.Context, from string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ fmt.Sprintf("--%s=%s", flags.FlagFrom, from), } @@ -28,12 +37,24 @@ func DefineServiceExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, servicecli.GetCmdDefineService(), args) } +// BindServiceExec executes the command to bind a service. +// +// Parameters: +// - t: *testing.T - the testing object +// - network: simapp.Network - the network object +// - clientCtx: client.Context - the client context object +// - from: string - the address of the user binding the service +// - extraArgs: ...string - additional arguments for the command +// +// Returns: +// - *simapp.ResponseTx - the response transaction object func BindServiceExec(t *testing.T, network simapp.Network, clientCtx client.Context, from string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ fmt.Sprintf("--%s=%s", flags.FlagFrom, from), } @@ -42,12 +63,24 @@ func BindServiceExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, servicecli.GetCmdBindService(), args) } +// UpdateBindingExec executes the command to update a service binding. +// +// Parameters: +// - t: *testing.T - the testing object +// - network: simapp.Network - the network object +// - clientCtx: client.Context - the client context object +// - from: string - the address of the user updating the service binding +// - extraArgs: ...string - additional arguments for the command +// +// Returns: +// - *simapp.ResponseTx - the response transaction object func UpdateBindingExec(t *testing.T, network simapp.Network, clientCtx client.Context, from string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ fmt.Sprintf("--%s=%s", flags.FlagFrom, from), } @@ -56,6 +89,19 @@ func UpdateBindingExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, servicecli.GetCmdUpdateServiceBinding(), args) } +// RefundDepositExec executes the command to refund the deposit for a service. +// +// Parameters: +// - t: *testing.T - the testing object +// - network: simapp.Network - the network object +// - clientCtx: client.Context - the client context object +// - serviceName: string - the name of the service +// - provider: string - the provider of the service +// - from: string - the address of the user refunding the deposit +// - extraArgs: ...string - additional arguments for the command +// +// Returns: +// - *simapp.ResponseTx - the response transaction object func RefundDepositExec(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -64,6 +110,7 @@ func RefundDepositExec(t *testing.T, from string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ serviceName, provider, @@ -74,6 +121,19 @@ func RefundDepositExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, servicecli.GetCmdRefundServiceDeposit(), args) } +// DisableServiceExec executes the command to disable a service binding. +// +// Parameters: +// - t: *testing.T - the testing object +// - network: simapp.Network - the network object +// - clientCtx: client.Context - the client context object +// - serviceName: string - the name of the service +// - provider: string - the provider of the service +// - from: string - the address of the user disabling the service +// - extraArgs: ...string - additional arguments for the command +// +// Returns: +// - *simapp.ResponseTx - the response transaction object func DisableServiceExec(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -82,6 +142,7 @@ func DisableServiceExec(t *testing.T, from string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ serviceName, provider, @@ -92,6 +153,19 @@ func DisableServiceExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, servicecli.GetCmdDisableServiceBinding(), args) } +// EnableServiceExec executes the command to enable a service binding. +// +// Parameters: +// - t: *testing.T - the testing object +// - network: simapp.Network - the network object +// - clientCtx: client.Context - the client context object +// - serviceName: string - the name of the service +// - provider: string - the provider of the service +// - from: string - the address of the user enabling the service +// - extraArgs: ...string - additional arguments for the command +// +// Returns: +// - *simapp.ResponseTx - the response transaction object func EnableServiceExec(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -100,6 +174,7 @@ func EnableServiceExec(t *testing.T, from string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ serviceName, provider, @@ -110,12 +185,24 @@ func EnableServiceExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, servicecli.GetCmdEnableServiceBinding(), args) } +// CallServiceExec executes the command to call a service. +// +// Parameters: +// - t: *testing.T - the testing object +// - network: simapp.Network - the network object +// - clientCtx: client.Context - the client context object +// - from: string - the address of the user calling the service +// - extraArgs: ...string - additional arguments for the command +// +// Returns: +// - *simapp.ResponseTx - the response transaction object func CallServiceExec(t *testing.T, network simapp.Network, clientCtx client.Context, from string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ fmt.Sprintf("--%s=%s", flags.FlagFrom, from), } @@ -124,12 +211,24 @@ func CallServiceExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, servicecli.GetCmdCallService(), args) } +// RespondServiceExec executes the command to respond to a service request. +// +// Parameters: +// - t: *testing.T - the testing object +// - network: simapp.Network - the network object +// - clientCtx: client.Context - the client context object +// - from: string - the address of the user responding to the service request +// - extraArgs: ...string - additional arguments for the command +// +// Returns: +// - *simapp.ResponseTx - the response transaction object func RespondServiceExec(t *testing.T, network simapp.Network, clientCtx client.Context, from string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ fmt.Sprintf("--%s=%s", flags.FlagFrom, from), } @@ -138,6 +237,18 @@ func RespondServiceExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, servicecli.GetCmdRespondService(), args) } +// SetWithdrawAddrExec executes the command to set a withdrawal address. +// +// Parameters: +// - t: *testing.T - the testing object +// - network: simapp.Network - the network object +// - clientCtx: client.Context - the client context object +// - withdrawalAddress: string - the address to set for withdrawal +// - from: string - the address of the user setting the withdrawal address +// - extraArgs: ...string - additional arguments for the command +// +// Returns: +// - *simapp.ResponseTx - the response transaction object func SetWithdrawAddrExec(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -145,6 +256,7 @@ func SetWithdrawAddrExec(t *testing.T, from string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ withdrawalAddress, fmt.Sprintf("--%s=%s", flags.FlagFrom, from), @@ -154,6 +266,18 @@ func SetWithdrawAddrExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, servicecli.GetCmdSetWithdrawAddr(), args) } +// WithdrawEarnedFeesExec executes the command to withdraw earned fees. +// +// Parameters: +// - t: *testing.T - the testing object +// - network: simapp.Network - the network object +// - clientCtx: client.Context - the client context object +// - provider: string - the provider of the service +// - from: string - the address of the user withdrawing the fees +// - extraArgs: ...string - additional arguments for the command +// +// Returns: +// - *simapp.ResponseTx - the response transaction object func WithdrawEarnedFeesExec(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -161,6 +285,7 @@ func WithdrawEarnedFeesExec(t *testing.T, from string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ provider, fmt.Sprintf("--%s=%s", flags.FlagFrom, from), @@ -170,12 +295,24 @@ func WithdrawEarnedFeesExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, servicecli.GetCmdWithdrawEarnedFees(), args) } +// QueryServiceDefinitionExec executes a query to retrieve a service definition from the network. +// +// Parameters: +// - t: *testing.T - the testing object +// - network: simapp.Network - the network object +// - clientCtx: client.Context - the client context object +// - serviceName: string - the name of the service +// - extraArgs: ...string - additional arguments for the command +// +// Returns: +// - *servicetypes.ServiceDefinition - the response object containing the service definition func QueryServiceDefinitionExec(t *testing.T, network simapp.Network, clientCtx client.Context, serviceName string, extraArgs ...string, ) *servicetypes.ServiceDefinition { + t.Helper() args := []string{ serviceName, fmt.Sprintf("--%s=json", cli.OutputFlag), @@ -187,6 +324,18 @@ func QueryServiceDefinitionExec(t *testing.T, return response } +// QueryServiceBindingExec executes a query to retrieve a service binding from the network. +// +// Parameters: +// - t: *testing.T - the testing object. +// - network: simapp.Network - the network object. +// - clientCtx: client.Context - the client context object. +// - serviceName: string - the name of the service. +// - provider: string - the provider of the service. +// - extraArgs: ...string - additional arguments for the command. +// +// Returns: +// - *servicetypes.ServiceBinding - the response object containing the service binding. func QueryServiceBindingExec(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -194,6 +343,7 @@ func QueryServiceBindingExec(t *testing.T, provider string, extraArgs ...string, ) *servicetypes.ServiceBinding { + t.Helper() args := []string{ serviceName, provider, @@ -206,12 +356,24 @@ func QueryServiceBindingExec(t *testing.T, return response } +// QueryServiceBindingsExec executes a query to retrieve service bindings from the network. +// +// Parameters: +// - t: *testing.T - the testing object +// - network: simapp.Network - the network object +// - clientCtx: client.Context - the client context object +// - serviceName: string - the name of the service +// - extraArgs: ...string - additional arguments for the command +// +// Returns: +// - *servicetypes.QueryBindingsResponse - the response object containing the service bindings func QueryServiceBindingsExec(t *testing.T, network simapp.Network, clientCtx client.Context, serviceName string, extraArgs ...string, ) *servicetypes.QueryBindingsResponse { + t.Helper() args := []string{ serviceName, fmt.Sprintf("--%s=json", cli.OutputFlag), @@ -223,12 +385,26 @@ func QueryServiceBindingsExec(t *testing.T, return response } +// QueryServiceRequestsExec queries the service requests by service name and provider. +// +// Parameters: +// - t: *testing.T - the testing object +// - network: simapp.Network - the network object +// - clientCtx: client.Context - the client context object +// - serviceName: string - the name of the service +// - provider: string - the provider of the service +// - extraArgs: ...string - additional arguments for the command +// +// Returns: +// - *servicetypes.QueryRequestsResponse - the response object containing the service requests func QueryServiceRequestsExec(t *testing.T, network simapp.Network, clientCtx client.Context, serviceName, provider string, - extraArgs ...string) *servicetypes.QueryRequestsResponse { + extraArgs ...string, +) *servicetypes.QueryRequestsResponse { + t.Helper() args := []string{ serviceName, provider, @@ -241,6 +417,18 @@ func QueryServiceRequestsExec(t *testing.T, return response } +// QueryServiceRequestsByReqCtx queries the service requests by request context ID. +// +// Parameters: +// - t: *testing.T +// - network: simapp.Network +// - clientCtx: client.Context +// - requestContextID: string +// - batchCounter: string +// - extraArgs: ...string +// +// Returns: +// - *servicetypes.QueryRequestsResponse func QueryServiceRequestsByReqCtx(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -248,6 +436,7 @@ func QueryServiceRequestsByReqCtx(t *testing.T, batchCounter string, extraArgs ...string, ) *servicetypes.QueryRequestsResponse { + t.Helper() args := []string{ requestContextID, batchCounter, @@ -258,14 +447,24 @@ func QueryServiceRequestsByReqCtx(t *testing.T, response := &servicetypes.QueryRequestsResponse{} network.ExecQueryCmd(t, clientCtx, servicecli.GetCmdQueryServiceRequests(), args, response) return response - } +// QueryEarnedFeesExec executes the command to query the earned fees. +// +// Parameters: +// - t: *testing.T - the testing object +// - network: simapp.Network - the network object +// - clientCtx: client.Context - the client context object +// - extraArgs: ...string - additional arguments for the command +// +// Returns: +// - *servicetypes.QueryEarnedFeesResponse - the response object containing the earned fees func QueryEarnedFeesExec(t *testing.T, network simapp.Network, clientCtx client.Context, extraArgs ...string, ) *servicetypes.QueryEarnedFeesResponse { + t.Helper() args := []string{ fmt.Sprintf("--%s=json", cli.OutputFlag), } @@ -276,14 +475,24 @@ func QueryEarnedFeesExec(t *testing.T, return response } +// QueryRequestContextExec executes a query to retrieve a request context from the network. +// +// Parameters: +// - t: *testing.T +// - network: simapp.Network +// - clientCtx: client.Context +// - contextId: string +// - extraArgs: ...string +// Returns *servicetypes.RequestContext func QueryRequestContextExec(t *testing.T, network simapp.Network, clientCtx client.Context, - contextId string, + contextID string, extraArgs ...string, ) *servicetypes.RequestContext { + t.Helper() args := []string{ - contextId, + contextID, fmt.Sprintf("--%s=json", cli.OutputFlag), } args = append(args, extraArgs...) @@ -293,14 +502,24 @@ func QueryRequestContextExec(t *testing.T, return response } +// QueryServiceRequestExec executes a query to retrieve a service request from the network. +// +// Parameters: +// - t: *testing.T +// - network: simapp.Network +// - clientCtx: client.Context +// - requestID: string +// - extraArgs: ...string +// Returns *servicetypes.Request func QueryServiceRequestExec(t *testing.T, network simapp.Network, clientCtx client.Context, - requestId string, + requestID string, extraArgs ...string, ) *servicetypes.Request { + t.Helper() args := []string{ - requestId, + requestID, fmt.Sprintf("--%s=json", cli.OutputFlag), } args = append(args, extraArgs...) @@ -310,14 +529,24 @@ func QueryServiceRequestExec(t *testing.T, return response } +// QueryServiceResponseExec executes a query to retrieve a service response from the network. +// +// Parameters: +// - t: *testing.T +// - network: simapp.Network +// - clientCtx: client.Context +// - requestID: string +// - extraArgs: ...string +// Returns *servicetypes.Response func QueryServiceResponseExec(t *testing.T, network simapp.Network, clientCtx client.Context, - requestId string, + requestID string, extraArgs ...string, ) *servicetypes.Response { + t.Helper() args := []string{ - requestId, + requestID, fmt.Sprintf("--%s=json", cli.OutputFlag), } args = append(args, extraArgs...) diff --git a/e2e/service/tx.go b/e2e/service/tx.go index 2aeed917..da6bfbaf 100644 --- a/e2e/service/tx.go +++ b/e2e/service/tx.go @@ -7,7 +7,6 @@ import ( "time" "github.com/cometbft/cometbft/crypto" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -17,7 +16,6 @@ import ( "mods.irisnet.org/e2e" servicecli "mods.irisnet.org/modules/service/client/cli" - "mods.irisnet.org/modules/service/types" servicetypes "mods.irisnet.org/modules/service/types" "mods.irisnet.org/simapp" ) @@ -33,8 +31,8 @@ func (s *TxTestSuite) SetupSuite() { var serviceGenesisState servicetypes.GenesisState cfg.Codec.MustUnmarshalJSON(cfg.GenesisState[servicetypes.ModuleName], &serviceGenesisState) - serviceGenesisState.Params.ArbitrationTimeLimit = time.Duration(time.Second) - serviceGenesisState.Params.ComplaintRetrospect = time.Duration(time.Second) + serviceGenesisState.Params.ArbitrationTimeLimit = time.Second + serviceGenesisState.Params.ComplaintRetrospect = time.Second cfg.GenesisState[servicetypes.ModuleName] = cfg.Codec.MustMarshalJSON(&serviceGenesisState) cfg.NumValidators = 1 }) @@ -315,11 +313,11 @@ func (s *TxTestSuite) TestQueryCmd() { var requests []servicetypes.CompactRequest var requestsBz []byte for _, attribute := range event.Attributes { - if string(attribute.Key) == types.AttributeKeyRequests { + if attribute.Key == servicetypes.AttributeKeyRequests { requestsBz = []byte(attribute.GetValue()) } - if string(attribute.Key) == types.AttributeKeyRequestContextID && - string(attribute.GetValue()) == requestContextId { + if attribute.Key == servicetypes.AttributeKeyRequestContextID && + attribute.GetValue() == requestContextId { found = true } } diff --git a/e2e/suite.go b/e2e/suite.go index 0e4fc9c6..3d59f8f2 100644 --- a/e2e/suite.go +++ b/e2e/suite.go @@ -21,7 +21,7 @@ type TestSuite struct { // SetupSuite creates a new network for integration tests func (s *TestSuite) SetupSuite() { s.T().Log("setting up e2e test suite") - + depInjectOptions := simapp.DepinjectOptions{ Config: AppConfig, Providers: []interface{}{ @@ -29,7 +29,7 @@ func (s *TestSuite) SetupSuite() { keeper.ProvideMockICS20(), }, } - if s.modifyConfigFn == nil { + if s.modifyConfigFn == nil { s.Network = simapp.SetupNetwork(s.T(), depInjectOptions) return } diff --git a/e2e/token/cli_test.go b/e2e/token/cli_test.go index f0728d10..cafa44b1 100644 --- a/e2e/token/cli_test.go +++ b/e2e/token/cli_test.go @@ -12,4 +12,4 @@ func TestTxTestSuite(t *testing.T) { func TestQueryTestSuite(t *testing.T) { suite.Run(t, new(QueryTestSuite)) -} \ No newline at end of file +} diff --git a/e2e/token/query.go b/e2e/token/query.go index 2ef2ec31..54665561 100644 --- a/e2e/token/query.go +++ b/e2e/token/query.go @@ -4,11 +4,10 @@ import ( "encoding/json" "fmt" - "github.com/cosmos/gogoproto/proto" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/gogoproto/proto" "mods.irisnet.org/e2e" tokencli "mods.irisnet.org/modules/token/client/cli" @@ -25,16 +24,7 @@ type QueryTestSuite struct { func (s *QueryTestSuite) TestQueryCmd() { val := s.Network.Validators[0] clientCtx := val.ClientCtx - // --------------------------------------------------------------------------- - from := val.Address - symbol := "kitty" - name := "Kitty Token" - minUnit := "kitty" - scale := 0 - initialSupply := int64(100000000) - maxSupply := int64(200000000) - mintable := true baseURL := val.APIAddress //------test GetCmdIssueToken()------------- diff --git a/e2e/token/test_helper.go b/e2e/token/test_helper.go index ffc33111..3f5f6a8c 100644 --- a/e2e/token/test_helper.go +++ b/e2e/token/test_helper.go @@ -5,25 +5,36 @@ import ( "testing" "github.com/cometbft/cometbft/libs/cli" - "github.com/cosmos/gogoproto/proto" - "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" codectypes "github.com/cosmos/cosmos-sdk/codec/types" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" + "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/require" tokencli "mods.irisnet.org/modules/token/client/cli" v1 "mods.irisnet.org/modules/token/types/v1" "mods.irisnet.org/simapp" ) +// IssueTokenExec executes the command to issue a token on the specified network with the given client context and sender address. +// +// Parameters: +// - t: *testing.T - the testing object for running tests. +// - network: simapp.Network - the network on which the token will be issued. +// - clientCtx: client.Context - the client context for the transaction. +// - from: string - the address of the sender. +// - extraArgs: ...string - additional arguments for the command. +// +// Returns: +// - *simapp.ResponseTx - the response transaction from executing the command. func IssueTokenExec(t *testing.T, network simapp.Network, clientCtx client.Context, from string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ fmt.Sprintf("--%s=%s", flags.FlagFrom, from), } @@ -32,6 +43,18 @@ func IssueTokenExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, tokencli.GetCmdIssueToken(), args) } +// EditTokenExec executes the command to edit a token on the specified network with the given client context and sender address. +// +// Parameters: +// - t: *testing.T - the testing object for running tests. +// - network: simapp.Network - the network on which the token will be edited. +// - clientCtx: client.Context - the client context for the transaction. +// - from: string - the address of the sender. +// - symbol: string - the symbol of the token to be edited. +// - extraArgs: ...string - additional arguments for the command. +// +// Returns: +// - *simapp.ResponseTx - the response transaction from executing the command. func EditTokenExec(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -39,6 +62,7 @@ func EditTokenExec(t *testing.T, symbol string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ symbol, fmt.Sprintf("--%s=%s", flags.FlagFrom, from), @@ -48,6 +72,18 @@ func EditTokenExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, tokencli.GetCmdEditToken(), args) } +// MintTokenExec executes the command to mint a token on the specified network with the given client context and sender address. +// +// Parameters: +// - t: *testing.T - the testing object for running tests. +// - network: simapp.Network - the network on which the token will be minted. +// - clientCtx: client.Context - the client context for the transaction. +// - from: string - the address of the sender. +// - coinStr: string - the amount and coin type to be minted. +// - extraArgs: ...string - additional arguments for the command. +// +// Returns: +// - *simapp.ResponseTx - the response transaction from executing the command. func MintTokenExec(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -55,6 +91,7 @@ func MintTokenExec(t *testing.T, coinStr string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ coinStr, fmt.Sprintf("--%s=%s", flags.FlagFrom, from), @@ -64,6 +101,18 @@ func MintTokenExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, tokencli.GetCmdMintToken(), args) } +// BurnTokenExec executes the command to burn a token on the specified network with the given client context and sender address. +// +// Parameters: +// - t: *testing.T - the testing object for running tests. +// - network: simapp.Network - the network on which the token will be burned. +// - clientCtx: client.Context - the client context for the transaction. +// - from: string - the address of the sender. +// - coinStr: string - the amount and coin type to be burned. +// - extraArgs: ...string - additional arguments for the command. +// +// Returns: +// - *simapp.ResponseTx - the response transaction from executing the command. func BurnTokenExec(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -71,6 +120,7 @@ func BurnTokenExec(t *testing.T, coinStr string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ coinStr, fmt.Sprintf("--%s=%s", flags.FlagFrom, from), @@ -80,6 +130,18 @@ func BurnTokenExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, tokencli.GetCmdBurnToken(), args) } +// TransferTokenOwnerExec executes the command to transfer the ownership of a token on the specified network with the given client context and sender address. +// +// Parameters: +// - t: *testing.T - the testing object for running tests. +// - network: simapp.Network - the network on which the token ownership will be transferred. +// - clientCtx: client.Context - the client context for the transaction. +// - from: string - the address of the current owner. +// - symbol: string - the symbol of the token for which ownership will be transferred. +// - extraArgs: ...string - additional arguments for the command. +// +// Returns: +// - *simapp.ResponseTx - the response transaction from executing the command. func TransferTokenOwnerExec(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -87,6 +149,7 @@ func TransferTokenOwnerExec(t *testing.T, symbol string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ symbol, fmt.Sprintf("--%s=%s", flags.FlagFrom, from), @@ -96,6 +159,18 @@ func TransferTokenOwnerExec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, tokencli.GetCmdTransferTokenOwner(), args) } +// SwapToERC20Exec executes the command to swap a given coin to ERC20 on the specified network with the given client context and sender address. +// +// Parameters: +// - t: *testing.T - the testing object for running tests. +// - network: simapp.Network - the network on which the swap will be executed. +// - clientCtx: client.Context - the client context for the transaction. +// - from: string - the address of the sender. +// - coinStr: string - the amount and coin type to be swapped. +// - extraArgs: ...string - additional arguments for the command. +// +// Returns: +// - *simapp.ResponseTx - the response transaction from executing the command. func SwapToERC20Exec(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -103,6 +178,7 @@ func SwapToERC20Exec(t *testing.T, coinStr string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ coinStr, fmt.Sprintf("--%s=%s", flags.FlagFrom, from), @@ -112,6 +188,18 @@ func SwapToERC20Exec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, tokencli.GetCmdSwapToErc20(), args) } +// SwapFromERC20Exec executes the command to swap a given coin from ERC20 to native token on the specified network with the given client context and sender address. +// +// Parameters: +// - t: *testing.T - the testing object for running tests. +// - network: simapp.Network - the network on which the swap will be executed. +// - clientCtx: client.Context - the client context for the transaction. +// - from: string - the address of the sender. +// - coinStr: string - the amount and coin type to be swapped. +// - extraArgs: ...string - additional arguments for the command. +// +// Returns: +// - *simapp.ResponseTx - the response transaction from executing the command. func SwapFromERC20Exec(t *testing.T, network simapp.Network, clientCtx client.Context, @@ -119,6 +207,7 @@ func SwapFromERC20Exec(t *testing.T, coinStr string, extraArgs ...string, ) *simapp.ResponseTx { + t.Helper() args := []string{ coinStr, fmt.Sprintf("--%s=%s", flags.FlagFrom, from), @@ -128,12 +217,24 @@ func SwapFromERC20Exec(t *testing.T, return network.ExecTxCmdWithResult(t, clientCtx, tokencli.GetCmdSwapFromErc20(), args) } +// QueryTokenExec executes a query command to retrieve information about a token. +// +// Parameters: +// - t: testing instance +// - network: simapp.Network instance +// - clientCtx: client.Context instance +// - denom: string representing the denomination of the token +// - extraArgs: variadic string arguments +// +// Returns: +// - v1.TokenI interface func QueryTokenExec(t *testing.T, network simapp.Network, clientCtx client.Context, denom string, extraArgs ...string, ) v1.TokenI { + t.Helper() args := []string{ denom, fmt.Sprintf("--%s=json", cli.OutputFlag), @@ -149,12 +250,24 @@ func QueryTokenExec(t *testing.T, return token } +// QueryTokensExec executes a query command to retrieve information about tokens owned by a specific owner. +// +// Parameters: +// - t: testing instance +// - network: simapp.Network instance +// - clientCtx: client.Context instance +// - owner: string representing the owner of the tokens +// - extraArgs: variadic string arguments +// +// Returns: +// - []v1.TokenI: a slice of v1.TokenI representing the tokens owned by the specified owner func QueryTokensExec(t *testing.T, network simapp.Network, clientCtx client.Context, owner string, extraArgs ...string, ) []v1.TokenI { + t.Helper() args := []string{ owner, fmt.Sprintf("--%s=json", cli.OutputFlag), @@ -167,12 +280,24 @@ func QueryTokensExec(t *testing.T, return tokens } +// QueryFeeExec executes a query command to retrieve information about a token's fees. +// +// Parameters: +// - t: *testing.T - the testing object for running tests. +// - network: simapp.Network - the network on which the query will be executed. +// - clientCtx: client.Context - the client context for the query. +// - symbol: string - the symbol of the token. +// - extraArgs: ...string - additional arguments for the query command. +// +// Returns: +// - *v1.QueryFeesResponse - the response containing the token's fees. func QueryFeeExec(t *testing.T, network simapp.Network, clientCtx client.Context, symbol string, extraArgs ...string, ) *v1.QueryFeesResponse { + t.Helper() args := []string{ symbol, fmt.Sprintf("--%s=json", cli.OutputFlag), @@ -184,11 +309,22 @@ func QueryFeeExec(t *testing.T, return response } +// QueryParamsExec executes a query command to retrieve parameters. +// +// Parameters: +// - t: *testing.T - the testing object for running tests. +// - network: simapp.Network - the network on which the query will be executed. +// - clientCtx: client.Context - the client context for the query. +// - extraArgs: ...string - additional arguments for the query command. +// +// Returns: +// - *v1.Params - the response containing the parameters. func QueryParamsExec(t *testing.T, network simapp.Network, clientCtx client.Context, extraArgs ...string, ) *v1.Params { + t.Helper() args := []string{ fmt.Sprintf("--%s=json", cli.OutputFlag), } diff --git a/e2e/token/tx.go b/e2e/token/tx.go index dc3c19ff..ad71abe5 100644 --- a/e2e/token/tx.go +++ b/e2e/token/tx.go @@ -14,6 +14,16 @@ import ( "mods.irisnet.org/simapp" ) +const ( + symbol = "kitty" + name = "Kitty Token" + minUnit = "kitty" + scale = 0 + initialSupply = int64(100000000) + maxSupply = int64(200000000) + mintable = true +) + // TxTestSuite is a suite of end-to-end tests for the nft module type TxTestSuite struct { e2e.TestSuite @@ -23,16 +33,7 @@ type TxTestSuite struct { func (s *TxTestSuite) TestTxCmd() { val := s.Network.Validators[0] clientCtx := val.ClientCtx - // --------------------------------------------------------------------------- - from := val.Address - symbol := "kitty" - name := "Kitty Token" - minUnit := "kitty" - scale := 0 - initialSupply := int64(100000000) - maxSupply := int64(200000000) - mintable := true //------test GetCmdIssueToken()------------- args := []string{ @@ -159,7 +160,7 @@ func (s *TxTestSuite) TestTxCmd() { from.String(), symbol, ) - exceptedAmount = exceptedAmount - burnAmount + exceptedAmount -= burnAmount s.Require().Equal(exceptedAmount, balance.Amount.Int64()) //------test GetCmdEditToken()------------- diff --git a/modules/coinswap/depinject.go b/modules/coinswap/depinject.go index acc037b9..fd027d9d 100644 --- a/modules/coinswap/depinject.go +++ b/modules/coinswap/depinject.go @@ -3,7 +3,6 @@ package coinswap import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" - "github.com/cosmos/cosmos-sdk/codec" store "github.com/cosmos/cosmos-sdk/store/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -23,7 +22,7 @@ func init() { } func ProvideKeyTable() types.KeyTable { - return types.ParamKeyTable() //nolint:staticcheck + return types.ParamKeyTable() } var _ appmodule.AppModule = AppModule{} diff --git a/modules/coinswap/keeper/depinject_test.go b/modules/coinswap/keeper/depinject_test.go index bca0692d..32fa22b9 100644 --- a/modules/coinswap/keeper/depinject_test.go +++ b/modules/coinswap/keeper/depinject_test.go @@ -25,8 +25,6 @@ import ( upgrademodulev1 "cosmossdk.io/api/cosmos/upgrade/module/v1" vestingmodulev1 "cosmossdk.io/api/cosmos/vesting/module/v1" "cosmossdk.io/core/appconfig" - "google.golang.org/protobuf/types/known/durationpb" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" "github.com/cosmos/cosmos-sdk/x/authz" @@ -45,6 +43,7 @@ import ( slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + "google.golang.org/protobuf/types/known/durationpb" coinswapmodule "mods.irisnet.org/api/irismod/coinswap/module/v1" _ "mods.irisnet.org/modules/coinswap" @@ -247,7 +246,7 @@ var ( Config: appconfig.WrapAny(&consensusmodulev1.Module{}), }, { - Name: coinswaptypes.ModuleName, + Name: coinswaptypes.ModuleName, Config: appconfig.WrapAny(&coinswapmodule.Module{ FeeCollectorName: authtypes.FeeCollectorName, }), diff --git a/modules/coinswap/keeper/fees.go b/modules/coinswap/keeper/fees.go index 158612ce..86c95adc 100644 --- a/modules/coinswap/keeper/fees.go +++ b/modules/coinswap/keeper/fees.go @@ -1,4 +1,3 @@ -// nolint package keeper import ( diff --git a/modules/coinswap/keeper/genesis.go b/modules/coinswap/keeper/genesis.go index 321bb94c..4ade34f1 100644 --- a/modules/coinswap/keeper/genesis.go +++ b/modules/coinswap/keeper/genesis.go @@ -11,13 +11,16 @@ import ( // InitGenesis initializes the coinswap module's state from a given genesis state. func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState) { if err := types.ValidateGenesis(genState); err != nil { - panic(fmt.Errorf("panic for ValidateGenesis,%v", err)) + panic(fmt.Errorf("panic for ValidateGenesis,%w", err)) + } + if err := k.SetParams(ctx, genState.Params); err != nil { + panic(fmt.Errorf("panic for SetParams,%w", err)) } - k.SetParams(ctx, genState.Params) k.SetStandardDenom(ctx, genState.StandardDenom) k.setSequence(ctx, genState.Sequence) for _, pool := range genState.Pool { - k.setPool(ctx, &pool) + poolCopy := pool // Create a copy of the pool variable + k.setPool(ctx, &poolCopy) } } diff --git a/modules/coinswap/keeper/grpc_query.go b/modules/coinswap/keeper/grpc_query.go index dfab1373..a0f8d15a 100644 --- a/modules/coinswap/keeper/grpc_query.go +++ b/modules/coinswap/keeper/grpc_query.go @@ -3,13 +3,12 @@ package keeper import ( "context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - errorsmod "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "mods.irisnet.org/modules/coinswap/types" ) @@ -72,7 +71,7 @@ func (k Keeper) LiquidityPools( store := ctx.KVStore(k.storeKey) nftStore := prefix.NewStore(store, []byte(types.KeyPool)) - pageRes, err := query.Paginate(nftStore, req.Pagination, func(_ []byte, value []byte) error { + pageRes, err := query.Paginate(nftStore, req.Pagination, func(_, value []byte) error { var pool types.Pool k.cdc.MustUnmarshal(value, &pool) diff --git a/modules/coinswap/keeper/keeper.go b/modules/coinswap/keeper/keeper.go index b687bd2e..8efb3441 100644 --- a/modules/coinswap/keeper/keeper.go +++ b/modules/coinswap/keeper/keeper.go @@ -5,10 +5,9 @@ import ( "math/big" "strconv" + errorsmod "cosmossdk.io/errors" sdkmath "cosmossdk.io/math" "github.com/cometbft/cometbft/libs/log" - - errorsmod "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -157,7 +156,7 @@ func (k Keeper) AddLiquidity(ctx sdk.Context, msg *types.MsgAddLiquidity) (sdk.C return sdk.Coin{}, err } - //pool exist but has no balances,so do same operations as firist addLiquidity(but without creating pool) + // pool exist but has no balances,so do same operations as firist addLiquidity(but without creating pool) if balances == nil || balances.IsZero() { mintLiquidityAmt = msg.ExactStandardAmt if mintLiquidityAmt.LT(msg.MinLiquidity) { @@ -324,8 +323,8 @@ func (k Keeper) AddUnilateralLiquidity( Mul(lptBalanceAmt). Quo(denominator.Mul(tokenBalanceAmt)) - // lpt = square^0.5 - lpt_balance - var squareBigInt = &big.Int{} + // lpt = square^0.5 - lpt_balance + squareBigInt := &big.Int{} squareBigInt.Sqrt(square.BigInt()) mintLptAmt := sdkmath.NewIntFromBigInt(squareBigInt).Sub(lptBalanceAmt) diff --git a/modules/coinswap/keeper/keeper_test.go b/modules/coinswap/keeper/keeper_test.go index 25945446..7df2d7a9 100644 --- a/modules/coinswap/keeper/keeper_test.go +++ b/modules/coinswap/keeper/keeper_test.go @@ -4,16 +4,14 @@ import ( "testing" "time" - "github.com/stretchr/testify/suite" - + sdkmath "cosmossdk.io/math" "github.com/cometbft/cometbft/crypto/tmhash" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - - sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/stretchr/testify/suite" "mods.irisnet.org/modules/coinswap/keeper" "mods.irisnet.org/modules/coinswap/types" @@ -69,7 +67,7 @@ func (suite *TestSuite) TestParams() { {types.DefaultParams()}, } for _, tc := range cases { - suite.keeper.SetParams(suite.ctx, tc.params) + suite.NoError(suite.keeper.SetParams(suite.ctx, tc.params), "set params failed") feeParam := suite.keeper.GetParams(suite.ctx) suite.Equal(tc.params.Fee, feeParam.Fee) @@ -77,6 +75,7 @@ func (suite *TestSuite) TestParams() { } func setupWithGenesisAccounts(t *testing.T, keeper *keeper.Keeper) *simapp.SimApp { + t.Helper() amountInitStandard, _ := sdkmath.NewIntFromString("30000000000000000000") amountInitBTC, _ := sdkmath.NewIntFromString("3000000000") diff --git a/modules/coinswap/keeper/params.go b/modules/coinswap/keeper/params.go index dc13bcbd..b7f5307d 100644 --- a/modules/coinswap/keeper/params.go +++ b/modules/coinswap/keeper/params.go @@ -48,7 +48,7 @@ func (k Keeper) GetStandardDenom(ctx sdk.Context) string { store := ctx.KVStore(k.storeKey) bz := store.Get(types.KeyStandardDenom) - var denomWrap = gogotypes.StringValue{} + denomWrap := gogotypes.StringValue{} k.cdc.MustUnmarshal(bz, &denomWrap) return denomWrap.Value } diff --git a/modules/coinswap/keeper/pool.go b/modules/coinswap/keeper/pool.go index b9896ba4..ef5d0a0e 100644 --- a/modules/coinswap/keeper/pool.go +++ b/modules/coinswap/keeper/pool.go @@ -3,10 +3,9 @@ package keeper import ( "fmt" - gogotypes "github.com/cosmos/gogoproto/types" - errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + gogotypes "github.com/cosmos/gogoproto/types" "mods.irisnet.org/modules/coinswap/types" ) diff --git a/modules/coinswap/keeper/swap_test.go b/modules/coinswap/keeper/swap_test.go index b9986ed9..91fe35a2 100644 --- a/modules/coinswap/keeper/swap_test.go +++ b/modules/coinswap/keeper/swap_test.go @@ -7,9 +7,8 @@ import ( "time" sdkmath "cosmossdk.io/math" - "github.com/stretchr/testify/suite" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" "mods.irisnet.org/modules/coinswap/keeper" "mods.irisnet.org/modules/coinswap/types" @@ -31,7 +30,7 @@ type SwapCase struct { } func (suite *TestSuite) TestGetInputPrice() { - var datas = []SwapCase{{ + datas := []SwapCase{{ data: Data{delta: sdk.NewInt(100), x: sdk.NewInt(1000), y: sdk.NewInt(1000), fee: sdk.NewDecWithPrec(3, 3)}, expect: sdk.NewInt(90), }, { @@ -55,7 +54,7 @@ func (suite *TestSuite) TestGetInputPrice() { } func (suite *TestSuite) TestGetOutputPrice() { - var datas = []SwapCase{{ + datas := []SwapCase{{ data: Data{delta: sdk.NewInt(100), x: sdk.NewInt(1000), y: sdk.NewInt(1000), fee: sdk.NewDecWithPrec(3, 3)}, expect: sdk.NewInt(112), }, { diff --git a/modules/coinswap/migrations/v2/migrate.go b/modules/coinswap/migrations/v2/migrate.go index c74c88fa..567e7cff 100644 --- a/modules/coinswap/migrations/v2/migrate.go +++ b/modules/coinswap/migrations/v2/migrate.go @@ -30,11 +30,11 @@ func Migrate(ctx sdk.Context, // 2. Create a new liquidity pool based on the results of the first step standardDenom := k.GetStandardDenom(ctx) - var pools = make(map[string]coinswaptypes.Pool, len(lptDenoms)) + pools := make(map[string]coinswaptypes.Pool, len(lptDenoms)) for _, ltpDenom := range lptDenoms { counterpartyDenom := strings.TrimPrefix(ltpDenom, FormatUniABSPrefix) pools[ltpDenom] = k.CreatePool(ctx, counterpartyDenom) - //3. Transfer tokens from the old liquidity to the newly created liquidity pool + // 3. Transfer tokens from the old liquidity to the newly created liquidity pool if err := migratePool(ctx, bk, pools[ltpDenom], ltpDenom, standardDenom); err != nil { return err } @@ -65,7 +65,7 @@ func migrateProvider(ctx sdk.Context, pool coinswaptypes.Pool, provider sdk.AccAddress, ) error { - //1. Burn the old liquidity tokens + // 1. Burn the old liquidity tokens burnCoins := sdk.NewCoins(originLptCoin) // send liquidity vouchers to be burned from sender account to module account if err := bk.SendCoinsFromAccountToModule(ctx, provider, coinswaptypes.ModuleName, burnCoins); err != nil { @@ -76,7 +76,7 @@ func migrateProvider(ctx sdk.Context, return err } - //2. Issue new liquidity tokens + // 2. Issue new liquidity tokens mintToken := sdk.NewCoin(pool.LptDenom, originLptCoin.Amount) mintTokens := sdk.NewCoins(mintToken) if err := bk.MintCoins(ctx, coinswaptypes.ModuleName, mintTokens); err != nil { @@ -94,7 +94,7 @@ func migratePool(ctx sdk.Context, counterpartyDenom := strings.TrimPrefix(ltpDenom, FormatUniABSPrefix) originPoolAddress := GetReservePoolAddr(ltpDenom) - //Query the amount of the original liquidity pool account + // Query the amount of the original liquidity pool account originPoolBalances := bk.GetAllBalances(ctx, originPoolAddress) transferCoins := sdk.NewCoins( sdk.NewCoin(standardDenom, originPoolBalances.AmountOf(standardDenom)), diff --git a/modules/coinswap/migrations/v2/types.go b/modules/coinswap/migrations/v2/types.go index f53aa2c0..10509f66 100644 --- a/modules/coinswap/migrations/v2/types.go +++ b/modules/coinswap/migrations/v2/types.go @@ -5,7 +5,6 @@ import ( "strings" "github.com/cometbft/cometbft/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/modules/coinswap/module.go b/modules/coinswap/module.go index f2298bb5..c6547a98 100644 --- a/modules/coinswap/module.go +++ b/modules/coinswap/module.go @@ -5,17 +5,15 @@ import ( "encoding/json" "fmt" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" "mods.irisnet.org/modules/coinswap/keeper" "mods.irisnet.org/modules/coinswap/simulation" @@ -174,7 +172,6 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { // RegisterStoreDecoder registers a decoder for coinswap module's types func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - } // WeightedOperations returns the all the coinswap module operations with their respective weights. diff --git a/modules/coinswap/simulation/operations.go b/modules/coinswap/simulation/operations.go index f11fc51b..119f3f0a 100644 --- a/modules/coinswap/simulation/operations.go +++ b/modules/coinswap/simulation/operations.go @@ -236,7 +236,6 @@ func SimulateMsgAddLiquidity( []uint64{account.GetSequence()}, simAccount.PrivKey, ) - if err != nil { return simtypes.NoOpMsg( types.ModuleName, @@ -251,7 +250,6 @@ func SimulateMsgAddLiquidity( return simtypes.NewOperationMsg(msg, true, "", nil), nil, nil } - } // SimulateMsgSwapOrder simulates the swap of order @@ -450,7 +448,6 @@ func SimulateMsgSwapOrder( []uint64{account.GetSequence()}, simAccount.PrivKey, ) - if err != nil { return simtypes.NoOpMsg( types.ModuleName, @@ -609,7 +606,6 @@ func SimulateMsgRemoveLiquidity( []uint64{account.GetSequence()}, simAccount.PrivKey, ) - if err != nil { return simtypes.NoOpMsg( types.ModuleName, @@ -623,7 +619,6 @@ func SimulateMsgRemoveLiquidity( } return simtypes.NewOperationMsg(msg, true, "", nil), nil, nil - } } @@ -719,7 +714,7 @@ func SimulateMsgAddUnilateralLiquidity( ), nil, err } // lpt = square^0.5 - lpt_balance - var squareBigInt = &big.Int{} + squareBigInt := &big.Int{} squareBigInt.Sqrt(square.BigInt()) mintLptAmt := sdkmath.NewIntFromBigInt(squareBigInt).Sub(lptBalanceAmt) @@ -759,7 +754,6 @@ func SimulateMsgAddUnilateralLiquidity( []uint64{account.GetSequence()}, simAccount.PrivKey, ) - if err != nil { return simtypes.NoOpMsg( types.ModuleName, @@ -833,6 +827,13 @@ func SimulateMsgRemoveUnilateralLiquidity( } balances, err := k.GetPoolBalances(ctx, pool.EscrowAddress) + if err != nil { + return simtypes.NoOpMsg( + types.ModuleName, + types.TypeMsgRemoveUnilateralLiquidity, + "pool balances not found", + ), nil, err + } lptDenom := pool.LptDenom targetTokenDenom := targetToken.Denom @@ -919,7 +920,6 @@ func SimulateMsgRemoveUnilateralLiquidity( []uint64{account.GetSequence()}, simAccount.PrivKey, ) - if err != nil { return simtypes.NoOpMsg( types.ModuleName, @@ -949,7 +949,7 @@ func randToken(r *rand.Rand, spendableCoin sdk.Coins) (sdk.Coin, error) { } func randDeadline(r *rand.Rand) int64 { - var delta = time.Duration(simtypes.RandIntBetween(r, 10, 100)) * time.Second + delta := time.Duration(simtypes.RandIntBetween(r, 10, 100)) * time.Second return time.Now().Add(delta).UnixNano() } diff --git a/modules/coinswap/types/events.go b/modules/coinswap/types/events.go index 1ec2aace..d9728b7f 100644 --- a/modules/coinswap/types/events.go +++ b/modules/coinswap/types/events.go @@ -1,4 +1,3 @@ -// nolint package types // coinswap module event types diff --git a/modules/coinswap/types/expected_keepers.go b/modules/coinswap/types/expected_keepers.go index 413ae7ad..a9798a4b 100644 --- a/modules/coinswap/types/expected_keepers.go +++ b/modules/coinswap/types/expected_keepers.go @@ -8,7 +8,7 @@ import ( // BankKeeper defines the expected bank keeper type BankKeeper interface { - SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error + SendCoins(ctx sdk.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) error GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin diff --git a/modules/coinswap/types/genesis.go b/modules/coinswap/types/genesis.go index ea444cb0..1889c0df 100644 --- a/modules/coinswap/types/genesis.go +++ b/modules/coinswap/types/genesis.go @@ -29,9 +29,9 @@ func ValidateGenesis(data GenesisState) error { return err } - var poolIds = make(map[string]bool, len(data.Pool)) - var lptDenoms = make(map[string]bool, len(data.Pool)) - var maxSequence = uint64(0) + poolIds := make(map[string]bool, len(data.Pool)) + lptDenoms := make(map[string]bool, len(data.Pool)) + maxSequence := uint64(0) for _, pool := range data.Pool { if poolIds[pool.Id] { return fmt.Errorf("duplicate pool: %s", pool.Id) @@ -42,7 +42,7 @@ func ValidateGenesis(data GenesisState) error { poolIds[pool.Id] = true lptDenoms[pool.LptDenom] = true - //validate the liquidity pool token denom + // validate the liquidity pool token denom seq, err := ParseLptDenom(pool.LptDenom) if err != nil { return err @@ -52,17 +52,17 @@ func ValidateGenesis(data GenesisState) error { maxSequence = seq } - //validate the token denom + // validate the token denom if err := sdk.ValidateDenom(pool.CounterpartyDenom); err != nil { return err } - //validate the token denom + // validate the token denom if err := sdk.ValidateDenom(pool.StandardDenom); err != nil { return err } - //validate the address + // validate the address if _, err := sdk.AccAddressFromBech32(pool.EscrowAddress); err != nil { return err } diff --git a/modules/coinswap/types/msgs.go b/modules/coinswap/types/msgs.go index 368909c5..bee5cef3 100644 --- a/modules/coinswap/types/msgs.go +++ b/modules/coinswap/types/msgs.go @@ -125,7 +125,6 @@ func (msg MsgAddLiquidity) Type() string { return TypeMsgAddLiquidity } // ValidateBasic implements Msg. func (msg MsgAddLiquidity) ValidateBasic() error { - if err := ValidateToken(msg.MaxToken); err != nil { return err } diff --git a/modules/coinswap/types/msgs_test.go b/modules/coinswap/types/msgs_test.go index e27de0be..f161dff1 100644 --- a/modules/coinswap/types/msgs_test.go +++ b/modules/coinswap/types/msgs_test.go @@ -8,9 +8,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -var ( - sender = sdk.AccAddress(tmhash.SumTruncated([]byte("sender"))).String() -) +var sender = sdk.AccAddress(tmhash.SumTruncated([]byte("sender"))).String() func TestMsgSwapOrder_ValidateBasic(t *testing.T) { type fields struct { diff --git a/modules/coinswap/types/params.go b/modules/coinswap/types/params.go index f387a827..6d97f786 100644 --- a/modules/coinswap/types/params.go +++ b/modules/coinswap/types/params.go @@ -3,9 +3,8 @@ package types import ( "fmt" - "sigs.k8s.io/yaml" - sdk "github.com/cosmos/cosmos-sdk/types" + "sigs.k8s.io/yaml" ) // NewParams is the coinswap params constructor diff --git a/modules/coinswap/types/utils.go b/modules/coinswap/types/utils.go index 65f63993..342f8913 100644 --- a/modules/coinswap/types/utils.go +++ b/modules/coinswap/types/utils.go @@ -6,7 +6,6 @@ import ( "strings" "github.com/cometbft/cometbft/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/modules/farm/client/cli/query.go b/modules/farm/client/cli/query.go index 45df80ba..8a727836 100644 --- a/modules/farm/client/cli/query.go +++ b/modules/farm/client/cli/query.go @@ -4,11 +4,10 @@ import ( "context" "fmt" - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" "mods.irisnet.org/modules/farm/types" ) diff --git a/modules/farm/client/cli/tx.go b/modules/farm/client/cli/tx.go index 88d60530..f9b2d404 100644 --- a/modules/farm/client/cli/tx.go +++ b/modules/farm/client/cli/tx.go @@ -4,13 +4,12 @@ import ( "context" "fmt" - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" "mods.irisnet.org/modules/farm/types" ) diff --git a/modules/farm/depinject.go b/modules/farm/depinject.go index 0d2b4029..bfb7655c 100644 --- a/modules/farm/depinject.go +++ b/modules/farm/depinject.go @@ -3,7 +3,6 @@ package farm import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" - "github.com/cosmos/cosmos-sdk/codec" store "github.com/cosmos/cosmos-sdk/store/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -23,7 +22,7 @@ func init() { } func ProvideKeyTable() types.KeyTable { - return types.ParamKeyTable() //nolint:staticcheck + return types.ParamKeyTable() } var _ appmodule.AppModule = AppModule{} diff --git a/modules/farm/genesis.go b/modules/farm/genesis.go index a9493d91..d28f5aab 100644 --- a/modules/farm/genesis.go +++ b/modules/farm/genesis.go @@ -34,7 +34,9 @@ func InitGenesis(ctx sdk.Context, k keeper.Keeper, data types.GenesisState) { k.SetEscrowInfo(ctx, info) } k.SetSequence(ctx, data.Sequence) - k.SetParams(ctx, data.Params) + if err := k.SetParams(ctx, data.Params); err != nil { + panic(err) + } } // ExportGenesis outputs the genesis state diff --git a/modules/farm/keeper/depinject_test.go b/modules/farm/keeper/depinject_test.go index 1b8a9eb5..ccdcebd8 100644 --- a/modules/farm/keeper/depinject_test.go +++ b/modules/farm/keeper/depinject_test.go @@ -26,8 +26,6 @@ import ( upgrademodulev1 "cosmossdk.io/api/cosmos/upgrade/module/v1" vestingmodulev1 "cosmossdk.io/api/cosmos/vesting/module/v1" "cosmossdk.io/core/appconfig" - "google.golang.org/protobuf/types/known/durationpb" - sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" @@ -47,11 +45,11 @@ import ( slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + "google.golang.org/protobuf/types/known/durationpb" farmmodule "mods.irisnet.org/api/irismod/farm/module/v1" - farmtypes "mods.irisnet.org/modules/farm/types" - _ "mods.irisnet.org/modules/farm" + farmtypes "mods.irisnet.org/modules/farm/types" ) var ( @@ -262,9 +260,9 @@ var ( }) ) -type mockCoinswapKeeper struct {} +type mockCoinswapKeeper struct{} func (mck *mockCoinswapKeeper) ValidatePool(ctx sdk.Context, lptDenom string) error { fmt.Println("mock coinswap keeper") return nil -} \ No newline at end of file +} diff --git a/modules/farm/keeper/farmer.go b/modules/farm/keeper/farmer.go index 65d6d989..ae1f4a7a 100644 --- a/modules/farm/keeper/farmer.go +++ b/modules/farm/keeper/farmer.go @@ -48,7 +48,7 @@ func (k Keeper) Stake( return reward, err } - //update pool reward shards + // update pool reward shards pool, _, err = k.updatePool(ctx, pool, lpToken.Amount, false) if err != nil { return nil, err @@ -65,7 +65,7 @@ func (k Keeper) Stake( } rewards, rewardDebt := pool.CaclRewards(farmInfo, lpToken.Amount) - //reward users + // reward users if rewards.IsAllPositive() { if err = k.bk.SendCoinsFromModuleToAccount(ctx, types.RewardCollector, sender, rewards); err != nil { return reward, err @@ -85,7 +85,7 @@ func (k Keeper) Unstake(ctx sdk.Context, poolId string, lpToken sdk.Coin, sender return nil, errorsmod.Wrapf(types.ErrPoolNotFound, poolId) } - //lpToken demon must be same as pool.TotalLptLocked.Denom + // lpToken demon must be same as pool.TotalLptLocked.Denom if lpToken.Denom != pool.TotalLptLocked.Denom { return nil, errorsmod.Wrapf( types.ErrNotMatch, @@ -94,7 +94,7 @@ func (k Keeper) Unstake(ctx sdk.Context, poolId string, lpToken sdk.Coin, sender ) } - //farmInfo must be exist + // farmInfo must be exist farmInfo, exist := k.GetFarmInfo(ctx, poolId, sender.String()) if !exist { return nil, errorsmod.Wrapf( @@ -104,7 +104,7 @@ func (k Keeper) Unstake(ctx sdk.Context, poolId string, lpToken sdk.Coin, sender ) } - //the lp token unstaked must be less than staked + // the lp token unstaked must be less than staked if farmInfo.Locked.LT(lpToken.Amount) { return nil, errorsmod.Wrapf( sdkerrors.ErrInsufficientFunds, @@ -113,7 +113,7 @@ func (k Keeper) Unstake(ctx sdk.Context, poolId string, lpToken sdk.Coin, sender ) } - //the lp token unstaked must be less than pool + // the lp token unstaked must be less than pool if pool.TotalLptLocked.Amount.LT(lpToken.Amount) { return nil, errorsmod.Wrapf( sdkerrors.ErrInsufficientFunds, @@ -123,27 +123,27 @@ func (k Keeper) Unstake(ctx sdk.Context, poolId string, lpToken sdk.Coin, sender } if k.Expired(ctx, pool) { - //If the farm has ended, the reward rules cannot be updated + // If the farm has ended, the reward rules cannot be updated pool.Rules = k.GetRewardRules(ctx, pool.Id) pool.TotalLptLocked = pool.TotalLptLocked.Sub(lpToken) k.SetPool(ctx, pool) } else { - //update pool reward shards + // update pool reward shards pool, _, err = k.updatePool(ctx, pool, lpToken.Amount.Neg(), false) if err != nil { return nil, err } } - //unstake lpToken to sender account + // unstake lpToken to sender account if err = k.bk.SendCoinsFromModuleToAccount(ctx, types.ModuleName, sender, sdk.NewCoins(lpToken)); err != nil { return nil, err } - //compute farmer rewards + // compute farmer rewards rewards, rewardDebt := pool.CaclRewards(farmInfo, lpToken.Amount.Neg()) if rewards.IsAllPositive() { - //distribute reward + // distribute reward if err = k.bk.SendCoinsFromModuleToAccount(ctx, types.RewardCollector, sender, rewards); err != nil { return nil, err } @@ -184,14 +184,14 @@ func (k Keeper) Harvest(ctx sdk.Context, poolId string, sender sdk.AccAddress) ( } amtAdded := sdk.ZeroInt() - //update pool reward shards + // update pool reward shards pool, _, err := k.updatePool(ctx, pool, amtAdded, false) if err != nil { return nil, err } rewards, rewardDebt := pool.CaclRewards(farmInfo, amtAdded) - //reward users + // reward users if rewards.IsAllPositive() { if err = k.bk.SendCoinsFromModuleToAccount(ctx, types.RewardCollector, sender, rewards); err != nil { return nil, err @@ -205,7 +205,7 @@ func (k Keeper) Harvest(ctx sdk.Context, poolId string, sender sdk.AccAddress) ( // Refund refund the remaining reward to pool creator func (k Keeper) Refund(ctx sdk.Context, pool types.FarmPool) (sdk.Coins, error) { - //remove from active Pool + // remove from active Pool k.DequeueActivePool(ctx, pool.Id, pool.EndHeight) pool, _, err := k.updatePool(ctx, pool, sdk.ZeroInt(), true) if err != nil { @@ -238,7 +238,7 @@ func (k Keeper) Refund(ctx sdk.Context, pool types.FarmPool) (sdk.Coins, error) return refundTotal, k.refundToFeePool(ctx, types.ModuleName, refundTotal) } - //refund the total remaining reward to creator + // refund the total remaining reward to creator if err := k.bk.SendCoinsFromModuleToAccount(ctx, types.ModuleName, creator, refundTotal); err != nil { return nil, err } diff --git a/modules/farm/keeper/fees.go b/modules/farm/keeper/fees.go index 554eb6d7..cfe2c274 100644 --- a/modules/farm/keeper/fees.go +++ b/modules/farm/keeper/fees.go @@ -1,4 +1,3 @@ -// nolint package keeper import ( diff --git a/modules/farm/keeper/grpc_query.go b/modules/farm/keeper/grpc_query.go index 08a81fb6..80ca5bde 100644 --- a/modules/farm/keeper/grpc_query.go +++ b/modules/farm/keeper/grpc_query.go @@ -4,12 +4,11 @@ import ( "context" errorsmod "cosmossdk.io/errors" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "mods.irisnet.org/modules/farm/types" ) @@ -21,7 +20,7 @@ func (k Keeper) FarmPools(goctx context.Context, request *types.QueryFarmPoolsRe var list []*types.FarmPoolEntry prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.FarmPoolKey) - pageRes, err := query.Paginate(prefixStore, request.Pagination, func(_ []byte, value []byte) error { + pageRes, err := query.Paginate(prefixStore, request.Pagination, func(_, value []byte) error { var pool types.FarmPool k.cdc.MustUnmarshal(value, &pool) var totalReward sdk.Coins @@ -58,7 +57,8 @@ func (k Keeper) FarmPools(goctx context.Context, request *types.QueryFarmPoolsRe } func (k Keeper) FarmPool(goctx context.Context, - request *types.QueryFarmPoolRequest) (*types.QueryFarmPoolResponse, error) { + request *types.QueryFarmPoolRequest, +) (*types.QueryFarmPoolResponse, error) { if request == nil { return nil, status.Errorf(codes.InvalidArgument, "empty request") } @@ -125,7 +125,7 @@ func (k Keeper) Farmer(goctx context.Context, request *types.QueryFarmerRequest) return nil, errorsmod.Wrapf(types.ErrPoolNotFound, farmer.PoolId) } - //The farm pool has not started, no reward + // The farm pool has not started, no reward if pool.StartHeight > ctx.BlockHeight() { list = append(list, &types.LockedInfo{ PoolId: farmer.PoolId, diff --git a/modules/farm/keeper/keeper.go b/modules/farm/keeper/keeper.go index d4d8d51d..56679b43 100644 --- a/modules/farm/keeper/keeper.go +++ b/modules/farm/keeper/keeper.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/modules/farm/keeper/keeper_test.go b/modules/farm/keeper/keeper_test.go index c66e4dfa..ab31ab2e 100644 --- a/modules/farm/keeper/keeper_test.go +++ b/modules/farm/keeper/keeper_test.go @@ -3,11 +3,10 @@ package keeper_test import ( "testing" + "cosmossdk.io/math" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" "mods.irisnet.org/modules/farm/keeper" @@ -49,17 +48,17 @@ func TestKeeperTestSuite(t *testing.T) { func (suite *KeeperTestSuite) SetupTest() { depInjectOptions := simapp.DepinjectOptions{ - Config: AppConfig, + Config: AppConfig, Providers: []interface{}{ &mockCoinswapKeeper{}, }, Consumers: []interface{}{&suite.keeper}, } - app := simapp.Setup(suite.T(), isCheckTx,depInjectOptions) + app := simapp.Setup(suite.T(), isCheckTx, depInjectOptions) suite.cdc = codec.NewAminoCodec(app.LegacyAmino()) suite.ctx = app.BaseApp.NewContext(isCheckTx, tmproto.Header{Height: 1}) suite.app = app - suite.keeper.SetParams(suite.ctx, types.DefaultParams()) + suite.Require().NoError(suite.keeper.SetParams(suite.ctx, types.DefaultParams()), "set params failed") suite.setTestAddrs() } @@ -95,7 +94,7 @@ func (suite *KeeperTestSuite) TestCreatePool() { suite.Require().Equal(testDestructible, pool.Editable) suite.Require().Equal(testCreator.String(), pool.Creator) - //check reward rules + // check reward rules rules := suite.keeper.GetRewardRules(ctx, pool.Id) suite.Require().Len(rules, len(testRewardPerBlock)) @@ -110,12 +109,12 @@ func (suite *KeeperTestSuite) TestCreatePool() { endHeight, _ := pool.ExpiredHeight() suite.Require().Equal(endHeight, pool.EndHeight) - //check queue + // check queue suite.keeper.IteratorExpiredPool(ctx, pool.EndHeight, func(pool types.FarmPool) { suite.Require().Equal(pool.Id, pool.Id) }) - //check balance + // check balance expectedBal := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, testInitCoinAmt)). Sub(sdk.NewCoins(suite.keeper.CreatePoolFee(ctx))...). Sub(testTotalReward...) @@ -142,14 +141,14 @@ func (suite *KeeperTestSuite) TestDestroyPool() { _, err = suite.keeper.DestroyPool(newCtx, pool.Id, testCreator) suite.Require().NoError(err) - //check farm pool + // check farm pool p, exist := suite.keeper.GetPool(newCtx, pool.Id) suite.Require().True(exist) suite.Require().EqualValues(newCtx.BlockHeight(), p.LastHeightDistrRewards) suite.Require().EqualValues(newCtx.BlockHeight(), p.EndHeight) - //check balance + // check balance expectedBal := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, testInitCoinAmt)). Sub(sdk.NewCoins(suite.keeper.CreatePoolFee(ctx))...) actualBal := suite.app.BankKeeper.GetAllBalances(ctx, testCreator) @@ -182,11 +181,11 @@ func (suite *KeeperTestSuite) TestAppendReward() { ) suite.Require().NoError(err) - //check farm pool + // check farm pool p, exist := suite.keeper.GetPool(ctx, pool.Id) suite.Require().True(exist) - //panic with adding new token as reward + // panic with adding new token as reward rewardAdded := sdk.NewCoins( sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), sdk.NewCoin("uiris", sdk.NewInt(10_000_000)), @@ -210,12 +209,12 @@ func (suite *KeeperTestSuite) TestAppendReward() { ) suite.Require().NoError(err) - //check farm pool + // check farm pool pool2, exist := suite.keeper.GetPool(ctx, p.Id) suite.Require().True(exist) suite.Require().EqualValues(p.EndHeight+10, pool2.EndHeight) - //check reward rules + // check reward rules rules := suite.keeper.GetRewardRules(ctx, pool.Id) suite.Require().Len(rules, len(testRewardPerBlock)) @@ -249,13 +248,13 @@ func (suite *KeeperTestSuite) TestStake() { type args struct { height int64 stakeCoin sdk.Coin - locked sdk.Int + locked math.Int expectReward sdk.Coins debt sdk.Coins rewardPerShare sdk.Dec } - var testcase = []args{ + testcase := []args{ { height: 100, stakeCoin: lpToken, @@ -389,7 +388,7 @@ func (suite *KeeperTestSuite) TestHarvest() { rewardPerShare sdk.Dec } - var testcase = []args{ + testcase := []args{ { index: 1, height: 200, @@ -449,7 +448,7 @@ func (suite *KeeperTestSuite) AssertStake( poolID string, height int64, stakeCoin sdk.Coin, - locked sdk.Int, + locked math.Int, expectReward, debt sdk.Coins, rewardPerShare sdk.Dec, ) { @@ -464,7 +463,7 @@ func (suite *KeeperTestSuite) AssertStake( suite.Require().Equal(debt, info.RewardDebt) suite.Require().Equal(locked, info.Locked) - //check reward rules again + // check reward rules again rules := suite.keeper.GetRewardRules(ctx, poolID) suite.Require().Len(rules, len(testRewardPerBlock)) for _, r := range rules { @@ -482,16 +481,16 @@ func (suite *KeeperTestSuite) AssertUnstake( ) { ctx := suite.app.BaseApp.NewContext(isCheckTx, tmproto.Header{Height: height}) - //check farm pool + // check farm pool poolSrc, _ := suite.keeper.GetPool(ctx, poolID) - //check farm information + // check farm information farmInfoSrc, _ := suite.keeper.GetFarmInfo(ctx, poolID, testFarmer1.String()) reward, err := suite.keeper.Unstake(ctx, poolID, unstakeCoin, testFarmer1) suite.Require().NoError(err) suite.Require().Equal(expectReward, reward) - //check farm information + // check farm information farmInfo, exist := suite.keeper.GetFarmInfo(ctx, poolID, testFarmer1.String()) if unstakeAll { suite.Require().False(exist) @@ -501,13 +500,13 @@ func (suite *KeeperTestSuite) AssertUnstake( suite.Require().Equal(expectDebt, farmInfo.RewardDebt) } - //check farm pool + // check farm pool pool, exist := suite.keeper.GetPool(ctx, poolID) suite.Require().True(exist) suite.Require(). Equal(pool.TotalLptLocked.String(), poolSrc.TotalLptLocked.Sub(unstakeCoin).String()) - //check reward rules again + // check reward rules again rules := suite.keeper.GetRewardRules(ctx, poolID) suite.Require().Len(rules, len(testRewardPerBlock)) for _, r := range rules { @@ -533,7 +532,7 @@ func (suite *KeeperTestSuite) AssertHarvest( suite.Require().True(exist) suite.Require().Equal(debt, info.RewardDebt) - //check reward rules again + // check reward rules again rules := suite.keeper.GetRewardRules(ctx, poolID) suite.Require().Len(rules, len(testRewardPerBlock)) for _, r := range rules { diff --git a/modules/farm/keeper/msg_server.go b/modules/farm/keeper/msg_server.go index c99f971c..dcc2c897 100644 --- a/modules/farm/keeper/msg_server.go +++ b/modules/farm/keeper/msg_server.go @@ -35,8 +35,8 @@ func (m msgServer) CreatePool( } ctx := sdk.UnwrapSDKContext(goCtx) - //check valid begin height - if ctx.BlockHeight() > int64(msg.StartHeight) { + // check valid begin height + if ctx.BlockHeight() > msg.StartHeight { return nil, errorsmod.Wrapf( types.ErrExpiredHeight, "The current block height[%d] is greater than StartHeight[%d]", @@ -54,7 +54,7 @@ func (m msgServer) CreatePool( ) } - //check valid lp token denom + // check valid lp token denom if err := m.k.ck.ValidatePool(ctx, msg.LptDenom); err != nil { return nil, errorsmod.Wrapf( types.ErrInvalidLPToken, @@ -106,7 +106,7 @@ func (m msgServer) CreatePoolWithCommunityPool( ) } - //check valid lp token denom + // check valid lp token denom if err := m.k.ck.ValidatePool(ctx, msg.Content.LptDenom); err != nil { return nil, errorsmod.Wrapf( types.ErrInvalidLPToken, @@ -115,13 +115,13 @@ func (m msgServer) CreatePoolWithCommunityPool( ) } - //escrow FundSelfBond to EscrowCollector + // escrow FundSelfBond to EscrowCollector if err := m.k.bk.SendCoinsFromAccountToModule(ctx, proposer, types.EscrowCollector, msg.Content.FundSelfBond); err != nil { return nil, err } - //escrow FundApplied to EscrowCollector + // escrow FundApplied to EscrowCollector if err := m.k.escrowFromFeePool(ctx, msg.Content.FundApplied); err != nil { return nil, err } @@ -138,7 +138,7 @@ func (m msgServer) CreatePoolWithCommunityPool( }, } - //create new proposal given a content + // create new proposal given a content proposal, err := m.k.gk.SubmitProposal( ctx, msgs, diff --git a/modules/farm/keeper/params.go b/modules/farm/keeper/params.go index e814ad7b..3510c801 100644 --- a/modules/farm/keeper/params.go +++ b/modules/farm/keeper/params.go @@ -24,7 +24,7 @@ func (k Keeper) TaxRate(ctx sdk.Context) sdk.Dec { // GetParams sets the farm module parameters. func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { store := ctx.KVStore(k.storeKey) - bz := store.Get([]byte(types.ParamsKey)) + bz := store.Get(types.ParamsKey) if bz == nil { return params } diff --git a/modules/farm/keeper/pool.go b/modules/farm/keeper/pool.go index 333d1fa6..a949047e 100644 --- a/modules/farm/keeper/pool.go +++ b/modules/farm/keeper/pool.go @@ -4,6 +4,7 @@ import ( "fmt" errorsmod "cosmossdk.io/errors" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -25,7 +26,7 @@ func (k Keeper) CreatePool( if err := k.DeductPoolCreationFee(ctx, creator); err != nil { return nil, err } - //Escrow total reward + // Escrow total reward if err := k.bk.SendCoinsFromAccountToModule(ctx, creator, types.ModuleName, totalReward); err != nil { return nil, err @@ -63,32 +64,32 @@ func (k Keeper) DestroyPool(ctx sdk.Context, poolId string, creator sdk.AccAddre // AdjustPool adjusts farm pool parameters func (k Keeper) AdjustPool( ctx sdk.Context, - poolId string, + poolID string, reward sdk.Coins, rewardPerBlock sdk.Coins, creator sdk.AccAddress, ) (err error) { - pool, exist := k.GetPool(ctx, poolId) - //check if the liquidity pool exists + pool, exist := k.GetPool(ctx, poolID) + // check if the liquidity pool exists if !exist { - return errorsmod.Wrapf(types.ErrPoolNotFound, poolId) + return errorsmod.Wrapf(types.ErrPoolNotFound, poolID) } if !pool.Editable { return errorsmod.Wrapf( - types.ErrInvalidOperate, "pool [%s] is not editable", poolId) + types.ErrInvalidOperate, "pool [%s] is not editable", poolID) } - //check permissions + // check permissions if creator.String() != pool.Creator { return errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "creator [%s] is not the creator of the pool", creator.String()) } - //check for expiration + // check for expiration if k.Expired(ctx, pool) { return errorsmod.Wrapf(types.ErrPoolExpired, "pool [%s] has expired at height[%d], current [%d]", - poolId, + poolID, pool.EndHeight, ctx.BlockHeight(), ) @@ -109,13 +110,13 @@ func (k Keeper) AdjustPool( startHeight = ctx.BlockHeight() } - //update pool reward shards + // update pool reward shards pool, _, err = k.updatePool(ctx, pool, sdk.ZeroInt(), false) if err != nil { return err } - //update pool TotalReward、RemainingReward + // update pool TotalReward、RemainingReward rules = types.RewardRules(pool.Rules) if reward != nil { if err := k.bk.SendCoinsFromAccountToModule(ctx, @@ -144,10 +145,10 @@ func (k Keeper) AdjustPool( availableReward = remainingReward.Add(reward...) } - pool.Rules = types.RewardRules(rules).UpdateWith(rewardPerBlock) + pool.Rules = rules.UpdateWith(rewardPerBlock) k.SetRewardRules(ctx, pool.Id, pool.Rules) - //expiredHeight = [(srcEndHeight-beginPoint)*srcRewardPerBlock +appendReward]/RewardPerBlock + beginPoint + // expiredHeight = [(srcEndHeight-beginPoint)*srcRewardPerBlock +appendReward]/RewardPerBlock + beginPoint rewardsPerBlock := types.RewardRules(pool.Rules).RewardsPerBlock() availableHeight := availableReward[0].Amount.Quo(rewardsPerBlock.AmountOf(availableReward[0].Denom)).Int64() for _, c := range availableReward[1:] { @@ -158,7 +159,7 @@ func (k Keeper) AdjustPool( } } expiredHeight := startHeight + availableHeight - //if the expiration height does not change, + // if the expiration height does not change, // there is no need to update the pool and the expired queue if expiredHeight == pool.EndHeight { return nil @@ -224,7 +225,7 @@ func (k Keeper) createPool( func (k Keeper) updatePool( ctx sdk.Context, pool types.FarmPool, - amount sdk.Int, + amount math.Int, isDestroy bool, ) (types.FarmPool, sdk.Coins, error) { height := ctx.BlockHeight() @@ -241,12 +242,12 @@ func (k Keeper) updatePool( return pool, nil, errorsmod.Wrapf(types.ErrPoolNotFound, pool.Id) } var rewardTotal sdk.Coins - //when there are multiple farm operations in the same block, the value needs to be updated once + // when there are multiple farm operations in the same block, the value needs to be updated once if height > pool.LastHeightDistrRewards && pool.TotalLptLocked.Amount.GT(sdk.ZeroInt()) { blockInterval := height - pool.LastHeightDistrRewards for i := range rules { - rewardCollected := rules[i].RewardPerBlock.MulRaw(int64(blockInterval)) + rewardCollected := rules[i].RewardPerBlock.MulRaw(blockInterval) coinCollected := sdk.NewCoin(rules[i].Reward, rewardCollected) if rules[i].RemainingReward.LT(rewardCollected) { k.Logger(ctx).Error( @@ -270,7 +271,7 @@ func (k Keeper) updatePool( } } - //escrow the collected rewards to the `RewardCollector` account + // escrow the collected rewards to the `RewardCollector` account if rewardTotal.IsAllPositive() { if err := k.bk.SendCoinsFromModuleToModule(ctx, types.ModuleName, types.RewardCollector, rewardTotal); err != nil { return pool, rewardTotal, err diff --git a/modules/farm/keeper/proposal.go b/modules/farm/keeper/proposal.go index 9b729593..9ab77e40 100644 --- a/modules/farm/keeper/proposal.go +++ b/modules/farm/keeper/proposal.go @@ -59,7 +59,7 @@ func (k Keeper) escrowFromFeePool(ctx sdk.Context, amount sdk.Coins) error { // refundToFeePool return the remaining funds of the farm pool to CommunityPool func (k Keeper) refundToFeePool(ctx sdk.Context, fromModule string, refundTotal sdk.Coins) error { - //refund the total remaining reward to creator + // refund the total remaining reward to creator if err := k.bk.SendCoinsFromModuleToModule(ctx, fromModule, k.communityPoolName, refundTotal); err != nil { return err } @@ -74,13 +74,13 @@ func (k Keeper) refundEscrow(ctx sdk.Context, info types.EscrowInfo) { if err != nil { return } - //refund the amount locked by the user + // refund the amount locked by the user if err := k.bk.SendCoinsFromModuleToAccount(ctx, types.EscrowCollector, proposer, info.FundSelfBond); err != nil { return } - //refund the amount locked by the CommunityPool + // refund the amount locked by the CommunityPool if err := k.refundToFeePool(ctx, types.EscrowCollector, sdk.NewCoins(info.FundApplied...)); err != nil { return } diff --git a/modules/farm/keeper/proposal_hook.go b/modules/farm/keeper/proposal_hook.go index b5923fd9..fb3101db 100644 --- a/modules/farm/keeper/proposal_hook.go +++ b/modules/farm/keeper/proposal_hook.go @@ -23,7 +23,7 @@ func (h GovHook) AfterProposalFailedMinDeposit(ctx sdk.Context, proposalID uint6 if !has { return } - //execute refund logic + // execute refund logic h.k.refundEscrow(ctx, info) } @@ -39,13 +39,13 @@ func (h GovHook) AfterProposalVotingPeriodEnded(ctx sdk.Context, proposalID uint return } - //when the proposal is passed, the content of the proposal is executed by the gov module, which is not directly processed here + // when the proposal is passed, the content of the proposal is executed by the gov module, which is not directly processed here if proposal.Status == v1.StatusPassed { h.k.deleteEscrowInfo(ctx, proposalID) return } - //when the proposal is not passed,execute refund logic + // when the proposal is not passed,execute refund logic h.k.refundEscrow(ctx, info) } diff --git a/modules/farm/migrations/v2/migrate.go b/modules/farm/migrations/v2/migrate.go index 3753ae7a..a62dae19 100644 --- a/modules/farm/migrations/v2/migrate.go +++ b/modules/farm/migrations/v2/migrate.go @@ -42,7 +42,7 @@ func Migrate( return err } - //Grant burner permissions to the farm module account + // Grant burner permissions to the farm module account acc := ak.GetModuleAccount(ctx, types.ModuleName) if !acc.HasPermission(authtypes.Burner) { moduleAcc, _ := acc.(*authtypes.ModuleAccount) diff --git a/modules/farm/module.go b/modules/farm/module.go index 44d0914f..241ce872 100644 --- a/modules/farm/module.go +++ b/modules/farm/module.go @@ -5,18 +5,16 @@ import ( "encoding/json" "fmt" - "github.com/gorilla/mux" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" "mods.irisnet.org/modules/farm/client/cli" "mods.irisnet.org/modules/farm/keeper" @@ -68,7 +66,7 @@ func (AppModuleBasic) ValidateGenesis( // RegisterRESTRoutes registers the REST routes for the farm module. func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { - //rest.RegisterHandlers(clientCtx, rtr) + // rest.RegisterHandlers(clientCtx, rtr) } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the farm module. diff --git a/modules/farm/simulation/decoder.go b/modules/farm/simulation/decoder.go index f420ba1e..bd185e39 100644 --- a/modules/farm/simulation/decoder.go +++ b/modules/farm/simulation/decoder.go @@ -47,5 +47,4 @@ func NewDecodeStore(cdc codec.Codec) func(kvA, kvB kv.Pair) string { panic(fmt.Sprintf("invalid farm key prefix %X", kvA.Key[:1])) } } - } diff --git a/modules/farm/simulation/genesis.go b/modules/farm/simulation/genesis.go index 96c61549..a0e8574e 100644 --- a/modules/farm/simulation/genesis.go +++ b/modules/farm/simulation/genesis.go @@ -5,6 +5,7 @@ import ( "fmt" "math/rand" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -19,7 +20,7 @@ const ( // RandomizedGenState generates a random GenesisState for farm func RandomizedGenState(simState *module.SimulationState) { var ( - createPoolFee sdk.Int + createPoolFee math.Int taxRate sdk.Dec maxRewardCategoryN uint32 ) diff --git a/modules/farm/simulation/operations.go b/modules/farm/simulation/operations.go index e2c47bfc..68669265 100644 --- a/modules/farm/simulation/operations.go +++ b/modules/farm/simulation/operations.go @@ -234,7 +234,6 @@ func SimulateMsgCreatePool( } keeper.RewardInvariant(k) return simtypes.NewOperationMsg(msg, true, "", nil), nil, nil - } } diff --git a/modules/farm/spec/01_state.md b/modules/farm/spec/01_state.md index 512ceffc..3abd8bfb 100644 --- a/modules/farm/spec/01_state.md +++ b/modules/farm/spec/01_state.md @@ -39,9 +39,9 @@ type FarmPool struct { type RewardRule struct { Reward string - TotalReward sdk.Int - RemainingReward sdk.Int - RewardPerBlock sdk.Int + TotalReward math.Int + RemainingReward math.Int + RewardPerBlock math.Int RewardPerShare sdk.Dec } ``` @@ -62,9 +62,9 @@ type RewardRule struct { ```go type RewardRule struct { Reward string - TotalReward sdk.Int - RemainingReward sdk.Int - RewardPerBlock sdk.Int + TotalReward math.Int + RemainingReward math.Int + RewardPerBlock math.Int RewardPerShare sdk.Dec } ``` @@ -83,7 +83,7 @@ type RewardRule struct { type FarmInfo struct { PoolId string Address string - Locked sdk.Int + Locked math.Int RewardDebt sdks.Coins } ``` diff --git a/modules/farm/types/codec.go b/modules/farm/types/codec.go index ed247610..e0aad676 100644 --- a/modules/farm/types/codec.go +++ b/modules/farm/types/codec.go @@ -1,14 +1,13 @@ package types import ( - gogotypes "github.com/cosmos/gogoproto/types" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" + gogotypes "github.com/cosmos/gogoproto/types" ) var ( diff --git a/modules/farm/types/event.go b/modules/farm/types/event.go index 99fbd061..90c1129a 100644 --- a/modules/farm/types/event.go +++ b/modules/farm/types/event.go @@ -1,4 +1,3 @@ -// nolint package types // farm module event types diff --git a/modules/farm/types/farm.go b/modules/farm/types/farm.go index ebd4e47a..d90ec73f 100644 --- a/modules/farm/types/farm.go +++ b/modules/farm/types/farm.go @@ -4,6 +4,7 @@ import ( math "math" errorsmod "cosmossdk.io/errors" + sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -13,7 +14,7 @@ func (pool FarmPool) Started(ctx sdk.Context) bool { } func (pool FarmPool) ExpiredHeight() (int64, error) { - var targetInteval = int64(math.MaxInt64) + targetInteval := int64(math.MaxInt64) for _, r := range pool.Rules { inteval := r.TotalReward.Quo(r.RewardPerBlock).Int64() if targetInteval > inteval { @@ -26,7 +27,7 @@ func (pool FarmPool) ExpiredHeight() (int64, error) { return pool.StartHeight + targetInteval, nil } -func (pool FarmPool) CaclRewards(farmInfo FarmInfo, deltaAmt sdk.Int) (rewards, rewardDebt sdk.Coins) { +func (pool FarmPool) CaclRewards(farmInfo FarmInfo, deltaAmt sdkmath.Int) (rewards, rewardDebt sdk.Coins) { for _, r := range pool.Rules { if farmInfo.Locked.GT(sdk.ZeroInt()) { pendingRewardTotal := r.RewardPerShare.MulInt(farmInfo.Locked).TruncateInt() diff --git a/modules/farm/types/farm_test.go b/modules/farm/types/farm_test.go index 5576f8f1..55255bf5 100644 --- a/modules/farm/types/farm_test.go +++ b/modules/farm/types/farm_test.go @@ -4,6 +4,7 @@ import ( "reflect" "testing" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -71,7 +72,7 @@ func TestFarmPool_CaclRewards(t *testing.T) { } type args struct { farmInfo FarmInfo - deltaAmt sdk.Int + deltaAmt math.Int } tests := []struct { name string diff --git a/modules/farm/types/keys.go b/modules/farm/types/keys.go index 7a9d33ee..a836cb90 100644 --- a/modules/farm/types/keys.go +++ b/modules/farm/types/keys.go @@ -2,7 +2,6 @@ package types import sdk "github.com/cosmos/cosmos-sdk/types" -// nolint const ( // module name ModuleName = "farm" diff --git a/modules/farm/types/params.go b/modules/farm/types/params.go index ee8efb10..a34c0de3 100644 --- a/modules/farm/types/params.go +++ b/modules/farm/types/params.go @@ -3,9 +3,8 @@ package types import ( fmt "fmt" - "sigs.k8s.io/yaml" - sdk "github.com/cosmos/cosmos-sdk/types" + "sigs.k8s.io/yaml" ) // NewParams creates a new Params instance diff --git a/modules/farm/types/params_legacy.go b/modules/farm/types/params_legacy.go index b1b3cd24..757b2bad 100644 --- a/modules/farm/types/params_legacy.go +++ b/modules/farm/types/params_legacy.go @@ -1,7 +1,7 @@ package types // Keys for parameter access -// nolint + var ( KeyPoolCreationFee = []byte("CreatePoolFee") KeyTaxRate = []byte("TaxRate") // fee key @@ -21,7 +21,7 @@ func (p *Params) ParamSetPairs() ParamSetPairs { &p.MaxRewardCategories, validateMaxRewardCategories, ), - NewParamSetPair(KeyTaxRate, &p.TaxRate, validateTaxRate), + NewParamSetPair(KeyTaxRate, &p.TaxRate, validateTaxRate), } } diff --git a/modules/farm/types/validation.go b/modules/farm/types/validation.go index 2eea1e5a..38beb9d1 100644 --- a/modules/farm/types/validation.go +++ b/modules/farm/types/validation.go @@ -65,7 +65,7 @@ func ValidateReward(rewardPerBlock, totalReward sdk.Coins) error { if !totalReward[i].IsGTE(rewardPerBlock[i]) { return errorsmod.Wrapf(ErrNotMatch, "The totalReward should be greater than or equal to rewardPerBlock") } - //uint64 overflow check + // uint64 overflow check h := totalReward[i].Amount.Quo(rewardPerBlock[i].Amount) if !h.IsInt64() { return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "Can not convert to int64, overflow") diff --git a/modules/htlc/abci.go b/modules/htlc/abci.go index edfedd2b..0ecf86d6 100644 --- a/modules/htlc/abci.go +++ b/modules/htlc/abci.go @@ -4,7 +4,6 @@ import ( "fmt" tmbytes "github.com/cometbft/cometbft/libs/bytes" - sdk "github.com/cosmos/cosmos-sdk/types" "mods.irisnet.org/modules/htlc/keeper" diff --git a/modules/htlc/client/cli/flags.go b/modules/htlc/client/cli/flags.go index 5073caf2..2f9f99cc 100644 --- a/modules/htlc/client/cli/flags.go +++ b/modules/htlc/client/cli/flags.go @@ -1,4 +1,3 @@ -// nolint package cli import ( @@ -17,9 +16,7 @@ const ( FlagTransfer = "transfer" ) -var ( - FsCreateHTLC = flag.NewFlagSet("", flag.ContinueOnError) -) +var FsCreateHTLC = flag.NewFlagSet("", flag.ContinueOnError) func init() { FsCreateHTLC.String(FlagTo, "", "Bech32 encoding address to receive tokens") diff --git a/modules/htlc/client/cli/query.go b/modules/htlc/client/cli/query.go index afe86f59..f8ed9acb 100644 --- a/modules/htlc/client/cli/query.go +++ b/modules/htlc/client/cli/query.go @@ -5,13 +5,11 @@ import ( "encoding/hex" "fmt" - "github.com/spf13/cobra" - tmbytes "github.com/cometbft/cometbft/libs/bytes" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" "mods.irisnet.org/modules/htlc/types" ) @@ -90,7 +88,6 @@ func GetCmdQueryAssetSupply() *cobra.Command { } return clientCtx.PrintProto(response.AssetSupply) - }, } flags.AddQueryFlagsToCmd(cmd) diff --git a/modules/htlc/client/cli/tx.go b/modules/htlc/client/cli/tx.go index de4aac26..eff4ed31 100644 --- a/modules/htlc/client/cli/tx.go +++ b/modules/htlc/client/cli/tx.go @@ -6,13 +6,12 @@ import ( "fmt" "strings" - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" "mods.irisnet.org/modules/htlc/types" ) diff --git a/modules/htlc/depinject.go b/modules/htlc/depinject.go index 764e369e..1b0ac44b 100644 --- a/modules/htlc/depinject.go +++ b/modules/htlc/depinject.go @@ -3,7 +3,6 @@ package htlc import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" - "github.com/cosmos/cosmos-sdk/codec" store "github.com/cosmos/cosmos-sdk/store/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -22,7 +21,7 @@ func init() { } func ProvideKeyTable() types.KeyTable { - return types.ParamKeyTable() //nolint:staticcheck + return types.ParamKeyTable() } var _ appmodule.AppModule = AppModule{} diff --git a/modules/htlc/genesis.go b/modules/htlc/genesis.go index 465bb375..5fc41f6a 100644 --- a/modules/htlc/genesis.go +++ b/modules/htlc/genesis.go @@ -18,7 +18,9 @@ func InitGenesis(ctx sdk.Context, k keeper.Keeper, data types.GenesisState) { } k.SetPreviousBlockTime(ctx, data.PreviousBlockTime) - k.SetParams(ctx, data.Params) + if err := k.SetParams(ctx, data.Params); err != nil { + panic(err.Error()) + } for _, supply := range data.Supplies { k.SetAssetSupply(ctx, supply, supply.CurrentSupply.Denom) } diff --git a/modules/htlc/go.mod b/modules/htlc/go.mod index db8cfe2c..fe0cda3e 100644 --- a/modules/htlc/go.mod +++ b/modules/htlc/go.mod @@ -7,6 +7,7 @@ require ( cosmossdk.io/core v0.5.1 cosmossdk.io/depinject v1.0.0-alpha.4 cosmossdk.io/errors v1.0.1 + cosmossdk.io/math v1.2.0 github.com/cometbft/cometbft v0.37.4 github.com/cosmos/cosmos-proto v1.0.0-beta.4 github.com/cosmos/cosmos-sdk v0.47.9 @@ -32,7 +33,6 @@ require ( cloud.google.com/go/iam v1.1.5 // indirect cloud.google.com/go/storage v1.30.1 // indirect cosmossdk.io/log v1.3.1 // indirect - cosmossdk.io/math v1.2.0 // indirect cosmossdk.io/tools/rosetta v0.2.1 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect diff --git a/modules/htlc/integration_test.go b/modules/htlc/integration_test.go index 6d182f31..c45b7b1f 100644 --- a/modules/htlc/integration_test.go +++ b/modules/htlc/integration_test.go @@ -6,7 +6,6 @@ import ( "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/crypto/secp256k1" - sdk "github.com/cosmos/cosmos-sdk/types" "mods.irisnet.org/modules/htlc/types" @@ -21,22 +20,6 @@ var ( SenderOnOtherChain = "SenderOnOtherChain" ) -func i(in int64) sdk.Int { - return sdk.NewInt(in) -} - -func c(denom string, amount int64) sdk.Coin { - return sdk.NewInt64Coin(denom, amount) -} - -func cs(coins ...sdk.Coin) sdk.Coins { - return sdk.NewCoins(coins...) -} - -func ts(minOffset int) uint64 { - return uint64(time.Now().Add(time.Duration(minOffset) * time.Minute).Unix()) -} - func NewHTLTGenesis(deputyAddress sdk.AccAddress) *types.GenesisState { return &types.GenesisState{ Params: types.Params{ @@ -118,39 +101,3 @@ func GenerateRandomSecret() ([]byte, error) { } return bytes, nil } - -func loadSwapAndSupply(addr sdk.AccAddress, index int) (types.HTLC, types.AssetSupply) { - coin := c(DenomMap[index], 50000) - expireOffset := MinTimeLock - timestamp := ts(index) - amount := cs(coin) - randomSecret, _ := GenerateRandomSecret() - randomHashLock := types.GetHashLock(randomSecret, timestamp) - id := types.GetID(addr, addr, amount, randomHashLock) - htlc := types.NewHTLC( - id, - addr, - addr, - ReceiverOnOtherChain, - SenderOnOtherChain, - amount, - randomHashLock, - []byte{}, - timestamp, - expireOffset, - types.Open, - 1, - true, - types.Incoming, - ) - - supply := types.NewAssetSupply( - coin, - c(coin.Denom, 0), - c(coin.Denom, 0), - c(coin.Denom, 0), - time.Duration(0), - ) - - return htlc, supply -} diff --git a/modules/htlc/keeper/asset.go b/modules/htlc/keeper/asset.go index 449222d9..f0b1c25c 100644 --- a/modules/htlc/keeper/asset.go +++ b/modules/htlc/keeper/asset.go @@ -3,10 +3,9 @@ package keeper import ( "time" - gogotypes "github.com/cosmos/gogoproto/types" - errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + gogotypes "github.com/cosmos/gogoproto/types" "mods.irisnet.org/modules/htlc/types" ) @@ -58,7 +57,7 @@ func (k Keeper) DecrementCurrentAssetSupply(ctx sdk.Context, coin sdk.Coin) erro } // Resulting current supply must be greater than or equal to 0 - // Use sdk.Int instead of sdk.Coin to prevent panic if true + // Use math.Int instead of sdk.Coin to prevent panic if true if supply.CurrentSupply.Amount.Sub(coin.Amount).IsNegative() { return errorsmod.Wrapf( types.ErrInvalidCurrentSupply, @@ -123,7 +122,7 @@ func (k Keeper) DecrementIncomingAssetSupply(ctx sdk.Context, coin sdk.Coin) err } // Resulting incoming supply must be greater than or equal to 0 - // Use sdk.Int instead of sdk.Coin to prevent panic if true + // Use math.Int instead of sdk.Coin to prevent panic if true if supply.IncomingSupply.Amount.Sub(coin.Amount).IsNegative() { return errorsmod.Wrapf( types.ErrInvalidIncomingSupply, @@ -167,7 +166,7 @@ func (k Keeper) DecrementOutgoingAssetSupply(ctx sdk.Context, coin sdk.Coin) err } // Resulting outgoing supply must be greater than or equal to 0 - // Use sdk.Int instead of sdk.Coin to prevent panic if true + // Use math.Int instead of sdk.Coin to prevent panic if true if supply.OutgoingSupply.Amount.Sub(coin.Amount).IsNegative() { return errorsmod.Wrapf( types.ErrInvalidOutgoingSupply, diff --git a/modules/htlc/keeper/asset_test.go b/modules/htlc/keeper/asset_test.go index 7d0e1597..ba89cb30 100644 --- a/modules/htlc/keeper/asset_test.go +++ b/modules/htlc/keeper/asset_test.go @@ -5,12 +5,10 @@ import ( "testing" "time" - "github.com/stretchr/testify/suite" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" "mods.irisnet.org/modules/htlc/keeper" "mods.irisnet.org/modules/htlc/types" @@ -53,7 +51,7 @@ func (suite *AssetTestSuite) setTestParams() { params.AssetParams[0].SupplyLimit.Limit = sdk.NewInt(50) params.AssetParams[1].SupplyLimit.Limit = sdk.NewInt(100) params.AssetParams[1].SupplyLimit.TimeBasedLimit = sdk.NewInt(15) - suite.keeper.SetParams(suite.ctx, params) + suite.NoError(suite.keeper.SetParams(suite.ctx, params), "set params failed") bnbSupply := types.NewAssetSupply( c("htltbnb", 5), @@ -149,7 +147,8 @@ func (suite *AssetTestSuite) TestIncrementTimeLimitedCurrentAssetSupply() { OutgoingSupply: c("htltinc", 5), CurrentSupply: c("htltinc", 10), TimeLimitedCurrentSupply: c("htltinc", 5), - TimeElapsed: time.Duration(0)}, + TimeElapsed: time.Duration(0), + }, }, errArgs{ expectPass: true, @@ -308,7 +307,8 @@ func (suite *AssetTestSuite) TestIncrementTimeLimitedIncomingAssetSupply() { OutgoingSupply: c("htltinc", 5), CurrentSupply: c("htltinc", 5), TimeLimitedCurrentSupply: c("htltinc", 0), - TimeElapsed: time.Duration(0)}, + TimeElapsed: time.Duration(0), + }, }, errArgs{ expectPass: true, @@ -686,7 +686,7 @@ func (suite *AssetTestSuite) TestUpdateTimeBasedSupplyLimits() { MaxBlockLock: MaxTimeLock, }}, } - suite.keeper.SetParams(suite.ctx, newParams) + suite.Require().NoError(suite.keeper.SetParams(suite.ctx, newParams), "SetParams should not panic") suite.ctx = suite.ctx.WithBlockTime(suite.ctx.BlockTime().Add(tc.args.duration)) suite.NotPanics( func() { diff --git a/modules/htlc/keeper/depinject_test.go b/modules/htlc/keeper/depinject_test.go index 27086975..7e94b180 100644 --- a/modules/htlc/keeper/depinject_test.go +++ b/modules/htlc/keeper/depinject_test.go @@ -25,8 +25,6 @@ import ( upgrademodulev1 "cosmossdk.io/api/cosmos/upgrade/module/v1" vestingmodulev1 "cosmossdk.io/api/cosmos/vesting/module/v1" "cosmossdk.io/core/appconfig" - "google.golang.org/protobuf/types/known/durationpb" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" "github.com/cosmos/cosmos-sdk/x/authz" @@ -45,6 +43,7 @@ import ( slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + "google.golang.org/protobuf/types/known/durationpb" htlcmodule "mods.irisnet.org/api/irismod/htlc/module/v1" _ "mods.irisnet.org/modules/htlc" diff --git a/modules/htlc/keeper/grpc_query.go b/modules/htlc/keeper/grpc_query.go index e9986015..53026a72 100644 --- a/modules/htlc/keeper/grpc_query.go +++ b/modules/htlc/keeper/grpc_query.go @@ -4,11 +4,10 @@ import ( "context" "encoding/hex" + sdk "github.com/cosmos/cosmos-sdk/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - sdk "github.com/cosmos/cosmos-sdk/types" - "mods.irisnet.org/modules/htlc/types" ) @@ -35,7 +34,7 @@ func (k Keeper) AssetSupply(c context.Context, request *types.QueryAssetSupplyRe assetSupply, found := k.GetAssetSupply(ctx, request.Denom) if !found { - return nil, status.Errorf(codes.NotFound, string(request.Denom)) + return nil, status.Errorf(codes.NotFound, request.Denom) } return &types.QueryAssetSupplyResponse{AssetSupply: &assetSupply}, nil diff --git a/modules/htlc/keeper/grpc_query_test.go b/modules/htlc/keeper/grpc_query_test.go index 13aa34fb..a94e2270 100644 --- a/modules/htlc/keeper/grpc_query_test.go +++ b/modules/htlc/keeper/grpc_query_test.go @@ -6,14 +6,12 @@ import ( "testing" "time" - "github.com/stretchr/testify/suite" - tmbytes "github.com/cometbft/cometbft/libs/bytes" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" "mods.irisnet.org/modules/htlc/keeper" "mods.irisnet.org/modules/htlc/types" diff --git a/modules/htlc/keeper/htlc.go b/modules/htlc/keeper/htlc.go index 7aedc9fc..a957ce88 100644 --- a/modules/htlc/keeper/htlc.go +++ b/modules/htlc/keeper/htlc.go @@ -6,9 +6,8 @@ import ( "fmt" "time" - tmbytes "github.com/cometbft/cometbft/libs/bytes" - errorsmod "cosmossdk.io/errors" + tmbytes "github.com/cometbft/cometbft/libs/bytes" sdk "github.com/cosmos/cosmos-sdk/types" "mods.irisnet.org/modules/htlc/types" diff --git a/modules/htlc/keeper/htlc_test.go b/modules/htlc/keeper/htlc_test.go index 8b8ef19a..e5b01b30 100644 --- a/modules/htlc/keeper/htlc_test.go +++ b/modules/htlc/keeper/htlc_test.go @@ -4,13 +4,11 @@ import ( "testing" "time" - "github.com/stretchr/testify/suite" - tmbytes "github.com/cometbft/cometbft/libs/bytes" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" "mods.irisnet.org/modules/htlc" "mods.irisnet.org/modules/htlc/keeper" @@ -86,7 +84,7 @@ func (suite *HTLCTestSuite) SetupTest() { func (suite *HTLCTestSuite) setTestParams() { params := suite.keeper.GetParams(suite.ctx) params.AssetParams[1].Active = true - suite.keeper.SetParams(suite.ctx, params) + suite.NoError(suite.keeper.SetParams(suite.ctx, params), "set params failed") } func (suite *HTLCTestSuite) GenerateHTLCDetails() { @@ -201,7 +199,6 @@ func (suite *HTLCTestSuite) TestCreateHTLC() { true, }, { - "outgoing htlt amount not greater than fixed fee", currentTmTime, args{ diff --git a/modules/htlc/keeper/integration_test.go b/modules/htlc/keeper/integration_test.go index 7b3d4ecd..0fb0fe90 100644 --- a/modules/htlc/keeper/integration_test.go +++ b/modules/htlc/keeper/integration_test.go @@ -6,7 +6,6 @@ import ( "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/crypto/secp256k1" - sdk "github.com/cosmos/cosmos-sdk/types" "mods.irisnet.org/modules/htlc/types" diff --git a/modules/htlc/keeper/keeper.go b/modules/htlc/keeper/keeper.go index 0ddc4688..09a6ad99 100644 --- a/modules/htlc/keeper/keeper.go +++ b/modules/htlc/keeper/keeper.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/modules/htlc/keeper/params.go b/modules/htlc/keeper/params.go index 3b875e5f..52e392ed 100644 --- a/modules/htlc/keeper/params.go +++ b/modules/htlc/keeper/params.go @@ -2,6 +2,7 @@ package keeper import ( errorsmod "cosmossdk.io/errors" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "mods.irisnet.org/modules/htlc/types" @@ -10,7 +11,7 @@ import ( // GetParams sets the farm module parameters. func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { store := ctx.KVStore(k.storeKey) - bz := store.Get([]byte(types.ParamsKey)) + bz := store.Get(types.ParamsKey) if bz == nil { return params } @@ -63,7 +64,7 @@ func (k Keeper) SetAsset(ctx sdk.Context, asset types.AssetParam) { params.AssetParams[i] = asset } } - k.SetParams(ctx, params) + _ = k.SetParams(ctx, params) } // GetAssets returns a list containing all supported assets @@ -87,28 +88,28 @@ func (k Keeper) GetDeputyAddress(ctx sdk.Context, denom string) (sdk.AccAddress, } // GetFixedFee returns the fixed fee for incoming swaps -func (k Keeper) GetFixedFee(ctx sdk.Context, denom string) (sdk.Int, error) { +func (k Keeper) GetFixedFee(ctx sdk.Context, denom string) (math.Int, error) { asset, err := k.GetAsset(ctx, denom) if err != nil { - return sdk.Int{}, err + return math.Int{}, err } return asset.FixedFee, nil } // GetMinSwapAmount returns the minimum swap amount -func (k Keeper) GetMinSwapAmount(ctx sdk.Context, denom string) (sdk.Int, error) { +func (k Keeper) GetMinSwapAmount(ctx sdk.Context, denom string) (math.Int, error) { asset, err := k.GetAsset(ctx, denom) if err != nil { - return sdk.Int{}, err + return math.Int{}, err } return asset.MinSwapAmount, nil } // GetMaxSwapAmount returns the maximum swap amount -func (k Keeper) GetMaxSwapAmount(ctx sdk.Context, denom string) (sdk.Int, error) { +func (k Keeper) GetMaxSwapAmount(ctx sdk.Context, denom string) (math.Int, error) { asset, err := k.GetAsset(ctx, denom) if err != nil { - return sdk.Int{}, err + return math.Int{}, err } return asset.MaxSwapAmount, nil } diff --git a/modules/htlc/keeper/params_test.go b/modules/htlc/keeper/params_test.go index 960336e3..22355aca 100644 --- a/modules/htlc/keeper/params_test.go +++ b/modules/htlc/keeper/params_test.go @@ -5,12 +5,10 @@ import ( "testing" "time" - "github.com/stretchr/testify/suite" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" "mods.irisnet.org/modules/htlc/keeper" "mods.irisnet.org/modules/htlc/types" @@ -80,7 +78,6 @@ func (suite *ParamsTestSuite) TestGetSetDeputyAddress() { addr, err := suite.keeper.GetDeputyAddress(suite.ctx, "htltbnb") suite.Require().NoError(err) suite.Equal(TestDeputy.String(), addr) - } func (suite *ParamsTestSuite) TestGetDeputyFixedFee() { diff --git a/modules/htlc/module.go b/modules/htlc/module.go index 8da145b7..492b6001 100644 --- a/modules/htlc/module.go +++ b/modules/htlc/module.go @@ -5,18 +5,16 @@ import ( "encoding/json" "fmt" - "github.com/gorilla/mux" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" "mods.irisnet.org/modules/htlc/client/cli" "mods.irisnet.org/modules/htlc/keeper" @@ -67,7 +65,7 @@ func (AppModuleBasic) ValidateGenesis( // RegisterRESTRoutes registers the REST routes for the HTLC module. func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { - //rest.RegisterHandlers(clientCtx, rtr) + // rest.RegisterHandlers(clientCtx, rtr) } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the HTLC module. @@ -131,7 +129,6 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil { panic(err) } - } // RegisterInvariants registers the HTLC module invariants. diff --git a/modules/htlc/simulation/operation.go b/modules/htlc/simulation/operation.go index ce850078..76f0c80d 100644 --- a/modules/htlc/simulation/operation.go +++ b/modules/htlc/simulation/operation.go @@ -6,7 +6,6 @@ import ( "time" tmbytes "github.com/cometbft/cometbft/libs/bytes" - "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" @@ -64,7 +63,6 @@ func SimulateMsgCreateHtlc( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - sender, _ := simtypes.RandomAcc(r, accs) to, _ := simtypes.RandomAcc(r, accs) recvOnOtherChain, _ := simtypes.RandomAcc(r, accs) @@ -155,7 +153,6 @@ func SimulateMsgClaimHtlc( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - htlc := GenRandomHtlc(ctx, k, r) if htlc.Size() == 0 { return simtypes.NoOpMsg( diff --git a/modules/htlc/spec/04_params.md b/modules/htlc/spec/04_params.md index 002e5e98..d20e54b6 100644 --- a/modules/htlc/spec/04_params.md +++ b/modules/htlc/spec/04_params.md @@ -20,17 +20,17 @@ type AssetParam struct { SupplyLimit SupplyLimit Active bool DeputyAddress string - FixedFee sdk.Int - MinSwapAmount sdk.Int - MaxSwapAmount sdk.Int + FixedFee math.Int + MinSwapAmount math.Int + MaxSwapAmount math.Int MinBlockLock uint64 MaxBlockLock uint64 } type SupplyLimit struct { - Limit sdk.Int + Limit math.Int TimeLimited bool TimePeriod time.Duration - TimeBasedLimit sdk.Int + TimeBasedLimit math.Int } ``` diff --git a/modules/htlc/types/conmmon_test.go b/modules/htlc/types/conmmon_test.go index df128dc7..ac662701 100644 --- a/modules/htlc/types/conmmon_test.go +++ b/modules/htlc/types/conmmon_test.go @@ -6,7 +6,6 @@ import ( "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/crypto/secp256k1" - sdk "github.com/cosmos/cosmos-sdk/types" "mods.irisnet.org/modules/htlc/types" diff --git a/modules/htlc/types/events.go b/modules/htlc/types/events.go index a974fc62..3a379709 100644 --- a/modules/htlc/types/events.go +++ b/modules/htlc/types/events.go @@ -1,4 +1,3 @@ -// nolint package types // HTLC module event types and attributes diff --git a/modules/htlc/types/genesis.go b/modules/htlc/types/genesis.go index 23a462a5..bde1c51b 100644 --- a/modules/htlc/types/genesis.go +++ b/modules/htlc/types/genesis.go @@ -8,11 +8,11 @@ import ( ) // NewGenesisState constructs a new GenesisState instance -func NewGenesisState(params Params, htlcs []HTLC, Supplies []AssetSupply, previousBlockTime time.Time) *GenesisState { +func NewGenesisState(params Params, htlcs []HTLC, supplies []AssetSupply, previousBlockTime time.Time) *GenesisState { return &GenesisState{ Params: params, Htlcs: htlcs, - Supplies: Supplies, + Supplies: supplies, PreviousBlockTime: previousBlockTime, } } diff --git a/modules/htlc/types/genesis_test.go b/modules/htlc/types/genesis_test.go index 84101259..129e1fd7 100644 --- a/modules/htlc/types/genesis_test.go +++ b/modules/htlc/types/genesis_test.go @@ -4,9 +4,8 @@ import ( "testing" "time" - "github.com/stretchr/testify/suite" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" "mods.irisnet.org/modules/htlc/types" ) @@ -18,7 +17,6 @@ type GenesisTestSuite struct { } func (suite *GenesisTestSuite) SetupTest() { - coin := sdk.NewCoin("htltbnb", sdk.OneInt()) suite.htlcs = htlcs(10) diff --git a/modules/htlc/types/htlc.go b/modules/htlc/types/htlc.go index ac5129fd..4714ed8c 100644 --- a/modules/htlc/types/htlc.go +++ b/modules/htlc/types/htlc.go @@ -4,10 +4,9 @@ import ( fmt "fmt" time "time" + errorsmod "cosmossdk.io/errors" "github.com/cometbft/cometbft/crypto/tmhash" tmbytes "github.com/cometbft/cometbft/libs/bytes" - - errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) diff --git a/modules/htlc/types/msgs_test.go b/modules/htlc/types/msgs_test.go index c162f5cc..0dc25b2a 100644 --- a/modules/htlc/types/msgs_test.go +++ b/modules/htlc/types/msgs_test.go @@ -5,12 +5,10 @@ import ( "strings" "testing" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/crypto/tmhash" tmbytes "github.com/cometbft/cometbft/libs/bytes" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" "mods.irisnet.org/modules/htlc/types" ) diff --git a/modules/htlc/types/params.go b/modules/htlc/types/params.go index 6814f742..1219ed14 100644 --- a/modules/htlc/types/params.go +++ b/modules/htlc/types/params.go @@ -4,9 +4,9 @@ import ( fmt "fmt" "strings" - "gopkg.in/yaml.v2" - + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" + "gopkg.in/yaml.v2" ) const ( @@ -33,8 +33,8 @@ func (p Params) String() string { func NewAssetParam( denom string, coinID int, limit SupplyLimit, active bool, - deputyAddr string, fixedFee sdk.Int, minSwapAmount sdk.Int, - maxSwapAmount sdk.Int, minBlockLock uint64, maxBlockLock uint64, + deputyAddr string, fixedFee, minSwapAmount math.Int, + maxSwapAmount math.Int, minBlockLock, maxBlockLock uint64, ) AssetParam { return AssetParam{ Denom: denom, diff --git a/modules/htlc/types/params_test.go b/modules/htlc/types/params_test.go index 44e31642..37f188d1 100644 --- a/modules/htlc/types/params_test.go +++ b/modules/htlc/types/params_test.go @@ -4,9 +4,8 @@ import ( "testing" "time" - "github.com/stretchr/testify/suite" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" "mods.irisnet.org/modules/htlc/types" ) @@ -36,7 +35,6 @@ func (suite *ParamsTestSuite) SetupTest() { } func (suite *ParamsTestSuite) TestParamValidation() { - type args struct { assetParams []types.AssetParam } diff --git a/modules/mt/client/cli/query.go b/modules/mt/client/cli/query.go index 0375cb82..e9e36cb0 100644 --- a/modules/mt/client/cli/query.go +++ b/modules/mt/client/cli/query.go @@ -4,11 +4,10 @@ import ( "context" "fmt" - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" "mods.irisnet.org/modules/mt/types" ) diff --git a/modules/mt/client/cli/tx.go b/modules/mt/client/cli/tx.go index 9f4aabeb..e51eeae6 100644 --- a/modules/mt/client/cli/tx.go +++ b/modules/mt/client/cli/tx.go @@ -5,13 +5,12 @@ 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" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" "mods.irisnet.org/modules/mt/types" ) @@ -59,7 +58,7 @@ func GetCmdIssueDenom() *cobra.Command { return err } - var sender = clientCtx.GetFromAddress().String() + sender := clientCtx.GetFromAddress().String() name, err := cmd.Flags().GetString(FlagName) if err != nil { @@ -101,7 +100,10 @@ func GetCmdTransferDenom() *cobra.Command { ), Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { - cmd.Flags().Set(flags.FlagFrom, args[0]) + if err := cmd.Flags().Set(flags.FlagFrom, args[0]); err != nil { + return err + } + clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err @@ -176,7 +178,7 @@ func GetCmdMintMT() *cobra.Command { return err } - var sender = clientCtx.GetFromAddress().String() + sender := clientCtx.GetFromAddress().String() recipient, err := cmd.Flags().GetString(FlagRecipient) if err != nil { @@ -272,7 +274,10 @@ func GetCmdTransferMT() *cobra.Command { ), Args: cobra.ExactArgs(5), RunE: func(cmd *cobra.Command, args []string) error { - cmd.Flags().Set(flags.FlagFrom, args[0]) + if err := cmd.Flags().Set(flags.FlagFrom, args[0]); err != nil { + return err + } + clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err diff --git a/modules/mt/depinject.go b/modules/mt/depinject.go index 9ab6ca38..97b43709 100644 --- a/modules/mt/depinject.go +++ b/modules/mt/depinject.go @@ -3,7 +3,6 @@ package mt import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" - "github.com/cosmos/cosmos-sdk/codec" store "github.com/cosmos/cosmos-sdk/store/types" diff --git a/modules/mt/genesis.go b/modules/mt/genesis.go index e76beda7..357e6282 100644 --- a/modules/mt/genesis.go +++ b/modules/mt/genesis.go @@ -48,9 +48,13 @@ func InitGenesis(ctx sdk.Context, k keeper.Keeper, data types.GenesisState) { for _, d := range o.Denoms { for _, b := range d.Balances { // increase supply - k.IncreaseMTSupply(ctx, d.DenomId, b.MtId, b.Amount) + if err := k.IncreaseMTSupply(ctx, d.DenomId, b.MtId, b.Amount); err != nil { + panic(err) + } // add balance to account - k.AddBalance(ctx, d.DenomId, b.MtId, b.Amount, addr) + if err := k.AddBalance(ctx, d.DenomId, b.MtId, b.Amount, addr); err != nil { + panic(err) + } } } } diff --git a/modules/mt/keeper/balance.go b/modules/mt/keeper/balance.go index 0952a9b2..6dab84ad 100644 --- a/modules/mt/keeper/balance.go +++ b/modules/mt/keeper/balance.go @@ -15,8 +15,8 @@ import ( func (k Keeper) AddBalance(ctx sdk.Context, denomID, mtID string, amount uint64, - addr sdk.AccAddress) error { - + addr sdk.AccAddress, +) error { balance := k.GetBalance(ctx, denomID, mtID, addr) if math.MaxUint64-balance < amount { return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "overflow: max %d, got %d", math.MaxUint64-balance, amount) @@ -33,8 +33,8 @@ func (k Keeper) AddBalance(ctx sdk.Context, func (k Keeper) SubBalance(ctx sdk.Context, denomID, mtID string, amount uint64, - addr sdk.AccAddress) { - + addr sdk.AccAddress, +) { store := ctx.KVStore(k.storeKey) balance := k.GetBalance(ctx, denomID, mtID, addr) balance -= amount @@ -46,8 +46,8 @@ func (k Keeper) SubBalance(ctx sdk.Context, // GetBalance gets balance of an MT func (k Keeper) GetBalance(ctx sdk.Context, denomID, mtID string, - addr sdk.AccAddress) uint64 { - + addr sdk.AccAddress, +) uint64 { store := ctx.KVStore(k.storeKey) amount := store.Get(types.KeyBalance(addr, denomID, mtID)) @@ -60,14 +60,12 @@ func (k Keeper) GetBalance(ctx sdk.Context, // getBalances gets balances of all accounts, should only be used in exporting genesis states func (k Keeper) getBalances(ctx sdk.Context) []types.Owner { - store := ctx.KVStore(k.storeKey) it := sdk.KVStorePrefixIterator(store, types.PrefixBalance) defer it.Close() - var ownerMap map[string]map[string]map[string]uint64 - ownerMap = make(map[string]map[string]map[string]uint64) + ownerMap := make(map[string]map[string]map[string]uint64) for ; it.Valid(); it.Next() { keys := bytes.Split(it.Key(), types.Delimiter) @@ -112,8 +110,8 @@ func (k Keeper) getBalances(ctx sdk.Context) []types.Owner { func (k Keeper) Transfer(ctx sdk.Context, denomID, mtID string, amount uint64, - from, to sdk.AccAddress) error { - + from, to sdk.AccAddress, +) error { k.SubBalance(ctx, denomID, mtID, amount, from) return k.AddBalance(ctx, denomID, mtID, amount, to) diff --git a/modules/mt/keeper/grpc_query.go b/modules/mt/keeper/grpc_query.go index 5ba99a79..ea145574 100644 --- a/modules/mt/keeper/grpc_query.go +++ b/modules/mt/keeper/grpc_query.go @@ -25,7 +25,7 @@ func (k Keeper) Denoms(c context.Context, request *types.QueryDenomsRequest) (*t var denoms []types.Denom store := ctx.KVStore(k.storeKey) denomStore := prefix.NewStore(store, types.KeyDenom("")) - pageRes, err := query.Paginate(denomStore, request.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(denomStore, request.Pagination, func(key, value []byte) error { var denom types.Denom k.cdc.MustUnmarshal(value, &denom) denoms = append(denoms, denom) @@ -45,7 +45,7 @@ func (k Keeper) Denom(c context.Context, request *types.QueryDenomRequest) (*typ ctx := sdk.UnwrapSDKContext(c) denomID := strings.TrimSpace(request.DenomId) - if len(denomID) <= 0 { + if len(denomID) == 0 { return nil, status.Errorf(codes.InvalidArgument, "denom id is required") } @@ -63,11 +63,11 @@ func (k Keeper) MTSupply(c context.Context, request *types.QueryMTSupplyRequest) denomID := strings.TrimSpace(request.DenomId) mtID := strings.TrimSpace(request.MtId) - if len(denomID) <= 0 { + if len(denomID) == 0 { return nil, status.Errorf(codes.InvalidArgument, "denom id is required") } - if len(mtID) <= 0 { + if len(mtID) == 0 { return nil, status.Errorf(codes.InvalidArgument, "mt id is required") } @@ -78,14 +78,14 @@ func (k Keeper) MTs(c context.Context, request *types.QueryMTsRequest) (*types.Q ctx := sdk.UnwrapSDKContext(c) denomID := strings.TrimSpace(request.DenomId) - if len(denomID) <= 0 { + if len(denomID) == 0 { return nil, status.Errorf(codes.InvalidArgument, "denom id is required") } var mts []types.MT store := ctx.KVStore(k.storeKey) mtStore := prefix.NewStore(store, types.KeyMT(denomID, "")) - pageRes, err := query.Paginate(mtStore, request.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(mtStore, request.Pagination, func(key, value []byte) error { var mt types.MT k.cdc.MustUnmarshal(value, &mt) @@ -101,7 +101,6 @@ func (k Keeper) MTs(c context.Context, request *types.QueryMTsRequest) (*types.Q Mts: mts, Pagination: pageRes, }, nil - } func (k Keeper) MT(c context.Context, request *types.QueryMTRequest) (*types.QueryMTResponse, error) { @@ -110,11 +109,11 @@ func (k Keeper) MT(c context.Context, request *types.QueryMTRequest) (*types.Que denomID := strings.TrimSpace(request.DenomId) mtID := strings.TrimSpace(request.MtId) - if len(denomID) <= 0 { + if len(denomID) == 0 { return nil, status.Errorf(codes.InvalidArgument, "denom id is required") } - if len(mtID) <= 0 { + if len(mtID) == 0 { return nil, status.Errorf(codes.InvalidArgument, "mt id is required") } @@ -133,7 +132,7 @@ func (k Keeper) Balances(c context.Context, request *types.QueryBalancesRequest) denomID := strings.TrimSpace(request.DenomId) owner := strings.TrimSpace(request.Owner) - if len(denomID) <= 0 { + if len(denomID) == 0 { return nil, status.Errorf(codes.InvalidArgument, "denom id is required") } @@ -145,7 +144,7 @@ func (k Keeper) Balances(c context.Context, request *types.QueryBalancesRequest) var bals []types.Balance store := ctx.KVStore(k.storeKey) mtStore := prefix.NewStore(store, types.KeyBalance(addr, denomID, "")) - pageRes, err := query.Paginate(mtStore, request.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(mtStore, request.Pagination, func(key, value []byte) error { bal := types.Balance{ MtId: string(key), Amount: types.MustUnMarshalAmount(k.cdc, value), diff --git a/modules/mt/keeper/keeper.go b/modules/mt/keeper/keeper.go index 1971f810..4c5960db 100644 --- a/modules/mt/keeper/keeper.go +++ b/modules/mt/keeper/keeper.go @@ -3,9 +3,8 @@ package keeper import ( "fmt" - "github.com/cometbft/cometbft/libs/log" - errorsmod "cosmossdk.io/errors" + "github.com/cometbft/cometbft/libs/log" "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -57,7 +56,6 @@ func (k Keeper) IssueMT(ctx sdk.Context, data []byte, recipient sdk.AccAddress, ) (types.MT, error) { - mt := types.NewMT(mtID, amount, data) // store MT @@ -119,7 +117,6 @@ func (k Keeper) TransferOwner(ctx sdk.Context, amount uint64, srcOwner, dstOwner sdk.AccAddress, ) error { - srcOwnerAmount := k.GetBalance(ctx, denomID, mtID, srcOwner) if srcOwnerAmount < amount { return errorsmod.Wrapf( @@ -136,8 +133,8 @@ func (k Keeper) TransferOwner(ctx sdk.Context, func (k Keeper) BurnMT(ctx sdk.Context, denomID, mtID string, amount uint64, - owner sdk.AccAddress) error { - + owner sdk.AccAddress, +) error { srcOwnerAmount := k.GetBalance(ctx, denomID, mtID, owner) if srcOwnerAmount < amount { return errorsmod.Wrapf( @@ -160,7 +157,6 @@ func (k Keeper) BurnMT(ctx sdk.Context, func (k Keeper) TransferDenomOwner( ctx sdk.Context, denomID string, srcOwner, dstOwner sdk.AccAddress, ) error { - // authorize if err := k.Authorize(ctx, denomID, srcOwner); err != nil { return err @@ -178,7 +174,6 @@ func (k Keeper) TransferDenomOwner( } func (k Keeper) ExportGenesisState(ctx sdk.Context) *types.GenesisState { - var collections []types.Collection denoms := k.GetDenoms(ctx) for _, d := range denoms { diff --git a/modules/mt/module.go b/modules/mt/module.go index 44094d30..df3149c5 100644 --- a/modules/mt/module.go +++ b/modules/mt/module.go @@ -5,18 +5,16 @@ import ( "encoding/json" "fmt" - "github.com/gorilla/mux" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" "mods.irisnet.org/modules/mt/client/cli" "mods.irisnet.org/modules/mt/keeper" diff --git a/modules/mt/simulation/genesis.go b/modules/mt/simulation/genesis.go index 9d5e830a..2ed919c0 100644 --- a/modules/mt/simulation/genesis.go +++ b/modules/mt/simulation/genesis.go @@ -93,7 +93,7 @@ func RandomizedGenState(simState *module.SimulationState) { var ( collections []mt.Collection owners []mt.Owner - accLen int = 10 + accLen = 10 ) if len(simState.Accounts) < accLen { @@ -124,5 +124,4 @@ func RandomizedGenState(simState *module.SimulationState) { } simState.GenState[mt.ModuleName] = simState.Cdc.MustMarshalJSON(mtGenesis) - } diff --git a/modules/mt/simulation/genesis_test.go b/modules/mt/simulation/genesis_test.go index e5c182b7..ff57d039 100644 --- a/modules/mt/simulation/genesis_test.go +++ b/modules/mt/simulation/genesis_test.go @@ -5,15 +5,14 @@ import ( "math/rand" "testing" - mt "mods.irisnet.org/modules/mt/types" - - "github.com/stretchr/testify/require" - sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/stretchr/testify/require" + + mt "mods.irisnet.org/modules/mt/types" ) func TestRandomizedGenState(t *testing.T) { diff --git a/modules/mt/simulation/operations.go b/modules/mt/simulation/operations.go index 42507be8..7bd1d2bd 100644 --- a/modules/mt/simulation/operations.go +++ b/modules/mt/simulation/operations.go @@ -367,7 +367,6 @@ func SimulateMsgTransferMT( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (OperationMsg simtypes.OperationMsg, futureOps []simtypes.FutureOperation, err error, ) { - mtr, denomID, owner, ok := randMT(ctx, r, k) if !ok { return simtypes.NoOpMsg( diff --git a/modules/mt/types/common_test.go b/modules/mt/types/common_test.go index 2b6134ef..6cb2b438 100644 --- a/modules/mt/types/common_test.go +++ b/modules/mt/types/common_test.go @@ -7,19 +7,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// nolint: deadcode unused -var ( - denomID = "denom" - denom = "denom" - id = "id1" - mtName = "report" - address = CreateTestAddrs(1)[0] - address2 = CreateTestAddrs(2)[1] - tokenURI = "https://google.com/token-1.json" - uriHash = "uriHash" - tokenData = "https://google.com/token-1.json" -) - // CreateTestAddrs creates test addresses func CreateTestAddrs(numAddrs int) []sdk.AccAddress { var addresses []sdk.AccAddress @@ -28,9 +15,9 @@ func CreateTestAddrs(numAddrs int) []sdk.AccAddress { // start at 100 so we can make up to 999 test addresses with valid test addresses for i := 100; i < (numAddrs + 100); i++ { numString := strconv.Itoa(i) - buffer.WriteString("A58856F0FD53BF058B4909A21AEC019107BA6") //base address string + buffer.WriteString("A58856F0FD53BF058B4909A21AEC019107BA6") // base address string - buffer.WriteString(numString) //adding on final two digits to make addresses unique + buffer.WriteString(numString) // adding on final two digits to make addresses unique res, _ := sdk.AccAddressFromHexUnsafe(buffer.String()) bech := res.String() addresses = append(addresses, testAddr(buffer.String(), bech)) @@ -40,7 +27,7 @@ func CreateTestAddrs(numAddrs int) []sdk.AccAddress { } // for incode address generation -func testAddr(addr string, bech string) sdk.AccAddress { +func testAddr(addr, bech string) sdk.AccAddress { res, err := sdk.AccAddressFromHexUnsafe(addr) if err != nil { panic(err) diff --git a/modules/mt/types/genesis.go b/modules/mt/types/genesis.go index 37fd7862..92bb13d8 100644 --- a/modules/mt/types/genesis.go +++ b/modules/mt/types/genesis.go @@ -17,12 +17,8 @@ func NewGenesisState(collections []Collection, owners []Owner) *GenesisState { // ValidateGenesis performs basic validation of mts genesis data returning an // error for any failed validation criteria. func ValidateGenesis(data GenesisState) error { - - var denomMap1 map[string]int - denomMap1 = make(map[string]int) - - var mtMap1 map[string]uint64 - mtMap1 = make(map[string]uint64) + denomMap1 := make(map[string]int) + mtMap1 := make(map[string]uint64) for _, c := range data.Collections { denomMap1[c.Denom.Id] = len(c.Mts) @@ -35,11 +31,8 @@ func ValidateGenesis(data GenesisState) error { mtCount1 := len(mtMap1) // -------------------------- - var denomMap2 map[string]bool - denomMap2 = make(map[string]bool) - - var mtMap2 map[string]uint64 - mtMap2 = make(map[string]uint64) + denomMap2 := make(map[string]bool) + mtMap2 := make(map[string]uint64) for _, o := range data.Owners { for _, d := range o.Denoms { @@ -49,8 +42,7 @@ func ValidateGenesis(data GenesisState) error { return errorsmod.Wrapf(errorsmod.ErrPanic, "unknown mt denom, (%s)", d.DenomId) } for _, b := range d.Balances { - mtMap2[d.DenomId+b.MtId] = mtMap2[d.DenomId+b.MtId] + b.Amount - + mtMap2[d.DenomId+b.MtId] += b.Amount } } } diff --git a/modules/mt/types/msgs.go b/modules/mt/types/msgs.go index 2ff8d7ab..97d5f632 100644 --- a/modules/mt/types/msgs.go +++ b/modules/mt/types/msgs.go @@ -46,8 +46,7 @@ func (msg MsgIssueDenom) Type() string { return TypeMsgIssueDenom } // ValidateBasic Implements Msg. func (msg MsgIssueDenom) ValidateBasic() error { - - if len(strings.TrimSpace(msg.Name)) <= 0 { + if len(strings.TrimSpace(msg.Name)) == 0 { return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "name is required") } @@ -93,11 +92,11 @@ func (msg MsgTransferMT) Type() string { return TypeMsgTransferMT } // ValidateBasic Implements Msg. func (msg MsgTransferMT) ValidateBasic() error { - if len(strings.TrimSpace(msg.Id)) <= 0 { + if len(strings.TrimSpace(msg.Id)) == 0 { return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "mt id is required") } - if len(strings.TrimSpace(msg.DenomId)) <= 0 { + if len(strings.TrimSpace(msg.DenomId)) == 0 { return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "denom id is required") } @@ -150,11 +149,11 @@ func (msg MsgEditMT) Type() string { return TypeMsgEditMT } // ValidateBasic Implements Msg. func (msg MsgEditMT) ValidateBasic() error { - if len(strings.TrimSpace(msg.Id)) <= 0 { + if len(strings.TrimSpace(msg.Id)) == 0 { return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "mt id is required") } - if len(strings.TrimSpace(msg.DenomId)) <= 0 { + if len(strings.TrimSpace(msg.DenomId)) == 0 { return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "denom id is required") } @@ -202,8 +201,7 @@ func (msg MsgMintMT) Type() string { return TypeMsgMintMT } // ValidateBasic Implements Msg. func (msg MsgMintMT) ValidateBasic() error { - - if len(strings.TrimSpace(msg.DenomId)) <= 0 { + if len(strings.TrimSpace(msg.DenomId)) == 0 { return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "denom id is required") } @@ -261,11 +259,11 @@ func (msg MsgBurnMT) Type() string { return TypeMsgBurnMT } // ValidateBasic Implements Msg. func (msg MsgBurnMT) ValidateBasic() error { - if len(strings.TrimSpace(msg.Id)) <= 0 { + if len(strings.TrimSpace(msg.Id)) == 0 { return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "mt id is required") } - if len(strings.TrimSpace(msg.DenomId)) <= 0 { + if len(strings.TrimSpace(msg.DenomId)) == 0 { return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "denom id is required") } @@ -312,7 +310,7 @@ func (msg MsgTransferDenom) Type() string { return TypeMsgTransferDenom } // ValidateBasic Implements Msg. func (msg MsgTransferDenom) ValidateBasic() error { - if len(strings.TrimSpace(msg.Id)) <= 0 { + if len(strings.TrimSpace(msg.Id)) == 0 { return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "denom id is required") } diff --git a/modules/nft/client/cli/query.go b/modules/nft/client/cli/query.go index 80eb2d73..35e76a22 100644 --- a/modules/nft/client/cli/query.go +++ b/modules/nft/client/cli/query.go @@ -4,12 +4,11 @@ import ( "context" "fmt" - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" "mods.irisnet.org/modules/nft/types" ) diff --git a/modules/nft/client/cli/tx.go b/modules/nft/client/cli/tx.go index b7189b4e..880867a1 100644 --- a/modules/nft/client/cli/tx.go +++ b/modules/nft/client/cli/tx.go @@ -2,16 +2,15 @@ package cli import ( "fmt" - "io/ioutil" + "os" "strings" - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" "mods.irisnet.org/modules/nft/types" ) @@ -102,7 +101,7 @@ func GetCmdIssueDenom() *cobra.Command { if err != nil { return err } - optionsContent, err := ioutil.ReadFile(schema) + optionsContent, err := os.ReadFile(schema) if err == nil { schema = string(optionsContent) } @@ -156,7 +155,7 @@ func GetCmdMintNFT() *cobra.Command { return err } - var sender = clientCtx.GetFromAddress().String() + sender := clientCtx.GetFromAddress().String() recipient, err := cmd.Flags().GetString(FlagRecipient) if err != nil { diff --git a/modules/nft/depinject.go b/modules/nft/depinject.go index 9fa80ce8..70fa1403 100644 --- a/modules/nft/depinject.go +++ b/modules/nft/depinject.go @@ -3,7 +3,6 @@ package module import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" - "github.com/cosmos/cosmos-sdk/codec" store "github.com/cosmos/cosmos-sdk/store/types" diff --git a/modules/nft/keeper/collection_test.go b/modules/nft/keeper/collection_test.go index a411d717..c1e5e096 100644 --- a/modules/nft/keeper/collection_test.go +++ b/modules/nft/keeper/collection_test.go @@ -33,7 +33,6 @@ func (suite *KeeperSuite) TestSetCollection() { } func (suite *KeeperSuite) TestGetCollections() { - // SaveNFT shouldn't fail when collection does not exist err := suite.keeper.SaveNFT(suite.ctx, denomID, tokenID, tokenNm, tokenURI, tokenURIHash, tokenData, address) suite.NoError(err) @@ -73,7 +72,7 @@ func (suite *KeeperSuite) TestGetSupply() { supply = suite.keeper.GetTotalSupply(suite.ctx, denomID2) suite.Equal(uint64(1), supply) - //burn nft + // burn nft err = suite.keeper.RemoveNFT(suite.ctx, denomID, tokenID, address) suite.NoError(err) @@ -83,7 +82,7 @@ func (suite *KeeperSuite) TestGetSupply() { supply = suite.keeper.GetTotalSupply(suite.ctx, denomID) suite.Equal(uint64(1), supply) - //burn nft + // burn nft err = suite.keeper.RemoveNFT(suite.ctx, denomID, tokenID2, address2) suite.NoError(err) diff --git a/modules/nft/keeper/depinject_test.go b/modules/nft/keeper/depinject_test.go index f7aec735..4aecb7d8 100644 --- a/modules/nft/keeper/depinject_test.go +++ b/modules/nft/keeper/depinject_test.go @@ -25,8 +25,6 @@ import ( upgrademodulev1 "cosmossdk.io/api/cosmos/upgrade/module/v1" vestingmodulev1 "cosmossdk.io/api/cosmos/vesting/module/v1" "cosmossdk.io/core/appconfig" - "google.golang.org/protobuf/types/known/durationpb" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" "github.com/cosmos/cosmos-sdk/x/authz" @@ -45,6 +43,7 @@ import ( slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + "google.golang.org/protobuf/types/known/durationpb" nftmodule "mods.irisnet.org/api/irismod/nft/module/v1" _ "mods.irisnet.org/modules/nft" diff --git a/modules/nft/keeper/grpc_query.go b/modules/nft/keeper/grpc_query.go index ff29b786..08feb7af 100644 --- a/modules/nft/keeper/grpc_query.go +++ b/modules/nft/keeper/grpc_query.go @@ -3,12 +3,11 @@ package keeper import ( "context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/nft" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "mods.irisnet.org/modules/nft/types" ) @@ -46,7 +45,7 @@ func (k Keeper) NFTsOfOwner(c context.Context, request *types.QueryNFTsOfOwnerRe return nil, err } - var denomMap = make(map[string][]string) + denomMap := make(map[string][]string) var denoms []string for _, token := range result.Nfts { if denomMap[token.ClassId] == nil { diff --git a/modules/nft/keeper/keeper.go b/modules/nft/keeper/keeper.go index bc6605f6..b8b5314f 100644 --- a/modules/nft/keeper/keeper.go +++ b/modules/nft/keeper/keeper.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/modules/nft/keeper/keeper_test.go b/modules/nft/keeper/keeper_test.go index bcef24a4..55529986 100644 --- a/modules/nft/keeper/keeper_test.go +++ b/modules/nft/keeper/keeper_test.go @@ -5,13 +5,11 @@ import ( "strconv" "testing" - "github.com/stretchr/testify/suite" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" "mods.irisnet.org/modules/nft/keeper" "mods.irisnet.org/modules/nft/types" @@ -390,7 +388,7 @@ func CreateTestAddrs(numAddrs int) []sdk.AccAddress { } // for incode address generation -func testAddr(addr string, bech string) sdk.AccAddress { +func testAddr(addr, bech string) sdk.AccAddress { res, err := sdk.AccAddressFromHexUnsafe(addr) if err != nil { panic(err) diff --git a/modules/nft/keeper/msg_server.go b/modules/nft/keeper/msg_server.go index 1327a307..974ed9f9 100644 --- a/modules/nft/keeper/msg_server.go +++ b/modules/nft/keeper/msg_server.go @@ -139,7 +139,8 @@ func (k Keeper) EditNFT( } func (k Keeper) TransferNFT(goCtx context.Context, - msg *types.MsgTransferNFT) (*types.MsgTransferNFTResponse, error) { + msg *types.MsgTransferNFT, +) (*types.MsgTransferNFTResponse, error) { sender, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { return nil, err diff --git a/modules/nft/migrations/v2/store.go b/modules/nft/migrations/v2/store.go index ffb63734..6b69cc58 100644 --- a/modules/nft/migrations/v2/store.go +++ b/modules/nft/migrations/v2/store.go @@ -4,7 +4,6 @@ import ( "time" "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -39,7 +38,7 @@ func Migrate(ctx sdk.Context, var denom types.Denom cdc.MustUnmarshal(iterator.Value(), &denom) - //delete unused key + // delete unused key store.Delete(KeyDenom(denom.Id)) store.Delete(KeyDenomName(denom.Name)) store.Delete(KeyCollection(denom.Id)) @@ -79,6 +78,7 @@ func Migrate(ctx sdk.Context, ) return nil } + func migrateToken( ctx sdk.Context, k keeper, @@ -105,7 +105,7 @@ func migrateToken( return 0, err } - //delete unused key + // delete unused key store.Delete(KeyNFT(denomID, baseNFT.Id)) store.Delete(KeyOwner(owner, denomID, baseNFT.Id)) diff --git a/modules/nft/module.go b/modules/nft/module.go index d1c49cc3..6aa350fb 100644 --- a/modules/nft/module.go +++ b/modules/nft/module.go @@ -5,11 +5,7 @@ import ( "encoding/json" "fmt" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -18,6 +14,8 @@ import ( simtypes "github.com/cosmos/cosmos-sdk/types/simulation" sdknfttypes "github.com/cosmos/cosmos-sdk/x/nft" sdknftsim "github.com/cosmos/cosmos-sdk/x/nft/simulation" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" "mods.irisnet.org/modules/nft/client/cli" "mods.irisnet.org/modules/nft/keeper" diff --git a/modules/nft/simulation/operations.go b/modules/nft/simulation/operations.go index 1eacfff8..26946de6 100644 --- a/modules/nft/simulation/operations.go +++ b/modules/nft/simulation/operations.go @@ -27,12 +27,10 @@ const ( OpWeightMsgTransferDenom = "op_weight_msg_transfer_denom" ) -var ( - data = []string{ - "{\"key1\":\"value1\",\"key2\":\"value2\"}", - "{\"irismod:key1\":\"value1\",\"irismod:key2\":\"value2\"}", - } -) +var data = []string{ + "{\"key1\":\"value1\",\"key2\":\"value2\"}", + "{\"irismod:key1\":\"value1\",\"irismod:key2\":\"value2\"}", +} // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( @@ -409,7 +407,6 @@ func SimulateMsgTransferDenom( ) ( opMsg simtypes.OperationMsg, fOps []simtypes.FutureOperation, err error, ) { - denomID := randDenom(ctx, k, r, false, false) denom, err := k.GetDenomInfo(ctx, denomID) if err != nil { @@ -498,7 +495,6 @@ func SimulateMsgIssueDenom( ) ( opMsg simtypes.OperationMsg, fOps []simtypes.FutureOperation, err error, ) { - denomID := genDenomID(r) if k.HasDenom(ctx, denomID) { return simtypes.NoOpMsg( @@ -571,7 +567,7 @@ func randNFT( r *rand.Rand, mintable, editable bool, ) (sdk.AccAddress, string, string) { - var denoms = []string{kitties, doggos} + denoms := []string{kitties, doggos} res, err := k.Denoms(sdk.UnwrapSDKContext(ctx), &types.QueryDenomsRequest{}) if err == nil { @@ -624,7 +620,7 @@ func genNFTID(r *rand.Rand, min, max int) string { func randDenom(ctx sdk.Context, k keeper.Keeper, r *rand.Rand, mintable, editable bool) string { res, err := k.Denoms(sdk.UnwrapSDKContext(ctx), &types.QueryDenomsRequest{}) - var denoms = []string{kitties, doggos} + denoms := []string{kitties, doggos} if err != nil { i := r.Intn(len(denoms)) return denoms[i] diff --git a/modules/nft/types/builder.go b/modules/nft/types/builder.go index 83bb18ca..e9d19026 100644 --- a/modules/nft/types/builder.go +++ b/modules/nft/types/builder.go @@ -71,10 +71,10 @@ func (cb ClassBuilder) BuildMetadata(class nft.Class) (string, error) { if len(metadata.Data) > 0 { err := json.Unmarshal([]byte(metadata.Data), &kvals) if err != nil && IsIBCDenom(class.Id) { - //when classData is not a legal json, there is no need to parse the data + // when classData is not a legal json, there is no need to parse the data return Base64.EncodeToString([]byte(metadata.Data)), nil } - //note: if metadata.Data is null, it may cause map to be redefined as nil + // note: if metadata.Data is null, it may cause map to be redefined as nil if kvals == nil { kvals = make(map[string]interface{}) } @@ -216,7 +216,7 @@ func (cb ClassBuilder) Build(classID, classURI, classData string) (nft.Class, er } } - var data = "" + data := "" if len(dataMap) > 0 { dataBz, err := json.Marshal(dataMap) if err != nil { @@ -268,10 +268,10 @@ func (tb TokenBuilder) BuildMetadata(token nft.NFT) (string, error) { if len(nftMetadata.Data) > 0 { err := json.Unmarshal([]byte(nftMetadata.Data), &kvals) if err != nil && IsIBCDenom(token.ClassId) { - //when nftMetadata is not a legal json, there is no need to parse the data + // when nftMetadata is not a legal json, there is no need to parse the data return Base64.EncodeToString([]byte(nftMetadata.Data)), nil } - //note: if nftMetadata.Data is null, it may cause map to be redefined as nil + // note: if nftMetadata.Data is null, it may cause map to be redefined as nil if kvals == nil { kvals = make(map[string]interface{}) } @@ -331,7 +331,7 @@ func (tb TokenBuilder) Build(classId, tokenId, tokenURI, tokenData string) (nft. } } - var data = "" + data := "" if len(dataMap) > 0 { dataBz, err := json.Marshal(dataMap) if err != nil { diff --git a/modules/nft/types/builder_test.go b/modules/nft/types/builder_test.go index b0e02d41..34a4a674 100644 --- a/modules/nft/types/builder_test.go +++ b/modules/nft/types/builder_test.go @@ -6,7 +6,6 @@ import ( "github.com/cometbft/cometbft/crypto" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/nft" @@ -60,7 +59,7 @@ func TestTokenBuilder_Build(t *testing.T) { } func GetEncoding() codec.Codec { - interfaceRegistry := types.NewInterfaceRegistry() + interfaceRegistry := codectypes.NewInterfaceRegistry() interfaceRegistry.RegisterImplementations( (*proto.Message)(nil), &nft.Class{}, diff --git a/modules/nft/types/common_test.go b/modules/nft/types/common_test.go index 55e5569d..6e15c903 100644 --- a/modules/nft/types/common_test.go +++ b/modules/nft/types/common_test.go @@ -7,7 +7,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// nolint: deadcode unused var ( denomID = "denom" denom = "denom" @@ -28,9 +27,9 @@ func CreateTestAddrs(numAddrs int) []sdk.AccAddress { // start at 100 so we can make up to 999 test addresses with valid test addresses for i := 100; i < (numAddrs + 100); i++ { numString := strconv.Itoa(i) - buffer.WriteString("A58856F0FD53BF058B4909A21AEC019107BA6") //base address string + buffer.WriteString("A58856F0FD53BF058B4909A21AEC019107BA6") // base address string - buffer.WriteString(numString) //adding on final two digits to make addresses unique + buffer.WriteString(numString) // adding on final two digits to make addresses unique res, _ := sdk.AccAddressFromHexUnsafe(buffer.String()) bech := res.String() addresses = append(addresses, testAddr(buffer.String(), bech)) @@ -40,7 +39,7 @@ func CreateTestAddrs(numAddrs int) []sdk.AccAddress { } // for incode address generation -func testAddr(addr string, bech string) sdk.AccAddress { +func testAddr(addr, bech string) sdk.AccAddress { res, err := sdk.AccAddressFromHexUnsafe(addr) if err != nil { panic(err) diff --git a/modules/nft/types/msgs.go b/modules/nft/types/msgs.go index b7119252..f32b777b 100644 --- a/modules/nft/types/msgs.go +++ b/modules/nft/types/msgs.go @@ -1,10 +1,9 @@ package types import ( + errormod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - errormod "cosmossdk.io/errors" "github.com/tidwall/gjson" ) diff --git a/modules/oracle/client/cli/query.go b/modules/oracle/client/cli/query.go index ea9570d8..7eacc7fc 100644 --- a/modules/oracle/client/cli/query.go +++ b/modules/oracle/client/cli/query.go @@ -4,11 +4,10 @@ import ( "context" "fmt" - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" "mods.irisnet.org/modules/oracle/types" ) diff --git a/modules/oracle/client/cli/tx.go b/modules/oracle/client/cli/tx.go index 8b7040f0..a87cbadb 100644 --- a/modules/oracle/client/cli/tx.go +++ b/modules/oracle/client/cli/tx.go @@ -4,15 +4,14 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" - - "github.com/spf13/cobra" + "os" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" "mods.irisnet.org/modules/oracle/types" ) @@ -87,7 +86,7 @@ func GetCmdCreateFeed() *cobra.Command { return err } if !json.Valid([]byte(input)) { - inputContent, err := ioutil.ReadFile(input) + inputContent, err := os.ReadFile(input) if err != nil { return fmt.Errorf("invalid input data: neither JSON input nor path to .json file were provided") } diff --git a/modules/oracle/depinject.go b/modules/oracle/depinject.go index e146bc92..04a494ea 100644 --- a/modules/oracle/depinject.go +++ b/modules/oracle/depinject.go @@ -3,7 +3,6 @@ package oracle import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" - "github.com/cosmos/cosmos-sdk/codec" store "github.com/cosmos/cosmos-sdk/store/types" diff --git a/modules/oracle/keeper/ante.go b/modules/oracle/keeper/ante.go index bce4c8bb..6379bb6c 100644 --- a/modules/oracle/keeper/ante.go +++ b/modules/oracle/keeper/ante.go @@ -23,8 +23,7 @@ func NewValidateOracleAuthDecorator(k Keeper, ak types.AuthKeeper) ValidateOracl // AnteHandle returns an AnteHandler that checks if the creator is authorized func (dtf ValidateOracleAuthDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { for _, msg := range tx.GetMsgs() { - switch msg := msg.(type) { - case *types.MsgCreateFeed: + if msg, ok := msg.(*types.MsgCreateFeed); ok { creator, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { return ctx, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "invalid creator") diff --git a/modules/oracle/keeper/depinject_test.go b/modules/oracle/keeper/depinject_test.go index e5553a8c..eb86a2aa 100644 --- a/modules/oracle/keeper/depinject_test.go +++ b/modules/oracle/keeper/depinject_test.go @@ -25,8 +25,6 @@ import ( upgrademodulev1 "cosmossdk.io/api/cosmos/upgrade/module/v1" vestingmodulev1 "cosmossdk.io/api/cosmos/vesting/module/v1" "cosmossdk.io/core/appconfig" - "google.golang.org/protobuf/types/known/durationpb" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" "github.com/cosmos/cosmos-sdk/x/authz" @@ -45,14 +43,14 @@ import ( slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + "google.golang.org/protobuf/types/known/durationpb" oraclemodule "mods.irisnet.org/api/irismod/oracle/module/v1" servicemodule "mods.irisnet.org/api/irismod/service/module/v1" - oracletypes "mods.irisnet.org/modules/oracle/types" - servicetypes "mods.irisnet.org/modules/service/types" - _ "mods.irisnet.org/modules/oracle" + oracletypes "mods.irisnet.org/modules/oracle/types" _ "mods.irisnet.org/modules/service" + servicetypes "mods.irisnet.org/modules/service/types" ) var ( diff --git a/modules/oracle/keeper/feed.go b/modules/oracle/keeper/feed.go index 1c37af1a..6503a6d8 100644 --- a/modules/oracle/keeper/feed.go +++ b/modules/oracle/keeper/feed.go @@ -3,11 +3,9 @@ package keeper import ( "encoding/hex" - gogotypes "github.com/cosmos/gogoproto/types" - tmbytes "github.com/cometbft/cometbft/libs/bytes" - sdk "github.com/cosmos/cosmos-sdk/types" + gogotypes "github.com/cosmos/gogoproto/types" "mods.irisnet.org/modules/oracle/types" "mods.irisnet.org/modules/service/exported" diff --git a/modules/oracle/keeper/grpc_query.go b/modules/oracle/keeper/grpc_query.go index 38734053..181d7d70 100644 --- a/modules/oracle/keeper/grpc_query.go +++ b/modules/oracle/keeper/grpc_query.go @@ -4,14 +4,12 @@ import ( "context" "encoding/hex" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - gogotypes "github.com/cosmos/gogoproto/types" - "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" + gogotypes "github.com/cosmos/gogoproto/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "mods.irisnet.org/modules/oracle/types" ) @@ -54,7 +52,7 @@ func (k Keeper) Feeds( pageRes, err = query.Paginate( feedStore, shapePageRequest(req.Pagination), - func(key []byte, value []byte) error { + func(key, value []byte) error { var feed types.Feed k.cdc.MustUnmarshal(value, &feed) result = append(result, BuildFeedContext(ctx, k, feed)) @@ -68,10 +66,9 @@ func (k Keeper) Feeds( state, err := types.RequestContextStateFromString(req.State) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "invalid request state") - } feedStore := prefix.NewStore(store, types.GetFeedStatePrefixKey(state)) - pageRes, err = query.Paginate(feedStore, shapePageRequest(req.Pagination), func(key []byte, value []byte) error { + pageRes, err = query.Paginate(feedStore, shapePageRequest(req.Pagination), func(key, value []byte) error { var feedName gogotypes.StringValue k.cdc.MustUnmarshal(value, &feedName) if feed, found := k.GetFeed(ctx, feedName.Value); found { diff --git a/modules/oracle/keeper/keeper.go b/modules/oracle/keeper/keeper.go index e2d2039f..9923b9b8 100644 --- a/modules/oracle/keeper/keeper.go +++ b/modules/oracle/keeper/keeper.go @@ -6,14 +6,12 @@ import ( "fmt" "time" - "github.com/tidwall/gjson" - - tmbytes "github.com/cometbft/cometbft/libs/bytes" - errorsmod "cosmossdk.io/errors" + tmbytes "github.com/cometbft/cometbft/libs/bytes" "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/tidwall/gjson" "mods.irisnet.org/modules/oracle/types" serviceexported "mods.irisnet.org/modules/service/exported" @@ -326,7 +324,7 @@ func (k Keeper) GetRequestContext( return k.sk.GetRequestContext(ctx, requestContextID) } -func (k Keeper) ModuleServiceRequest(ctx sdk.Context, input string) (result string, output string) { +func (k Keeper) ModuleServiceRequest(ctx sdk.Context, input string) (result, output string) { feedName := gjson.Get(input, serviceexported.PATH_BODY).Get("pair").String() if _, found := k.GetFeed(ctx, feedName); !found { result = `{"code":"400","message":"feed not found"}` @@ -343,7 +341,7 @@ func (k Keeper) ModuleServiceRequest(ctx sdk.Context, input string) (result stri valueData := value.Data valueTime := value.Timestamp - if time.Since(valueTime) > time.Duration(time.Minute*5) { + if time.Since(valueTime) > time.Minute*5 { result = `{"code":"402","message":"all values expired"}` return } @@ -353,6 +351,7 @@ func (k Keeper) ModuleServiceRequest(ctx sdk.Context, input string) (result stri return } + func (k Keeper) GetServiceKeeper() types.ServiceKeeper { return k.sk } diff --git a/modules/oracle/keeper/keeper_test.go b/modules/oracle/keeper/keeper_test.go index 76f350b4..f2e47672 100644 --- a/modules/oracle/keeper/keeper_test.go +++ b/modules/oracle/keeper/keeper_test.go @@ -5,14 +5,12 @@ import ( "strings" "testing" - "github.com/stretchr/testify/suite" - "github.com/cometbft/cometbft/crypto" tmbytes "github.com/cometbft/cometbft/libs/bytes" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" "mods.irisnet.org/modules/oracle/keeper" "mods.irisnet.org/modules/oracle/types" diff --git a/modules/oracle/module.go b/modules/oracle/module.go index 6cb09e84..c837147a 100644 --- a/modules/oracle/module.go +++ b/modules/oracle/module.go @@ -5,18 +5,16 @@ import ( "encoding/json" "fmt" - "github.com/gorilla/mux" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" "mods.irisnet.org/modules/oracle/client/cli" "mods.irisnet.org/modules/oracle/keeper" @@ -64,7 +62,7 @@ func (AppModuleBasic) ValidateGenesis( // RegisterRESTRoutes registers the REST routes for the oracle module. func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { - //rest.RegisterHandlers(clientCtx, rtr) + // rest.RegisterHandlers(clientCtx, rtr) } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the oracle module. diff --git a/modules/oracle/simulation/operation.go b/modules/oracle/simulation/operation.go index 69c7ec6f..a43e02da 100644 --- a/modules/oracle/simulation/operation.go +++ b/modules/oracle/simulation/operation.go @@ -29,8 +29,8 @@ func WeightedOperations( cdc codec.JSONCodec, k keeper.Keeper, ak types.AccountKeeper, - bk types.BankKeeper) simulation.WeightedOperations { - + bk types.BankKeeper, +) simulation.WeightedOperations { var weightCreate, weightPause, weightStart, WeightEdit int appParams.GetOrGenerate( @@ -274,7 +274,6 @@ func SimulatePauseFeed( ) ( opMsg simtypes.OperationMsg, fOps []simtypes.FutureOperation, err error, ) { - feed := GenFeed(k, r, ctx) if feed.Size() == 0 { return simtypes.NoOpMsg( @@ -443,7 +442,6 @@ func SimulateEditFeed( } return simtypes.NewOperationMsg(msg, true, "", nil), nil, nil - } } @@ -480,15 +478,15 @@ func GenServiceBindingsAndProviders( ) (providers []string) { ownerAddr, err := sdk.AccAddressFromBech32(owner) if err != nil { - return + return providers } spendable := bk.SpendableCoins(ctx, ownerAddr) if spendable.IsZero() { - return + return providers } token := spendable[r.Intn(len(spendable))] if token.IsZero() { - return + return providers } for i := 0; i < 10; i++ { provider, _ := simtypes.RandomAcc(r, accs) @@ -514,7 +512,7 @@ func GenServiceBindingsAndProviders( providers = append(providers, provider.Address.String()) } } - return + return providers } func GenFeed(k keeper.Keeper, r *rand.Rand, ctx sdk.Context) types.Feed { diff --git a/modules/oracle/types/aggregate.go b/modules/oracle/types/aggregate.go index 35f01f35..191f1f3b 100644 --- a/modules/oracle/types/aggregate.go +++ b/modules/oracle/types/aggregate.go @@ -5,18 +5,17 @@ import ( "math" "strconv" - "github.com/tidwall/gjson" - errorsmod "cosmossdk.io/errors" + "github.com/tidwall/gjson" ) -var ( - router funcRouter -) +var router funcRouter -type ArgsType = gjson.Result -type funcRouter map[string]Aggregate -type Aggregate func(args []ArgsType) string +type ( + ArgsType = gjson.Result + funcRouter map[string]Aggregate + Aggregate func(args []ArgsType) string +) func init() { router = make(funcRouter) @@ -43,7 +42,7 @@ func RegisterAggregateFunc(methodNm string, fun Aggregate) error { } func Max(data []ArgsType) string { - var maxNumber = math.SmallestNonzeroFloat64 + maxNumber := math.SmallestNonzeroFloat64 for _, d := range data { f := d.Float() if maxNumber < f { @@ -54,7 +53,7 @@ func Max(data []ArgsType) string { } func Min(data []ArgsType) string { - var minNum = math.MaxFloat64 + minNum := math.MaxFloat64 for _, d := range data { f := d.Float() if minNum > d.Float() { @@ -65,7 +64,7 @@ func Min(data []ArgsType) string { } func Avg(data []ArgsType) string { - var total = 0.0 + total := 0.0 for _, d := range data { f := d.Float() total += f diff --git a/modules/oracle/types/aggregate_test.go b/modules/oracle/types/aggregate_test.go index d40c59a6..0d5e4878 100644 --- a/modules/oracle/types/aggregate_test.go +++ b/modules/oracle/types/aggregate_test.go @@ -8,7 +8,7 @@ import ( ) func TestMax(t *testing.T) { - var data = []ArgsType{ + data := []ArgsType{ StringArgsType("1"), StringArgsType("2"), StringArgsType("3"), @@ -21,7 +21,7 @@ func TestMax(t *testing.T) { } func TestMin(t *testing.T) { - var data = []ArgsType{ + data := []ArgsType{ StringArgsType("1"), StringArgsType("2"), StringArgsType("3"), @@ -35,7 +35,7 @@ func TestMin(t *testing.T) { } func TestAvg(t *testing.T) { - var data = []ArgsType{ + data := []ArgsType{ StringArgsType("1"), StringArgsType("2"), StringArgsType("3"), diff --git a/modules/oracle/types/expected_keepers.go b/modules/oracle/types/expected_keepers.go index 2171065a..9f92682e 100644 --- a/modules/oracle/types/expected_keepers.go +++ b/modules/oracle/types/expected_keepers.go @@ -2,7 +2,6 @@ package types import ( tmbytes "github.com/cometbft/cometbft/libs/bytes" - sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -92,9 +91,7 @@ type AuthKeeper interface { Authorized(ctx sdk.Context, addr sdk.AccAddress) bool } -var ( - RequestContextStateFromString = service.RequestContextStateFromString -) +var RequestContextStateFromString = service.RequestContextStateFromString type BankKeeper interface { SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins diff --git a/modules/oracle/types/keys.go b/modules/oracle/types/keys.go index 78a5d2dd..d9392dea 100644 --- a/modules/oracle/types/keys.go +++ b/modules/oracle/types/keys.go @@ -6,7 +6,6 @@ import ( servicetypes "mods.irisnet.org/modules/service/types" ) -// nolint const ( // module name ModuleName = "oracle" @@ -45,7 +44,7 @@ func GetReqCtxIDKey(requestContextID []byte) []byte { func GetFeedValueKey(feedName string, batchCounter uint64) []byte { key := make([]byte, 8) - binary.BigEndian.PutUint64(key[:], batchCounter) + binary.BigEndian.PutUint64(key, batchCounter) return append(GetFeedValuePrefixKey(feedName), key...) } diff --git a/modules/oracle/types/msgs_test.go b/modules/oracle/types/msgs_test.go index 55f8b02b..95822c13 100644 --- a/modules/oracle/types/msgs_test.go +++ b/modules/oracle/types/msgs_test.go @@ -3,11 +3,9 @@ package types import ( "testing" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/crypto/tmhash" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" ) var ( @@ -163,7 +161,8 @@ func TestMsgCreateFeed_ValidateBasic(t *testing.T) { RepeatedFrequency: 5, ResponseThreshold: 1, Creator: addr1, - }, false, + }, + false, }, { "empty Providers", MsgCreateFeed{ @@ -216,7 +215,8 @@ func TestMsgCreateFeed_ValidateBasic(t *testing.T) { RepeatedFrequency: 5, ResponseThreshold: 1, Creator: emptyAddr, - }, false, + }, + false, }} for _, tc := range tests { @@ -307,67 +307,68 @@ func TestMsgEditFeed_ValidateBasic(t *testing.T) { testCase string MsgEditFeed expectPass bool - }{{ - "basic good", - MsgEditFeed{ - FeedName: "feedEthPrice", - LatestHistory: 10, - Providers: []string{addr1, addr2}, - ServiceFeeCap: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))), - RepeatedFrequency: 5, - ResponseThreshold: 1, - Creator: addr1, + }{ + { + "basic good", + MsgEditFeed{ + FeedName: "feedEthPrice", + LatestHistory: 10, + Providers: []string{addr1, addr2}, + ServiceFeeCap: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))), + RepeatedFrequency: 5, + ResponseThreshold: 1, + Creator: addr1, + }, + true, + }, { + "wrong FeedName, invalid char", + MsgEditFeed{ + FeedName: "$feedEthPrice", + LatestHistory: 10, + Providers: []string{addr1, addr2}, + ServiceFeeCap: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))), + RepeatedFrequency: 5, + ResponseThreshold: 1, + Creator: addr1, + }, + false, + }, { + "wrong MaxLatestHistory(>100)", + MsgEditFeed{ + FeedName: "feedEthPrice", + LatestHistory: 101, + Providers: []string{addr1, addr2}, + ServiceFeeCap: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))), + RepeatedFrequency: 5, + ResponseThreshold: 1, + Creator: addr1, + }, + false, + }, { + "invalid ResponseThreshold", + MsgEditFeed{ + FeedName: "feedEthPrice", + LatestHistory: 10, + Providers: []string{addr1, addr2}, + ServiceFeeCap: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))), + RepeatedFrequency: 5, + ResponseThreshold: 3, + Creator: addr1, + }, + false, + }, { + "empty Creator", + MsgEditFeed{ + FeedName: "feedEthPrice", + LatestHistory: 10, + Providers: []string{addr1, addr2}, + ServiceFeeCap: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))), + RepeatedFrequency: 5, + ResponseThreshold: 1, + Creator: emptyAddr, + }, + false, }, - true, - }, { - "wrong FeedName, invalid char", - MsgEditFeed{ - FeedName: "$feedEthPrice", - LatestHistory: 10, - Providers: []string{addr1, addr2}, - ServiceFeeCap: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))), - RepeatedFrequency: 5, - ResponseThreshold: 1, - Creator: addr1, - }, - false, - }, { - "wrong MaxLatestHistory(>100)", - MsgEditFeed{ - FeedName: "feedEthPrice", - LatestHistory: 101, - Providers: []string{addr1, addr2}, - ServiceFeeCap: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))), - RepeatedFrequency: 5, - ResponseThreshold: 1, - Creator: addr1, - }, - false, - }, { - "invalid ResponseThreshold", - MsgEditFeed{ - FeedName: "feedEthPrice", - LatestHistory: 10, - Providers: []string{addr1, addr2}, - ServiceFeeCap: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))), - RepeatedFrequency: 5, - ResponseThreshold: 3, - Creator: addr1, - }, - false, - }, { - "empty Creator", - MsgEditFeed{ - FeedName: "feedEthPrice", - LatestHistory: 10, - Providers: []string{addr1, addr2}, - ServiceFeeCap: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))), - RepeatedFrequency: 5, - ResponseThreshold: 1, - Creator: emptyAddr, - }, - false, - }, } for _, tc := range tests { diff --git a/modules/oracle/types/validation.go b/modules/oracle/types/validation.go index ab6930ce..143c1c25 100644 --- a/modules/oracle/types/validation.go +++ b/modules/oracle/types/validation.go @@ -11,18 +11,16 @@ import ( ) const ( - //MaxLatestHistory defines the the maximum number of feed values saved + // MaxLatestHistory defines the the maximum number of feed values saved MaxLatestHistory = 100 - //MaxAggregateFuncNameLen defines the the maximum length of the aggregation function name + // MaxAggregateFuncNameLen defines the the maximum length of the aggregation function name MaxAggregateFuncNameLen = 10 - //MaxDescriptionLen defines the the maximum length of the description + // MaxDescriptionLen defines the the maximum length of the description MaxDescriptionLen = 280 ) -var ( - // the feed name only accepts alphanumeric characters, _ and - / - regexpFeedName = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9/_-]*$`) -) +// the feed name only accepts alphanumeric characters, _ and - / +var regexpFeedName = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9/_-]*$`) // ValidateFeedName verifies if the feed name is legal func ValidateFeedName(feedName string) error { diff --git a/modules/random/client/cli/flags.go b/modules/random/client/cli/flags.go index 0f1f3fad..7bae42fd 100644 --- a/modules/random/client/cli/flags.go +++ b/modules/random/client/cli/flags.go @@ -14,9 +14,7 @@ const ( FlagQueueHeight = "queue-height" ) -var ( - FsRequestRand = flag.NewFlagSet("", flag.ContinueOnError) -) +var FsRequestRand = flag.NewFlagSet("", flag.ContinueOnError) func init() { FsRequestRand.Uint64(FlagBlockInterval, randomtypes.DefaultBlockInterval, "The block interval") diff --git a/modules/random/client/cli/query.go b/modules/random/client/cli/query.go index 0a56e7c2..b5329ce2 100644 --- a/modules/random/client/cli/query.go +++ b/modules/random/client/cli/query.go @@ -5,11 +5,10 @@ import ( "fmt" "strconv" - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" "mods.irisnet.org/modules/random/types" ) diff --git a/modules/random/client/cli/tx.go b/modules/random/client/cli/tx.go index 81bef3f4..f610f23a 100644 --- a/modules/random/client/cli/tx.go +++ b/modules/random/client/cli/tx.go @@ -3,13 +3,12 @@ package cli import ( "fmt" - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" "mods.irisnet.org/modules/random/types" ) diff --git a/modules/random/depinject.go b/modules/random/depinject.go index 10a4c952..de9c2471 100644 --- a/modules/random/depinject.go +++ b/modules/random/depinject.go @@ -3,7 +3,6 @@ package random import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" - "github.com/cosmos/cosmos-sdk/codec" store "github.com/cosmos/cosmos-sdk/store/types" diff --git a/modules/random/keeper/depinject_test.go b/modules/random/keeper/depinject_test.go index e7f28548..a9bd71b8 100644 --- a/modules/random/keeper/depinject_test.go +++ b/modules/random/keeper/depinject_test.go @@ -25,8 +25,6 @@ import ( upgrademodulev1 "cosmossdk.io/api/cosmos/upgrade/module/v1" vestingmodulev1 "cosmossdk.io/api/cosmos/vesting/module/v1" "cosmossdk.io/core/appconfig" - "google.golang.org/protobuf/types/known/durationpb" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" "github.com/cosmos/cosmos-sdk/x/authz" @@ -45,14 +43,14 @@ import ( slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + "google.golang.org/protobuf/types/known/durationpb" randommodule "mods.irisnet.org/api/irismod/random/module/v1" servicemodule "mods.irisnet.org/api/irismod/service/module/v1" - randomtypes "mods.irisnet.org/modules/random/types" - servicetypes "mods.irisnet.org/modules/service/types" - _ "mods.irisnet.org/modules/random" + randomtypes "mods.irisnet.org/modules/random/types" _ "mods.irisnet.org/modules/service" + servicetypes "mods.irisnet.org/modules/service/types" ) var ( diff --git a/modules/random/keeper/grpc_query.go b/modules/random/keeper/grpc_query.go index 0cff7559..4a36e03d 100644 --- a/modules/random/keeper/grpc_query.go +++ b/modules/random/keeper/grpc_query.go @@ -4,15 +4,10 @@ import ( "context" "encoding/hex" - "cosmossdk.io/api/tendermint/abci" + sdk "github.com/cosmos/cosmos-sdk/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "mods.irisnet.org/modules/random/types" ) @@ -63,36 +58,8 @@ func (k Keeper) RandomRequestQueue(c context.Context, req *types.QueryRandomRequ return &types.QueryRandomRequestQueueResponse{Requests: requests}, nil } -func queryRandomRequestQueue(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - var params types.QueryRandomRequestQueueParams - if err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - - if params.Height < 0 { - return nil, errorsmod.Wrap(types.ErrInvalidHeight, string(rune(params.Height))) - } - - var requests []types.Request - - if params.Height == 0 { - // query all pending requests - requests = queryAllRandomRequestsInQueue(ctx, k) - } else { - // query the pending requests by the specified height - requests = queryRandomRequestQueueByHeight(ctx, params.Height, k) - } - - bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, requests) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return bz, nil -} - func queryRandomRequestQueueByHeight(ctx sdk.Context, height int64, k Keeper) []types.Request { - var requests = make([]types.Request, 0) + requests := make([]types.Request, 0) iterator := k.IterateRandomRequestQueueByHeight(ctx, height) defer iterator.Close() @@ -108,7 +75,7 @@ func queryRandomRequestQueueByHeight(ctx sdk.Context, height int64, k Keeper) [] } func queryAllRandomRequestsInQueue(ctx sdk.Context, k Keeper) []types.Request { - var requests = make([]types.Request, 0) + requests := make([]types.Request, 0) k.IterateRandomRequestQueue(ctx, func(h int64, reqID []byte, r types.Request) (stop bool) { requests = append(requests, r) diff --git a/modules/random/keeper/grpc_query_test.go b/modules/random/keeper/grpc_query_test.go index 00692f43..0be1ca25 100644 --- a/modules/random/keeper/grpc_query_test.go +++ b/modules/random/keeper/grpc_query_test.go @@ -49,7 +49,7 @@ func (suite *KeeperTestSuite) TestGRPCRandomRequestQueue() { randomResp, err := queryClient.RandomRequestQueue(gocontext.Background(), &types.QueryRandomRequestQueueRequest{Height: 1}) suite.Require().NoError(err) - var requests = make([]types.Request, 0) + requests := make([]types.Request, 0) suite.keeper.IterateRandomRequestQueue(ctx, func(h int64, reqID []byte, r types.Request) (stop bool) { requests = append(requests, r) diff --git a/modules/random/keeper/keeper.go b/modules/random/keeper/keeper.go index 5d87655e..21fdc708 100644 --- a/modules/random/keeper/keeper.go +++ b/modules/random/keeper/keeper.go @@ -3,9 +3,8 @@ package keeper import ( "encoding/hex" - "github.com/cometbft/cometbft/libs/log" - errorsmod "cosmossdk.io/errors" + "github.com/cometbft/cometbft/libs/log" "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/modules/random/keeper/keeper_test.go b/modules/random/keeper/keeper_test.go index abc2ebf3..a7bb9b5c 100644 --- a/modules/random/keeper/keeper_test.go +++ b/modules/random/keeper/keeper_test.go @@ -6,13 +6,11 @@ import ( "math/big" "testing" - "github.com/stretchr/testify/suite" - "github.com/cometbft/cometbft/crypto" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" "mods.irisnet.org/modules/random/keeper" "mods.irisnet.org/modules/random/types" diff --git a/modules/random/keeper/service.go b/modules/random/keeper/service.go index 70068369..9c780e5e 100644 --- a/modules/random/keeper/service.go +++ b/modules/random/keeper/service.go @@ -3,12 +3,10 @@ package keeper import ( "encoding/hex" - "github.com/tidwall/gjson" - tmbytes "github.com/cometbft/cometbft/libs/bytes" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/tidwall/gjson" "mods.irisnet.org/modules/random/types" "mods.irisnet.org/modules/service/exported" diff --git a/modules/random/module.go b/modules/random/module.go index d874c48a..8debd596 100644 --- a/modules/random/module.go +++ b/modules/random/module.go @@ -5,18 +5,16 @@ import ( "encoding/json" "fmt" - "github.com/gorilla/mux" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" "mods.irisnet.org/modules/random/client/cli" "mods.irisnet.org/modules/random/keeper" @@ -64,7 +62,7 @@ func (AppModuleBasic) ValidateGenesis( // RegisterRESTRoutes registers the REST routes for the random module. func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { - //rest.RegisterHandlers(clientCtx, rtr) + // rest.RegisterHandlers(clientCtx, rtr) } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the random module. diff --git a/modules/random/simulation/decoder_test.go b/modules/random/simulation/decoder_test.go index 5db87ed9..8c67e1d3 100644 --- a/modules/random/simulation/decoder_test.go +++ b/modules/random/simulation/decoder_test.go @@ -6,10 +6,9 @@ import ( "math/big" "testing" - "github.com/stretchr/testify/require" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/kv" + "github.com/stretchr/testify/require" "mods.irisnet.org/modules/random/simulation" "mods.irisnet.org/modules/random/types" diff --git a/modules/random/simulation/operations.go b/modules/random/simulation/operations.go index 12ed99f4..a454e49f 100644 --- a/modules/random/simulation/operations.go +++ b/modules/random/simulation/operations.go @@ -21,7 +21,7 @@ func WeightedOperations( ak types.AccountKeeper, bk types.BankKeeper, ) simulation.WeightedOperations { - var weightMsgRequestRandom = 100 + weightMsgRequestRandom := 100 return simulation.WeightedOperations{ simulation.NewWeightedOperation( weightMsgRequestRandom, diff --git a/modules/random/types/events.go b/modules/random/types/events.go index 0613b7a9..eb1bc31a 100644 --- a/modules/random/types/events.go +++ b/modules/random/types/events.go @@ -1,4 +1,3 @@ -// nolint package types // random module event types diff --git a/modules/random/types/expected_keepers.go b/modules/random/types/expected_keepers.go index c71f66a9..b4d3ffcd 100644 --- a/modules/random/types/expected_keepers.go +++ b/modules/random/types/expected_keepers.go @@ -2,7 +2,6 @@ package types import ( tmbytes "github.com/cometbft/cometbft/libs/bytes" - sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" diff --git a/modules/random/types/keys.go b/modules/random/types/keys.go index 0e267648..e8363335 100644 --- a/modules/random/types/keys.go +++ b/modules/random/types/keys.go @@ -18,7 +18,7 @@ const ( RouterKey = ModuleName // ServiceName is the name of the random service - ServiceName = ModuleName + ServiceName = ModuleName ) var ( diff --git a/modules/random/types/msgs_test.go b/modules/random/types/msgs_test.go index 99505206..6304f7d7 100644 --- a/modules/random/types/msgs_test.go +++ b/modules/random/types/msgs_test.go @@ -4,11 +4,9 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/crypto/tmhash" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" ) var ( @@ -56,7 +54,7 @@ func TestMsgRequestRandomValidation(t *testing.T) { } func TestMsgRequestRandomGetSignBytes(t *testing.T) { - var msg = NewMsgRequestRandom(testAddr, blockInterval, true, serviceFeeCap) + msg := NewMsgRequestRandom(testAddr, blockInterval, true, serviceFeeCap) res := msg.GetSignBytes() expected := fmt.Sprintf( @@ -67,7 +65,7 @@ func TestMsgRequestRandomGetSignBytes(t *testing.T) { } func TestMsgRequestRandomGetSigners(t *testing.T) { - var msg = NewMsgRequestRandom(testAddr, blockInterval, false, serviceFeeCap) + msg := NewMsgRequestRandom(testAddr, blockInterval, false, serviceFeeCap) res := msg.GetSigners() expected := "[8C739F254AB0A7EB5D6D71DBE535041E5EB36682]" diff --git a/modules/random/types/rng.go b/modules/random/types/rng.go index 9e73ba6a..83b95739 100644 --- a/modules/random/types/rng.go +++ b/modules/random/types/rng.go @@ -8,8 +8,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -const RandPrec = 20 // the precision for generated random numbers -const SeedBytesLength = 32 // +const ( + RandPrec = 20 // the precision for generated random numbers + SeedBytesLength = 32 // +) // RNG is a random number generator type RNG interface { diff --git a/modules/record/client/cli/flags.go b/modules/record/client/cli/flags.go index 27cbeddc..bd8ef56d 100644 --- a/modules/record/client/cli/flags.go +++ b/modules/record/client/cli/flags.go @@ -1,4 +1,3 @@ -// nolint package cli import ( diff --git a/modules/record/client/cli/query.go b/modules/record/client/cli/query.go index 07b258e3..1b6cc6a4 100644 --- a/modules/record/client/cli/query.go +++ b/modules/record/client/cli/query.go @@ -5,12 +5,10 @@ import ( "encoding/hex" "errors" - "github.com/spf13/cobra" - tmbytes "github.com/cometbft/cometbft/libs/bytes" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/spf13/cobra" "mods.irisnet.org/modules/record/types" ) diff --git a/modules/record/client/cli/tx.go b/modules/record/client/cli/tx.go index edddcc12..f718e819 100644 --- a/modules/record/client/cli/tx.go +++ b/modules/record/client/cli/tx.go @@ -1,11 +1,10 @@ package cli import ( - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/spf13/cobra" "mods.irisnet.org/modules/record/types" ) diff --git a/modules/record/depinject.go b/modules/record/depinject.go index e8eccf0b..97a11e61 100644 --- a/modules/record/depinject.go +++ b/modules/record/depinject.go @@ -3,7 +3,6 @@ package record import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" - "github.com/cosmos/cosmos-sdk/codec" store "github.com/cosmos/cosmos-sdk/store/types" diff --git a/modules/record/keeper/depinject_test.go b/modules/record/keeper/depinject_test.go index 097d5ffa..354cd375 100644 --- a/modules/record/keeper/depinject_test.go +++ b/modules/record/keeper/depinject_test.go @@ -25,8 +25,6 @@ import ( upgrademodulev1 "cosmossdk.io/api/cosmos/upgrade/module/v1" vestingmodulev1 "cosmossdk.io/api/cosmos/vesting/module/v1" "cosmossdk.io/core/appconfig" - "google.golang.org/protobuf/types/known/durationpb" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" "github.com/cosmos/cosmos-sdk/x/authz" @@ -45,6 +43,7 @@ import ( slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + "google.golang.org/protobuf/types/known/durationpb" recordmodule "mods.irisnet.org/api/irismod/record/module/v1" _ "mods.irisnet.org/modules/record" diff --git a/modules/record/keeper/grpc_query.go b/modules/record/keeper/grpc_query.go index ab9a545a..1586b379 100644 --- a/modules/record/keeper/grpc_query.go +++ b/modules/record/keeper/grpc_query.go @@ -4,11 +4,10 @@ import ( "context" "encoding/hex" + sdk "github.com/cosmos/cosmos-sdk/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - sdk "github.com/cosmos/cosmos-sdk/types" - "mods.irisnet.org/modules/record/types" ) diff --git a/modules/record/keeper/keeper.go b/modules/record/keeper/keeper.go index ef4d3dfd..1ad27501 100644 --- a/modules/record/keeper/keeper.go +++ b/modules/record/keeper/keeper.go @@ -4,14 +4,12 @@ import ( "encoding/binary" "fmt" - gogotypes "github.com/cosmos/gogoproto/types" - "github.com/cometbft/cometbft/crypto/tmhash" "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + gogotypes "github.com/cosmos/gogoproto/types" "mods.irisnet.org/modules/record/types" ) @@ -43,7 +41,7 @@ func (k Keeper) AddRecord(ctx sdk.Context, record types.Record) []byte { intraTxCounter := k.GetIntraTxCounter(ctx) bz := make([]byte, 4+len(recordBz)) - copy(bz[:len(recordBz)], recordBz[:]) + copy(bz[:len(recordBz)], recordBz) binary.BigEndian.PutUint32(bz[len(recordBz):], intraTxCounter) recordID := getRecordID(bz) diff --git a/modules/record/keeper/keeper_test.go b/modules/record/keeper/keeper_test.go index ae0c1b7e..fa640d63 100644 --- a/modules/record/keeper/keeper_test.go +++ b/modules/record/keeper/keeper_test.go @@ -3,22 +3,18 @@ package keeper_test import ( "testing" - "github.com/stretchr/testify/suite" - "github.com/cometbft/cometbft/crypto/tmhash" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" "mods.irisnet.org/modules/record/keeper" "mods.irisnet.org/modules/record/types" "mods.irisnet.org/simapp" ) -var ( - testCreator = sdk.AccAddress(tmhash.Sum([]byte("test-creator"))) -) +var testCreator = sdk.AccAddress(tmhash.Sum([]byte("test-creator"))) type KeeperTestSuite struct { suite.Suite @@ -35,7 +31,7 @@ func (suite *KeeperTestSuite) SetupTest() { Consumers: []interface{}{&suite.keeper}, } - app := simapp.Setup(suite.T(), false,depInjectOptions) + app := simapp.Setup(suite.T(), false, depInjectOptions) suite.cdc = codec.NewAminoCodec(app.LegacyAmino()) suite.ctx = app.BaseApp.NewContext(false, tmproto.Header{}) diff --git a/modules/record/keeper/msg_server.go b/modules/record/keeper/msg_server.go index da77687f..46eb1e3c 100644 --- a/modules/record/keeper/msg_server.go +++ b/modules/record/keeper/msg_server.go @@ -5,7 +5,6 @@ import ( "encoding/hex" "github.com/cometbft/cometbft/crypto/tmhash" - sdk "github.com/cosmos/cosmos-sdk/types" "mods.irisnet.org/modules/record/types" diff --git a/modules/record/module.go b/modules/record/module.go index b49140df..b3980eff 100644 --- a/modules/record/module.go +++ b/modules/record/module.go @@ -5,18 +5,16 @@ import ( "encoding/json" "fmt" - "github.com/gorilla/mux" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" "mods.irisnet.org/modules/record/client/cli" "mods.irisnet.org/modules/record/keeper" @@ -65,7 +63,7 @@ func (AppModuleBasic) ValidateGenesis( // RegisterRESTRoutes registers the REST routes for the record module. func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { - //rest.RegisterHandlers(clientCtx, rtr) + // rest.RegisterHandlers(clientCtx, rtr) } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the record module. diff --git a/modules/record/simulation/operations.go b/modules/record/simulation/operations.go index d7047628..bb901806 100644 --- a/modules/record/simulation/operations.go +++ b/modules/record/simulation/operations.go @@ -5,7 +5,6 @@ import ( "math/rand" tmbytes "github.com/cometbft/cometbft/libs/bytes" - "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" @@ -53,7 +52,6 @@ func SimulateCreateRecord(ak types.AccountKeeper, bk types.BankKeeper) simtypes. ) ( simtypes.OperationMsg, []simtypes.FutureOperation, error, ) { - record, err := genRecord(r, accs) if err != nil { return simtypes.NoOpMsg( diff --git a/modules/record/types/genesis.go b/modules/record/types/genesis.go index bbdc94f8..7839d1eb 100644 --- a/modules/record/types/genesis.go +++ b/modules/record/types/genesis.go @@ -29,7 +29,7 @@ func ValidateGenesis(data GenesisState) error { _, err := sdk.AccAddressFromBech32(record.Creator) if err != nil { - return fmt.Errorf("invalid record creator address (%s)", err) + return fmt.Errorf("invalid record creator address (%w)", err) } if err := ValidateContents(record.Contents...); err != nil { diff --git a/modules/record/types/keys.go b/modules/record/types/keys.go index b7f87d89..bfb8886b 100644 --- a/modules/record/types/keys.go +++ b/modules/record/types/keys.go @@ -1,6 +1,5 @@ package types -// nolint const ( // module name ModuleName = "record" diff --git a/modules/record/types/msgs.go b/modules/record/types/msgs.go index cc1f0734..6c4635dd 100644 --- a/modules/record/types/msgs.go +++ b/modules/record/types/msgs.go @@ -13,10 +13,10 @@ const ( var _ sdk.Msg = &MsgCreateRecord{} // NewMsgCreateRecord constructs a new MsgCreateRecord instance -func NewMsgCreateRecord(contents []Content, Creator string) *MsgCreateRecord { +func NewMsgCreateRecord(contents []Content, creator string) *MsgCreateRecord { return &MsgCreateRecord{ Contents: contents, - Creator: Creator, + Creator: creator, } } diff --git a/modules/record/types/types.go b/modules/record/types/types.go index c6d67487..e0694b0f 100644 --- a/modules/record/types/types.go +++ b/modules/record/types/types.go @@ -2,7 +2,6 @@ package types import ( "github.com/cometbft/cometbft/libs/bytes" - sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/modules/service/abci.go b/modules/service/abci.go index b6b231e7..1e501735 100644 --- a/modules/service/abci.go +++ b/modules/service/abci.go @@ -5,7 +5,6 @@ import ( "strings" tmbytes "github.com/cometbft/cometbft/libs/bytes" - sdk "github.com/cosmos/cosmos-sdk/types" "mods.irisnet.org/modules/service/keeper" diff --git a/modules/service/client/cli/flags.go b/modules/service/client/cli/flags.go index f7fbea89..aa8a6f33 100644 --- a/modules/service/client/cli/flags.go +++ b/modules/service/client/cli/flags.go @@ -1,4 +1,3 @@ -// nolint package cli import ( diff --git a/modules/service/client/cli/query.go b/modules/service/client/cli/query.go index 37d1cc15..fc2edd1f 100644 --- a/modules/service/client/cli/query.go +++ b/modules/service/client/cli/query.go @@ -6,14 +6,12 @@ import ( "fmt" "strconv" - "github.com/spf13/cobra" - tmbytes "github.com/cometbft/cometbft/libs/bytes" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" "mods.irisnet.org/modules/service/client/utils" "mods.irisnet.org/modules/service/types" @@ -422,7 +420,6 @@ func GetCmdQueryServiceResponses() *cobra.Command { Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { return err } diff --git a/modules/service/client/cli/tx.go b/modules/service/client/cli/tx.go index c8502172..004e87bd 100644 --- a/modules/service/client/cli/tx.go +++ b/modules/service/client/cli/tx.go @@ -5,15 +5,14 @@ import ( "encoding/hex" "encoding/json" "fmt" - "io/ioutil" - - "github.com/spf13/cobra" + "os" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" "mods.irisnet.org/modules/service/types" ) @@ -93,7 +92,7 @@ func GetCmdDefineService() *cobra.Command { } if !json.Valid([]byte(schemas)) { - schemasContent, err := ioutil.ReadFile(schemas) + schemasContent, err := os.ReadFile(schemas) if err != nil { return fmt.Errorf("invalid schemas: neither JSON input nor path to .json file were provided") } @@ -180,7 +179,7 @@ func GetCmdBindService() *cobra.Command { return err } if !json.Valid([]byte(options)) { - optionsContent, err := ioutil.ReadFile(options) + optionsContent, err := os.ReadFile(options) if err != nil { return fmt.Errorf("invalid options: neither JSON input nor path to .json file were provided") } @@ -206,7 +205,7 @@ func GetCmdBindService() *cobra.Command { return err } if !json.Valid([]byte(pricing)) { - pricingContent, err := ioutil.ReadFile(pricing) + pricingContent, err := os.ReadFile(pricing) if err != nil { return fmt.Errorf("invalid pricing: neither JSON input nor path to .json file were provided") } @@ -294,7 +293,7 @@ func GetCmdUpdateServiceBinding() *cobra.Command { } if len(pricing) != 0 { if !json.Valid([]byte(pricing)) { - pricingContent, err := ioutil.ReadFile(pricing) + pricingContent, err := os.ReadFile(pricing) if err != nil { return fmt.Errorf("invalid pricing: neither JSON input nor path to .json file were provided") } @@ -324,7 +323,7 @@ func GetCmdUpdateServiceBinding() *cobra.Command { } if len(options) != 0 { if !json.Valid([]byte(options)) { - optionsContent, err := ioutil.ReadFile(options) + optionsContent, err := os.ReadFile(options) if err != nil { return fmt.Errorf("invalid options: neither JSON input nor path to .json file were provided") } @@ -568,7 +567,7 @@ func GetCmdCallService() *cobra.Command { input, _ := cmd.Flags().GetString(FlagData) if !json.Valid([]byte(input)) { - inputContent, err := ioutil.ReadFile(input) + inputContent, err := os.ReadFile(input) if err != nil { return fmt.Errorf("invalid input data: neither JSON input nor path to .json file were provided") } @@ -674,7 +673,7 @@ func GetCmdRespondService() *cobra.Command { if len(result) > 0 { if !json.Valid([]byte(result)) { - resultContent, err := ioutil.ReadFile(result) + resultContent, err := os.ReadFile(result) if err != nil { return fmt.Errorf("invalid result: neither JSON input nor path to .json file were provided") } @@ -696,7 +695,7 @@ func GetCmdRespondService() *cobra.Command { if len(output) > 0 { if !json.Valid([]byte(output)) { - outputContent, err := ioutil.ReadFile(output) + outputContent, err := os.ReadFile(output) if err != nil { return fmt.Errorf("invalid output data: neither JSON input nor path to .json file were provided") } diff --git a/modules/service/client/utils/query.go b/modules/service/client/utils/query.go index 03e74bd3..9c3dd5b4 100644 --- a/modules/service/client/utils/query.go +++ b/modules/service/client/utils/query.go @@ -9,7 +9,6 @@ import ( tmbytes "github.com/cometbft/cometbft/libs/bytes" rpcclient "github.com/cometbft/cometbft/rpc/client" - "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" @@ -49,7 +48,8 @@ func QueryRequestContextByTxQuery( queryRoute string, params types.QueryRequestContextRequest, ) ( - requestContext types.RequestContext, err error) { + requestContext types.RequestContext, err error, +) { requestContextId, err := hex.DecodeString(params.RequestContextId) if err != nil { return requestContext, err @@ -122,7 +122,6 @@ func QueryRequestByTxQuery( ) ( request types.Request, err error, ) { - contextID, _, requestHeight, batchRequestIndex, err := types.SplitRequestID(requestID) if err != nil { return request, err @@ -160,11 +159,11 @@ func QueryRequestByTxQuery( var requests []types.CompactRequest var requestsBz []byte for _, attribute := range event.Attributes { - if string(attribute.Key) == types.AttributeKeyRequests { + if attribute.Key == types.AttributeKeyRequests { requestsBz = []byte(attribute.GetValue()) } - if string(attribute.Key) == types.AttributeKeyRequestContextID && - string(attribute.GetValue()) == contextID.String() { + if attribute.Key == types.AttributeKeyRequestContextID && + attribute.GetValue() == contextID.String() { found = true } } @@ -213,7 +212,6 @@ func QueryResponseByTxQuery( ) ( response types.Response, err error, ) { - events := []string{ fmt.Sprintf( "%s.%s='%s'", @@ -275,7 +273,7 @@ func QueryResponseByTxQuery( // QueryRequestsByBinding queries active requests by the service binding func QueryRequestsByBinding( - cliCtx client.Context, queryRoute string, serviceName string, provider sdk.AccAddress, + cliCtx client.Context, queryRoute, serviceName string, provider sdk.AccAddress, ) ( []types.Request, int64, error, ) { diff --git a/modules/service/client/utils/schema.go b/modules/service/client/utils/schema.go index af42892a..c9a4dad0 100644 --- a/modules/service/client/utils/schema.go +++ b/modules/service/client/utils/schema.go @@ -5,9 +5,7 @@ import ( "regexp" ) -var ( - reSchemaReplace = regexp.MustCompile(`[\n\t]`) -) +var reSchemaReplace = regexp.MustCompile(`[\n\t]`) // SchemaType defines the schema type type SchemaType string diff --git a/modules/service/depinject.go b/modules/service/depinject.go index 178e1739..6a7909e3 100644 --- a/modules/service/depinject.go +++ b/modules/service/depinject.go @@ -3,7 +3,6 @@ package service import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" - "github.com/cosmos/cosmos-sdk/codec" store "github.com/cosmos/cosmos-sdk/store/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -23,7 +22,7 @@ func init() { } func ProvideKeyTable() types.KeyTable { - return types.ParamKeyTable() //nolint:staticcheck + return types.ParamKeyTable() } var _ appmodule.AppModule = AppModule{} diff --git a/modules/service/genesis.go b/modules/service/genesis.go index 3345f456..7c894075 100644 --- a/modules/service/genesis.go +++ b/modules/service/genesis.go @@ -6,7 +6,6 @@ import ( "sort" tmbytes "github.com/cometbft/cometbft/libs/bytes" - sdk "github.com/cosmos/cosmos-sdk/types" "mods.irisnet.org/modules/service/keeper" @@ -19,7 +18,9 @@ func InitGenesis(ctx sdk.Context, k keeper.Keeper, data types.GenesisState) { panic(err.Error()) } - k.SetParams(ctx, data.Params) + if err := k.SetParams(ctx, data.Params); err != nil { + panic(err.Error()) + } for _, definition := range data.Definitions { k.SetServiceDefinition(ctx, definition) @@ -68,7 +69,7 @@ func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { k.IterateWithdrawAddresses( ctx, - func(ownerAddress sdk.AccAddress, withdrawAddress sdk.AccAddress) bool { + func(ownerAddress, withdrawAddress sdk.AccAddress) bool { withdrawAddresses[ownerAddress.String()] = withdrawAddress.String() return false }, diff --git a/modules/service/keeper/binding.go b/modules/service/keeper/binding.go index c926ed9b..04beaa79 100644 --- a/modules/service/keeper/binding.go +++ b/modules/service/keeper/binding.go @@ -4,11 +4,10 @@ import ( "bytes" "time" - gogotypes "github.com/cosmos/gogoproto/types" - errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" v1 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" + gogotypes "github.com/cosmos/gogoproto/types" "mods.irisnet.org/modules/service/types" ) @@ -555,7 +554,7 @@ func (k Keeper) GetWithdrawAddress(ctx sdk.Context, owner sdk.AccAddress) sdk.Ac // IterateWithdrawAddresses iterates through all withdrawal addresses func (k Keeper) IterateWithdrawAddresses( ctx sdk.Context, - op func(owner sdk.AccAddress, withdrawAddress sdk.AccAddress) (stop bool), + op func(owner, withdrawAddress sdk.AccAddress) (stop bool), ) { store := ctx.KVStore(k.storeKey) diff --git a/modules/service/keeper/depinject_test.go b/modules/service/keeper/depinject_test.go index fef392d5..be1de7dc 100644 --- a/modules/service/keeper/depinject_test.go +++ b/modules/service/keeper/depinject_test.go @@ -25,8 +25,6 @@ import ( upgrademodulev1 "cosmossdk.io/api/cosmos/upgrade/module/v1" vestingmodulev1 "cosmossdk.io/api/cosmos/vesting/module/v1" "cosmossdk.io/core/appconfig" - "google.golang.org/protobuf/types/known/durationpb" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" "github.com/cosmos/cosmos-sdk/x/authz" @@ -45,6 +43,7 @@ import ( slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + "google.golang.org/protobuf/types/known/durationpb" servicemodule "mods.irisnet.org/api/irismod/service/module/v1" _ "mods.irisnet.org/modules/service" @@ -249,7 +248,7 @@ var ( Config: appconfig.WrapAny(&consensusmodulev1.Module{}), }, { - Name: servicetypes.ModuleName, + Name: servicetypes.ModuleName, Config: appconfig.WrapAny(&servicemodule.Module{ FeeCollectorName: servicetypes.FeeCollectorName, }), diff --git a/modules/service/keeper/fees.go b/modules/service/keeper/fees.go index 593d9ab6..7807d83a 100644 --- a/modules/service/keeper/fees.go +++ b/modules/service/keeper/fees.go @@ -1,12 +1,11 @@ package keeper import ( - gogotypes "github.com/cosmos/gogoproto/types" - errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" v1 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" + gogotypes "github.com/cosmos/gogoproto/types" "mods.irisnet.org/modules/service/types" ) diff --git a/modules/service/keeper/grpc_query.go b/modules/service/keeper/grpc_query.go index cccf8df3..211ebbc2 100644 --- a/modules/service/keeper/grpc_query.go +++ b/modules/service/keeper/grpc_query.go @@ -4,16 +4,14 @@ import ( "context" "encoding/hex" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - errorsmod "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/query" - gogotypes "github.com/cosmos/gogoproto/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "mods.irisnet.org/modules/service/types" ) @@ -87,7 +85,7 @@ func (k Keeper) Bindings( pageRes, err = query.Paginate( bindingStore, shapePageRequest(req.Pagination), - func(key []byte, value []byte) error { + func(key, value []byte) error { var binding types.ServiceBinding k.cdc.MustUnmarshal(value, &binding) bindings = append(bindings, &binding) @@ -103,7 +101,7 @@ func (k Keeper) Bindings( return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid owner address (%s)", err) } bindingStore := prefix.NewStore(store, types.GetOwnerBindingsSubspace(owner, req.ServiceName)) - pageRes, err = query.Paginate(bindingStore, shapePageRequest(req.Pagination), func(key []byte, value []byte) error { + pageRes, err = query.Paginate(bindingStore, shapePageRequest(req.Pagination), func(key, value []byte) error { provider := sdk.AccAddress(key) if binding, found := k.GetServiceBinding(ctx, req.ServiceName, provider); found { @@ -226,7 +224,7 @@ func (k Keeper) Requests( pageRes, err := query.Paginate( requestStore, shapePageRequest(req.Pagination), - func(key []byte, value []byte) error { + func(key, value []byte) error { var requestID gogotypes.BytesValue k.cdc.MustUnmarshal(value, &requestID) request, _ := k.GetRequest(ctx, requestID.Value) @@ -274,7 +272,7 @@ func (k Keeper) RequestsByReqCtx( pageRes, err := query.Paginate( requestStore, shapePageRequest(req.Pagination), - func(key []byte, value []byte) error { + func(key, value []byte) error { requestID := append( append(requestContextId, sdk.Uint64ToBigEndian(req.BatchCounter)...), key...) @@ -353,7 +351,7 @@ func (k Keeper) Responses( pageRes, err := query.Paginate( responseStore, shapePageRequest(req.Pagination), - func(key []byte, value []byte) error { + func(key, value []byte) error { var response types.Response k.cdc.MustUnmarshal(value, &response) responses = append(responses, &response) diff --git a/modules/service/keeper/invocation.go b/modules/service/keeper/invocation.go index 1403edf7..1a819332 100644 --- a/modules/service/keeper/invocation.go +++ b/modules/service/keeper/invocation.go @@ -5,14 +5,12 @@ import ( "encoding/json" "fmt" - gogotypes "github.com/cosmos/gogoproto/types" - + errorsmod "cosmossdk.io/errors" "github.com/cometbft/cometbft/crypto/tmhash" tmbytes "github.com/cometbft/cometbft/libs/bytes" - - errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + gogotypes "github.com/cosmos/gogoproto/types" "mods.irisnet.org/modules/service/types" ) diff --git a/modules/service/keeper/keeper.go b/modules/service/keeper/keeper.go index 4e817943..9ef42089 100644 --- a/modules/service/keeper/keeper.go +++ b/modules/service/keeper/keeper.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/modules/service/keeper/keeper_test.go b/modules/service/keeper/keeper_test.go index 4b2e5ecc..da41a950 100644 --- a/modules/service/keeper/keeper_test.go +++ b/modules/service/keeper/keeper_test.go @@ -5,18 +5,16 @@ import ( "testing" "time" - gogotypes "github.com/cosmos/gogoproto/types" - "github.com/stretchr/testify/suite" - "github.com/tidwall/gjson" - abci "github.com/cometbft/cometbft/abci/types" tmbytes "github.com/cometbft/cometbft/libs/bytes" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" v1 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + gogotypes "github.com/cosmos/gogoproto/types" + "github.com/stretchr/testify/suite" + "github.com/tidwall/gjson" "mods.irisnet.org/modules/service/keeper" "mods.irisnet.org/modules/service/types" @@ -98,8 +96,7 @@ func (suite *KeeperTestSuite) SetupTest() { suite.ctx = app.BaseApp.NewContext(isCheckTx, tmproto.Header{}) suite.app = app - suite.keeper.SetParams(suite.ctx, types.DefaultParams()) - + suite.NoError(suite.keeper.SetParams(suite.ctx, types.DefaultParams()), "set params failed") suite.setTestAddrs() } @@ -881,7 +878,7 @@ type MockOracleService struct { func (m MockOracleService) GetExchangeRate( ctx sdk.Context, input string, -) (result string, output string) { +) (result, output string) { feedName := gjson.Get(input, "body").Get("pair").String() value, ok := m.feeds[feedName] diff --git a/modules/service/keeper/module_service.go b/modules/service/keeper/module_service.go index 9dab4c73..b6768962 100644 --- a/modules/service/keeper/module_service.go +++ b/modules/service/keeper/module_service.go @@ -1,9 +1,8 @@ package keeper import ( - tmbytes "github.com/cometbft/cometbft/libs/bytes" - errorsmod "cosmossdk.io/errors" + tmbytes "github.com/cometbft/cometbft/libs/bytes" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" diff --git a/modules/service/keeper/msg_server.go b/modules/service/keeper/msg_server.go index 5fccb39a..0851df93 100644 --- a/modules/service/keeper/msg_server.go +++ b/modules/service/keeper/msg_server.go @@ -4,9 +4,8 @@ import ( "context" "encoding/hex" - tmbytes "github.com/cometbft/cometbft/libs/bytes" - errorsmod "cosmossdk.io/errors" + tmbytes "github.com/cometbft/cometbft/libs/bytes" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" diff --git a/modules/service/keeper/oracle_price.go b/modules/service/keeper/oracle_price.go index c53e1260..3e95c0c9 100644 --- a/modules/service/keeper/oracle_price.go +++ b/modules/service/keeper/oracle_price.go @@ -3,10 +3,9 @@ package keeper import ( "fmt" - "github.com/tidwall/gjson" - errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/tidwall/gjson" "mods.irisnet.org/modules/service/types" ) diff --git a/modules/service/keeper/params.go b/modules/service/keeper/params.go index ebe0aea3..40259f9c 100644 --- a/modules/service/keeper/params.go +++ b/modules/service/keeper/params.go @@ -62,7 +62,7 @@ func (k Keeper) RestrictedServiceFeeDenom(ctx sdk.Context) bool { // GetParams sets the farm module parameters. func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { store := ctx.KVStore(k.storeKey) - bz := store.Get([]byte(types.ParamsKey)) + bz := store.Get(types.ParamsKey) if bz == nil { return params } diff --git a/modules/service/keeper/state_change.go b/modules/service/keeper/state_change.go index a1dc872b..cd6cdfd3 100644 --- a/modules/service/keeper/state_change.go +++ b/modules/service/keeper/state_change.go @@ -4,7 +4,6 @@ import ( "encoding/json" tmbytes "github.com/cometbft/cometbft/libs/bytes" - sdk "github.com/cosmos/cosmos-sdk/types" "mods.irisnet.org/modules/service/types" diff --git a/modules/service/module.go b/modules/service/module.go index 6dd0d91e..241e678a 100644 --- a/modules/service/module.go +++ b/modules/service/module.go @@ -5,17 +5,15 @@ import ( "encoding/json" "fmt" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" "mods.irisnet.org/modules/service/client/cli" "mods.irisnet.org/modules/service/keeper" diff --git a/modules/service/simulation/operations.go b/modules/service/simulation/operations.go index 5a470321..9d257199 100644 --- a/modules/service/simulation/operations.go +++ b/modules/service/simulation/operations.go @@ -6,7 +6,6 @@ import ( "math/rand" tmbytes "github.com/cometbft/cometbft/libs/bytes" - "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" @@ -246,7 +245,6 @@ func SimulateMsgDefineService( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - simAccount, _ := simtypes.RandomAcc(r, accs) serviceName := simtypes.RandStringOfLength(r, 70) @@ -313,7 +311,6 @@ func SimulateMsgBindService( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - def, err := GenServiceDefinition(r, k, ctx) if err != nil { return simtypes.NoOpMsg( @@ -462,7 +459,6 @@ func SimulateMsgUpdateServiceBinding( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - binding, err := GenServiceBinding(r, k, ctx) if err != nil { return simtypes.NoOpMsg( @@ -582,7 +578,6 @@ func SimulateMsgSetWithdrawAddress( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - withdrawalAccount, _ := simtypes.RandomAcc(r, accs) binding, err := GenServiceBinding(r, k, ctx) @@ -661,7 +656,6 @@ func SimulateMsgDisableServiceBinding( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - binding, err := GenServiceBinding(r, k, ctx) if err != nil { return simtypes.NoOpMsg( @@ -749,7 +743,6 @@ func SimulateMsgEnableServiceBinding( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - binding, err := GenServiceBinding(r, k, ctx) if err != nil { return simtypes.NoOpMsg( @@ -865,7 +858,6 @@ func SimulateMsgRefundServiceDeposit( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - binding, err := GenServiceBindingDisabled(r, k, ctx) if err != nil { return simtypes.NoOpMsg( @@ -1066,7 +1058,6 @@ func SimulateMsgRespondService( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - request := GenRequest(r, k, ctx) if request.Size() == 0 { return simtypes.NoOpMsg( @@ -1135,7 +1126,6 @@ func SimulateMsgRespondService( } return simtypes.NewOperationMsg(msg, true, "", nil), nil, nil - } } @@ -1241,7 +1231,6 @@ func SimulateMsgStartRequestContext( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - requestContextId := GenPausedRequestContextId(r, k, ctx) if len(requestContextId) == 0 { return simtypes.NoOpMsg( @@ -1343,7 +1332,6 @@ func SimulateMsgKillRequestContext( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - requestContextId := GenRequestContextId(r, k, ctx) if len(requestContextId) == 0 { return simtypes.NoOpMsg( @@ -1444,7 +1432,6 @@ func SimulateMsgUpdateRequestContext( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - requestContextId := GenRequestContextId(r, k, ctx) if len(requestContextId) == 0 { return simtypes.NoOpMsg( @@ -1580,7 +1567,6 @@ func SimulateMsgWithdrawEarnedFees( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - binding, err := GenServiceBinding(r, k, ctx) if err != nil { return simtypes.NoOpMsg( @@ -1646,7 +1632,6 @@ func SimulateMsgWithdrawEarnedFees( } return simtypes.NewOperationMsg(msg, true, "", nil), nil, nil - } } diff --git a/modules/service/types/invocation.go b/modules/service/types/invocation.go index bddcfa6a..de1aae77 100644 --- a/modules/service/types/invocation.go +++ b/modules/service/types/invocation.go @@ -8,9 +8,8 @@ import ( "fmt" "strings" - tmbytes "github.com/cometbft/cometbft/libs/bytes" - errorsmod "cosmossdk.io/errors" + tmbytes "github.com/cometbft/cometbft/libs/bytes" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/modules/service/types/invocation_test.go b/modules/service/types/invocation_test.go index 570a59bb..740f34c2 100644 --- a/modules/service/types/invocation_test.go +++ b/modules/service/types/invocation_test.go @@ -4,10 +4,9 @@ import ( "math" "testing" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/crypto/tmhash" tmbytes "github.com/cometbft/cometbft/libs/bytes" + "github.com/stretchr/testify/require" ) func TestIDGenerate(t *testing.T) { diff --git a/modules/service/types/keys.go b/modules/service/types/keys.go index 25955ccb..473b46e8 100644 --- a/modules/service/types/keys.go +++ b/modules/service/types/keys.go @@ -29,7 +29,7 @@ const ( // FeeCollectorName is the root string for the service fee collector address used for testing FeeCollectorName = "service_fee_collector" - //Address length (binary) + // Address length (binary) AddrLen = 20 ) diff --git a/modules/service/types/module_service.go b/modules/service/types/module_service.go index 9c60bd39..c8994f0e 100644 --- a/modules/service/types/module_service.go +++ b/modules/service/types/module_service.go @@ -7,5 +7,5 @@ import ( type ModuleService struct { ServiceName string Provider sdk.AccAddress - ReuquestService func(ctx sdk.Context, input string) (result string, output string) + ReuquestService func(ctx sdk.Context, input string) (result, output string) } diff --git a/modules/service/types/msgs_test.go b/modules/service/types/msgs_test.go index 59cf7c69..504a612e 100644 --- a/modules/service/types/msgs_test.go +++ b/modules/service/types/msgs_test.go @@ -5,11 +5,9 @@ import ( "strings" "testing" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/crypto/tmhash" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" ) var ( @@ -55,7 +53,8 @@ var ( // ------------- - invalidName = "invalid/service/name" + invalidName = "invalid/service/name" + invalidRequestContextID = "invalid-request-context-id" ) // TestMsgDefineServiceRoute tests Route for MsgDefineService @@ -1366,8 +1365,6 @@ func TestMsgPauseRequestContextType(t *testing.T) { // TestMsgPauseRequestContextValidation tests ValidateBasic for MsgPauseRequestContext func TestMsgPauseRequestContextValidation(t *testing.T) { - invalidRequestContextID := "invalid-request-context-id" - testMsgs := []*MsgPauseRequestContext{ NewMsgPauseRequestContext(testRequestContextID, testConsumer), // valid msg NewMsgPauseRequestContext( @@ -1432,8 +1429,6 @@ func TestMsgStartRequestContextType(t *testing.T) { // TestMsgStartRequestContextValidation tests ValidateBasic for MsgStartRequestContext func TestMsgStartRequestContextValidation(t *testing.T) { - invalidRequestContextID := "invalid-request-context-id" - testMsgs := []*MsgStartRequestContext{ NewMsgStartRequestContext(testRequestContextID, testConsumer), // valid msg NewMsgStartRequestContext( @@ -1498,8 +1493,6 @@ func TestMsgKillRequestContextType(t *testing.T) { // TestMsgKillRequestContextValidation tests ValidateBasic for MsgKillRequestContext func TestMsgKillRequestContextValidation(t *testing.T) { - invalidRequestContextID := "invalid-request-context-id" - testMsgs := []*MsgKillRequestContext{ NewMsgKillRequestContext(testRequestContextID, testConsumer), // valid msg NewMsgKillRequestContext(testRequestContextID, emptyAddress), // missing consumer address @@ -1561,7 +1554,6 @@ func TestMsgUpdateRequestContextType(t *testing.T) { // TestMsgUpdateRequestContextValidation tests ValidateBasic for MsgUpdateRequestContext func TestMsgUpdateRequestContextValidation(t *testing.T) { - invalidRequestContextID := "invalid-request-context-id" invalidDuplicateProviders := []string{testProvider, testProvider} invalidTimeout := int64(-1) invalidLessRepeatedFreq := uint64(testTimeout) - 10 diff --git a/modules/service/types/oracle_price.go b/modules/service/types/oracle_price.go index 09b15c8a..8bab381d 100644 --- a/modules/service/types/oracle_price.go +++ b/modules/service/types/oracle_price.go @@ -5,7 +5,6 @@ import ( "time" "github.com/cometbft/cometbft/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/modules/service/types/params.go b/modules/service/types/params.go index 020527b3..c76d2649 100644 --- a/modules/service/types/params.go +++ b/modules/service/types/params.go @@ -4,9 +4,8 @@ import ( "fmt" "time" - "gopkg.in/yaml.v2" - sdk "github.com/cosmos/cosmos-sdk/types" + "gopkg.in/yaml.v2" ) // Service params default values diff --git a/modules/service/types/params_legacy.go b/modules/service/types/params_legacy.go index 20677e1f..4fd8ee87 100644 --- a/modules/service/types/params_legacy.go +++ b/modules/service/types/params_legacy.go @@ -1,7 +1,7 @@ package types // Keys for parameter access -// nolint + var ( KeyMaxRequestTimeout = []byte("MaxRequestTimeout") KeyMinDepositMultiple = []byte("MinDepositMultiple") diff --git a/modules/service/types/querier.go b/modules/service/types/querier.go index dffce165..8f531b1f 100644 --- a/modules/service/types/querier.go +++ b/modules/service/types/querier.go @@ -2,7 +2,6 @@ package types import ( tmbytes "github.com/cometbft/cometbft/libs/bytes" - sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/modules/service/types/random.go b/modules/service/types/random.go index 925d1539..b2837827 100644 --- a/modules/service/types/random.go +++ b/modules/service/types/random.go @@ -2,7 +2,6 @@ package types import ( "github.com/cometbft/cometbft/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -54,4 +53,4 @@ func GetRandomSvcDefinition() ServiceDefinition { RandomAuthorDescription, RandomServiceSchemas, ) -} \ No newline at end of file +} diff --git a/modules/service/types/schema.go b/modules/service/types/schema.go index 7f09da05..b9a1fcf0 100644 --- a/modules/service/types/schema.go +++ b/modules/service/types/schema.go @@ -5,9 +5,8 @@ import ( "errors" "fmt" - "github.com/xeipuuv/gojsonschema" - errorsmod "cosmossdk.io/errors" + "github.com/xeipuuv/gojsonschema" ) const PATH_BODY = "body" @@ -61,7 +60,7 @@ func ValidateRequestInput(input string) error { return nil } -func ValidateRequestInputBody(schemas string, inputBody string) error { +func ValidateRequestInputBody(schemas, inputBody string) error { inputSchemaBz, err := parseInputSchema(schemas) if err != nil { return err @@ -95,7 +94,7 @@ func ValidateResponseOutput(output string) error { return nil } -func ValidateResponseOutputBody(schemas string, outputBody string) error { +func ValidateResponseOutputBody(schemas, outputBody string) error { outputSchemaBz, err := parseOutputSchema(schemas) if err != nil { return err diff --git a/modules/token/client/cli/query.go b/modules/token/client/cli/query.go index 08c82d7c..8bba7f25 100644 --- a/modules/token/client/cli/query.go +++ b/modules/token/client/cli/query.go @@ -4,12 +4,11 @@ import ( "context" "fmt" - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" "mods.irisnet.org/modules/token/types" v1 "mods.irisnet.org/modules/token/types/v1" diff --git a/modules/token/client/cli/tx.go b/modules/token/client/cli/tx.go index aebaa725..535b4b95 100644 --- a/modules/token/client/cli/tx.go +++ b/modules/token/client/cli/tx.go @@ -4,14 +4,13 @@ import ( "fmt" "strings" - "github.com/ethereum/go-ethereum/common" - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" + "github.com/ethereum/go-ethereum/common" + "github.com/spf13/cobra" "mods.irisnet.org/modules/token/types" v1 "mods.irisnet.org/modules/token/types/v1" @@ -444,12 +443,12 @@ func GetCmdSwapToErc20() *cobra.Command { if err != nil { return err } - + paidAmount, token, err := parseMainCoin(clientCtx, args[0]) if err != nil { return err } - if len(token.GetContract()) <= 0 { + if len(token.GetContract()) == 0 { return fmt.Errorf("corresponding erc20 contract of %s does not exist", paidAmount.Denom) } @@ -459,7 +458,7 @@ func GetCmdSwapToErc20() *cobra.Command { } from := clientCtx.GetFromAddress() - if len(receiver) <= 0 { + if len(receiver) == 0 { // set default receiver receiver = common.BytesToAddress(from.Bytes()).Hex() } @@ -513,7 +512,7 @@ func GetCmdSwapFromErc20() *cobra.Command { if err != nil { return err } - if len(token.GetContract()) <= 0 { + if len(token.GetContract()) == 0 { return fmt.Errorf("corresponding erc20 contract of %s does not exist", wantedAmount.Denom) } @@ -521,7 +520,7 @@ func GetCmdSwapFromErc20() *cobra.Command { if err != nil { return err } - if len(receiver) <= 0 { + if len(receiver) == 0 { // set default receiver receiver = from } @@ -548,4 +547,4 @@ func GetCmdSwapFromErc20() *cobra.Command { flags.AddTxFlagsToCmd(cmd) return cmd -} \ No newline at end of file +} diff --git a/modules/token/contracts/erc20.go b/modules/token/contracts/erc20.go index 42e50db5..efcaac54 100644 --- a/modules/token/contracts/erc20.go +++ b/modules/token/contracts/erc20.go @@ -1,30 +1,39 @@ package contracts import ( - _ "embed" + _ "embed" // embed "encoding/json" "mods.irisnet.org/modules/token/types" ) const ( + // EventSwapToNative is the name of the event emitted when swapping to native EventSwapToNative = "SwapToNative" - MethodMint = "mint" - MethodBurn = "burn" - MethodBalanceOf = "balanceOf" - MethodInitialize = "initialize" - MethodUpgradeTo = "upgradeTo" + // MethodMint is the name of the method mint of the ERC20 contract + MethodMint = "mint" + // MethodBurn is the name of the method burn of the ERC20 contract + MethodBurn = "burn" + // MethodBalanceOf is the name of the method balanceOf of the ERC20 contract + MethodBalanceOf = "balanceOf" + // MethodInitialize is the name of the method initialize of the ERC20 contract + MethodInitialize = "initialize" + // MethodUpgradeTo is the name of the method upgradeTo of the Beacon contract + MethodUpgradeTo = "upgradeTo" ) var ( + // ERC20JSON is the json abi of the ERC20 contract //go:embed compiled_contracts/Token.json - ERC20JSON []byte //nolint: golint + ERC20JSON []byte //nolint: golint // Generate by solc + // TokenProxyJSON is the json abi of the ERC20 contract //go:embed compiled_contracts/TokenProxy.json - TokenProxyJSON []byte //nolint: golint + TokenProxyJSON []byte //nolint: golint // Generate by solc + // BeaconJSON is the json abi of the Beacon contract //go:embed compiled_contracts/UpgradeableBeacon.json - BeaconJSON []byte //nolint: golint + BeaconJSON []byte //nolint: golint // Generate by solc // ERC20TokenContract is the compiled erc20 contract ERC20TokenContract types.CompiledContract diff --git a/modules/token/depinject.go b/modules/token/depinject.go index 4df1e2d7..2f3b81a3 100644 --- a/modules/token/depinject.go +++ b/modules/token/depinject.go @@ -3,7 +3,6 @@ package token import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" - "github.com/cosmos/cosmos-sdk/codec" store "github.com/cosmos/cosmos-sdk/store/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -25,7 +24,7 @@ func init() { // ProvideKeyTable returns the key table for the Token module func ProvideKeyTable() types.KeyTable { - return v1.ParamKeyTable() //nolint:staticcheck + return v1.ParamKeyTable() } var _ appmodule.AppModule = AppModule{} diff --git a/modules/token/keeper/depinject_test.go b/modules/token/keeper/depinject_test.go index 61812a40..7dd068fc 100644 --- a/modules/token/keeper/depinject_test.go +++ b/modules/token/keeper/depinject_test.go @@ -25,8 +25,6 @@ import ( upgrademodulev1 "cosmossdk.io/api/cosmos/upgrade/module/v1" vestingmodulev1 "cosmossdk.io/api/cosmos/vesting/module/v1" "cosmossdk.io/core/appconfig" - "google.golang.org/protobuf/types/known/durationpb" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" "github.com/cosmos/cosmos-sdk/x/authz" @@ -45,6 +43,7 @@ import ( slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + "google.golang.org/protobuf/types/known/durationpb" tokenmodule "mods.irisnet.org/api/irismod/token/module/v1" _ "mods.irisnet.org/modules/token" @@ -247,11 +246,11 @@ var ( Config: appconfig.WrapAny(&consensusmodulev1.Module{}), }, { - Name: tokentypes.ModuleName, + Name: tokentypes.ModuleName, Config: appconfig.WrapAny(&tokenmodule.Module{ FeeCollectorName: authtypes.FeeCollectorName, }), }, }, }) -) \ No newline at end of file +) diff --git a/modules/token/keeper/erc20.go b/modules/token/keeper/erc20.go index 33be7041..b0c054cb 100644 --- a/modules/token/keeper/erc20.go +++ b/modules/token/keeper/erc20.go @@ -93,13 +93,15 @@ func (k Keeper) DeployERC20( token.Contract = contractAddr.String() k.upsertToken(ctx, *token) - ctx.EventManager().EmitTypedEvent(&v1.EventDeployERC20{ + if err := ctx.EventManager().EmitTypedEvent(&v1.EventDeployERC20{ Symbol: symbol, Name: name, Scale: uint32(scale), MinUnit: minUnit, Contract: contractAddr.String(), - }) + }); err != nil { + return common.Address{}, err + } return contractAddr, nil } @@ -144,14 +146,12 @@ func (k Keeper) SwapFromERC20( if err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, receiver, mintedCoins); err != nil { return err } - - ctx.EventManager().EmitTypedEvent(&v1.EventSwapFromERC20{ + return ctx.EventManager().EmitTypedEvent(&v1.EventSwapFromERC20{ FromContract: contract.String(), WantedAmount: &wantedAmount, Sender: sender.String(), Receiver: receiver.String(), }) - return nil } // SwapToERC20 executes a swap from a native token to its ERC20 token counterpart @@ -202,14 +202,12 @@ func (k Keeper) SwapToERC20( if err := k.MintERC20(ctx, contract, receiver, amount.Amount.BigInt()); err != nil { return err } - - ctx.EventManager().EmitTypedEvent(&v1.EventSwapToERC20{ + return ctx.EventManager().EmitTypedEvent(&v1.EventSwapToERC20{ Amount: amount, Sender: sender.String(), Receiver: receiver.String(), ToContract: token.Contract, }) - return nil } // MintERC20 mints ERC20 tokens to an account. diff --git a/modules/token/keeper/erc20_test.go b/modules/token/keeper/erc20_test.go index b761c4aa..5366896f 100644 --- a/modules/token/keeper/erc20_test.go +++ b/modules/token/keeper/erc20_test.go @@ -4,9 +4,8 @@ import ( "math/big" "github.com/cometbft/cometbft/crypto/tmhash" - "github.com/ethereum/go-ethereum/common" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/ethereum/go-ethereum/common" v1 "mods.irisnet.org/modules/token/types/v1" ) diff --git a/modules/token/keeper/evm.go b/modules/token/keeper/evm.go index 20b575ce..44d41d32 100644 --- a/modules/token/keeper/evm.go +++ b/modules/token/keeper/evm.go @@ -4,15 +4,13 @@ import ( "encoding/json" "math/big" + errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" ethtypes "github.com/ethereum/go-ethereum/core/types" - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "mods.irisnet.org/modules/token/types" tokentypes "mods.irisnet.org/modules/token/types" ) @@ -37,7 +35,7 @@ func (k Keeper) CallEVM( commit bool, method string, args ...interface{}, -) (*types.Result, error) { +) (*tokentypes.Result, error) { data, err := contractABI.Pack(method, args...) if err != nil { return nil, errorsmod.Wrap( @@ -71,15 +69,15 @@ func (k Keeper) CallEVMWithData( contract *common.Address, data []byte, commit bool, -) (*types.Result, error) { +) (*tokentypes.Result, error) { nonce, err := k.accountKeeper.GetSequence(ctx, from.Bytes()) if err != nil { return nil, err } - gasCap := types.DefaultGasCap + gasCap := tokentypes.DefaultGasCap if commit { - args, err := json.Marshal(types.TransactionArgs{ + args, err := json.Marshal(tokentypes.TransactionArgs{ From: &from, To: contract, Data: (*hexutil.Bytes)(&data), @@ -88,9 +86,9 @@ func (k Keeper) CallEVMWithData( return nil, errorsmod.Wrapf(tokentypes.ErrJSONMarshal, "failed to marshal tx args: %s", err.Error()) } - gas, err := k.evmKeeper.EstimateGas(sdk.WrapSDKContext(ctx), &types.EthCallRequest{ + gas, err := k.evmKeeper.EstimateGas(sdk.WrapSDKContext(ctx), &tokentypes.EthCallRequest{ Args: args, - GasCap: types.DefaultGasCap, + GasCap: tokentypes.DefaultGasCap, ChainID: k.evmKeeper.ChainID().Int64(), }) if err != nil { @@ -113,7 +111,7 @@ func (k Keeper) CallEVMWithData( !commit, // isFake ) - res, err := k.evmKeeper.ApplyMessage(ctx, msg, types.NewNoOpTracer(), commit) + res, err := k.evmKeeper.ApplyMessage(ctx, msg, tokentypes.NewNoOpTracer(), commit) if err != nil { return nil, err } diff --git a/modules/token/keeper/evm_hook.go b/modules/token/keeper/evm_hook.go index 7aceef0f..8b0e7e6d 100644 --- a/modules/token/keeper/evm_hook.go +++ b/modules/token/keeper/evm_hook.go @@ -6,7 +6,6 @@ import ( errorsmod "cosmossdk.io/errors" sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ethereum/go-ethereum/core" ethtypes "github.com/ethereum/go-ethereum/core/types" diff --git a/modules/token/keeper/fees.go b/modules/token/keeper/fees.go index 900ac5c0..a615adad 100644 --- a/modules/token/keeper/fees.go +++ b/modules/token/keeper/fees.go @@ -1,10 +1,10 @@ -// nolint package keeper import ( "math" "strconv" + sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "mods.irisnet.org/modules/token/types" @@ -101,7 +101,7 @@ func feeHandler(ctx sdk.Context, k Keeper, feeAcc sdk.AccAddress, fee sdk.Coin) } // calcFeeByBase computes the actual fee according to the given base fee -func calcFeeByBase(name string, baseFee sdk.Int) sdk.Dec { +func calcFeeByBase(name string, baseFee sdkmath.Int) sdk.Dec { feeFactor := calcFeeFactor(name) actualFee := sdk.NewDecFromInt(baseFee).Quo(feeFactor) diff --git a/modules/token/keeper/grpc_query.go b/modules/token/keeper/grpc_query.go index e9bc23a7..bafb0a30 100644 --- a/modules/token/keeper/grpc_query.go +++ b/modules/token/keeper/grpc_query.go @@ -4,18 +4,16 @@ import ( "context" "fmt" - "github.com/cosmos/gogoproto/proto" - "github.com/ethereum/go-ethereum/common" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - sdkmath "cosmossdk.io/math" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" - + "github.com/cosmos/gogoproto/proto" gogotypes "github.com/cosmos/gogoproto/types" + "github.com/ethereum/go-ethereum/common" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "mods.irisnet.org/modules/token/types" v1 "mods.irisnet.org/modules/token/types/v1" @@ -90,7 +88,7 @@ func (k Keeper) Tokens(c context.Context, req *v1.QueryTokensRequest) (*v1.Query pageRes, err = query.Paginate( tokenStore, shapePageRequest(req.Pagination), - func(_ []byte, value []byte) error { + func(_, value []byte) error { var token v1.Token k.cdc.MustUnmarshal(value, &token) tokens = append(tokens, &token) @@ -102,7 +100,7 @@ func (k Keeper) Tokens(c context.Context, req *v1.QueryTokensRequest) (*v1.Query } } else { tokenStore := prefix.NewStore(store, types.KeyTokens(owner, "")) - pageRes, err = query.Paginate(tokenStore, shapePageRequest(req.Pagination), func(_ []byte, value []byte) error { + pageRes, err = query.Paginate(tokenStore, shapePageRequest(req.Pagination), func(_, value []byte) error { var symbol gogotypes.StringValue k.cdc.MustUnmarshal(value, &symbol) token, err := k.GetToken(ctx, symbol.Value) diff --git a/modules/token/keeper/keeper.go b/modules/token/keeper/keeper.go index 37460b9b..0c18dc83 100644 --- a/modules/token/keeper/keeper.go +++ b/modules/token/keeper/keeper.go @@ -3,10 +3,9 @@ package keeper import ( "fmt" - "github.com/cometbft/cometbft/libs/log" - errorsmod "cosmossdk.io/errors" sdkmath "cosmossdk.io/math" + "github.com/cometbft/cometbft/libs/log" "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/modules/token/keeper/keeper_test.go b/modules/token/keeper/keeper_test.go index d0c3f2b9..ea3d760b 100644 --- a/modules/token/keeper/keeper_test.go +++ b/modules/token/keeper/keeper_test.go @@ -3,16 +3,14 @@ package keeper_test import ( "testing" - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/suite" - + sdkmath "cosmossdk.io/math" "github.com/cometbft/cometbft/crypto/tmhash" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - - sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + "github.com/ethereum/go-ethereum/common" + "github.com/stretchr/testify/suite" "mods.irisnet.org/modules/token/keeper" tokentypes "mods.irisnet.org/modules/token/types" @@ -30,7 +28,7 @@ var ( add2 = sdk.AccAddress(tmhash.SumTruncated([]byte("tokenTest1"))) initAmt = sdkmath.NewIntWithDecimal(100000000, int(6)) initCoin = sdk.Coins{sdk.NewCoin(denom, initAmt)} - beacon = common.BytesToAddress(owner.Bytes()) + beacon = common.BytesToAddress(owner.Bytes()) ) type KeeperTestSuite struct { @@ -45,7 +43,7 @@ type KeeperTestSuite struct { func (suite *KeeperTestSuite) SetupTest() { depInjectOptions := simapp.DepinjectOptions{ - Config: AppConfig, + Config: AppConfig, Providers: []interface{}{ keeper.ProvideMockEVM(), keeper.ProvideMockICS20(), @@ -53,7 +51,7 @@ func (suite *KeeperTestSuite) SetupTest() { Consumers: []interface{}{&suite.keeper}, } - app := simapp.Setup(suite.T(), isCheckTx,depInjectOptions) + app := simapp.Setup(suite.T(), isCheckTx, depInjectOptions) suite.legacyAmino = app.LegacyAmino() suite.ctx = app.BaseApp.NewContext(isCheckTx, tmproto.Header{}) @@ -63,7 +61,7 @@ func (suite *KeeperTestSuite) SetupTest() { // set params params := v1.DefaultParams() params.Beacon = beacon.String() - suite.keeper.SetParams(suite.ctx, params) + suite.NoError(suite.keeper.SetParams(suite.ctx, params), "SetParams failed") // init tokens to addr err := suite.bk.MintCoins(suite.ctx, tokentypes.ModuleName, initCoin) @@ -268,4 +266,4 @@ func (suite *KeeperTestSuite) TestSwapFeeToken() { amt = suite.bk.GetBalance(suite.ctx, token2.GetOwner(), token2.MinUnit) suite.Equal("0t2min", amt.String()) -} \ No newline at end of file +} diff --git a/modules/token/keeper/legacy_grpc_query.go b/modules/token/keeper/legacy_grpc_query.go index 6967a908..4360a155 100644 --- a/modules/token/keeper/legacy_grpc_query.go +++ b/modules/token/keeper/legacy_grpc_query.go @@ -3,11 +3,10 @@ package keeper import ( "context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" v1 "mods.irisnet.org/modules/token/types/v1" "mods.irisnet.org/modules/token/types/v1beta1" diff --git a/modules/token/keeper/mock.go b/modules/token/keeper/mock.go index 37b40552..8f10bf35 100644 --- a/modules/token/keeper/mock.go +++ b/modules/token/keeper/mock.go @@ -17,13 +17,11 @@ import ( tokentypes "mods.irisnet.org/modules/token/types" ) - var ( _ tokentypes.EVMKeeper = (*mockEVM)(nil) _ tokentypes.ICS20Keeper = (*mockICS20)(nil) ) - // ProvideMockEVM returns an instance of tokentypes.EVMKeeper. // // No parameters. diff --git a/modules/token/keeper/msg_server.go b/modules/token/keeper/msg_server.go index 8b22304a..c6e12f5a 100644 --- a/modules/token/keeper/msg_server.go +++ b/modules/token/keeper/msg_server.go @@ -335,7 +335,7 @@ func (m msgServer) UpgradeERC20(goCtx context.Context, msg *v1.MsgUpgradeERC20) msg.Authority, ) } - + implementation := common.HexToAddress(msg.Implementation) if err := m.k.UpgradeERC20(ctx, implementation); err != nil { return nil, err diff --git a/modules/token/keeper/params.go b/modules/token/keeper/params.go index bbfc7938..2b6889b2 100644 --- a/modules/token/keeper/params.go +++ b/modules/token/keeper/params.go @@ -10,7 +10,7 @@ import ( // GetParams sets the token module parameters. func (k Keeper) GetParams(ctx sdk.Context) (params v1.Params) { store := ctx.KVStore(k.storeKey) - bz := store.Get([]byte(types.PrefixParamsKey)) + bz := store.Get(types.PrefixParamsKey) if bz == nil { return params } diff --git a/modules/token/keeper/token.go b/modules/token/keeper/token.go index 36496d9d..6460554c 100644 --- a/modules/token/keeper/token.go +++ b/modules/token/keeper/token.go @@ -3,12 +3,12 @@ package keeper import ( "fmt" - gogotypes "github.com/cosmos/gogoproto/types" - "github.com/ethereum/go-ethereum/common" - errorsmod "cosmossdk.io/errors" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + gogotypes "github.com/cosmos/gogoproto/types" + "github.com/ethereum/go-ethereum/common" "mods.irisnet.org/modules/token/types" v1 "mods.irisnet.org/modules/token/types/v1" @@ -19,33 +19,32 @@ func (k Keeper) GetTokens(ctx sdk.Context, owner sdk.AccAddress) (tokens []v1.To store := ctx.KVStore(k.storeKey) var it sdk.Iterator + + // 获取迭代器 if owner == nil { it = sdk.KVStorePrefixIterator(store, types.PrefixTokenForSymbol) - defer it.Close() - - for ; it.Valid(); it.Next() { - var token v1.Token - k.cdc.MustUnmarshal(it.Value(), &token) - - tokens = append(tokens, &token) - } - return + } else { + it = sdk.KVStorePrefixIterator(store, types.KeyTokens(owner, "")) } - - it = sdk.KVStorePrefixIterator(store, types.KeyTokens(owner, "")) defer it.Close() for ; it.Valid(); it.Next() { - var symbol gogotypes.StringValue - k.cdc.MustUnmarshal(it.Value(), &symbol) - - token, err := k.getTokenBySymbol(ctx, symbol.Value) - if err != nil { - continue + if owner == nil { + var token v1.Token + k.cdc.MustUnmarshal(it.Value(), &token) + tokens = append(tokens, &token) + } else { + var symbol gogotypes.StringValue + k.cdc.MustUnmarshal(it.Value(), &symbol) + + token, err := k.getTokenBySymbol(ctx, symbol.Value) + if err != nil { + continue + } + tokens = append(tokens, token) } - tokens = append(tokens, token) } - return + return tokens } // GetToken returns the token of the specified symbol or min uint @@ -283,7 +282,7 @@ func (k Keeper) resetStoreKeyForQueryToken( } // getTokenSupply queries the token supply from the total supply -func (k Keeper) getTokenSupply(ctx sdk.Context, denom string) sdk.Int { +func (k Keeper) getTokenSupply(ctx sdk.Context, denom string) math.Int { return k.bankKeeper.GetSupply(ctx, denom).Amount } diff --git a/modules/token/module.go b/modules/token/module.go index 1186f00d..ada70251 100644 --- a/modules/token/module.go +++ b/modules/token/module.go @@ -5,18 +5,16 @@ import ( "encoding/json" "fmt" - "github.com/gorilla/mux" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" "mods.irisnet.org/modules/token/client/cli" "mods.irisnet.org/modules/token/keeper" diff --git a/modules/token/simulation/decoder.go b/modules/token/simulation/decoder.go index 98807332..ed3ce0de 100644 --- a/modules/token/simulation/decoder.go +++ b/modules/token/simulation/decoder.go @@ -6,11 +6,10 @@ import ( "bytes" "fmt" - gogotypes "github.com/cosmos/gogoproto/types" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/kv" + gogotypes "github.com/cosmos/gogoproto/types" "mods.irisnet.org/modules/token/types" v1 "mods.irisnet.org/modules/token/types/v1" diff --git a/modules/token/simulation/genesis.go b/modules/token/simulation/genesis.go index dccf3456..ca0abfb3 100644 --- a/modules/token/simulation/genesis.go +++ b/modules/token/simulation/genesis.go @@ -7,6 +7,7 @@ import ( "fmt" "math/rand" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -27,15 +28,15 @@ func RandomDec(r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(r.Int63n(9)+1, 1) } -// RandomInt randomized sdk.Int -func RandomInt(r *rand.Rand) sdk.Int { +// RandomInt randomized math.Int +func RandomInt(r *rand.Rand) math.Int { return sdk.NewInt(r.Int63()) } // RandomizedGenState generates a random GenesisState for bank func RandomizedGenState(simState *module.SimulationState) { var tokenTaxRate sdk.Dec - var issueTokenBaseFee sdk.Int + var issueTokenBaseFee math.Int var mintTokenFeeRatio sdk.Dec var enableErc20 bool var tokens []v1.Token diff --git a/modules/token/simulation/operations.go b/modules/token/simulation/operations.go index 1a5a8103..6dff866a 100644 --- a/modules/token/simulation/operations.go +++ b/modules/token/simulation/operations.go @@ -186,7 +186,6 @@ func SimulateEditToken( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - token, _, skip := selectOneToken(ctx, k, ak, bk, false) if skip { return simtypes.NoOpMsg( @@ -266,7 +265,6 @@ func SimulateMintToken( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - token, maxFee, skip := selectOneToken(ctx, k, ak, bk, true) if skip { return simtypes.NoOpMsg( @@ -346,7 +344,6 @@ func SimulateTransferTokenOwner( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - token, _, skip := selectOneToken(ctx, k, ak, bk, false) if skip { return simtypes.NoOpMsg( @@ -355,7 +352,7 @@ func SimulateTransferTokenOwner( "skip TransferTokenOwner", ), nil, nil } - var simToAccount, _ = simtypes.RandomAcc(r, accs) + simToAccount, _ := simtypes.RandomAcc(r, accs) for simToAccount.Address.Equals(token.GetOwner()) { simToAccount, _ = simtypes.RandomAcc(r, accs) } @@ -429,7 +426,6 @@ func SimulateBurnToken( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - token, _, skip := selectOneToken(ctx, k, ak, bk, false) if skip { return simtypes.NoOpMsg( @@ -555,7 +551,7 @@ func selectOneToken( sdk.NewCoin(v1.GetNativeToken().MinUnit, spendableStake).Sub(mintFee), ) token = t - return + break } return token, maxFees, true } @@ -573,7 +569,6 @@ func genToken(ctx sdk.Context, bk types.BankKeeper, accs []simtypes.Account, ) (v1.Token, sdk.Coins) { - var token v1.Token token = randToken(r, accs) diff --git a/modules/token/types/errors.go b/modules/token/types/errors.go index 407d8f88..d294031f 100644 --- a/modules/token/types/errors.go +++ b/modules/token/types/errors.go @@ -1,4 +1,3 @@ -// nolint package types import ( @@ -32,5 +31,5 @@ var ( ErrUnsupportedKey = errorsmod.Register(ModuleName, 24, "evm not supported public key") ErrInvalidContract = errorsmod.Register(ModuleName, 25, "invalid contract") ErrERC20Disabled = errorsmod.Register(ModuleName, 26, "erc20 swap is disabled") - ErrBeaconNotSet = errorsmod.Register(ModuleName, 27, "beacon contract not set") + ErrBeaconNotSet = errorsmod.Register(ModuleName, 27, "beacon contract not set") ) diff --git a/modules/token/types/events.go b/modules/token/types/events.go index 64fde553..e108eeff 100644 --- a/modules/token/types/events.go +++ b/modules/token/types/events.go @@ -1,4 +1,3 @@ -// nolint package types const ( diff --git a/modules/token/types/evm.go b/modules/token/types/evm.go index 70b8e2a1..33b52b4d 100644 --- a/modules/token/types/evm.go +++ b/modules/token/types/evm.go @@ -127,7 +127,7 @@ func (dt NoOpTracer) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, sco func (dt NoOpTracer) CaptureEnd(output []byte, gasUsed uint64, tm time.Duration, err error) {} // CaptureEnter implements vm.Tracer interface -func (dt NoOpTracer) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) { +func (dt NoOpTracer) CaptureEnter(typ vm.OpCode, from, to common.Address, input []byte, gas uint64, value *big.Int) { } // CaptureExit implements vm.Tracer interface diff --git a/modules/token/types/expected_keepers.go b/modules/token/types/expected_keepers.go index f6b1b7e4..c711fd9b 100644 --- a/modules/token/types/expected_keepers.go +++ b/modules/token/types/expected_keepers.go @@ -4,14 +4,13 @@ import ( "context" "math/big" - "github.com/ethereum/go-ethereum/core" - ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/core/vm" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/ethereum/go-ethereum/core" + ethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/core/vm" ) // BankKeeper defines the expected bank keeper (noalias) diff --git a/modules/token/types/types.go b/modules/token/types/types.go index 619c443a..b8cc47aa 100644 --- a/modules/token/types/types.go +++ b/modules/token/types/types.go @@ -36,7 +36,7 @@ func (b Bool) Marshal() ([]byte, error) { // Unmarshal needed for protobuf compatibility func (b *Bool) Unmarshal(data []byte) error { - *b = Bool(data[:]) + *b = Bool(data) return nil } @@ -55,6 +55,7 @@ func (b *Bool) UnmarshalJSON(data []byte) error { *b = Bool(s) return nil } + func ParseBool(v string) (Bool, error) { if len(v) == 0 { return Nil, nil @@ -74,7 +75,7 @@ func ParseBool(v string) (Bool, error) { // ratio: swap rate // inputScale: the decimal scale of input amount // outputScale: the decimal scale of output amount -func LossLessSwap(input sdk.Int, ratio sdk.Dec, inputScale, outputScale uint32) (sdk.Int, sdk.Int) { +func LossLessSwap(input sdkmath.Int, ratio sdk.Dec, inputScale, outputScale uint32) (sdkmath.Int, sdkmath.Int) { inputDec := sdk.NewDecFromInt(input) scaleFactor := int64(inputScale) - int64(outputScale) var scaleMultipler, scaleReverseMultipler sdk.Dec diff --git a/modules/token/types/types_test.go b/modules/token/types/types_test.go index 8e5d13cb..641d9a4d 100644 --- a/modules/token/types/types_test.go +++ b/modules/token/types/types_test.go @@ -4,12 +4,13 @@ import ( "reflect" "testing" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" ) func TestLossLessConvert(t *testing.T) { type args struct { - a sdk.Int + a math.Int ratio sdk.Dec aScale uint32 bScale uint32 @@ -17,8 +18,8 @@ func TestLossLessConvert(t *testing.T) { tests := []struct { name string args args - want sdk.Int - want1 sdk.Int + want math.Int + want1 math.Int wantErr bool }{ { @@ -68,7 +69,8 @@ func TestLossLessConvert(t *testing.T) { want: Int("1000001"), want1: Int("1000001000000000000"), wantErr: false, - }, { + }, + { name: "fully conversion(non-equivalent ratio)", args: args{ a: Int("1000000"), @@ -94,11 +96,10 @@ func TestLossLessConvert(t *testing.T) { } } -func Int(i string) sdk.Int { +func Int(i string) math.Int { iInt, ok := sdk.NewIntFromString(i) if !ok { panic("invalid i: " + i) } return iInt - } diff --git a/modules/token/types/v1/msgs.go b/modules/token/types/v1/msgs.go index eedf23e7..238af694 100644 --- a/modules/token/types/v1/msgs.go +++ b/modules/token/types/v1/msgs.go @@ -45,7 +45,7 @@ var ( // NewMsgIssueToken - construct token issue msg. func NewMsgIssueToken( - symbol string, minUnit string, name string, + symbol, minUnit, name string, scale uint32, initialSupply, maxSupply uint64, mintable bool, owner string, ) *MsgIssueToken { diff --git a/modules/token/types/v1/msgs_test.go b/modules/token/types/v1/msgs_test.go index b3dab38a..97ffb1a4 100644 --- a/modules/token/types/v1/msgs_test.go +++ b/modules/token/types/v1/msgs_test.go @@ -3,12 +3,10 @@ package v1 import ( "testing" - "github.com/stretchr/testify/require" - - "github.com/cometbft/cometbft/crypto/tmhash" - sdkmath "cosmossdk.io/math" + "github.com/cometbft/cometbft/crypto/tmhash" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" tokentypes "mods.irisnet.org/modules/token/types" ) @@ -269,9 +267,9 @@ func TestMsgDeployERC20(t *testing.T) { authority string expectPass bool }{ - {symbol: "btc", name: "BTC TOKEN", scale: 18, minUnit: "staoshi", authority: addr1, expectPass: true}, - {symbol: "BTC", name: "BTC TOKEN", scale: 18, minUnit: "staoshi", authority: addr1, expectPass: false}, - {symbol: "bTC", name: "BTC TOKEN", scale: 18, minUnit: "staoshi", authority: addr1, expectPass: true}, + {symbol: "btc", name: "BTC TOKEN", scale: 18, minUnit: "satoshi", authority: addr1, expectPass: true}, + {symbol: "BTC", name: "BTC TOKEN", scale: 18, minUnit: "satoshi", authority: addr1, expectPass: false}, + {symbol: "bTC", name: "BTC TOKEN", scale: 18, minUnit: "satoshi", authority: addr1, expectPass: true}, {symbol: "stake", name: "Stake Token", scale: 18, minUnit: "ibc/3C3D7B3BE4ECC85A0E5B52A3AEC3B7DFC2AA9CA47C37821E57020D6807043BE9", authority: addr1, expectPass: true}, {symbol: "ibc/3C3D7B3BE4ECC85A0E5B52A3AEC3B7DFC2AA9CA47C37821E57020D6807043BE9", name: "Stake Token", scale: 18, minUnit: "ibc/3C3D7B3BE4ECC85A0E5B52A3AEC3B7DFC2AA9CA47C37821E57020D6807043BE9", authority: addr1, expectPass: true}, } diff --git a/modules/token/types/v1/params_test.go b/modules/token/types/v1/params_test.go index f9fb9f04..394e7bc1 100644 --- a/modules/token/types/v1/params_test.go +++ b/modules/token/types/v1/params_test.go @@ -4,9 +4,8 @@ import ( "math" "testing" - "github.com/stretchr/testify/require" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" ) func TestValidateParams(t *testing.T) { diff --git a/modules/token/types/v1/token.go b/modules/token/types/v1/token.go index 357af4ab..a568aa78 100644 --- a/modules/token/types/v1/token.go +++ b/modules/token/types/v1/token.go @@ -3,11 +3,10 @@ package v1 import ( "math/big" - "github.com/cosmos/gogoproto/proto" - errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/cosmos/gogoproto/proto" tokentypes "mods.irisnet.org/modules/token/types" ) @@ -17,11 +16,13 @@ var ( tenInt = big.NewInt(10) ) -type SwapRegistry map[string]SwapParams -type SwapParams struct { - MinUnit string - Ratio sdk.Dec -} +type ( + SwapRegistry map[string]SwapParams + SwapParams struct { + MinUnit string + Ratio sdk.Dec + } +) // TokenI defines an interface for Token type TokenI interface { diff --git a/modules/token/types/v1/token_test.go b/modules/token/types/v1/token_test.go index 8629b9da..b751eca9 100644 --- a/modules/token/types/v1/token_test.go +++ b/modules/token/types/v1/token_test.go @@ -11,18 +11,16 @@ import ( tokentypes "mods.irisnet.org/modules/token/types" ) -var ( - token = Token{ - Symbol: "iris", - Name: "irisnet", - Scale: 18, - MinUnit: "atto", - InitialSupply: 1000000, - MaxSupply: 10000000, - Mintable: true, - Owner: "", - } -) +var token = Token{ + Symbol: "iris", + Name: "irisnet", + Scale: 18, + MinUnit: "atto", + InitialSupply: 1000000, + MaxSupply: 10000000, + Mintable: true, + Owner: "", +} func TestToken_ToMinCoin(t *testing.T) { type args struct { diff --git a/modules/token/types/v1beta1/msgs.go b/modules/token/types/v1beta1/msgs.go index 73e421ee..cd2298d8 100644 --- a/modules/token/types/v1beta1/msgs.go +++ b/modules/token/types/v1beta1/msgs.go @@ -32,7 +32,7 @@ var ( // NewMsgIssueToken - construct token issue msg. func NewMsgIssueToken( - symbol string, minUnit string, name string, + symbol, minUnit, name string, scale uint32, initialSupply, maxSupply uint64, mintable bool, owner string, ) *MsgIssueToken { @@ -256,7 +256,7 @@ func (msg MsgMintToken) ValidateBasic() error { } // NewMsgBurnToken creates a MsgMintToken -func NewMsgBurnToken(symbol string, owner string, amount uint64) *MsgBurnToken { +func NewMsgBurnToken(symbol, owner string, amount uint64) *MsgBurnToken { return &MsgBurnToken{ Symbol: symbol, Amount: amount, diff --git a/modules/token/types/v1beta1/msgs_test.go b/modules/token/types/v1beta1/msgs_test.go index 1b81ee91..9ad04a4d 100644 --- a/modules/token/types/v1beta1/msgs_test.go +++ b/modules/token/types/v1beta1/msgs_test.go @@ -3,11 +3,9 @@ package v1beta1 import ( "testing" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/crypto/tmhash" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" tokentypes "mods.irisnet.org/modules/token/types" ) @@ -154,7 +152,7 @@ func TestMsgEditTokenRoute(t *testing.T) { func TestMsgEditTokenGetSignBytes(t *testing.T) { mintable := tokentypes.False - var msg = MsgEditToken{ + msg := MsgEditToken{ Name: "BTC TOKEN", Owner: sdk.AccAddress(tmhash.SumTruncated([]byte("owner"))).String(), Symbol: "btc", diff --git a/modules/token/types/v1beta1/params.go b/modules/token/types/v1beta1/params.go index 40bd85a2..b69b1508 100644 --- a/modules/token/types/v1beta1/params.go +++ b/modules/token/types/v1beta1/params.go @@ -3,10 +3,9 @@ package v1beta1 import ( "fmt" - "gopkg.in/yaml.v2" - sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + "gopkg.in/yaml.v2" ) var _ paramtypes.ParamSet = (*Params)(nil) diff --git a/modules/token/types/v1beta1/params_test.go b/modules/token/types/v1beta1/params_test.go index a9e6cb24..296f9d0e 100644 --- a/modules/token/types/v1beta1/params_test.go +++ b/modules/token/types/v1beta1/params_test.go @@ -4,9 +4,8 @@ import ( "math" "testing" - "github.com/stretchr/testify/require" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" ) func TestValidateParams(t *testing.T) { diff --git a/modules/token/types/v1beta1/token.go b/modules/token/types/v1beta1/token.go index cbe34fc3..915dc3a2 100644 --- a/modules/token/types/v1beta1/token.go +++ b/modules/token/types/v1beta1/token.go @@ -3,12 +3,11 @@ package v1beta1 import ( "math/big" - "github.com/cosmos/gogoproto/proto" - "gopkg.in/yaml.v2" - errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/cosmos/gogoproto/proto" + "gopkg.in/yaml.v2" tokentypes "mods.irisnet.org/modules/token/types" ) diff --git a/modules/token/types/v1beta1/token_test.go b/modules/token/types/v1beta1/token_test.go index b880830a..d82263ca 100644 --- a/modules/token/types/v1beta1/token_test.go +++ b/modules/token/types/v1beta1/token_test.go @@ -11,18 +11,16 @@ import ( tokentypes "mods.irisnet.org/modules/token/types" ) -var ( - token = Token{ - Symbol: "iris", - Name: "irisnet", - Scale: 18, - MinUnit: "atto", - InitialSupply: 1000000, - MaxSupply: 10000000, - Mintable: true, - Owner: "", - } -) +var token = Token{ + Symbol: "iris", + Name: "irisnet", + Scale: 18, + MinUnit: "atto", + InitialSupply: 1000000, + MaxSupply: 10000000, + Mintable: true, + Owner: "", +} func TestToken_ToMinCoin(t *testing.T) { type args struct { diff --git a/modules/token/types/validation.go b/modules/token/types/validation.go index 24d477b9..704ba5df 100644 --- a/modules/token/types/validation.go +++ b/modules/token/types/validation.go @@ -50,9 +50,6 @@ var ( regexpMinUintFmt = fmt.Sprintf("^[a-z][a-z0-9]{%d,%d}$", MinimumMinUnitLen-1, MaximumMinUnitLen-1) regexpMinUint = regexp.MustCompile(regexpMinUintFmt).MatchString - - regexpEthAddressStr = "^0x[0-9a-f]{40}$" - regexpEthAddress = regexp.MustCompile(regexpEthAddressStr).MatchString ) // ValidateInitialSupply verifies whether the initial supply is legal diff --git a/scripts/go-lint-all.bash b/scripts/go-lint-all.bash index 546f1a5b..30690219 100755 --- a/scripts/go-lint-all.bash +++ b/scripts/go-lint-all.bash @@ -41,21 +41,4 @@ else echo "no files to lint" exit 0 fi - - GIT_DIFF=$(echo $GIT_DIFF | tr -d "'" | tr ' ' '\n' | grep '\.go$' | grep -v '\.pb\.go$' | grep -Eo '^[^/]+\/[^/]+' | uniq) - - lint_sdk=false - for dir in ${GIT_DIFF[@]}; do - if [[ ! -f "$REPO_ROOT/$dir/go.mod" ]]; then - lint_sdk=true - else - lint_module $dir "$@" - fi - done - - if [[ $lint_sdk ]]; then - cd "$REPO_ROOT" - echo "linting github.com/cosmos/cosmos-sdk [$(date -Iseconds -u)]" - golangci-lint run ./... -c "${REPO_ROOT}/.golangci.yml" "$@" --build-tags=${LINT_TAGS} - fi fi \ No newline at end of file diff --git a/simapp/app_v2.go b/simapp/app_v2.go index 027c8831..ed8df16a 100644 --- a/simapp/app_v2.go +++ b/simapp/app_v2.go @@ -6,12 +6,10 @@ import ( "os" "path/filepath" + "cosmossdk.io/depinject" dbm "github.com/cometbft/cometbft-db" abci "github.com/cometbft/cometbft/abci/types" "github.com/cometbft/cometbft/libs/log" - - "cosmossdk.io/depinject" - "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" @@ -163,7 +161,7 @@ func NewSimApp( app = &SimApp{} appBuilder *runtime.AppBuilder - providers = append(depInjectOptions.Providers[:], appOpts) + providers = append(depInjectOptions.Providers, appOpts) // merge the AppConfig and other configuration in one config appConfig = depinject.Configs( depInjectOptions.Config, @@ -200,7 +198,7 @@ func NewSimApp( ) ) - consumer := append(depInjectOptions.Consumers[:], + consumer := append(depInjectOptions.Consumers, &appBuilder, &app.appCodec, &app.legacyAmino, diff --git a/simapp/export.go b/simapp/export.go index 07617b53..62b77bae 100644 --- a/simapp/export.go +++ b/simapp/export.go @@ -6,7 +6,6 @@ import ( "log" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - servertypes "github.com/cosmos/cosmos-sdk/server/types" sdk "github.com/cosmos/cosmos-sdk/types" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" @@ -17,7 +16,7 @@ import ( // ExportAppStateAndValidators exports the state of the application for a genesis // file. func (app *SimApp) ExportAppStateAndValidators( - forZeroHeight bool, jailAllowedAddrs []string, modulesToExport []string, + forZeroHeight bool, jailAllowedAddrs, modulesToExport []string, ) (servertypes.ExportedApp, error) { // as if they could withdraw from the start of the next block ctx := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()}) @@ -48,7 +47,7 @@ func (app *SimApp) ExportAppStateAndValidators( // prepare for fresh start at zero height // NOTE zero height genesis is a temporary feature which will be deprecated // -// in favour of export at a block height +// in favor of export at a block height func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) { applyAllowedAddrs := false diff --git a/simapp/go.mod b/simapp/go.mod index 1f0d11ea..bbc02a7f 100644 --- a/simapp/go.mod +++ b/simapp/go.mod @@ -4,6 +4,7 @@ go 1.19 require ( cosmossdk.io/depinject v1.0.0-alpha.4 + cosmossdk.io/errors v1.0.1 cosmossdk.io/math v1.2.0 github.com/cometbft/cometbft v0.37.4 github.com/cometbft/cometbft-db v0.7.0 @@ -21,7 +22,6 @@ require ( cloud.google.com/go/storage v1.30.1 // indirect cosmossdk.io/api v0.3.1 // indirect cosmossdk.io/core v0.5.1 // indirect - cosmossdk.io/errors v1.0.1 // indirect cosmossdk.io/log v1.3.1 // indirect cosmossdk.io/tools/rosetta v0.2.1 // indirect filippo.io/edwards25519 v1.0.0 // indirect diff --git a/simapp/network.go b/simapp/network.go index 9b8135ed..687dd96d 100644 --- a/simapp/network.go +++ b/simapp/network.go @@ -32,9 +32,10 @@ type ResponseTx struct { } func SetupNetwork(t *testing.T, depInjectOptions DepinjectOptions) Network { - cfg,err := NewConfig(depInjectOptions) + t.Helper() + cfg, err := NewConfig(depInjectOptions) require.NoError(t, err) - + cfg.NumValidators = 4 network, err := network.New(t, t.TempDir(), cfg) @@ -44,11 +45,12 @@ func SetupNetwork(t *testing.T, depInjectOptions DepinjectOptions) Network { Network: network, Config: cfg, } - n.WaitForNBlock(2) + require.NoError(t, n.WaitForNBlock(2), "WaitForNBlock failed") return n } func SetupNetworkWithConfig(t *testing.T, cfg network.Config) Network { + t.Helper() network, err := network.New(t, t.TempDir(), cfg) require.NoError(t, err, "SetupNetwork failed") @@ -65,10 +67,11 @@ func (n Network) ExecTxCmdWithResult(t *testing.T, cmd *cobra.Command, extraArgs []string, ) *ResponseTx { + t.Helper() buf, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, extraArgs) require.NoError(t, err, "ExecTestCLICmd failed") - n.WaitForNextBlock() + require.NoError(t, n.WaitForNextBlock(), "WaitForNextBlock failed") respType := proto.Message(&sdk.TxResponse{}) require.NoError(t, clientCtx.Codec.UnmarshalJSON(buf.Bytes(), respType), buf.String()) @@ -84,6 +87,7 @@ func (n Network) ExecQueryCmd(t *testing.T, extraArgs []string, resp proto.Message, ) { + t.Helper() buf, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, extraArgs) require.NoError(t, err, "ExecTestCLICmd failed") require.NoError(t, clientCtx.Codec.UnmarshalJSON(buf.Bytes(), resp), buf.String()) @@ -107,6 +111,7 @@ func (n Network) QueryTx(t *testing.T, clientCtx client.Context, txHash string, ) *ResponseTx { + t.Helper() var ( result *coretypes.ResultTx err error @@ -119,7 +124,8 @@ func (n Network) QueryTx(t *testing.T, reTry: result, err = clientCtx.Client.Tx(context.Background(), txHashBz, false) if err != nil && strings.Contains(err.Error(), "not found") && tryCnt > 0 { - n.WaitForNextBlock() + require.NoError(t, n.WaitForNextBlock(), "WaitForNextBlock failed") + tryCnt-- goto reTry } @@ -145,6 +151,7 @@ func (n Network) SendMsgs( t *testing.T, msgs ...sdk.Msg, ) *sdk.TxResponse { + t.Helper() val := n.Validators[0] client := val.ClientCtx.WithBroadcastMode(flags.BroadcastSync) @@ -171,13 +178,14 @@ func (n Network) SendMsgs( res, err := client.BroadcastTx(txBytes) require.NoError(t, err, "BroadcastTx failed") require.Equal(t, uint32(0), res.Code, res.RawLog) - n.WaitForNBlock(2) + require.NoError(t, n.WaitForNBlock(2), "WaitForNextBlock failed") return res } func (n Network) BlockSendMsgs(t *testing.T, msgs ...sdk.Msg, ) *ResponseTx { + t.Helper() response := n.SendMsgs(t, msgs...) return n.QueryTx(t, n.Validators[0].ClientCtx, response.TxHash) } diff --git a/simapp/state.go b/simapp/state.go index efd9e85c..7db0d302 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -4,14 +4,13 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "math/rand" + "os" "time" + sdkmath "cosmossdk.io/math" tmjson "github.com/cometbft/cometbft/libs/json" tmtypes "github.com/cometbft/cometbft/types" - - sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" sdk "github.com/cosmos/cosmos-sdk/types" @@ -38,7 +37,6 @@ func AppStateFn(cdc codec.JSONCodec, simManager *module.SimulationManager) simty ) ( appState json.RawMessage, simAccs []simtypes.Account, chainID string, genesisTimestamp time.Time, ) { - if simcli.FlagGenesisTimeValue == 0 { genesisTimestamp = simtypes.RandTimestamp(r) } else { @@ -65,7 +63,7 @@ func AppStateFn(cdc codec.JSONCodec, simManager *module.SimulationManager) simty case config.ParamsFile != "": appParams := make(simtypes.AppParams) - bz, err := ioutil.ReadFile(config.ParamsFile) + bz, err := os.ReadFile(config.ParamsFile) if err != nil { panic(err) } @@ -225,7 +223,7 @@ func AppStateFromGenesisFileFn( cdc codec.JSONCodec, genesisFile string, ) (tmtypes.GenesisDoc, []simtypes.Account) { - bytes, err := ioutil.ReadFile(genesisFile) + bytes, err := os.ReadFile(genesisFile) if err != nil { panic(err) } diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 3dcf147b..27ea7973 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -13,19 +13,17 @@ import ( "time" "cosmossdk.io/depinject" + errorsmod "cosmossdk.io/errors" + "cosmossdk.io/math" dbm "github.com/cometbft/cometbft-db" abci "github.com/cometbft/cometbft/abci/types" "github.com/cometbft/cometbft/libs/log" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" tmtypes "github.com/cometbft/cometbft/types" - "github.com/cosmos/gogoproto/proto" - "github.com/stretchr/testify/require" - bam "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" - codectype "github.com/cosmos/cosmos-sdk/codec/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" @@ -44,12 +42,13 @@ import ( "github.com/cosmos/cosmos-sdk/types/module/testutil" authcli "github.com/cosmos/cosmos-sdk/x/auth/client/cli" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/bank/client/cli" bankcli "github.com/cosmos/cosmos-sdk/x/bank/client/cli" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/require" ) // SetupOptions defines arguments that are passed into `Simapp` constructor. @@ -108,6 +107,7 @@ func SetupWithGenesisStateFn( depInjectOptions DepinjectOptions, merge func(cdc codec.Codec, state GenesisState) GenesisState, ) *SimApp { + t.Helper() app, genesisState := setup(true, 5, depInjectOptions) privVal := mock.NewPV() @@ -176,7 +176,7 @@ func NewConfig(depInjectOptions DepinjectOptions) (network.Config, error) { interfaceRegistry codectypes.InterfaceRegistry ) - providers := append(depInjectOptions.Providers[:], log.NewNopLogger()) + providers := append(depInjectOptions.Providers, log.NewNopLogger()) if err := depinject.Inject( depinject.Configs( depInjectOptions.Config, @@ -228,6 +228,7 @@ func genesisStateWithValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance, ) GenesisState { + t.Helper() // set genesis accounts authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis) @@ -399,7 +400,7 @@ func CreateTestAddrs(numAddrs int) []sdk.AccAddress { } // for incode address generation -func testAddr(addr string, bech string) sdk.AccAddress { +func testAddr(addr, bech string) sdk.AccAddress { res, err := sdk.AccAddressFromHexUnsafe(addr) if err != nil { panic(err) @@ -447,7 +448,7 @@ func AddTestAddrsFromPubKeys( app *SimApp, ctx sdk.Context, pubKeys []cryptotypes.PubKey, - accAmt sdk.Int, + accAmt math.Int, ) { initCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), accAmt)) @@ -458,7 +459,7 @@ func AddTestAddrsFromPubKeys( // AddTestAddrs constructs and returns accNum amount of accounts with an // initial balance of accAmt in random order -func AddTestAddrs(app *SimApp, ctx sdk.Context, accNum int, accAmt sdk.Int) []sdk.AccAddress { +func AddTestAddrs(app *SimApp, ctx sdk.Context, accNum int, accAmt math.Int) []sdk.AccAddress { return addTestAddrs(app, ctx, accNum, accAmt, createRandomAccounts) } @@ -468,7 +469,7 @@ func AddTestAddrsIncremental( app *SimApp, ctx sdk.Context, accNum int, - accAmt sdk.Int, + accAmt math.Int, ) []sdk.AccAddress { return addTestAddrs(app, ctx, accNum, accAmt, createIncrementalAccounts) } @@ -477,7 +478,7 @@ func addTestAddrs( app *SimApp, ctx sdk.Context, accNum int, - accAmt sdk.Int, + accAmt math.Int, strategy GenerateAccountStrategy, ) []sdk.AccAddress { testAddrs := strategy(accNum) @@ -514,7 +515,7 @@ func ConvertAddrsToValAddrs(addrs []sdk.AccAddress) []sdk.ValAddress { return valAddrs } -func TestAddr(addr string, bech string) (sdk.AccAddress, error) { +func TestAddr(addr, bech string) (sdk.AccAddress, error) { res, err := sdk.AccAddressFromHexUnsafe(addr) if err != nil { return nil, err @@ -537,6 +538,7 @@ func TestAddr(addr string, bech string) (sdk.AccAddress, error) { // CheckBalance checks the balance of an account. func CheckBalance(t *testing.T, app *SimApp, addr sdk.AccAddress, balances sdk.Coins) { + t.Helper() ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{}) require.True(t, balances.IsEqual(app.BankKeeper.GetAllBalances(ctxCheck, addr))) } @@ -556,6 +558,7 @@ func SignCheckDeliver( expSimPass, expPass bool, priv ...cryptotypes.PrivKey, ) (sdk.GasInfo, *sdk.Result, error) { + t.Helper() tx, err := simtestutil.GenSignedMockTx( rand.New(rand.NewSource(time.Now().UnixNano())), txCfg, @@ -668,7 +671,7 @@ func NewPubKeyFromHex(pk string) (res cryptotypes.PubKey) { panic(err) } if len(pkBytes) != ed25519.PubKeySize { - panic(errors.Wrap(errors.ErrInvalidPubKey, "invalid pubkey size")) + panic(errorsmod.Wrap(errors.ErrInvalidPubKey, "invalid pubkey size")) } return &ed25519.PubKey{Key: pkBytes} } @@ -726,6 +729,7 @@ func QueryBalancesExec( address string, extraArgs ...string, ) sdk.Coins { + t.Helper() args := []string{ address, fmt.Sprintf("--%s=json", "output"), @@ -745,6 +749,7 @@ func QueryBalanceExec( denom string, extraArgs ...string, ) *sdk.Coin { + t.Helper() args := []string{ address, fmt.Sprintf("--%s=%s", bankcli.FlagDenom, denom), @@ -764,6 +769,7 @@ func QueryAccountExec( address string, extraArgs ...string, ) authtypes.AccountI { + t.Helper() args := []string{ address, fmt.Sprintf("--%s=json", "output"), @@ -772,11 +778,11 @@ func QueryAccountExec( out, err := clitestutil.ExecTestCLICmd(clientCtx, authcli.GetAccountCmd(), args) require.NoError(t, err, "QueryAccountExec failed") - respType := proto.Message(&codectype.Any{}) + respType := proto.Message(&codectypes.Any{}) require.NoError(t, clientCtx.Codec.UnmarshalJSON(out.Bytes(), respType)) var account authtypes.AccountI - err = clientCtx.InterfaceRegistry.UnpackAny(respType.(*codectype.Any), &account) + err = clientCtx.InterfaceRegistry.UnpackAny(respType.(*codectypes.Any), &account) require.NoError(t, err, "UnpackAccount failed") return account @@ -789,13 +795,15 @@ func MsgSendExec( from, to, amount fmt.Stringer, extraArgs ...string, ) *ResponseTx { + t.Helper() args := []string{from.String(), to.String(), amount.String()} args = append(args, extraArgs...) - return network.ExecTxCmdWithResult(t, clientCtx, cli.NewSendTxCmd(), args) + return network.ExecTxCmdWithResult(t, clientCtx, bankcli.NewSendTxCmd(), args) } func QueryTx(t *testing.T, clientCtx client.Context, txHash string) abci.ResponseDeliverTx { + t.Helper() txResult, _ := QueryTxWithHeight(t, clientCtx, txHash) return txResult } @@ -805,6 +813,7 @@ func QueryTxWithHeight( clientCtx client.Context, txHash string, ) (abci.ResponseDeliverTx, int64) { + t.Helper() txHashBz, err := hex.DecodeString(txHash) require.NoError(t, err, "query tx failed") diff --git a/simapp/types.go b/simapp/types.go index 0d91d46c..441183ac 100644 --- a/simapp/types.go +++ b/simapp/types.go @@ -8,5 +8,3 @@ type DepinjectOptions struct { Providers []interface{} Consumers []interface{} } - -